unofficial mirror of bug-gnu-emacs@gnu.org 
 help / color / mirror / code / Atom feed
blob a267fc644821f5d43ab2022ef8bddd8b6188d680 241676 bytes (raw)
name: lisp/net/ange-ftp.el 	 # note: path name is non-authoritative(*)

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

;; Copyright (C) 1989-1996, 1998, 2000-2018 Free Software Foundation,
;; Inc.

;; Author: Andy Norman (ange@hplb.hpl.hp.com)
;; Maintainer: emacs-devel@gnu.org
;; Keywords: comm

;; This file is part of GNU Emacs.

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

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

;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.

;;; Commentary:

;; This package attempts to make accessing files and directories using FTP
;; from within GNU Emacs as simple and transparent as possible.  A subset of
;; the common file-handling routines are extended to interact with FTP.

;; Usage:
;;
;; Some of the common GNU Emacs file-handling operations have been made
;; FTP-smart.  If one of these routines is given a filename that matches
;; '/user@host:name' then it will spawn an FTP process connecting to machine
;; 'host' as account 'user' and perform its operation on the file 'name'.
;;
;; For example: if find-file is given a filename of:
;;
;;   /ange@anorman:/tmp/notes
;;
;; then ange-ftp spawns an FTP process, connect to the host 'anorman' as
;; user 'ange', get the file '/tmp/notes' and pop up a buffer containing the
;; contents of that file as if it were on the local filesystem.  If ange-ftp
;; needs a password to connect then it reads one in the echo area.

;; Extended filename syntax:
;;
;; The default extended filename syntax is '/user@host:name', where the
;; 'user@' part may be omitted.  This syntax can be customized to a certain
;; extent by changing ange-ftp-name-format.  There are limitations.
;; The `host' part has an optional suffix `#port' which may be used to
;; specify a non-default port number for the connection.
;;
;; If the user part is omitted then ange-ftp generates a default user
;; instead whose value depends on the variable ange-ftp-default-user.

;; Passwords:
;;
;; A password is required for each host/user pair.  Ange-ftp reads passwords
;; as needed.  You can also specify a password with ange-ftp-set-passwd, or
;; in a *valid* ~/.netrc file.

;; Passwords for user "anonymous":
;;
;; Passwords for the user "anonymous" (or "ftp") are handled
;; specially.  The variable `ange-ftp-generate-anonymous-password'
;; controls what happens: if the value of this variable is a string,
;; then this is used as the password; if non-nil (the default), then
;; the value of `user-mail-address' is used; if nil then the user
;; is prompted for a password as normal.

;; "Dumb" UNIX hosts:
;;
;; The FTP servers on some UNIX machines have problems if the 'ls' command is
;; used.
;;
;; The routine ange-ftp-add-dumb-unix-host can be called to tell ange-ftp to
;; limit itself to the DIR command and not 'ls' for a given UNIX host.  Note
;; that this change will take effect for the current GNU Emacs session only.
;; See below for a discussion of non-UNIX hosts.  If a large number of
;; machines with similar hostnames have this problem then it is easier to set
;; the value of ange-ftp-dumb-unix-host-regexp in your init file.  ange-ftp
;; is unable to automatically recognize dumb unix hosts.

;; File name completion:
;;
;; Full file-name completion is supported on UNIX, VMS, CMS, and MTS hosts.
;; To do filename completion, ange-ftp needs a listing from the remote host.
;; Therefore, for very slow connections, it might not save any time.

;; FTP processes:
;;
;; When ange-ftp starts up an FTP process, it leaves it running for speed
;; purposes.  Some FTP servers will close the connection after a period of
;; time, but ange-ftp should be able to quietly reconnect the next time that
;; the process is needed.
;;
;; Killing the "*ftp user@host*" buffer also kills the ftp process.
;; This should not cause ange-ftp any grief.

;; Binary file transfers:
;;
;; By default ange-ftp transfers files in ASCII mode.  If a file being
;; transferred matches the value of ange-ftp-binary-file-name-regexp then
;; binary mode is used for that transfer.

;; Account passwords:
;;
;; Some FTP servers require an additional password which is sent by the
;; ACCOUNT command.  ange-ftp partially supports this by allowing the user to
;; specify an account password by either calling ange-ftp-set-account, or by
;; specifying an account token in the .netrc file.  If the account password
;; is set by either of these methods then ange-ftp will issue an ACCOUNT
;; command upon starting the FTP process.

;; Preloading:
;;
;; ange-ftp can be preloaded, but must be put in the site-init.el file and
;; not the site-load.el file in order for the documentation strings for the
;; functions being overloaded to be available.

;; Status reports:
;;
;; Most ange-ftp commands that talk to the FTP process output a status
;; message on what they are doing.  In addition, ange-ftp can take advantage
;; of the FTP client's HASH command to display the status of transferring
;; files and listing directories.  See the documentation for the variables
;; ange-ftp-{ascii,binary}-hash-mark-size, ange-ftp-send-hash and
;; ange-ftp-process-verbose for more details.

;; Gateways:
;;
;; Sometimes it is necessary for the FTP process to be run on a different
;; machine than the machine running GNU Emacs.  This can happen when the
;; local machine has restrictions on what hosts it can access.
;;
;; ange-ftp has support for running the ftp process on a different (gateway)
;; machine.  The way it works is as follows:
;;
;; 1) Set the variable 'ange-ftp-gateway-host' to the name of a machine
;;    that doesn't have the access restrictions.
;;
;; 2) Set the variable 'ange-ftp-local-host-regexp' to a regular expression
;;    that matches hosts that can be contacted from running a local ftp
;;    process, but fails to match hosts that can't be accessed locally.  For
;;    example:
;;
;;    "\\.hp\\.com$\\|^[^.]*$"
;;
;;    will match all hosts that are in the .hp.com domain, or don't have an
;;    explicit domain in their name, but will fail to match hosts with
;;    explicit domains or that are specified by their ip address.
;;
;; 3) Using NFS and symlinks, make sure that there is a shared directory with
;;    the *same* name between the local machine and the gateway machine.
;;    This directory is necessary for temporary files created by ange-ftp.
;;
;; 4) Set the variable 'ange-ftp-gateway-tmp-name-template' to the name of
;;    this directory plus an identifying filename prefix.  For example:
;;
;;    "/nfs/hplose/ange/ange-ftp"
;;
;;    where /nfs/hplose/ange is a directory that is shared between the
;;    gateway machine and the local machine.
;;
;; The simplest way of getting a ftp process running on the gateway machine
;; is if you can spawn a remote shell using either 'rsh' or 'remsh'.  If you
;; can't do this for some reason such as security then points 7 onwards will
;; discuss an alternative approach.
;;
;; 5) Set the variable ange-ftp-gateway-program to the name of the remote
;;    shell process such as 'remsh' or 'rsh' if the default isn't correct.
;;
;; 6) Set the variable ange-ftp-gateway-program-interactive to nil if it
;;    isn't already.  This tells ange-ftp that you are using a remote shell
;;    rather than logging in using telnet or rlogin.
;;
;; That should be all you need to allow ange-ftp to spawn a ftp process on
;; the gateway machine.  If you have to use telnet or rlogin to get to the
;; gateway machine then follow the instructions below.
;;
;; 7) Set the variable ange-ftp-gateway-program to the name of the program
;;    that lets you log onto the gateway machine.  This may be something like
;;    telnet or rlogin.
;;
;; 8) Set the variable ange-ftp-gateway-prompt-pattern to a regular
;;    expression that matches the prompt you get when you login to the
;;    gateway machine.  Be very specific here; this regexp must not match
;;    *anything* in your login banner except this prompt.
;;    shell-prompt-pattern is far too general as it appears to match some
;;    login banners from Sun machines.  For example:
;;
;;    "^$*$ *"
;;
;; 9) Set the variable ange-ftp-gateway-program-interactive to t to let
;;    ange-ftp know that it has to "hand-hold" the login to the gateway
;;    machine.
;;
;; 10) Set the variable ange-ftp-gateway-setup-term-command to a UNIX command
;;     that will put the pty connected to the gateway machine into a
;;     no-echoing mode, and will strip off carriage-returns from output from
;;     the gateway machine.  For example:
;;
;;     "stty -onlcr -echo"
;;
;;     will work on HP-UX machines, whereas:
;;
;;     "stty -echo nl"
;;
;;     appears to work for some Sun machines.
;;
;; That's all there is to it.

;; Smart gateways:
;;
;; If you have a "smart" ftp program that allows you to issue commands like
;; "USER foo@bar" which do nice proxy things, then look at the variables
;; ange-ftp-smart-gateway and ange-ftp-smart-gateway-port.
;;
;; Otherwise, if there is an alternate ftp program that implements proxy in
;; a transparent way (i.e. w/o specifying the proxy host), that will
;; connect you directly to the desired destination host:
;; Set ange-ftp-gateway-ftp-program-name to that program's name.
;; Set ange-ftp-local-host-regexp to a value as stated earlier on.
;; Leave ange-ftp-gateway-host set to nil.
;; Set ange-ftp-smart-gateway to t.

;; Tips for using ange-ftp:
;;
;; 1. For dired to work on a host which marks symlinks with a trailing @ in
;;    an ls -alF listing, you need to (setq dired-ls-F-marks-symlinks t).
;;    Most UNIX systems do not do this, but ULTRIX does. If you think that
;;    there is a chance you might connect to an ULTRIX machine (such as
;;    prep.ai.mit.edu), then set this variable accordingly.  This will have
;;    the side effect that dired will have problems with symlinks whose names
;;    end in an @.  If you get yourself into this situation then editing
;;    dired's ls-switches to remove "F", will temporarily fix things.
;;
;; 2. If you know that you are connecting to a certain non-UNIX machine
;;    frequently, and ange-ftp seems to be unable to guess its host-type,
;;    then setting the appropriate host-type regexp
;;    (ange-ftp-vms-host-regexp, ange-ftp-mts-host-regexp, or
;;    ange-ftp-cms-host-regexp) accordingly should help. Also, please report
;;    ange-ftp's inability to recognize the host-type as a bug.
;;
;; 3. For slow connections, you might get "listing unreadable" error
;;    messages, or get an empty buffer for a file that you know has something
;;    in it. The solution is to increase the value of ange-ftp-retry-time.
;;    Its default value is 5 which is plenty for reasonable connections.
;;    However, for some transatlantic connections I set this to 20.
;;
;; 4. Beware of compressing files on non-UNIX hosts. Ange-ftp will do it by
;;    copying the file to the local machine, compressing it there, and then
;;    sending it back. Binary file transfers between machines of different
;;    architectures can be a risky business. Test things out first on some
;;    test files. See "Bugs" below. Also, note that ange-ftp copies files by
;;    moving them through the local machine. Again, be careful when doing
;;    this with binary files on non-Unix machines.
;;
;; 5. Beware that dired over ftp will use your setting of dired-no-confirm
;;    (list of dired commands for which confirmation is not asked).  You
;;    might want to reconsider your setting of this variable, because you
;;    might want confirmation for more commands on remote direds than on
;;    local direds. For example, I strongly recommend that you not include
;;    compress and uncompress in this list. If there is enough demand it
;;    might be a good idea to have an alist ange-ftp-dired-no-confirm of
;;    pairs ( TYPE . LIST ), where TYPE is an operating system type and LIST
;;    is a list of commands for which confirmation would be suppressed.  Then
;;    remote dired listings would take their (buffer-local) value of
;;    dired-no-confirm from this alist. Who votes for this?

;; ---------------------------------------------------------------------
;; Non-UNIX support:
;; ---------------------------------------------------------------------

;; VMS support:
;;
;; Ange-ftp has full support for VMS hosts.  It should be able to
;; automatically recognize any VMS machine. However, if it fails to do
;; this, you can use the command ange-ftp-add-vms-host.  Also, you can
;; set the variable ange-ftp-vms-host-regexp in your init file.  We
;; would be grateful if you would report any failures to automatically
;; recognize a VMS host as a bug.
;;
;; Filename Syntax:
;;
;; For ease of *implementation*, the user enters the VMS filename syntax in a
;; UNIX-y way.  For example:
;;  PUB$:[ANONYMOUS.SDSCPUB.NEXT]README.TXT;1
;; would be entered as:
;;  /PUB$$:/ANONYMOUS/SDSCPUB/NEXT/README.TXT;1
;; i.e. to log in as anonymous on ymir.claremont.edu and grab the file:
;;  [.CSV.POLICY]RULES.MEM
;; you would type:
;;  C-x C-f /anonymous@ymir.claremont.edu:CSV/POLICY/RULES.MEM
;;
;; A valid VMS filename is of the form: FILE.TYPE;##
;; where FILE can be up to 39 characters
;;       TYPE can be up to 39 characters
;;       ## is a version number (an integer between 1 and 32,767)
;; Valid characters in FILE and TYPE are A-Z 0-9 _ - $
;; $ cannot begin a filename, and - cannot be used as the first or last
;; character.
;;
;; Tips:
;; 1. Although VMS is not case sensitive, EMACS running under UNIX is.
;;    Therefore, to access a VMS file, you must enter the filename with upper
;;    case letters.
;; 2. To access the latest version of file under VMS, you use the filename
;;    without the ";" and version number. You should always edit the latest
;;    version of a file. If you want to edit an earlier version, copy it to a
;;    new file first. This has nothing to do with ange-ftp, but is simply
;;    good VMS operating practice. Therefore, to edit FILE.TXT;3 (say 3 is
;;    latest version), do C-x C-f /ymir.claremont.edu:FILE.TXT. If you
;;    inadvertently do C-x C-f /ymir.claremont.edu:FILE.TXT;3, you will find
;;    that VMS will not allow you to save the file because it will refuse to
;;    overwrite FILE.TXT;3, but instead will want to create FILE.TXT;4, and
;;    attach the buffer to this file. To get out of this situation, M-x
;;    write-file /ymir.claremont.edu:FILE.TXT will attach the buffer to
;;    latest version of the file. For this reason, in dired "f"
;;    (dired-find-file), always loads the file sans version, whereas "v",
;;    (dired-view-file), always loads the explicit version number. The
;;    reasoning being that it reasonable to view old versions of a file, but
;;    not to edit them.
;; 3. EMACS has a feature in which it does environment variable substitution
;;    in filenames. Therefore, to enter a $ in a filename, you must quote it
;;    by typing $$.

;; MTS support:
;;
;; Ange-ftp has full support for hosts running
;; the Michigan terminal system.  It should be able to automatically
;; recognize any MTS machine. However, if it fails to do this, you can use
;; the command ange-ftp-add-mts-host.  As well, you can set the variable
;; ange-ftp-mts-host-regexp in your init file. We would be grateful if you
;; would report any failures to automatically recognize a MTS host as a bug.
;;
;; Filename syntax:
;;
;; MTS filenames are entered in a UNIX-y way. For example, if your account
;; was YYYY, the file FILE in the account XXXX: on mtsg.ubc.ca would be
;; entered as
;;   /YYYY@mtsg.ubc.ca:/XXXX:/FILE
;; In other words, MTS accounts are treated as UNIX directories. Of course,
;; to access a file in another account, you must have access permission for
;; it.  If FILE were in your own account, then you could enter it in a
;; relative name fashion as
;;   /YYYY@mtsg.ubc.ca:FILE
;; MTS filenames can be up to 12 characters. Like UNIX, the structure of the
;; filename does not contain a TYPE (i.e. it can have as many "."'s as you
;; like.) MTS filenames are always in upper case, and hence be sure to enter
;; them as such! MTS is not case sensitive, but an EMACS running under UNIX
;; is.

;; CMS support:
;;
;; Ange-ftp has full support for hosts running
;; CMS.  It should be able to automatically recognize any CMS machine.
;; However, if it fails to do this, you can use the command
;; ange-ftp-add-cms-host.  As well, you can set the variable
;; ange-ftp-cms-host-regexp in your init file. We would be grateful if you
;; would report any failures to automatically recognize a CMS host as a bug.
;;
;; Filename syntax:
;;
;; CMS filenames are entered in a UNIX-y way. In other words, minidisks are
;; treated as UNIX directories. For example to access the file READ.ME in
;; minidisk *.311 on cuvmb.cc.columbia.edu, you would enter
;;   /anonymous@cuvmb.cc.columbia.edu:/*.311/READ.ME
;; If *.301 is the default minidisk for this account, you could access
;; FOO.BAR on this minidisk as
;;   /anonymous@cuvmb.cc.columbia.edu:FOO.BAR
;; CMS filenames are of the form FILE.TYPE, where both FILE and TYPE can be
;; up to 8 characters. Again, beware that CMS filenames are always upper
;; case, and hence must be entered as such.
;;
;; Tips:
;; 1. CMS machines, with the exception of anonymous accounts, nearly always
;;    need an account password. To have ange-ftp send an account password,
;;    you can either include it in your .netrc file, or use
;;    ange-ftp-set-account.
;; 2. Ange-ftp cannot send "write passwords" for a minidisk. Hopefully, we
;;    can fix this.
;;
;; BS2000 support:
;;
;; Ange-ftp has full support for BS2000 hosts.  It should be able to
;; automatically recognize any BS2000 machine. However, if it fails to
;; do this, you can use the command ange-ftp-add-bs2000-host.  As well,
;; you can set the variable ange-ftp-bs2000-host-regexp in your .emacs
;; file. We would be grateful if you would report any failures to auto-
;; matically recognize a BS2000 host as a bug.
;;
;; If you want to access the POSIX subsystem on BS2000 you MUST use
;; command ange-ftp-add-bs2000-posix-host for that particular
;; hostname.  ange-ftp can't decide if you want to access the native
;; filesystem or the POSIX filesystem, so it accesses the native
;; filesystem by default.  And if you have an ASCII filesystem in
;; your BS2000 POSIX subsystem you must use
;; ange-ftp-binary-file-name-regexp to access its files.
;;
;; Filename Syntax:
;;
;; For ease of *implementation*, the user enters the BS2000 filename
;; syntax in a UNIX-y way.  For example:
;;  :PUB:$PUBLIC.ANONYMOUS.SDSCPUB.NEXT.README.TXT
;; would be entered as:
;;  /:PUB:/$$PUBLIC/ANONYMOUS.SDSCPUB.NEXT.README.TXT
;; You don't have to type pubset and account, if they have default values,
;; i.e. to log in as anonymous on bs2000.anywhere.com and grab the file
;; IMPORTANT.TEXT.ON.BS2000 on the default pubset X on userid PUBLIC
;; (there are only 8 characters in a valid username), you could type:
;;  C-x C-f /public@bs2000.anywhere.com:/IMPORTANT.TEXT.ON.BS2000
;; or
;;  C-x C-f /anonym@bs2000.anywhere.com:/:X:/$$PUBLIC/IMPORTANT.TEXT.ON.BS2000
;;
;; If X is not your default pubset, you could add it as 'subdirectory' (BS2000
;; has a flat architecture) with the command
;; (setq ange-ftp-bs2000-additional-pubsets '(":X:"))
;; and then you could type:
;;  C-x C-f /anonym@bs2000.anywhere.com:/:X:/IMPORTANT.TEXT.ON.BS2000
;;
;; Valid characters in an BS2000 filename are A-Z 0-9 $ # @ . -
;; If the first character in a filename is # or @, this is replaced with
;; ange-ftp-bs2000-special-prefix because names starting with # or @
;; are reserved for temporary files.
;; This is especially important for auto-save files.
;; Valid file generations are ending with ([+|-|*]0-9...) .
;; File generations are not supported yet!
;; A filename must at least contain one character (A-Z) and cannot be longer
;; than 41 characters.
;;
;; Tips:
;; 1. Although BS2000 is not case sensitive, EMACS running under UNIX is.
;;    Therefore, to access a BS2000 file, you must enter the filename with
;;    upper case letters.
;; 2. EMACS has a feature in which it does environment variable substitution
;;    in filenames. Therefore, to enter a $ in a filename, you must quote it
;;    by typing $$.
;; 3. BS2000 machines, with the exception of anonymous accounts, nearly
;;    always need an account password. To have ange-ftp send an account
;;    password, you can either include it in your .netrc file, or use
;;    ange-ftp-set-account.
;;
;; ------------------------------------------------------------------
;; Bugs:
;; ------------------------------------------------------------------
;;
;; 1. Umask problems:
;;    Be warned that files created by using ange-ftp will take account of the
;;    umask of the ftp daemon process rather than the umask of the creating
;;    user.  This is particularly important when logging in as the root user.
;;    The way that I tighten up the ftp daemon's umask under HP-UX is to make
;;    sure that the umask is changed to 027 before I spawn /etc/inetd.  I
;;    suspect that there is something similar on other systems.
;;
;; 2. Some combinations of FTP clients and servers break and get out of sync
;;    when asked to list a non-existent directory.  Some of the ai.mit.edu
;;    machines cause this problem for some FTP clients. Using
;;    ange-ftp-kill-ftp-process can restart the ftp process, which
;;    should get things back in sync.
;;
;; 3. Ange-ftp does not check to make sure that when creating a new file,
;;    you provide a valid filename for the remote operating system.
;;    If you do not, then the remote FTP server will most likely
;;    translate your filename in some way. This may cause ange-ftp to
;;    get confused about what exactly is the name of the file. The
;;    most common causes of this are using lower case filenames on systems
;;    which support only upper case, and using filenames which are too
;;    long.
;;
;; 4. Null (blank) passwords confuse both ange-ftp and some FTP daemons.
;;
;; 5. Ange-ftp likes to use pty's to talk to its FTP processes.  If GNU Emacs
;;    for some reason creates a FTP process that only talks via pipes then
;;    ange-ftp won't be getting the information it requires at the time that
;;    it wants it since pipes flush at different times to pty's.  One
;;    disgusting way around this problem is to talk to the FTP process via
;;    rlogin which does the 'right' things with pty's.
;;
;; 6. For CMS support, we send too many cd's. Since cd's are cheap, I haven't
;;    worried about this too much. Eventually, we should have some caching
;;    of the current minidisk.
;;
;; 7. Some CMS machines do not assign a default minidisk when you ftp them as
;;    anonymous. It is then necessary to guess a valid minidisk name, and cd
;;    to it. This is (understandably) beyond ange-ftp.
;;
;; 8. Remote to remote copying of files on non-Unix machines can be risky.
;;    Depending on the variable ange-ftp-binary-file-name-regexp, ange-ftp
;;    will use binary mode for the copy. Between systems of different
;;    architecture, this still may not be enough to guarantee the integrity
;;    of binary files. Binary file transfers from VMS machines are
;;    particularly problematical. Should ange-ftp-binary-file-name-regexp be
;;    an alist of OS type, regexp pairs?
;;
;; 9. The code to do compression of files over ftp is not as careful as it
;;    should be. It deletes the old remote version of the file, before
;;    actually checking if the local to remote transfer of the compressed
;;    file succeeds. Of course to delete the original version of the file
;;    after transferring the compressed version back is also dangerous,
;;    because some OS's have severe restrictions on the length of filenames,
;;    and when the compressed version is copied back the "-Z" or ".Z" may be
;;    truncated. Then, ange-ftp would delete the only remaining version of
;;    the file.  Maybe ange-ftp should make backups when it compresses files
;;    (of course, the backup "~" could also be truncated off, sigh...).
;;    Suggestions?
;;
;; 10. If a dir listing is attempted for an empty directory on (at least
;;     some) VMS hosts, an ftp error is given. This is really an ftp bug, and
;;     I don't know how to get ange-ftp work to around it.
;;
;; 11. Bombs on filenames that start with a space. Deals well with filenames
;;     containing spaces, but beware that the remote ftpd may not like them
;;     much.
;;
;; 12. The dired support for non-Unix-like systems does not currently work.
;;     It needs to be reimplemented by modifying the parse-...-listing
;;	functions to convert the directory listing to ls -l format.
;;
;; 13. The famous @ bug. As mentioned above in TIPS, ULTRIX marks symlinks
;;     with a trailing @ in a ls -alF listing. In order to account for this
;;     ange-ftp looks to chop trailing @'s off of symlink names when it is
;;     parsing a listing with the F switch. This will cause ange-ftp to
;;     incorrectly get the name of a symlink on a non-ULTRIX host if its name
;;     ends in an @. ange-ftp will correct itself if you take F out of the
;;     dired ls switches (C-u s will allow you to edit the switches). The
;;     dired buffer will be automatically reverted, which will allow ange-ftp
;;     to fix its files hashtable.  A cookie to anyone who can think of a
;;     fast, sure-fire way to recognize ULTRIX over ftp.

;; If you find any bugs or problems with this package, PLEASE report a
;; bug to the Emacs maintainers via M-x report-emacs-bug.
\f
;; -----------------------------------------------------------
;; Technical information on this package:
;; -----------------------------------------------------------

;; ange-ftp works by putting a handler on file-name-handler-alist
;; which is called by many primitives, and a few non-primitives,
;; whenever they see a file name of the appropriate sort.

;; Checklist for adding non-UNIX support for TYPE
;;
;; The following functions may need TYPE versions:
;; (not all functions will be needed for every OS)
;;
;; ange-ftp-fix-name-for-TYPE
;; ange-ftp-fix-dir-name-for-TYPE
;; ange-ftp-TYPE-host
;; ange-ftp-TYPE-add-host
;; ange-ftp-parse-TYPE-listing
;; ange-ftp-TYPE-delete-file-entry
;; ange-ftp-TYPE-add-file-entry
;; ange-ftp-TYPE-file-name-as-directory
;; ange-ftp-TYPE-make-compressed-filename
;; ange-ftp-TYPE-file-name-sans-versions
;;
;; Variables:
;;
;; ange-ftp-TYPE-host-regexp
;; May need to add TYPE to ange-ftp-dumb-host-types
;;
;; Check the following functions for OS dependent coding:
;;
;; ange-ftp-host-type
;; ange-ftp-guess-host-type
;; ange-ftp-allow-child-lookup

;; Host type conventions:
;;
;; The function ange-ftp-host-type and the variable ange-ftp-dired-host-type
;; (mostly) follow the following conventions for remote host types.  At
;; least, I think that future code should try to follow these conventions,
;; and the current code should eventually be made compliant.
;;
;; nil = local host type, whatever that is (probably unix).
;;       Think nil as in "not a remote host". This value is used by
;;       ange-ftp-dired-host-type for local buffers.
;;
;; t = a remote host of unknown type. Think t as in true, it's remote.
;;     Currently, `unix' is used as the default remote host type.
;;     Maybe we should use t.
;;
;; TYPE = a remote host of TYPE type.
;;
;; TYPE:LIST = a remote host of TYPE type, using a specialized ftp listing
;;             program called list. This is currently only used for Unix
;;             dl (descriptive listings), when ange-ftp-dired-host-type
;;             is set to `unix:dl'.

;; Bug report codes:
;;
;; Because of their naive faith in this code, there are certain situations
;; which the writers of this program believe could never happen. However,
;; being realists they have put calls to `error' in the program at these
;; points. These errors provide a code, which is an integer, greater than 1.
;; To aid debugging.  the error codes, and the functions in which they reside
;; are listed below.
;;
;; 1: See ange-ftp-ls
;;
\f
;; -----------------------------------------------------------
;; Hall of fame:
;; -----------------------------------------------------------
;;
;; Thanks to Roland McGrath for improving the filename syntax handling,
;; for suggesting many enhancements and for numerous cleanups to the code.
;;
;; Thanks to Jamie Zawinski for bugfixes and for ideas such as gateways.
;;
;; Thanks to Ken Laprade for improved .netrc parsing, password reading, and
;; dired / shell auto-loading.
;;
;; Thanks to Sebastian Kremer for dired support and for many ideas and
;; bugfixes.
;;
;; Thanks to Joe Wells for bugfixes, the original non-UNIX system support,
;; VOS support, and hostname completion.
;;
;; Thanks to Nakagawa Takayuki for many good ideas, filename-completion, help
;; with file-name expansion, efficiency worries, stylistic concerns and many
;; bugfixes.
;;
;; Thanks to Sandy Rutherford who re-wrote most of ange-ftp to support VMS,
;; MTS, CMS and UNIX-dls.  Sandy also added dired-support for non-UNIX OS and
;; auto-recognition of the host type.
;;
;; Thanks to Dave Smith who wrote the info file for ange-ftp.
;;
;; Finally, thanks to Keith Waclena, Mark D. Baushke, Terence Kelleher, Ping
;; Zhou, Edward Vielmetti, Jack Repenning, Mike Balenger, Todd Kaufmann,
;; Kjetil Svarstad, Tom Wurgler, Linus Tolke, Niko Makila, Carl Edman, Bill
;; Trost, Dave Brennan, Dan Jacobson, Andy Scott, Steve Anderson, Sanjay
;; Mathur, the folks on the ange-ftp-lovers mailing list and many others
;; whose names I've forgotten who have helped to debug and fix problems with
;; ange-ftp.el.
\f
;;; Code:

(require 'comint)

;;;; ------------------------------------------------------------
;;;; User customization variables.
;;;; ------------------------------------------------------------

(defgroup ange-ftp nil
  "Accessing remote files and directories using FTP."
  :group 'files
  :group 'comm
  :prefix "ange-ftp-")

(defcustom ange-ftp-name-format
  '("\\`/\\(\\([^/:]*\\)@\\)?\\([^@/:]*[^@/:.]\\):\\(.*\\)" . (3 2 4))
  "Format of a fully expanded remote file name.

This is a list of the form \(REGEXP HOST USER NAME),
where REGEXP is a regular expression matching
the full remote name, and HOST, USER, and NAME are the numbers of
parenthesized expressions in REGEXP for the components (in that order)."
  :group 'ange-ftp
  :type '(list (regexp  :tag "Name regexp")
	       (integer :tag "Host group")
	       (integer :tag "User group")
	       (integer :tag "Name group")))

;; ange-ftp-multi-skip-msgs should only match ###-, where ### is one of
;; the number codes corresponding to ange-ftp-good-msgs or ange-ftp-fatal-msgs.
;; Otherwise, ange-ftp will go into multi-skip mode, and never come out.

(defvar ange-ftp-multi-msgs
  "^150-\\|^220-\\|^230-\\|^226\\|^25.-\\|^221-\\|^200-\\|^331-\\|^4[25]1-\\|^530-"
  "Regular expression matching the start of a multiline FTP reply.")

(defvar ange-ftp-good-msgs
  "^220 \\|^230 \\|^226 \\|^25. \\|^221 \\|^200 \\|^[Hh]ash mark\\|^Remote directory:"
  "Regular expression matching FTP \"success\" messages.")

;; CMS and the odd VMS machine say 200 Port rather than 200 PORT.
;; Also CMS machines use a multiline 550- reply to say that you
;; don't have write permission. ange-ftp gets into multi-line skip
;; mode and hangs. Have it ignore 550- instead. It will then barf
;; when it gets the 550 line, as it should.

;; RFC2228 "FTP Security Extensions" defines extensions to the FTP
;; protocol which involve the client requesting particular
;; authentication methods (typically) at connection establishment. Non
;; security-aware FTP servers should respond to this with a 500 code,
;; which we ignore.

;; Further messages are needed to support ftp-ssl.
(defcustom ange-ftp-skip-msgs
  (concat "^200 \\(PORT\\|Port\\) \\|^331 \\|^150 \\|^350 \\|^[0-9]+ bytes \\|"
	  "^Connected \\|^$\\|^Remote system\\|^Using\\|^ \\|Password:\\|"
	  "^Data connection \\|"
          "^200 PBSZ\\|" "^200 Protection set to Private\\|"
          "^234 AUTH TLS successful\\|"
          "^SSL not available\\|"
	  "^\\[SSL Cipher .+\\]\\|"
	  "^\\[Encrypted data transfer\\.\\]\\|"
	  "^local:\\|^Trying\\|^125 \\|^550-\\|^221 .*oodbye\\|"
          "^500 .*AUTH\\|^KERBEROS\\|"
          "^500 This security scheme is not implemented\\|"
          "^504 Unknown security mechanism\\|"
	  "^530 Please login with USER and PASS\\|" ; non kerberized vsFTPd
	  "^534 Kerberos Authentication not enabled\\|"
	  "^22[789] .*[Pp]assive\\|^200 EPRT\\|^500 .*EPRT\\|^500 .*EPSV")
  "Regular expression matching FTP messages that can be ignored."
  :group 'ange-ftp
  :version "26.1"
  :type 'regexp)

(defcustom ange-ftp-fatal-msgs
  (concat "^ftp: \\|^Not connected\\|^530 \\|^4[25]1 \\|rcmd: \\|"
	  "^No control connection\\|unknown host\\|^lost connection")
  "Regular expression matching FTP messages that indicate serious errors.

These mean that the FTP process should be (or already has been) killed."
  :group 'ange-ftp
  :type 'regexp)

(defcustom ange-ftp-potential-error-msgs
  ;; On macOS we sometimes get things like:
  ;;
  ;;     ftp> open ftp.nluug.nl
  ;;     Trying 2001:610:1:80aa:192:87:102:36...
  ;;     ftp: connect to address 2001:610:1:80aa:192:87:102:36: No route to host
  ;;     Trying 192.87.102.36...
  ;;     Connected to ftp.nluug.nl.
  "^ftp: connect to address .*: No route to host"
  "Regular expression matching FTP messages that can indicate serious errors.
These mean that something went wrong, but they may be followed by more
messages indicating that the error was somehow corrected."
  :group 'ange-ftp
  :type 'regexp)

(defcustom ange-ftp-gateway-fatal-msgs
  "No route to host\\|Connection closed\\|No such host\\|Login incorrect"
  "Regular expression matching login failure messages from rlogin/telnet."
  :group 'ange-ftp
  :type 'regexp)

(defcustom ange-ftp-xfer-size-msgs
  "^150 .* connection for .* (\\([0-9]+\\) bytes)"
  "Regular expression used to determine the number of bytes in a FTP transfer."
  :group 'ange-ftp
  :type 'regexp)

(defcustom ange-ftp-tmp-name-template
  (expand-file-name "ange-ftp" temporary-file-directory)
  "Template used to create temporary files."
  :group 'ange-ftp
  :type 'directory)

(defcustom ange-ftp-gateway-tmp-name-template "/tmp/ange-ftp"
  "Template used to create temporary files when FTP-ing through a gateway.

Files starting with this prefix need to be accessible from BOTH the local
machine and the gateway machine, and need to have the SAME name on both
machines, that is, /tmp is probably NOT what you want, since that is rarely
cross-mounted."
  :group 'ange-ftp
  :type 'directory)

(defcustom ange-ftp-netrc-filename "~/.netrc"
  "File in .netrc format to search for passwords."
  :group 'ange-ftp
  :type 'file)

(defcustom ange-ftp-disable-netrc-security-check (eq system-type 'windows-nt)
  "If non-nil avoid checking permissions on the .netrc file."
  :group 'ange-ftp
  :type 'boolean)

(defcustom ange-ftp-default-user nil
  "User name to use when none is specified in a file name.

If non-nil but not a string, you are prompted for the name.
If nil, the value of `ange-ftp-netrc-default-user' is used.
If that is nil too, then your login name is used.

Once a connection to a given host has been initiated, the user name
and password information for that host are cached and re-used by
ange-ftp.  Use \\[ange-ftp-set-user] to change the cached values,
since setting `ange-ftp-default-user' directly does not affect
the cached information."
  :group 'ange-ftp
  :type '(choice (const :tag "Default" nil)
		 string
		 (other :tag "Prompt" t)))

(defcustom ange-ftp-netrc-default-user nil
  "Alternate default user name to use when none is specified.

This variable is set from the `default' command in your `.netrc' file,
if there is one."
  :group 'ange-ftp
  :type '(choice (const :tag "Default" nil)
		 string))

(defcustom ange-ftp-default-password nil
  "Password to use when the user name equals `ange-ftp-default-user'."
  :group 'ange-ftp
  :type '(choice (const :tag "Default" nil)
		 string))

(defcustom ange-ftp-default-account nil
  "Account to use when the user name equals `ange-ftp-default-user'."
  :group 'ange-ftp
  :type '(choice (const :tag "Default" nil)
		 string))

(defcustom ange-ftp-netrc-default-password nil
  "Password to use when the user name equals `ange-ftp-netrc-default-user'."
  :group 'ange-ftp
  :type '(choice (const :tag "Default" nil)
		 string))

(defcustom ange-ftp-netrc-default-account nil
  "Account to use when the user name equals `ange-ftp-netrc-default-user'."
  :group 'ange-ftp
  :type '(choice (const :tag "Default" nil)
		 string))

(defcustom ange-ftp-generate-anonymous-password t
  "If t, use value of `user-mail-address' as password for anonymous FTP.

If a string, then use that string as the password.
If nil, prompt the user for a password."
  :group 'ange-ftp
  :type '(choice (const :tag "Prompt" nil)
		 string
		 (other :tag "User address" t)))

(defcustom ange-ftp-dumb-unix-host-regexp nil
  "If non-nil, regexp matching hosts on which `dir' command lists directory."
  :group 'ange-ftp
  :type '(choice (const :tag "Default" nil)
		 string))

(defcustom ange-ftp-binary-file-name-regexp ""
  "If a file matches this regexp then it is transferred in binary mode."
  :group 'ange-ftp
  :type 'regexp
  :version "24.1")

(defcustom ange-ftp-gateway-host nil
  "Name of host to use as gateway machine when local FTP isn't possible."
  :group 'ange-ftp
  :type '(choice (const :tag "Default" nil)
		 string))

(defcustom ange-ftp-local-host-regexp ".*"
  "Regexp selecting hosts which can be reached directly with FTP.

For other hosts the FTP process is started on `ange-ftp-gateway-host'
instead, and/or reached via `ange-ftp-gateway-ftp-program-name'."
  :group 'ange-ftp
  :type 'regexp)

(defcustom ange-ftp-gateway-program-interactive nil
  "If non-nil then the gateway program should give a shell prompt.

Both telnet and rlogin do something like this."
  :group 'ange-ftp
  :type 'boolean)

(defcustom ange-ftp-gateway-program remote-shell-program
  "Name of program to spawn a shell on the gateway machine.

Valid candidates are rsh (remsh on some systems), telnet and rlogin.
See also the gateway variable above."
  :group 'ange-ftp
  :type '(choice (const "rsh")
		 (const "telnet")
		 (const "rlogin")
		 string))

(defcustom ange-ftp-gateway-prompt-pattern "^[^#$%>;\n]*[#$%>;] *"
  "Regexp matching prompt after complete login sequence on gateway machine.

A match for this means the shell is now awaiting input.  Make this regexp as
strict as possible; it shouldn't match *anything* at all except the user's
initial prompt.  The above string will fail under most SUN-3's since it
matches the login banner."
  :group 'ange-ftp
  :type 'regexp)

(defvar ange-ftp-gateway-setup-term-command
  (if (eq system-type 'hpux)
      "stty -onlcr -echo\n"
    "stty -echo nl\n")
  "Set up terminal after logging in to the gateway machine.
This command should stop the terminal from echoing each command, and
arrange to strip out trailing ^M characters.")

(defcustom ange-ftp-smart-gateway nil
  "Non-nil says the FTP gateway (proxy) or gateway FTP program is smart.

Don't bother telnetting, etc., already connected to desired host transparently,
or just issue a user@host command in case `ange-ftp-gateway-host' is non-nil.
See also `ange-ftp-smart-gateway-port'."
  :group 'ange-ftp
  :type 'boolean)

(defcustom ange-ftp-smart-gateway-port "21"
  "Port on gateway machine to use when smart gateway is in operation."
  :group 'ange-ftp
  :type 'string)

(defcustom ange-ftp-send-hash t
  "If non-nil, send the HASH command to the FTP client."
  :group 'ange-ftp
  :type 'boolean)

(defcustom ange-ftp-binary-hash-mark-size nil
  "Default size, in bytes, between hash-marks when transferring a binary file.
If nil, this variable will be locally overridden if the FTP client outputs a
suitable response to the HASH command.  If non-nil, this value takes
precedence over the local value."
  :group 'ange-ftp
  :type '(choice (const :tag "Overridden" nil)
		 integer))

(defcustom ange-ftp-ascii-hash-mark-size 1024
  "Default size, in bytes, between hash-marks when transferring an ASCII file.
This variable is buffer-local and will be locally overridden if the FTP client
outputs a suitable response to the HASH command."
  :group 'ange-ftp
  :type 'integer)

(defcustom ange-ftp-process-verbose t
  "If non-nil then be chatty about interaction with the FTP process."
  :group 'ange-ftp
  :type 'boolean)

(defcustom ange-ftp-ftp-program-name "ftp"
  "Name of FTP program to run."
  :group 'ange-ftp
  :type 'string)

(defcustom ange-ftp-gateway-ftp-program-name "ftp"
  "Name of FTP program to run when accessing non-local hosts.

Some AT&T folks claim to use something called `pftp' here."
  :group 'ange-ftp
  :type 'string)

(defcustom ange-ftp-ftp-program-args '("-i" "-n" "-g" "-v")
  "A list of arguments passed to the FTP program when started."
  :group 'ange-ftp
  :type '(repeat string))

(defcustom ange-ftp-nslookup-program nil
  "If non-nil, this is a string naming the nslookup program."
  :group 'ange-ftp
  :type '(choice (const :tag "None" nil)
		 string))

(defcustom ange-ftp-make-backup-files ()
  "Non-nil means make backup files for \"magic\" remote files."
  :group 'ange-ftp
  :type 'boolean)

(defcustom ange-ftp-retry-time 5
  "Number of seconds to wait before retry if file or listing doesn't arrive.
This might need to be increased for very slow connections."
  :group 'ange-ftp
  :type 'integer)

(defcustom ange-ftp-auto-save 0
  "If 1, allow ange-ftp files to be auto-saved.
If 0, inhibit auto-saving of ange-ftp files.
Don't use any other value."
  :group 'ange-ftp
  :type '(choice (const :tag "Suppress" 0)
		 (const :tag "Allow" 1)))

(defcustom ange-ftp-try-passive-mode nil
  "If t, try to use passive mode in FTP, if the client program supports it."
  :group 'ange-ftp
  :type 'boolean
  :version "21.1")

(defcustom ange-ftp-passive-host-alist nil
  "Alist of FTP servers that need \"passive\" mode.
Each element is of the form (HOSTNAME . SETTING).
HOSTNAME is a regular expression to match the FTP server host name(s).
SETTING is \"on\" to turn passive mode on, \"off\" to turn it off,
or nil meaning don't change it."
  :group 'ange-ftp
  :type '(repeat (cons regexp (choice (const :tag "On" "on")
				      (const :tag "Off" "off")
				      (const :tag "Don't change" nil))))
  :version "22.1")
\f
;;;; ------------------------------------------------------------
;;;; Hash table support.
;;;; ------------------------------------------------------------

(require 'backquote)

(defun ange-ftp-hash-entry-exists-p (key tbl)
  "Return whether there is an association for KEY in table TBL."
  (and tbl (not (eq (gethash key tbl 'unknown) 'unknown))))

(defun ange-ftp-hash-table-keys (tbl)
  "Return a sorted list of all the active keys in table TBL, as strings."
  ;; (let ((keys nil))
  ;;   (maphash (lambda (k v) (push k keys)) tbl)
  ;;   (sort keys 'string-lessp))
  (sort (all-completions "" tbl) 'string-lessp))
\f
;;;; ------------------------------------------------------------
;;;; Internal variables.
;;;; ------------------------------------------------------------

(defvar ange-ftp-data-buffer-name " *ftp data*"
  "Buffer name to hold directory listing data received from FTP process.")

(defvar ange-ftp-netrc-modtime nil
  "Last modified time of the netrc file from file-attributes.")

(defvar ange-ftp-user-hashtable (make-hash-table :test 'equal)
  "Hash table holding associations between HOST, USER pairs.")

(defvar ange-ftp-passwd-hashtable (make-hash-table :test 'equal)
  "Mapping between a HOST, USER pair and a PASSWORD for them.
All HOST values should be in lower case.")

(defvar ange-ftp-account-hashtable (make-hash-table :test 'equal)
  "Mapping between a HOST, USER pair and an ACCOUNT password for them.")

(defvar ange-ftp-files-hashtable (make-hash-table :test 'equal :size 97)
  "Hash table for storing directories and their respective files.")

(defvar ange-ftp-inodes-hashtable (make-hash-table :test 'equal :size 97)
  "Hash table for storing file names and their \"inode numbers\".")

(defvar ange-ftp-next-inode-number 1
  "Next \"inode number\" value.  We give each file name a unique number.")

(defvar ange-ftp-ls-cache-lsargs nil
  "Last set of args used by `ange-ftp-ls'.")

(defvar ange-ftp-ls-cache-file nil
  "Last file passed to `ange-ftp-ls'.")

(defvar ange-ftp-ls-cache-res nil
  "Last result returned from `ange-ftp-ls'.")

(defconst ange-ftp-expand-dir-hashtable (make-hash-table :test 'equal))

(defconst ange-ftp-expand-dir-regexp "^5.0 \\([^: ]+\\):")

;; These are local variables in each FTP process buffer.
(defvar ange-ftp-hash-mark-unit nil)
(defvar ange-ftp-hash-mark-count nil)
(defvar ange-ftp-xfer-size nil)
(defvar ange-ftp-process-string nil)
(defvar ange-ftp-process-result-line nil)
(defvar ange-ftp-pending-error-line nil)
(defvar ange-ftp-process-busy nil)
(defvar ange-ftp-process-result nil)
(defvar ange-ftp-process-multi-skip nil)
(defvar ange-ftp-process-msg nil)
(defvar ange-ftp-process-continue nil)
(defvar ange-ftp-last-percent nil)

;; These variables are bound by one function and examined by another.
;; Leave them void globally for error checking.
(defvar ange-ftp-this-file)
(defvar ange-ftp-this-dir)
(defvar ange-ftp-this-user)
(defvar ange-ftp-this-host)
(defvar ange-ftp-this-msg)
(defvar ange-ftp-completion-ignored-pattern)
(defvar ange-ftp-trample-marker)
\f
;; New error symbols.
(define-error 'ftp-error nil 'file-error) ;"FTP error"
\f
;;; ------------------------------------------------------------
;;; Enhanced message support.
;;; ------------------------------------------------------------

(defun ange-ftp-message (fmt &rest args)
  "Display message in echo area, but indicate if truncated.
Args are as in `message': a format string, plus arguments to be formatted."
  (let ((msg (apply #'format-message fmt args))
	(max (window-width (minibuffer-window))))
    (if noninteractive
	msg
      (if (>= (length msg) max)
	  ;; Take just the last MAX - 3 chars of the string.
	  (setq msg (concat "> " (substring msg (- 3 max)))))
      (message "%s" msg))))

(defun ange-ftp-abbreviate-filename (file &optional new)
  "Abbreviate the file name FILE relative to the `default-directory'.
If the optional parameter NEW is given and the non-directory parts match,
only return the directory part of FILE."
  (save-match-data
    (if (and default-directory
	     (string-match (concat "\\`"
				   (regexp-quote default-directory)
				   ".") file))
	(setq file (substring file (1- (match-end 0)))))
    (if (and new
	     (string-equal (file-name-nondirectory file)
			   (file-name-nondirectory new)))
	(setq file (file-name-directory file)))
    (or file "./")))
\f
;;;; ------------------------------------------------------------
;;;; User / Host mapping support.
;;;; ------------------------------------------------------------

(defun ange-ftp-set-user (host user)
  "For a given HOST, set or change the default USER."
  (interactive "sHost: \nsUser: ")
  (puthash host user ange-ftp-user-hashtable))

(defun ange-ftp-get-user (host)
  "Given a HOST, return the default user."
  (ange-ftp-parse-netrc)
  (let ((user (gethash host ange-ftp-user-hashtable)))
    (or user
	(prog1
	    (setq user
		  (cond ((stringp ange-ftp-default-user)
			 ;; We have a default name.  Use it.
			 ange-ftp-default-user)
			(ange-ftp-default-user
			 ;; Ask the user.
			 (let ((enable-recursive-minibuffers t))
			   (read-string (format "User for %s: " host)
					(user-login-name))))
			(ange-ftp-netrc-default-user)
			;; Default to the user's login name.
			(t
			 (user-login-name))))
	  (ange-ftp-set-user host user)))))
\f
;;;; ------------------------------------------------------------
;;;; Password support.
;;;; ------------------------------------------------------------

(defmacro ange-ftp-generate-passwd-key (host user)
  `(and (stringp ,host) (stringp ,user) (concat (downcase ,host) "/" ,user)))

(defmacro ange-ftp-lookup-passwd (host user)
  `(gethash (ange-ftp-generate-passwd-key ,host ,user)
	    ange-ftp-passwd-hashtable))

(defun ange-ftp-set-passwd (host user password)
  "For a given HOST and USER, set or change the associated PASSWORD."
  (interactive (list (read-string "Host: ")
		     (read-string "User: ")
		     (read-passwd "Password: ")))
  (puthash (ange-ftp-generate-passwd-key host user)
	   password ange-ftp-passwd-hashtable))

(defun ange-ftp-get-host-with-passwd (user)
  "Given a USER, return a host we know the password for."
  (ange-ftp-parse-netrc)
  (catch 'found-one
    (maphash
     (lambda (host val)
       (if (ange-ftp-lookup-passwd host user) (throw 'found-one host)))
     ange-ftp-user-hashtable)
    (save-match-data
      (maphash
       (lambda (key value)
	 (if (string-match "\\`[^/]*\\(/\\).*\\'" key)
	     (let ((host (substring key 0 (match-beginning 1))))
	       (if (and (string-equal user (substring key (match-end 1)))
			value)
		   (throw 'found-one host)))))
       ange-ftp-passwd-hashtable))
    nil))

(defun ange-ftp-get-passwd (host user)
  "Return the password for specified HOST and USER, asking user if necessary."
  ;; If `non-essential' is non-nil, don't ask for a password.  It will
  ;; be caught in Tramp.
  (when non-essential
    (throw 'non-essential 'non-essential))

  (ange-ftp-parse-netrc)

  ;; look up password in the hash table first; user might have overridden the
  ;; defaults.
  (cond ((ange-ftp-lookup-passwd host user))

	;; See if default user and password set.
	((and (stringp ange-ftp-default-user)
	      ange-ftp-default-password
	      (string-equal user ange-ftp-default-user))
	 ange-ftp-default-password)

	;; See if default user and password set from .netrc file.
	((and (stringp ange-ftp-netrc-default-user)
	      ange-ftp-netrc-default-password
	      (string-equal user ange-ftp-netrc-default-user))
	 ange-ftp-netrc-default-password)

	;; anonymous ftp password is handled specially since there is an
	;; unwritten rule about how that is used on the Internet.
	((and (or (string-equal user "anonymous")
		  (string-equal user "ftp"))
	      ange-ftp-generate-anonymous-password)
	 (if (stringp ange-ftp-generate-anonymous-password)
	     ange-ftp-generate-anonymous-password
	   user-mail-address))

	;; see if same user has logged in to other hosts; if so then prompt
	;; with the password that was used there.
	(t
	 (let* ((enable-recursive-minibuffers t)
		(other (ange-ftp-get-host-with-passwd user))
		(passwd (if other

			    ;; found another machine with the same user.
			    ;; Try that account.
			    (read-passwd
			     (format "passwd for %s@%s (default same as %s@%s): "
				     user host user other)
			     nil
			     (ange-ftp-lookup-passwd other user))

			  ;; I give up.  Ask the user for the password.
			  (read-passwd
			   (format "Password for %s@%s: " user host)))))
	   (ange-ftp-set-passwd host user passwd)
	   passwd))))
\f
;;;; ------------------------------------------------------------
;;;; Account support
;;;; ------------------------------------------------------------

;; Account passwords must be either specified in the .netrc file, or set
;; manually by calling ange-ftp-set-account.  For the moment, ange-ftp doesn't
;; check to see whether the FTP process is actually prompting for an account
;; password.

(defun ange-ftp-set-account (host user account)
  "For a given HOST and USER, set or change the associated ACCOUNT password."
  (interactive (list (read-string "Host: ")
		     (read-string "User: ")
		     (read-passwd "Account password: ")))
  (puthash (ange-ftp-generate-passwd-key host user)
	   account ange-ftp-account-hashtable))

(defun ange-ftp-get-account (host user)
  "Given a HOST and USER, return the FTP account."
  (ange-ftp-parse-netrc)
  (or (gethash (ange-ftp-generate-passwd-key host user)
	       ange-ftp-account-hashtable)
      (and (stringp ange-ftp-default-user)
	   (string-equal user ange-ftp-default-user)
	   ange-ftp-default-account)
      (and (stringp ange-ftp-netrc-default-user)
	   (string-equal user ange-ftp-netrc-default-user)
	   ange-ftp-netrc-default-account)))
\f
;;;; ------------------------------------------------------------
;;;; ~/.netrc support
;;;; ------------------------------------------------------------

(defun ange-ftp-chase-symlinks (file)
  "Return the filename that FILE references, following all symbolic links."
  (let (temp)
    (while (setq temp (ange-ftp-real-file-symlink-p file))
      (setq file
	    (if (file-name-absolute-p temp)
		temp
	      ;; Wouldn't `expand-file-name' be better than `concat' ?
	      ;; It would fail when `a/b/..' != `a', tho.  --Stef
	      (concat (file-name-directory file) temp)))))
  file)

;; Move along current line looking for the value of the TOKEN.
;; Valid separators between TOKEN and its value are commas and
;; whitespace.  Second arg LIMIT is a limit for the search.

(defun ange-ftp-parse-netrc-token (token limit)
  (if (search-forward token limit t)
      (let (beg)
	(skip-chars-forward ", \t\r\n" limit)
	(if (eq (following-char) ?\")	;quoted token value
	    (progn (forward-char 1)
		   (setq beg (point))
		   (skip-chars-forward "^\"" limit)
		   (forward-char 1)
		   (buffer-substring beg (1- (point))))
	  (setq beg (point))
	  (skip-chars-forward "^, \t\r\n" limit)
	  (buffer-substring beg (point))))))

;; Extract the values for the tokens `machine', `login',
;; `password' and `account' in the current buffer.  If successful,
;; record the information found.

(defun ange-ftp-parse-netrc-group ()
  (let ((start (point))
	(end (save-excursion
	       (if (looking-at "machine\\>")
		   ;; Skip `machine' and the machine name that follows.
		   (progn
		     (skip-chars-forward "^ \t\r\n")
		     (skip-chars-forward " \t\r\n")
		     (skip-chars-forward "^ \t\r\n"))
		 ;; Skip `default'.
		 (skip-chars-forward "^ \t\r\n"))
	       ;; Find start of the next `machine' or `default'
	       ;; or the end of the buffer.
	       (if (re-search-forward "machine\\>\\|default\\>" nil t)
		   (match-beginning 0)
		 (point-max))))
	machine login password account)
    (setq machine  (ange-ftp-parse-netrc-token "machine"  end)
	  login    (ange-ftp-parse-netrc-token "login"    end)
	  password (ange-ftp-parse-netrc-token "password" end)
	  account  (ange-ftp-parse-netrc-token "account"  end))
    (if (and machine login)
	;; found a `machine` token.
	(progn
	  (ange-ftp-set-user machine login)
	  (ange-ftp-set-passwd machine login password)
	  (and account
	       (ange-ftp-set-account machine login account)))
      (goto-char start)
      (if (search-forward "default" end t)
	  ;; found a `default' token
	  (progn
	    (setq login    (ange-ftp-parse-netrc-token "login"    end)
		  password (ange-ftp-parse-netrc-token "password" end)
		  account  (ange-ftp-parse-netrc-token "account"  end))
	    (and login
		 (setq ange-ftp-netrc-default-user login))
	    (and password
		 (setq ange-ftp-netrc-default-password password))
	    (and account
		 (setq ange-ftp-netrc-default-account account)))))
    (goto-char end)))

;; Read in ~/.netrc, if one exists.  If ~/.netrc file exists and has
;; the correct permissions then extract the machine, login,
;; password and account information from within.

(defun ange-ftp-parse-netrc ()
  ;; We set this before actually doing it to avoid the possibility
  ;; of an infinite loop if ange-ftp-netrc-filename is an FTP file.
  (interactive)
  (let (file attr)
    (let ((default-directory "/"))
      (setq file (ange-ftp-chase-symlinks
		  (ange-ftp-real-expand-file-name ange-ftp-netrc-filename)))
      (setq attr (ange-ftp-real-file-attributes file)))
    (if (and attr			; file exists.
	     (not (equal (nth 5 attr) ange-ftp-netrc-modtime)))	; file changed
	(save-match-data
	  (if (or ange-ftp-disable-netrc-security-check
		  (and (eq (nth 2 attr) (user-uid)) ; Same uids.
		       (string-match ".r..------" (nth 8 attr))))
	      (with-current-buffer
		;; we are cheating a bit here.  I'm trying to do the equivalent
		;; of find-file on the .netrc file, but then nuke it afterwards.
		;; with the bit of logic below we should be able to have
		;; encrypted .netrc files.
                  (generate-new-buffer "*ftp-.netrc*")
		(ange-ftp-real-insert-file-contents file)
		(setq buffer-file-name file)
		(setq default-directory (file-name-directory file))
		(normal-mode t)
		(run-hooks 'find-file-hook)
		(setq buffer-file-name nil)
		(goto-char (point-min))
		(while (search-forward-regexp "^[ \t]*#.*$" nil t)
		  (replace-match ""))
		(goto-char (point-min))
		(skip-chars-forward " \t\r\n")
		(while (not (eobp))
		  (ange-ftp-parse-netrc-group))
		(kill-buffer (current-buffer)))
	    (ange-ftp-message "%s either not owned by you or badly protected."
			      ange-ftp-netrc-filename)
	    (sit-for 1))
	  (setq ange-ftp-netrc-modtime (nth 5 attr))))))

;; Return a list of prefixes of the form 'user@host:' to be used when
;; completion is done in the root directory.

(defun ange-ftp-generate-root-prefixes ()
  (ange-ftp-parse-netrc)
  (save-match-data
    (let (res)
      (maphash
       (lambda (key value)
	 (if (string-match "\\`[^/]*\\(/\\).*\\'" key)
	     (let ((host (substring key 0 (match-beginning 1)))
		   (user (substring key (match-end 1))))
	       (push (concat user "@" host ":") res))))
       ange-ftp-passwd-hashtable)
      (maphash
       (lambda (host user) (push (concat host ":") res))
       ange-ftp-user-hashtable)
      (or res (list nil)))))
\f
;;;; ------------------------------------------------------------
;;;; Remote file name syntax support.
;;;; ------------------------------------------------------------

(defmacro ange-ftp-ftp-name-component (n ns name)
  "Extract the Nth FTP file name component from NS."
  `(let ((elt (nth ,n ,ns)))
     (match-string elt ,name)))

(defvar ange-ftp-ftp-name-arg "")
(defvar ange-ftp-ftp-name-res nil)

;; Parse NAME according to `ange-ftp-name-format' (which see).
;; Returns a list (HOST USER NAME), or nil if NAME does not match the format.
(defun ange-ftp-ftp-name (name)
  (if (string-equal name ange-ftp-ftp-name-arg)
      ange-ftp-ftp-name-res
    (setq ange-ftp-ftp-name-arg name
	  ange-ftp-ftp-name-res
	  (save-match-data
	    (if (posix-string-match (car ange-ftp-name-format) name)
		(let* ((ns (cdr ange-ftp-name-format))
		       (host (ange-ftp-ftp-name-component 0 ns name))
		       (user (ange-ftp-ftp-name-component 1 ns name))
		       (name (ange-ftp-ftp-name-component 2 ns name)))
		  (if (zerop (length user))
		      (setq user (ange-ftp-get-user host)))
		  (list host user name))
	      nil)))))

;; Take a FULLNAME that matches according to ange-ftp-name-format and
;; replace the name component with NAME.
(defun ange-ftp-replace-name-component (fullname name)
  (save-match-data
    (if (posix-string-match (car ange-ftp-name-format) fullname)
	(let* ((ns (cdr ange-ftp-name-format))
	       (elt (nth 2 ns)))
	  (concat (substring fullname 0 (match-beginning elt))
		  name
		  (substring fullname (match-end elt)))))))
\f
;;;; ------------------------------------------------------------
;;;; Miscellaneous utils.
;;;; ------------------------------------------------------------

;; (setq ange-ftp-tmp-keymap (make-sparse-keymap))
;; (define-key ange-ftp-tmp-keymap "\C-m" 'exit-minibuffer)

(defun ange-ftp-repaint-minibuffer ()
  "Clear any existing minibuffer message; let the minibuffer contents show."
  (message nil))

;; Return the name of the buffer that collects output from the ftp process
;; connected to the given HOST and USER pair.
(defun ange-ftp-ftp-process-buffer (host user)
  (concat "*ftp " user "@" host "*"))

;; Display the last chunk of output from the ftp process for the given HOST
;; USER pair, and signal an error including MSG in the text.
(defun ange-ftp-error (host user msg)
  (save-excursion  ;; Prevent pop-to-buffer from changing current buffer.
    (let ((cur (selected-window))
	  (pop-up-windows t))
      (pop-to-buffer
       (get-buffer-create
	(ange-ftp-ftp-process-buffer host user)))
      (goto-char (point-max))
      (select-window cur))
    (signal 'ftp-error (list (format "FTP Error: %s" msg)))))

(defun ange-ftp-set-buffer-mode ()
  "Set correct modes for the current buffer if visiting a remote file."
  (if (and (stringp buffer-file-name)
	   (ange-ftp-ftp-name buffer-file-name))
      (auto-save-mode ange-ftp-auto-save)))

(defun ange-ftp-kill-ftp-process (&optional buffer)
  "Kill the FTP process associated with BUFFER (the current buffer, if nil).
If the BUFFER's visited filename or `default-directory' is an FTP filename
then kill the related FTP process."
  (interactive "bKill FTP process associated with buffer: ")
  (if (null buffer)
      (setq buffer (current-buffer))
    (setq buffer (get-buffer buffer)))
  (let ((file (or (buffer-file-name buffer)
		  (with-current-buffer buffer default-directory))))
    (if file
	(let ((parsed (ange-ftp-ftp-name (expand-file-name file))))
	  (if parsed
	      (let ((host (nth 0 parsed))
		    (user (nth 1 parsed)))
		(kill-buffer (get-buffer (ange-ftp-ftp-process-buffer host user)))))))))

(defun ange-ftp-quote-string (string)
  "Quote any characters in STRING that may confuse the FTP process."
  ;; This is said to be wrong; ftp is said to need quoting only for ",
  ;; and that by doubling it.  But experiment says UNIX-style kind of
  ;; quoting is correct when talking to ftp on GNU/Linux systems, and
  ;; W32-style kind of quoting on, yes, W32 systems.
  (if (stringp string)
      (shell-quote-argument string)
    ""))

(defun ange-ftp-barf-if-not-directory (directory)
  (or (file-directory-p directory)
      (let ((exists (file-exists-p directory)))
	(signal (if exists 'file-error 'file-missing)
		(list "Opening directory"
		      (if exists "Not a directory" "No such file or directory")
		      directory)))))
\f
;;;; ------------------------------------------------------------
;;;; FTP process filter support.
;;;; ------------------------------------------------------------

(defun ange-ftp-process-handle-line (line proc)
  "Look at the given LINE from the FTP process PROC.
Try to categorize it into one of four categories:
good, skip, fatal, or unknown."
  (cond ((string-match ange-ftp-xfer-size-msgs line)
	 (setq ange-ftp-xfer-size
	       (/ (string-to-number (match-string 1 line))
		  1024)))
	((string-match ange-ftp-skip-msgs line)
	 t)
	((string-match ange-ftp-good-msgs line)
	 (setq ange-ftp-process-busy nil
	       ange-ftp-process-result t
               ange-ftp-pending-error-line nil
	       ange-ftp-process-result-line line))
	;; Check this before checking for errors.
	;; Otherwise the last line of these three seems to be an error:
	;; 230-see a significant impact from the move.  For those of you who can't
	;; 230-use DNS to resolve hostnames and get an error message like
	;; 230-"ftp.stsci.edu: unknown host", the new IP address will be...
	((string-match ange-ftp-multi-msgs line)
	 (setq ange-ftp-process-multi-skip t))
	((string-match ange-ftp-potential-error-msgs line)
         ;; This looks like an error, but we have to keep reading the output
         ;; to see if it was fixed or not.  E.g. it may indicate that IPv6
         ;; failed, but maybe a subsequent IPv4 fallback succeeded.
         (set (make-local-variable 'ange-ftp-pending-error-line) line)
         t)
	((string-match ange-ftp-fatal-msgs line)
	 (delete-process proc)
	 (setq ange-ftp-process-busy nil
	       ange-ftp-process-result-line line))
        (ange-ftp-process-multi-skip
	 t)
	(t
	 (setq ange-ftp-process-busy nil
	       ange-ftp-process-result-line line))))

(defun ange-ftp-set-xfer-size (host user bytes)
  "Set the size of the next FTP transfer in bytes."
  (let ((proc (ange-ftp-get-process host user)))
    (when proc
      (let ((buf (process-buffer proc)))
	(when buf
	  (with-current-buffer buf
	    (setq ange-ftp-xfer-size
		  ;; For very large files, BYTES can be a float.
		  (if (integerp bytes)
		      (ash bytes -10)
		    (/ bytes 1024)))))))))

(defun ange-ftp-process-handle-hash (string)
  "Remove hash marks from STRING and display count so far."
  (setq string (concat (substring string 0 (match-beginning 0))
		       (substring string (match-end 0)))
	ange-ftp-hash-mark-count (+ (- (match-end 0)
				       (match-beginning 0))
				    ange-ftp-hash-mark-count))
  (and ange-ftp-hash-mark-unit
       ange-ftp-process-msg
       ange-ftp-process-verbose
       (not (eq (selected-window) (minibuffer-window)))
       (not (boundp 'search-message))	;screws up isearch otherwise
       (not cursor-in-echo-area)	;screws up y-or-n-p otherwise
       (let ((kbytes (ash (* ange-ftp-hash-mark-unit
			     ange-ftp-hash-mark-count)
			  -6)))
	 (if (zerop ange-ftp-xfer-size)
	     (ange-ftp-message "%s...%dk" ange-ftp-process-msg kbytes)
	   (let ((percent (floor (* 100.0 kbytes) ange-ftp-xfer-size)))
	     ;; cut out the redisplay of identical %-age messages.
	     (unless (eq percent ange-ftp-last-percent)
	       (setq ange-ftp-last-percent percent)
	       (ange-ftp-message "%s...%d%%" ange-ftp-process-msg percent))))))
  string)

;; Call the function specified by CONT.  CONT can be either a function
;; or a list of a function and some args.  The first two parameters
;; passed to the function will be RESULT and LINE.  The remaining args
;; will be taken from CONT if a list was passed.

(defun ange-ftp-call-cont (cont result line)
  (when cont
    (if (and (listp cont)
	     (not (eq (car cont) 'lambda)))
	(apply (car cont) result line (cdr cont))
      (funcall cont result line))))

;; Build up a complete line of output from the ftp PROCESS and pass it
;; on to ange-ftp-process-handle-line to deal with.

(defun ange-ftp-process-filter (proc str)
  ;; Eliminate nulls.
  (while (string-match "\000+" str)
    (setq str (replace-match "" nil nil str)))

  ;; see if the buffer is still around... it could have been deleted.
  (when (buffer-live-p (process-buffer proc))
    (with-current-buffer (process-buffer proc)

      ;; handle hash mark printing
      (and ange-ftp-process-busy
           (string-match "^#+$" str)
           (setq str (ange-ftp-process-handle-hash str)))
      (comint-output-filter proc str)
      ;; Replace STR by the result of the comint processing.
      (setq str (buffer-substring comint-last-output-start
                                  (process-mark proc)))
      (when ange-ftp-process-busy
	(setq ange-ftp-process-string (concat ange-ftp-process-string
					      str))

	;; if we gave an empty password to the USER command earlier
	;; then we should send a null password now.
	(if (string-match "Password: *$" ange-ftp-process-string)
	    (process-send-string proc "\n")))
      (while (and ange-ftp-process-busy
                  (string-match "\n" ange-ftp-process-string))
        (let ((line (substring ange-ftp-process-string
                               0
                               (match-beginning 0)))
              (seen-prompt nil))
          (setq ange-ftp-process-string (substring ange-ftp-process-string
                                                   (match-end 0)))
          (while (string-match "\\`ftp> *" line)
            (setq seen-prompt t)
            (setq line (substring line (match-end 0))))
          (if (not (and seen-prompt ange-ftp-pending-error-line))
              (ange-ftp-process-handle-line line proc)
            ;; If we've seen a potential error message and it
            ;; hasn't been canceled by a good message before
            ;; seeing a prompt, then the error was real.
            (delete-process proc)
            (setq ange-ftp-process-busy nil
                  ange-ftp-process-result-line ange-ftp-pending-error-line))))

      ;; has the ftp client finished?  if so then do some clean-up
      ;; actions.
      (unless ange-ftp-process-busy
	;; reset the xfer size
	(setq ange-ftp-xfer-size 0)

	;; issue the "done" message since we've finished.
	(when (and ange-ftp-process-msg
		   ange-ftp-process-verbose
		   ange-ftp-process-result)
	  (ange-ftp-message "%s...done" ange-ftp-process-msg)
	  (ange-ftp-repaint-minibuffer)
	  (setq ange-ftp-process-msg nil))

	;; is there a continuation we should be calling?  if so,
	;; we'd better call it, making sure we only call it once.
	(when ange-ftp-process-continue
	  (let ((cont ange-ftp-process-continue))
	    (setq ange-ftp-process-continue nil)
	    (ange-ftp-call-cont cont
				ange-ftp-process-result
				ange-ftp-process-result-line)))))))

(defun ange-ftp-process-sentinel (proc str)
  "When FTP process changes state, nuke all file-entries in cache."
  (let ((name (process-name proc)))
    (when (string-match "\\*ftp \\([^@]+\\)@\\([^*]+\\)\\*" name)
      (let ((user (match-string 1 name))
	    (host (match-string 2 name)))
	(ange-ftp-wipe-file-entries host user))))
  (setq ange-ftp-ls-cache-file nil))
\f
;;;; ------------------------------------------------------------
;;;; Gateway support.
;;;; ------------------------------------------------------------

(defun ange-ftp-use-gateway-p (host)
  "Return whether to access this HOST via a normal (non-smart) gateway."
  ;; yes, I know that I could simplify the following expression, but it is
  ;; clearer (to me at least) this way.
  (and (not ange-ftp-smart-gateway)
       (not (string-match-p ange-ftp-local-host-regexp host))))

(defun ange-ftp-use-smart-gateway-p (host)
  "Returns whether to access this HOST via a smart gateway."
  (and ange-ftp-smart-gateway
       (not (string-match-p ange-ftp-local-host-regexp host))))

\f
;;; ------------------------------------------------------------
;;; Temporary file location and deletion...
;;; ------------------------------------------------------------

(defun ange-ftp-make-tmp-name (host &optional suffix)
  "This routine will return the name of a new file."
  (make-temp-file (if (ange-ftp-use-gateway-p host)
		      ange-ftp-gateway-tmp-name-template
		    ange-ftp-tmp-name-template)
		  nil suffix))

(defun ange-ftp-del-tmp-name (filename)
  "Force to delete temporary file."
  (delete-file filename))

\f
;;;; ------------------------------------------------------------
;;;; Interactive gateway program support.
;;;; ------------------------------------------------------------

(defvar ange-ftp-gwp-running t)
(defvar ange-ftp-gwp-status nil)

(defun ange-ftp-gwp-sentinel (proc str)
  (setq ange-ftp-gwp-running nil))

(defun ange-ftp-gwp-filter (proc str)
  (comint-output-filter proc str)
  (with-current-buffer (process-buffer proc)
    ;; Replace STR by the result of the comint processing.
    (setq str (buffer-substring comint-last-output-start (process-mark proc))))
  (cond ((string-match "login: *$" str)
	 (process-send-string proc
                              (concat
                               (let ((ange-ftp-default-user t))
                                 (ange-ftp-get-user ange-ftp-gateway-host))
                               "\n")))
	((string-match "Password: *$" str)
	 (process-send-string proc
                              (concat
                               (ange-ftp-get-passwd ange-ftp-gateway-host
                                                    (ange-ftp-get-user
                                                     ange-ftp-gateway-host))
                               "\n")))
	((string-match ange-ftp-gateway-fatal-msgs str)
	 (delete-process proc)
	 (setq ange-ftp-gwp-running nil))
	((string-match ange-ftp-gateway-prompt-pattern str)
	 (setq ange-ftp-gwp-running nil
	       ange-ftp-gwp-status t))))

(defun ange-ftp-gwp-start (host user name args)
  "Login to the gateway machine and fire up an FTP process."
  ;; If `non-essential' is non-nil, don't reopen a new connection.  It
  ;; will be caught in Tramp.
  (when non-essential
    (throw 'non-essential 'non-essential))
  (let (;; It would be nice to make process-connection-type nil,
	;; but that doesn't work: ftp never responds.
	;; Can anyone find a fix for that?
	(proc (let ((process-connection-type t))
		(start-process name name
			       ange-ftp-gateway-program
			       ange-ftp-gateway-host)))
	(ftp (mapconcat 'identity args " ")))
    (set-process-query-on-exit-flag proc nil)
    (set-process-sentinel proc 'ange-ftp-gwp-sentinel)
    (set-process-filter proc 'ange-ftp-gwp-filter)
    (with-current-buffer (process-buffer proc)
      (goto-char (point-max))
      (set-marker (process-mark proc) (point)))
    (setq ange-ftp-gwp-running t
	  ange-ftp-gwp-status nil)
    (ange-ftp-message "Connecting to gateway %s..." ange-ftp-gateway-host)
    (while ange-ftp-gwp-running		;perform login sequence
      (accept-process-output proc))
    (unless ange-ftp-gwp-status
      (ange-ftp-error host user "unable to login to gateway"))
    (ange-ftp-message "Connecting to gateway %s...done" ange-ftp-gateway-host)
    (setq ange-ftp-gwp-running t
	  ange-ftp-gwp-status nil)
    (process-send-string proc ange-ftp-gateway-setup-term-command)
    (while ange-ftp-gwp-running		;zap ^M's and double echoing.
      (accept-process-output proc))
    (unless ange-ftp-gwp-status
      (ange-ftp-error host user "unable to set terminal modes on gateway"))
    (setq ange-ftp-gwp-running t
	  ange-ftp-gwp-status nil)
    (process-send-string proc (concat "exec " ftp "\n")) ;spawn ftp process
    proc))
\f
;;;; ------------------------------------------------------------
;;;; Support for sending commands to the ftp process.
;;;; ------------------------------------------------------------

(defun ange-ftp-raw-send-cmd (proc cmd &optional msg cont nowait)
  "Low-level routine to send the given FTP CMD to the FTP process PROC.
MSG is an optional message to output before and after the command.
If CONT is non-nil then it is either a function or a list of function
and some arguments.  The function will be called when the FTP command
has completed.
If CONT is nil then this routine will return (RESULT . LINE) where RESULT
is whether the command was successful, and LINE is the line from the FTP
process that caused the command to complete.
If NOWAIT is given then the routine will return immediately the command has
been queued with no result.  CONT will still be called, however."
  (if (memq (process-status proc) '(run open))
      (with-current-buffer (process-buffer proc)
	(ange-ftp-wait-not-busy proc)
	(setq ange-ftp-process-string ""
	      ange-ftp-process-result-line ""
	      ange-ftp-process-busy t
	      ange-ftp-process-result nil
	      ange-ftp-process-multi-skip nil
	      ange-ftp-process-msg msg
	      ange-ftp-process-continue cont
	      ange-ftp-hash-mark-count 0
	      ange-ftp-last-percent -1
	      cmd (concat cmd "\n"))
	(and msg ange-ftp-process-verbose (ange-ftp-message "%s..." msg))
	(goto-char (point-max))
	(move-marker comint-last-input-start (point))
	;; don't insert the password into the buffer on the USER command.
	(save-match-data
	  (if (string-match "\\`user \"[^\"]*\"" cmd)
	      (insert (substring cmd 0 (match-end 0)) " Turtle Power!\n")
	    (insert cmd)))
	(move-marker comint-last-input-end (point))
	(process-send-string proc cmd)
	(set-marker (process-mark proc) (point))
	(if nowait
	    nil
	  (ange-ftp-wait-not-busy proc)
	  (if cont
	      nil			;cont has already been called
	    (cons ange-ftp-process-result ange-ftp-process-result-line))))))

;; Wait for the ange-ftp process PROC not to be busy.
(defun ange-ftp-wait-not-busy (proc)
  (with-current-buffer (process-buffer proc)
    (condition-case nil
	;; This is a kludge to let user quit in case ftp gets hung.
	;; It matters because this function can be called from the filter.
	;; It is bad to allow quitting in a filter, but getting hung
	;; is worse.  By binding quit-flag to nil, we might avoid
	;; most of the probability of getting screwed because the user
	;; wants to quit some command.
	(let ((quit-flag nil)
	      (inhibit-quit nil))
	  (while ange-ftp-process-busy
	    (accept-process-output proc)))
      (quit
       ;; If the user does quit out of this,
       ;; kill the process.  That stops any transfer in progress.
       ;; The next operation will open a new ftp connection.
       (delete-process proc)
       (signal 'quit nil)))))

(defun ange-ftp-nslookup-host (hostname)
  "Attempt to resolve the given HOSTNAME using nslookup if possible."
  (interactive "sHost:  ")
  (if ange-ftp-nslookup-program
      (let ((default-directory
	      (if (file-accessible-directory-p default-directory)
		  default-directory
		exec-directory))
	    ;; It would be nice to make process-connection-type nil,
	    ;; but that doesn't work: ftp never responds.
	    ;; Can anyone find a fix for that?
	    (proc (let ((process-connection-type t))
		    (start-process " *nslookup*" " *nslookup*"
				   ange-ftp-nslookup-program hostname)))
	    (res hostname))
	(set-process-query-on-exit-flag proc nil)
	(with-current-buffer (process-buffer proc)
	  (while (memq (process-status proc) '(run open))
	    (accept-process-output proc))
	  (goto-char (point-min))
	  (if (re-search-forward "Name:.*\nAddress: *\\(.*\\)$" nil t)
	      (setq res (match-string 1)))
	  (kill-buffer (current-buffer)))
	res)
    hostname))

(defun ange-ftp-start-process (host user name)
  "Spawn a new FTP process ready to connect to machine HOST and give it NAME.
If HOST is only FTP-able through a gateway machine then spawn a shell
on the gateway machine to do the FTP instead."
  ;; If `non-essential' is non-nil, don't reopen a new connection.  It
  ;; will be caught in Tramp.
  (when non-essential
    (throw 'non-essential 'non-essential))
  (let* ((use-gateway (ange-ftp-use-gateway-p host))
	 (use-smart-ftp (and (not ange-ftp-gateway-host)
			     (ange-ftp-use-smart-gateway-p host)))
	 (ftp-prog (if (or use-gateway
			   use-smart-ftp)
		       ange-ftp-gateway-ftp-program-name
		     ange-ftp-ftp-program-name))
	 (args (append (list ftp-prog) ange-ftp-ftp-program-args))
	 ;; Without the following binding, ange-ftp-start-process
	 ;; recurses on file-accessible-directory-p, since it needs to
	 ;; restart its process in order to determine anything about
	 ;; default-directory.
	 (file-name-handler-alist)
	 (default-directory
	   (if (file-accessible-directory-p default-directory)
	       default-directory
	     exec-directory))
	 proc)
    ;; It would be nice to make process-connection-type nil,
    ;; but that doesn't work: ftp never responds.
    ;; Can anyone find a fix for that?
    (let ((process-connection-type t)
	  ;; Copy this so we don't alter it permanently.
	  (process-environment (copy-tree process-environment))
	  (buffer (get-buffer-create name)))
      (with-current-buffer buffer
	(internal-ange-ftp-mode))
      ;; This tells GNU ftp not to output any fancy escape sequences.
      (setenv "TERM" "dumb")
      (if use-gateway
	  (if ange-ftp-gateway-program-interactive
	      (setq proc (ange-ftp-gwp-start host user name args))
	    (setq proc (apply 'start-process name name
			      (append (list ange-ftp-gateway-program
					    ange-ftp-gateway-host)
				      args))))
	(setq proc (apply 'start-process name name args))))
    (with-current-buffer (process-buffer proc)
      (goto-char (point-max))
      (set-marker (process-mark proc) (point)))
    (set-process-query-on-exit-flag proc nil)
    (set-process-sentinel proc 'ange-ftp-process-sentinel)
    (set-process-filter proc 'ange-ftp-process-filter)
    ;; On Windows, the standard ftp client buffers its output (because
    ;; stdout is a pipe handle) so the startup message may never appear:
    ;; `accept-process-output' at this point would hang indefinitely.
    ;; However, sending an innocuous command ("help foo") forces some
    ;; output that will be ignored, which is just as good.  Once we
    ;; start sending normal commands, the output no longer appears to be
    ;; buffered, and everything works correctly.  My guess is that the
    ;; output of interest is being sent to stderr which is not buffered.
    (when (eq system-type 'windows-nt)
      ;; force ftp output to be treated as DOS text, otherwise the
      ;; output of "help foo" confuses the EOL detection logic.
      (set-process-coding-system proc 'raw-text-dos)
      (process-send-string proc "help foo\n"))
    (accept-process-output proc)	;wait for ftp startup message
    proc))

(define-derived-mode internal-ange-ftp-mode comint-mode "Internal Ange-ftp"
  "Major mode for interacting with the FTP process.

\\{comint-mode-map}"
  (make-local-variable 'ange-ftp-process-string)
  (setq ange-ftp-process-string "")
  (make-local-variable 'ange-ftp-process-busy)
  (make-local-variable 'ange-ftp-process-result)
  (make-local-variable 'ange-ftp-process-msg)
  (make-local-variable 'ange-ftp-process-multi-skip)
  (make-local-variable 'ange-ftp-process-result-line)
  (make-local-variable 'ange-ftp-process-continue)
  (make-local-variable 'ange-ftp-hash-mark-count)
  (make-local-variable 'ange-ftp-binary-hash-mark-size)
  (make-local-variable 'ange-ftp-ascii-hash-mark-size)
  (make-local-variable 'ange-ftp-hash-mark-unit)
  (make-local-variable 'ange-ftp-xfer-size)
  (make-local-variable 'ange-ftp-last-percent)
  (setq ange-ftp-hash-mark-count 0)
  (setq ange-ftp-xfer-size 0)
  (setq ange-ftp-process-result-line "")
  (setq comint-prompt-regexp "^ftp> ")
  (make-local-variable 'comint-password-prompt-regexp)
  ;; This is a regexp that can't match anything.
  ;; ange-ftp has its own ways of handling passwords.
  (setq comint-password-prompt-regexp "\\`a\\`")
  (make-local-variable 'paragraph-start)
  (setq paragraph-start comint-prompt-regexp))

(defcustom ange-ftp-raw-login nil
  "Use raw FTP commands for login, if account password is not nil.
Some FTP implementations need this, e.g. ftp in NT 4.0."
  :group 'ange-ftp
  :version "21.3"
  :type 'boolean)

(defun ange-ftp-smart-login (host user password account proc)
  "Connect to the FTP-server on HOST as USER using PASSWORD and ACCOUNT.
PROC is the FTP-client's process.  This routine uses the smart-gateway
host specified in `ange-ftp-gateway-host'."
  (let ((result (ange-ftp-raw-send-cmd
		 proc
		 (format "open %s %s"
			 (ange-ftp-nslookup-host ange-ftp-gateway-host)
			 ange-ftp-smart-gateway-port)
		 (format "Opening FTP connection to %s via %s"
			 host
			 ange-ftp-gateway-host))))
    (or (car result)
	(ange-ftp-error host user
			(concat "OPEN request failed: "
				(cdr result))))
    (setq result (ange-ftp-raw-send-cmd
		  proc (format "user \"%s\"@%s %s %s"
			       user
			       (ange-ftp-nslookup-host host)
			       password
			       account)
		  (format "Logging in as user %s@%s"
			  user host)))
    (or (car result)
	(progn
	  (ange-ftp-set-passwd host user nil) ; reset password
	  (ange-ftp-set-account host user nil) ; reset account
	  (ange-ftp-error host user
			  (concat "USER request failed: "
				  (cdr result)))))))

(defun ange-ftp-normal-login (host user password account proc)
  "Connect to the FTP-server on HOST as USER using PASSWORD and ACCOUNT.
PROC is the process to the FTP-client.  HOST may have an optional
suffix of the form #PORT to specify a non-default port."
  (save-match-data
    (string-match "\\`\\([^#]+\\)\\(#\\([0-9]+\\)\\)?\\'" host)
    (let* ((nshost (ange-ftp-nslookup-host (match-string 1 host)))
	   (port (match-string 3 host))
	   (result (ange-ftp-raw-send-cmd
		    proc
		    (if port
			(format "open %s %s" nshost port)
		      (format "open %s" nshost))
		    (format "Opening FTP connection to %s" host))))
      (or (car result)
	  (ange-ftp-error host user
			  (concat "OPEN request failed: "
				  (cdr result))))
      (if (not (and ange-ftp-raw-login (string< "" account)))
	  (setq result (ange-ftp-raw-send-cmd
			proc
			(if (and (ange-ftp-use-smart-gateway-p host)
				 ange-ftp-gateway-host)
			    (format "user \"%s\"@%s %s %s"
				    user nshost password account)
			  (format "user \"%s\" %s %s" user password account))
			(format "Logging in as user %s@%s" user host)))
	(let ((good ange-ftp-good-msgs)
	      (skip ange-ftp-skip-msgs))
	  (setq ange-ftp-good-msgs (concat ange-ftp-good-msgs
					   "\\|^331 \\|^332 "))
	  (if (string-match (regexp-quote "\\|^331 ") ange-ftp-skip-msgs)
	      (setq ange-ftp-skip-msgs
		    (replace-match "" t t ange-ftp-skip-msgs)))
	  (if (string-match (regexp-quote "\\|^332 ") ange-ftp-skip-msgs)
	      (setq ange-ftp-skip-msgs
		    (replace-match "" t t ange-ftp-skip-msgs)))
	  (setq result (ange-ftp-raw-send-cmd
			proc
			(format "quote \"USER %s\"" user)
			(format "Logging in as user %s@%s" user host)))
	  (and (car result)
	       (setq result (ange-ftp-raw-send-cmd
			     proc
			     (format "quote \"PASS %s\"" password)
			     (format "Logging in as user %s@%s" user host)))
	       (and (car result)
		    (setq result (ange-ftp-raw-send-cmd
				  proc
				  (format "quote \"ACCT %s\"" account)
				  (format "Logging in as user %s@%s" user host)))
		    ))
	  (setq ange-ftp-good-msgs good
		ange-ftp-skip-msgs skip)))
      (or (car result)
	  (progn
	    (ange-ftp-set-passwd host user nil)	;reset password.
	    (ange-ftp-set-account host user nil) ;reset account.
	    (ange-ftp-error host user
			    (concat "USER request failed: "
				    (cdr result))))))))

;; ange@hplb.hpl.hp.com says this should not be changed.
(defvar ange-ftp-hash-mark-msgs
  "[hH]ash mark [^0-9]*\\([0-9]+\\)"
  "Regexp matching the FTP client's output upon doing a HASH command.")

(defun ange-ftp-guess-hash-mark-size (proc)
  (if ange-ftp-send-hash
      (with-current-buffer (process-buffer proc)
	(let* ((status (ange-ftp-raw-send-cmd proc "hash"))
	       (line (cdr status)))
	  (save-match-data
	    (if (string-match ange-ftp-hash-mark-msgs line)
		(let ((size (string-to-number (match-string 1 line))))
		  (setq ange-ftp-ascii-hash-mark-size size
			ange-ftp-hash-mark-unit (ash size -4))

		  ;; if a default value for this is set, use that value.
		  (or ange-ftp-binary-hash-mark-size
		      (setq ange-ftp-binary-hash-mark-size size)))))))))

(defvar ange-ftp-process-startup-hook nil)

(defun ange-ftp-get-process (host user)
  "Return an FTP subprocess connected to HOST and logged in as USER.
Create a new process if needed."
  (let* ((name (ange-ftp-ftp-process-buffer host user))
	 (proc (get-process name)))
    (if (and proc (memq (process-status proc) '(run open)))
	proc
      ;; If `non-essential' is non-nil, don't reopen a new connection.  It
      ;; will be caught in Tramp.
      (when non-essential
	(throw 'non-essential 'non-essential))

      ;; Must delete dead process so that new process can reuse the name.
      (if proc (delete-process proc))
      (let ((pass (ange-ftp-quote-string
		   (ange-ftp-get-passwd host user)))
	    (account (ange-ftp-quote-string
		      (ange-ftp-get-account host user))))
	;; grab a suitable process.
	(setq proc (ange-ftp-start-process host user name))

	;; login to FTP server.
	(if (and (ange-ftp-use-smart-gateway-p host)
		 ange-ftp-gateway-host)
	    (ange-ftp-smart-login host user pass account proc)
	  (ange-ftp-normal-login host user pass account proc))

	;; Tell client to send back hash-marks as progress.  It isn't usually
	;; fatal if this command fails.
	(ange-ftp-guess-hash-mark-size proc)

	;; Guess at the host type.
	(ange-ftp-guess-host-type host user)

	;; Turn passive mode on or off as requested.
	(let* ((case-fold-search t)
	       (passive
		(or (assoc-default host ange-ftp-passive-host-alist
				   'string-match)
		    (if ange-ftp-try-passive-mode "on"))))
	  (if passive
	      (ange-ftp-passive-mode proc passive)))

	;; Run any user-specified hooks.  Note that proc, host and user are
	;; dynamically bound at this point.
	(let ((ange-ftp-this-user user)
	      (ange-ftp-this-host host))
	  (run-hooks 'ange-ftp-process-startup-hook)))
      proc)))

(defun ange-ftp-passive-mode (proc on-or-off)
  (if (string-match (concat "Passive mode " on-or-off)
                    (cdr (ange-ftp-raw-send-cmd
                          proc (concat "passive " on-or-off)
                          "Trying passive mode..." nil)))
      (ange-ftp-message (concat "Trying passive mode..." on-or-off))
    (error "Trying passive mode...failed")))

;; Variables for caching host and host-type
(defvar ange-ftp-host-cache nil)
(defvar ange-ftp-host-type-cache nil)

;; If ange-ftp-host-type is called with the optional user
;; argument, it will attempt to guess the host type by connecting
;; as user, if necessary. For efficiency, I have tried to give this
;; optional second argument only when necessary. Have I missed any calls
;; to ange-ftp-host-type where it should have been supplied?

(defun ange-ftp-host-type (host &optional user)
  "Return a symbol which represents the type of the HOST given.
If the optional argument USER is given, attempts to guess the
host-type by logging in as USER."
  (cond ((null host) 'unix)
	;; Return `unix' if HOST is nil, since that's the most vanilla
	;; possible return value.
	((eq host ange-ftp-host-cache)
	 ange-ftp-host-type-cache)
	;; Trigger an ftp connection, in case we need to guess at the host type.
	((and user (ange-ftp-get-process host user) (eq host ange-ftp-host-cache))
	 ange-ftp-host-type-cache)
	(t
         (setq ange-ftp-host-cache host
	       ange-ftp-host-type-cache
	       (cond ((ange-ftp-dumb-unix-host host)
		      'dumb-unix)
		     ;;		  ((and (fboundp 'ange-ftp-vos-host)
		     ;;			(ange-ftp-vos-host host))
		     ;;		   'vos)
		     ((and (fboundp 'ange-ftp-vms-host)
			   (ange-ftp-vms-host host))
		      'vms)
		     ((and (fboundp 'ange-ftp-mts-host)
			   (ange-ftp-mts-host host))
		      'mts)
		     ((and (fboundp 'ange-ftp-cms-host)
			   (ange-ftp-cms-host host))
		      'cms)
		     ((and (fboundp 'ange-ftp-bs2000-posix-host)
			   (ange-ftp-bs2000-posix-host host))
		      'text-unix)	; POSIX is a non-ASCII Unix
		     ((and (fboundp 'ange-ftp-bs2000-host)
			   (ange-ftp-bs2000-host host))
		      'bs2000)
		     (t
		      'unix))))))

;; It would be nice to abstract the functions ange-ftp-TYPE-host and
;; ange-ftp-add-TYPE-host. The trick is to abstract these functions
;; without sacrificing speed. Also, having separate variables
;; ange-ftp-TYPE-regexp is more user friendly then requiring the user to
;; set an alist to indicate that a host is of a given type. Even with
;; automatic host type recognition, setting a regexp is still a good idea
;; (for efficiency) if you log into a particular non-UNIX host frequently.

(defvar ange-ftp-fix-name-func-alist nil
  "Alist saying how to convert file name to the host's syntax.
Association list of (TYPE . FUNC) pairs, where FUNC is a routine which can
change a UNIX file name into a name more suitable for a host of type TYPE.")

(defvar ange-ftp-fix-dir-name-func-alist nil
  "Alist saying how to convert directory name to the host's syntax.
Association list of (TYPE . FUNC) pairs, where FUNC is a routine which can
change UNIX directory name into a directory name more suitable for a host
of type TYPE.")

;; *** Perhaps the sense of this variable should be inverted, since there
;; *** is only 1 host type that can take ls-style listing options.
(defvar ange-ftp-dumb-host-types '(dumb-unix)
  "List of host types that can't take UNIX ls-style listing options.")

(defun ange-ftp-send-cmd (host user cmd &optional msg cont nowait)
  "Find an FTP process connected to HOST logged in as USER and send it CMD.
MSG is an optional status message to be output before and after issuing the
command.
See the documentation for `ange-ftp-raw-send-cmd' for a description of CONT
and NOWAIT."
  ;; Handle conversion to remote file name syntax and remote ls option
  ;; capability.
  (let ((cmd0 (car cmd))
	(cmd1 (nth 1 cmd))
	(ange-ftp-this-user user)
	(ange-ftp-this-host host)
	(ange-ftp-this-msg msg)
	cmd2 cmd3 host-type fix-name-func result)

    (cond

     ;; pwd case (We don't care what host-type.)
     ((null cmd1))

     ;; cmd == 'dir "remote-name" "local-name" "ls-switches"
     ((progn
       (setq cmd2 (nth 2 cmd)
	     host-type (ange-ftp-host-type host user))
       ;; This will trigger an FTP login, if one doesn't exist
       (eq cmd0 'dir))
      (setq cmd1 (funcall
		  (or (cdr (assq host-type ange-ftp-fix-dir-name-func-alist))
		      'identity)
		  cmd1)
	    cmd3 (nth 3 cmd))
      ;; Need to deal with the HP-UX ftp bug. This should also allow us to
      ;; resolve symlinks to directories on SysV machines. (Sebastian will
      ;; be happy.)
      (and (eq host-type 'unix)
	   (string-match "/\\'" cmd1)
	   (not (string-match "R" cmd3))
	   (setq cmd1 (concat cmd1 ".")))

      ;; Using "ls -flags foo" has several problems:
      ;; - if foo is a symlink, we may get a single line showing the symlink
      ;;   rather than the listing of the directory it points to.
      ;; - if "foo" has spaces, the parsing of the command may be done wrong.
      ;; - some version of netbsd's ftpd only accept a single argument after
      ;;   `ls', which can either be the directory or the flags.
      ;; So to work around those problems, we use "cd foo; ls -flags".

      ;; If the dir name contains a space, some ftp servers will
      ;; refuse to list it.  We instead change directory to the
      ;; directory in question and ls ".".
      (when (string-match " " cmd1)
	;; Keep the result.  In case of failure, we will (see below)
	;; short-circuit CMD and return this result directly.
	(setq result (ange-ftp-cd host user (nth 1 cmd) 'noerror))
	(setq cmd1 "."))

      ;; If the remote ls can take switches, put them in
      (unless (memq host-type ange-ftp-dumb-host-types)
	(setq cmd0 'ls)
	;; We cd and then use `ls' with no directory argument.
	;; This works around a misfeature of some versions of netbsd ftpd
	;; where `ls' can only take one argument: either one set of flags
	;; or a file/directory name.
	;; If we're trying to `ls' a single file, this fails since we
	;; can't cd to a file.  We can't fix this problem here, tho, because
	;; at this point we don't know whether the argument is a file or
	;; a directory.  Such an `ls' is only ever used (apparently) from
	;; `insert-directory' when the `full-directory-p' argument is nil
	;; (which seems to only be used by dired when updating its display
	;; after operating on a set of files).  So we've changed
	;; `ange-ftp-insert-directory' such that in this case it gets
	;; a full listing of the directory and extracting the line
	;; corresponding to the requested file.
	(unless (equal cmd1 ".")
	  (setq result (ange-ftp-cd host user (nth 1 cmd) 'noerror)))
	(setq cmd1 cmd3)))

     ;; First argument is the remote name
     ((progn
	(setq fix-name-func (or (cdr (assq host-type
					   ange-ftp-fix-name-func-alist))
				'identity))
	(memq cmd0 '(get delete mkdir rmdir cd)))
      (setq cmd1 (funcall fix-name-func cmd1)))

     ;; Second argument is the remote name
     ((or (memq cmd0 '(append put chmod))
          (and (eq cmd0 'quote) (member cmd1 '("mdtm" "size"))))
      (setq cmd2 (funcall fix-name-func cmd2)))
     ;; Both arguments are remote names
     ((eq cmd0 'rename)
      (setq cmd1 (funcall fix-name-func cmd1)
	    cmd2 (funcall fix-name-func cmd2))))

    ;; Turn the command into one long string
    (setq cmd0 (symbol-name cmd0))
    (setq cmd (concat cmd0
		      (and cmd1 (concat " " cmd1))
		      (and cmd2 (concat " " cmd2))))

    ;; Actually send the resulting command.
    (if (and (consp result) (null (car result)))
	;; `ange-ftp-cd' has failed, so there's no point sending `cmd'.
	result
      (let (afsc-result
	    afsc-line)
	(ange-ftp-raw-send-cmd
	 (ange-ftp-get-process host user)
	 cmd
	 msg
	 (list (lambda (result line host user cmd msg cont nowait)
		 (or cont (setq afsc-result result
				afsc-line line))
		 (if result (ange-ftp-call-cont cont result line)
                   (ange-ftp-raw-send-cmd
                    (ange-ftp-get-process host user)
                    cmd
                    msg
                    (list (lambda (result line cont)
                            (or cont (setq afsc-result result
                                           afsc-line line))
                            (ange-ftp-call-cont cont result line))
                          cont)
		    nowait)))
	       host user cmd msg cont nowait)
	 nowait)

	(if nowait
	    nil
	  (if cont
	      nil
	    (cons afsc-result afsc-line)))))))

;; It might be nice to message users about the host type identified,
;; but there is so much other messaging going on, it would not be
;; seen. No point in slowing things down just so users can read
;; a host type message.

(defconst ange-ftp-cms-name-template
  (concat
   "^[-A-Z0-9$*][-A-Z0-9$*]?[-A-Z0-9$*]?[-A-Z0-9$*]?[-A-Z0-9$*]?"
   "[-A-Z0-9$*]?[-A-Z0-9$*]?[-A-Z0-9$*]?\\.[0-9][0-9][0-9A-Z]$"))
(defconst ange-ftp-vms-name-template
  "^[-A-Z0-9_$]+:\\[[-A-Z0-9_$]+\\(\\.[-A-Z0-9_$]+\\)*\\]$")
(defconst ange-ftp-mts-name-template
  "^[A-Z0-9._][A-Z0-9._][A-Z0-9._][A-Z0-9._]:$")
(defconst ange-ftp-bs2000-filename-pubset-regexp
  ":[A-Z0-9]+:"
  "Valid pubset for an BS2000 file name.")
(defconst ange-ftp-bs2000-filename-username-regexp
  (concat
   "\\$[A-Z0-9]*\\.")
  "Valid username for an BS2000 file name.")
(defconst ange-ftp-bs2000-filename-prefix-regexp
  (concat
   ange-ftp-bs2000-filename-pubset-regexp
   ange-ftp-bs2000-filename-username-regexp)
  "Valid prefix for an BS2000 file name (pubset and user).")
(defconst ange-ftp-bs2000-name-template
  (concat "^" ange-ftp-bs2000-filename-prefix-regexp "$"))

(defun ange-ftp-guess-host-type (host user)
  "Guess the host type of HOST.
Works by doing a pwd and examining the directory syntax."
  (let ((host-type (ange-ftp-host-type host))
	(key (concat host "/" user "/~")))
    (if (eq host-type 'unix)
	;; Note that ange-ftp-host-type returns unix as the default value.
	(save-match-data
	  (let* ((result (ange-ftp-get-pwd host user))
		 (dir (car result))
		 fix-name-func)
	    (cond ((null dir)
		   (message "Warning! Unable to get home directory")
		   (sit-for 1)
		   (if (string-match
			"^450 No current working directory defined$"
			(cdr result))

		       ;; We'll assume that if pwd bombs with this
		       ;; error message, then it's CMS.
		       (progn
			 (ange-ftp-add-cms-host host)
			 (setq ange-ftp-host-cache host
			       ange-ftp-host-type-cache 'cms))))

		  ;; try for VMS
		  ((string-match ange-ftp-vms-name-template dir)
		   (ange-ftp-add-vms-host host)
		   ;; The add-host functions clear the host type cache.
		   ;; Therefore, need to set the cache afterwards.
		   (setq ange-ftp-host-cache host
			 ange-ftp-host-type-cache 'vms))

		  ;; try for MTS
		  ((string-match ange-ftp-mts-name-template dir)
		   (ange-ftp-add-mts-host host)
		   (setq ange-ftp-host-cache host
			 ange-ftp-host-type-cache 'mts))

		  ;; try for CMS
		  ((string-match ange-ftp-cms-name-template dir)
		   (ange-ftp-add-cms-host host)
		   (setq ange-ftp-host-cache host
			 ange-ftp-host-type-cache 'cms))

		  ;; try for BS2000-POSIX
		  ((ange-ftp-bs2000-posix-host host)
		   (ange-ftp-add-bs2000-host host)
		   (setq ange-ftp-host-cache host
			 ange-ftp-host-type-cache 'text-unix))
		  ;; try for BS2000
		  ((and (string-match ange-ftp-bs2000-name-template dir)
			(not (ange-ftp-bs2000-posix-host host)))
		   (ange-ftp-add-bs2000-host host)
		   (setq ange-ftp-host-cache host
			 ange-ftp-host-type-cache 'bs2000))
		  ;; assume UN*X
		  (t
		   (setq ange-ftp-host-cache host
			 ange-ftp-host-type-cache 'unix)))

	    ;; Now that we have done a pwd, might as well put it in
	    ;; the expand-dir hashtable.
	    (let ((ange-ftp-this-user user)
		  (ange-ftp-this-host host))
	      (setq fix-name-func (cdr (assq ange-ftp-host-type-cache
					     ange-ftp-fix-name-func-alist)))
	      (if fix-name-func
		  (setq dir (funcall fix-name-func dir 'reverse))))
	    (puthash key dir ange-ftp-expand-dir-hashtable))))

    ;; In the special case of CMS make sure that know the
    ;; expansion of the home minidisk now, because we will
    ;; be doing a lot of cd's.
    (if (and (eq host-type 'cms)
	     (not (ange-ftp-hash-entry-exists-p
		   key ange-ftp-expand-dir-hashtable)))
	(let ((dir (car (ange-ftp-get-pwd host user))))
	  (if dir
	      (puthash key (concat "/" dir) ange-ftp-expand-dir-hashtable)
	    (message "Warning! Unable to get home directory")
	    (sit-for 1))))))

\f
;;;; ------------------------------------------------------------
;;;; Remote file and directory listing support.
;;;; ------------------------------------------------------------

;; Returns whether HOST's FTP server doesn't like 'ls' or 'dir' commands
;; to take switch arguments.
(defun ange-ftp-dumb-unix-host (host)
  (and host ange-ftp-dumb-unix-host-regexp
       (string-match-p ange-ftp-dumb-unix-host-regexp host)))

(defun ange-ftp-add-dumb-unix-host (host)
  "Interactively add a given HOST to `ange-ftp-dumb-unix-host-regexp'."
  (interactive
   (list (read-string "Host: "
		      (let ((name (or (buffer-file-name) default-directory)))
			(and name (car (ange-ftp-ftp-name name)))))))
  (if (not (ange-ftp-dumb-unix-host host))
      (setq ange-ftp-dumb-unix-host-regexp
	    (concat "^" (regexp-quote host) "$"
		    (and ange-ftp-dumb-unix-host-regexp "\\|")
		    ange-ftp-dumb-unix-host-regexp)
	    ange-ftp-host-cache nil)))

(defvar ange-ftp-parse-list-func-alist nil
  "Alist saying how to parse directory listings for certain OS types.
Association list of (TYPE . FUNC) pairs.  The FUNC is a routine which
can parse the output from a DIR listing for a host of type TYPE.")

;; With no-error nil, this function returns:
;; an error if file is not an ange-ftp-name
;;                      (This should never happen.)
;; an error if either the listing is unreadable or there is an ftp error.
;; the listing (a string), if everything works.
;;
;; With no-error t, it returns:
;; an error if not an ange-ftp-name
;; error if listing is unreadable (most likely caused by a slow connection)
;; nil if ftp error (this is because although asking to list a nonexistent
;;                   directory on a remote unix machine usually (except
;;                   maybe for dumb hosts) returns an ls error, but no
;;                   ftp error, if the same is done on a VMS machine,
;;                   an ftp error is returned. Need to trap the error
;;                   so we can go on and try to list the parent.)
;; the listing, if everything works.

;; If WILDCARD is non-nil, then this implements the guts of insert-directory
;; in the wildcard case.  Then we make a relative directory listing
;; of FILE within the directory specified by `default-directory'.

(defvar ange-ftp-before-parse-ls-hook nil
  "Normal hook run before parsing the text of an FTP directory listing.")

(defvar ange-ftp-after-parse-ls-hook nil
  "Normal hook run after parsing the text of an FTP directory listing.")

(defun ange-ftp-ls (file lsargs parse &optional no-error wildcard)
  "Return the output of a `DIR' or `ls' command done over FTP.
FILE is the full name of the remote file, LSARGS is any args to pass to the
`ls' command, and PARSE specifies that the output should be parsed and stored
away in the internal cache."
  (when (string-match "^--dired\\s-+" lsargs)
    (setq lsargs (replace-match "" nil t lsargs)))
  ;; If parse is t, we assume that file is a directory. i.e. we only parse
  ;; full directory listings.
  (let* ((ange-ftp-this-file (ange-ftp-expand-file-name file))
	 (parsed (ange-ftp-ftp-name ange-ftp-this-file)))
    (if parsed
	(let* ((host (nth 0 parsed))
	       (user (nth 1 parsed))
	       (name (ange-ftp-quote-string (nth 2 parsed)))
	       (key (directory-file-name ange-ftp-this-file))
	       (host-type (ange-ftp-host-type host user))
	       (dumb (memq host-type ange-ftp-dumb-host-types))
	       result
	       temp
	       lscmd parse-func)
	  (if (string-equal name "")
	      (setq name
		    (ange-ftp-real-file-name-as-directory
		     (ange-ftp-expand-dir host user "~"))))
	  (if (and ange-ftp-ls-cache-file
		   (string-equal key ange-ftp-ls-cache-file)
		   ;; Don't care about lsargs for dumb hosts.
		   (or dumb (string-equal lsargs ange-ftp-ls-cache-lsargs)))
	      ange-ftp-ls-cache-res
	    (setq temp (ange-ftp-make-tmp-name host))
	    (if wildcard
		(progn
		  (ange-ftp-cd host user (file-name-directory name))
		  (setq lscmd (list 'ls file temp lsargs)))
	      (setq lscmd (list 'dir name temp lsargs)))
	    (unwind-protect
		(if (car (setq result (ange-ftp-send-cmd
				       host
				       user
				       lscmd
				       (format "Listing %s"
					       (ange-ftp-abbreviate-filename
						ange-ftp-this-file)))))
		    (with-current-buffer (get-buffer-create
                                          ange-ftp-data-buffer-name)
		      (erase-buffer)
		      (if (ange-ftp-real-file-readable-p temp)
			  (ange-ftp-real-insert-file-contents temp)
			(sleep-for ange-ftp-retry-time)
					;wait for file to possibly appear
			(if (ange-ftp-real-file-readable-p temp)
			    ;; Try again.
			    (ange-ftp-real-insert-file-contents temp)
			  (ange-ftp-error host user
					  (format
					   "list data file %s not readable"
					   temp))))
                      ;; remove ^M inserted by the w32 ftp client
                      (while (re-search-forward "\r$" nil t)
                        (replace-match ""))
                      (goto-char 1)
		      (run-hooks 'ange-ftp-before-parse-ls-hook)
		      (if parse
			  (ange-ftp-set-files
			   ange-ftp-this-file
			   (if (setq
				parse-func
				(cdr (assq host-type
					   ange-ftp-parse-list-func-alist)))
			       (funcall parse-func)
			     (ange-ftp-parse-dired-listing lsargs))))
                      ;; Place this hook here to convert the contents of the
                      ;; buffer to a ls compatible format if the host system
                      ;; that is being queried is other than Unix i.e. VMS
                      ;; returns an ls format that really sucks.
                      (run-hooks 'ange-ftp-after-parse-ls-hook)
		      (setq ange-ftp-ls-cache-file key
			    ange-ftp-ls-cache-lsargs lsargs
					; For dumb hosts-types this is
					; meaningless but harmless.
			    ange-ftp-ls-cache-res (buffer-string))
		      ;; (kill-buffer (current-buffer))
		      (if (equal ange-ftp-ls-cache-res "total 0\n")
			  ;; wu-ftpd seems to return a successful result
			  ;; with an empty file-listing when doing a
			  ;; `DIR /some/file/.' which leads ange-ftp to
			  ;; believe that /some/file is a directory ;-(
			  nil
			ange-ftp-ls-cache-res))
		  (if no-error
		      nil
		    (ange-ftp-error host user
				    (concat "DIR failed: " (cdr result)))))
	      (ange-ftp-del-tmp-name temp))))
      (error "Should never happen. Please report. Bug ref. no.: 1"))))
\f
;;;; ------------------------------------------------------------
;;;; Directory information caching support.
;;;; ------------------------------------------------------------

(defvar ange-ftp-add-file-entry-alist nil
  "Alist saying how to add file entries on certain OS types.
Association list of pairs (TYPE . FUNC), where FUNC is a function
to be used to add a file entry for the OS TYPE.
The main reason for this alist is to deal with file versions in VMS.")

(defvar ange-ftp-delete-file-entry-alist nil
  "Alist saying how to delete files on certain OS types.
Association list of pairs (TYPE . FUNC), where FUNC is a function
to be used to delete a file entry for the OS TYPE.
The main reason for this alist is to deal with file versions in VMS.")

(defun ange-ftp-add-file-entry (name &optional dir-p)
  "Add a file entry for file NAME, if its directory info exists."
  (funcall (or (cdr (assq (ange-ftp-host-type
			   (car (ange-ftp-ftp-name name)))
			  ange-ftp-add-file-entry-alist))
	       'ange-ftp-internal-add-file-entry)
	   name dir-p)
  (setq ange-ftp-ls-cache-file nil))

(defun ange-ftp-delete-file-entry (name &optional dir-p)
  "Delete the file entry for file NAME, if its directory info exists."
  (funcall (or (cdr (assq (ange-ftp-host-type
			   (car (ange-ftp-ftp-name name)))
			  ange-ftp-delete-file-entry-alist))
	       'ange-ftp-internal-delete-file-entry)
	   name dir-p)
  (setq ange-ftp-ls-cache-file nil))

(defmacro ange-ftp-parse-filename ()
  ;;Extract the filename from the current line of a dired-like listing.
  `(save-match-data
     (let ((eol (progn (end-of-line) (point))))
       (beginning-of-line)
       (if (re-search-forward directory-listing-before-filename-regexp eol t)
	   (buffer-substring (point) eol)))))

;; This deals with the F switch. Should also do something about
;; unquoting names obtained with the SysV b switch and the GNU Q
;; switch. See Sebastian's dired-get-filename.

(defun ange-ftp-ls-parser (switches)
  ;; Meant to be called by ange-ftp-parse-dired-listing
  (let ((tbl (make-hash-table :test 'equal))
	(used-F (and (stringp switches)
		     (string-match "F" switches)))
	file-type symlink directory file)
    (while (setq file (ange-ftp-parse-filename))
      (beginning-of-line)
      (skip-chars-forward "\t 0-9")
      (setq file-type (following-char)
	    directory (eq file-type ?d))
      (if (eq file-type ?l)
	  (let ((end (string-match " -> " file)))
	    (if end
		;; Sometimes `ls' appends a @ at the end of the target.
		(setq symlink (substring file (match-end 0)
					 (string-match "@\\'" file))
		      file (substring file 0 end))
	      ;; Shouldn't happen
	      (setq symlink "")))
	(setq symlink nil))
      ;; Only do a costly regexp search if the F switch was used.
      (if (and used-F
	       (not (string-equal file ""))
	       (looking-at
		".[-r][-w]\\([^ ]\\)[-r][-w]\\([^ ]\\)[-r][-w]\\([^ ]\\)"))
	  (let ((socket (eq file-type ?s))
		(executable
		 (and (not symlink) ; x bits don't mean a thing for symlinks
		      (string-match
		       "[xst]"
		       (concat (match-string 1)
			       (match-string 2)
			       (match-string 3))))))
	    ;; Some ls's with the F switch mark symlinks with an @ (ULTRIX)
	    ;; and others don't. (sigh...) Beware, that some Unix's don't
	    ;; seem to believe in the F-switch
	    (if (or (and symlink (string-match "@\\'" file))
		    (and directory (string-match "/\\'" file))
		    (and executable (string-match "*\\'" file))
		    (and socket (string-match "=\\'" file)))
		(setq file (substring file 0 -1)))))
      (puthash file (or symlink directory) tbl)
      (forward-line 1))
    (puthash "." t tbl)
    (puthash ".." t tbl)
    tbl))

;;; The dl stuff for descriptive listings

(defvar ange-ftp-dl-dir-regexp nil
  "Regexp matching directories which are listed in dl format.
This regexp should not be anchored with a trailing `$', because it should
match subdirectories as well.")

(defun ange-ftp-add-dl-dir (dir)
  "Interactively add a DIR to `ange-ftp-dl-dir-regexp'."
  (interactive
   (list (read-string "Directory: "
		      (let ((name (or (buffer-file-name) default-directory)))
			(and name (ange-ftp-ftp-name name)
			     (file-name-directory name))))))
  (if (not (and ange-ftp-dl-dir-regexp
		(string-match ange-ftp-dl-dir-regexp dir)))
      (setq ange-ftp-dl-dir-regexp
	    (concat "^" (regexp-quote dir)
		    (and ange-ftp-dl-dir-regexp "\\|")
		    ange-ftp-dl-dir-regexp))))

(defmacro ange-ftp-dl-parser ()
  ;; Parse the current buffer, which is assumed to be a descriptive
  ;; listing, and return a hashtable.
  `(let ((tbl (make-hash-table :test 'equal)))
     (while (not (eobp))
       (puthash
        (buffer-substring (point)
                          (progn
                            (skip-chars-forward "^ /\n")
                            (point)))
        (eq (following-char) ?/)
        tbl)
       (forward-line 1))
     (puthash "." t tbl)
     (puthash ".." t tbl)
     tbl))

;; Parse the current buffer which is assumed to be in a dired-like listing
;; format, and return a hashtable as the result. If the listing is not really
;; a listing, then return nil.

(defun ange-ftp-parse-dired-listing (&optional switches)
  (save-match-data
    (cond
     ((looking-at "^total [0-9]+$")
      (forward-line 1)
      ;; Some systems put in a blank line here.
      (if (eolp) (forward-line 1))
      (ange-ftp-ls-parser switches))
     ((looking-at "[^\n]+\\( not found\\|: Not a directory\\)\n\\'")
      ;; It's an ls error message.
      nil)
     ((eobp) ; i.e. (zerop (buffer-size))
      ;; This could be one of:
      ;; (1) An Ultrix ls error message
      ;; (2) A listing with the A switch of an empty directory
      ;;     on a machine which doesn't give a total line.
      ;; (3) The twilight zone.
      ;; We'll assume (1) for now.
      nil)
     ((re-search-forward directory-listing-before-filename-regexp nil t)
      (beginning-of-line)
      (ange-ftp-ls-parser switches))
     ((re-search-forward "^[^ \n\t]+ +\\([0-9]+\\|-\\|=\\) " nil t)
      ;; It's a dl listing (I hope).
      ;; file is bound by the call to ange-ftp-ls
      (ange-ftp-add-dl-dir ange-ftp-this-file)
      (beginning-of-line)
      (ange-ftp-dl-parser))
     (t nil))))

(defun ange-ftp-set-files (directory files)
  "For a given DIRECTORY, set or change the associated FILES hashtable."
  (and files (puthash (file-name-as-directory directory)
		      files ange-ftp-files-hashtable)))

(defun ange-ftp-switches-ok (switches)
  "Return SWITCHES (a string) if suitable for use with ls over ftp."
  (and (stringp switches)
       ;; We allow the --almost-all switch, which lists all files
       ;; except "." and "..".  This is OK because we manually
       ;; insert these entries in the hash table.
       (string-match
        "--\\(almost-\\)?all\\>\\|\\(\\`\\| \\)-[[:alpha:]]*[aA]"
        switches)
       ;; Disallow other long flags except --(almost-)all.
       (not (string-match "\\(\\`\\| \\)--\\w+"
                          (replace-regexp-in-string
                           "--\\(almost-\\)?all\\>" ""
                           switches)))
       ;; Must include 'l'.
       (string-match "\\(\\`\\| \\)-[[:alpha:]]*l" switches)
       ;; Disallow recursive flag.
       (not (string-match
             "\\(\\`\\| \\)-[[:alpha:]]*R" switches))
       switches))

(defun ange-ftp-get-files (directory &optional no-error)
  "Given a DIRECTORY, return a hashtable of file entries.
This will give an error or return nil, depending on the value of
NO-ERROR, if a listing for DIRECTORY cannot be obtained."
  (setq directory (file-name-as-directory directory)) ;normalize
  (or (gethash directory ange-ftp-files-hashtable)
      (save-match-data
	(and (ange-ftp-ls directory
			  ;; This is an efficiency hack. We try to
			  ;; anticipate what sort of listing dired
			  ;; might want, and cache just such a listing.
			  (or (and (boundp 'dired-actual-switches)
				   (ange-ftp-switches-ok dired-actual-switches))
			      (and (boundp 'dired-listing-switches)
				   (ange-ftp-switches-ok
				    dired-listing-switches))
			      "-al")
			  t no-error)
	     (gethash directory ange-ftp-files-hashtable)))))

;; Given NAME, return the file part that can be used for looking up the
;; file's entry in a hashtable.
(defmacro ange-ftp-get-file-part (name)
  `(let ((file (file-name-nondirectory ,name)))
     (if (string-equal file "")
	 "."
       file)))

;; Return whether ange-ftp-file-entry-p and ange-ftp-get-file-entry are
;; allowed to determine if NAME is a sub-directory by listing it directly,
;; rather than listing its parent directory. This is used for efficiency so
;; that a wasted listing is not done:
;; 1. When looking for a .dired file in dired-x.el.
;; 2. The syntax of FILE and DIR make it impossible that FILE could be a valid
;;     subdirectory. This is of course an OS dependent judgment.

(defvar dired-local-variables-file)
(defmacro ange-ftp-allow-child-lookup (dir file)
  `(not
    (let* ((efile ,file)		; expand once.
           (edir ,dir)
           (parsed (ange-ftp-ftp-name edir))
           (host-type (ange-ftp-host-type
                       (car parsed))))
      (or
       ;; Deal with dired
       (and (boundp 'dired-local-variables-file) ; in the dired-x package
	    (stringp dired-local-variables-file)
	    (string-equal dired-local-variables-file efile))
       ;; No dots in dir names in vms.
       (and (eq host-type 'vms)
	    (string-match "\\." efile))
       ;; No subdirs in mts of cms.
       (and (memq host-type '(mts cms))
	    (not (string-equal "/" (nth 2 parsed))))
       ;; No dots in pseudo-dir names in bs2000.
       (and (eq host-type 'bs2000)
	    (string-match "\\." efile))))))

(defun ange-ftp-file-entry-p (name)
  "Given NAME, return whether there is a file entry for it."
  (let* ((name (directory-file-name name))
	 (dir (file-name-directory name))
	 (ent (gethash dir ange-ftp-files-hashtable))
	 (file (ange-ftp-get-file-part name)))
    (if ent
	(ange-ftp-hash-entry-exists-p file ent)
      (or (and (ange-ftp-allow-child-lookup dir file)
	       (setq ent (ange-ftp-get-files name t))
	       ;; Try a child lookup. i.e. try to list file as a
	       ;; subdirectory of dir. This is a good idea because
	       ;; we may not have read permission for file's parent. Also,
	       ;; people tend to work down directory trees anyway. We use
	       ;; no-error ;; because if file does not exist as a subdir.,
	       ;; then dumb hosts will give an ftp error. Smart unix hosts
	       ;; will simply send back the ls
	       ;; error message.
	       (gethash "." ent))
	  ;; Child lookup failed, so try the parent.
	  (ange-ftp-hash-entry-exists-p
	   file (ange-ftp-get-files dir 'no-error))))))

(defun ange-ftp-get-file-entry (name)
  "Given NAME, return the given file entry.
The entry will be either t for a directory, nil for a normal file,
or a string for a symlink.  If the file isn't in the hashtable,
this also returns nil."
  (let* ((name (directory-file-name name))
	 (dir (file-name-directory name))
	 (ent (gethash dir ange-ftp-files-hashtable))
	 (file (ange-ftp-get-file-part name)))
    (if ent
	(gethash file ent)
      (or (and (ange-ftp-allow-child-lookup dir file)
	       (setq ent (ange-ftp-get-files name t))
	       (gethash "." ent))
	  ;; i.e. it's a directory by child lookup
	  (and (setq ent (ange-ftp-get-files dir t))
	       (gethash file ent))))))

(defun ange-ftp-internal-delete-file-entry (name &optional dir-p)
  (when dir-p
    (setq name (file-name-as-directory name))
    (remhash name ange-ftp-files-hashtable)
    (setq name (directory-file-name name)))
  ;; Note that file-name-as-directory followed by directory-file-name
  ;; serves to canonicalize directory file names to their unix form.
  ;; i.e. in VMS, FOO.DIR -> FOO/ -> FOO
  (let ((files (gethash (file-name-directory name) ange-ftp-files-hashtable)))
    (if files
	(remhash (ange-ftp-get-file-part name) files))))

(defun ange-ftp-internal-add-file-entry (name &optional dir-p)
  (and dir-p
       (setq name (directory-file-name name)))
  (let ((files (gethash (file-name-directory name) ange-ftp-files-hashtable)))
    (if files
	(puthash (ange-ftp-get-file-part name) dir-p files))))

(defun ange-ftp-wipe-file-entries (host user)
  "Get rid of entry for HOST, USER pair from file entry information hashtable."
  (let ((new-tbl (make-hash-table :test 'equal
				  :size (hash-table-size
					 ange-ftp-files-hashtable))))
    (maphash
     (lambda (key val)
       (let ((parsed (ange-ftp-ftp-name key)))
         (if parsed
             (let ((h (nth 0 parsed))
                   (u (nth 1 parsed)))
               (or (and (equal host h) (equal user u))
                   (puthash key val new-tbl))))))
     ange-ftp-files-hashtable)
    (setq ange-ftp-files-hashtable new-tbl)))
\f
;;;; ------------------------------------------------------------
;;;; File transfer mode support.
;;;; ------------------------------------------------------------

(defun ange-ftp-set-binary-mode (host user)
  "Tell the FTP process for the given HOST & USER to switch to binary mode."
  ;; FIXME: We should keep track of the current mode, so as to avoid
  ;; unnecessary roundtrips.
  (let ((result (ange-ftp-send-cmd host user '(type "binary"))))
    (if (not (car result))
	(ange-ftp-error host user (concat "BINARY failed: " (cdr result)))
      (with-current-buffer (process-buffer (ange-ftp-get-process host user))
	(and ange-ftp-binary-hash-mark-size
	     (setq ange-ftp-hash-mark-unit
		   (ash ange-ftp-binary-hash-mark-size -4)))))))

(defun ange-ftp-set-ascii-mode (host user)
  "Tell the FTP process for the given HOST & USER to switch to ASCII mode."
  ;; FIXME: We should keep track of the current mode, so as to avoid
  ;; unnecessary roundtrips.
  (let ((result (ange-ftp-send-cmd host user '(type "ascii"))))
    (if (not (car result))
	(ange-ftp-error host user (concat "ASCII failed: " (cdr result)))
      (with-current-buffer (process-buffer (ange-ftp-get-process host user))
	(and ange-ftp-ascii-hash-mark-size
	     (setq ange-ftp-hash-mark-unit
		   (ash ange-ftp-ascii-hash-mark-size -4)))))))
\f
(defun ange-ftp-cd (host user dir &optional noerror)
  (let ((result (ange-ftp-send-cmd host user (list 'cd dir) "Doing CD")))
    (if noerror result
      (or (car result)
	  (ange-ftp-error host user (concat "CD failed: " (cdr result)))))))

(defun ange-ftp-get-pwd (host user)
  "Attempt to get the current working directory for the given HOST/USER pair.
Returns (DIR . LINE) where DIR is either the directory or nil if not found,
and LINE is the relevant success or fail line from the FTP-client."
  (let* ((result (ange-ftp-send-cmd host user '(pwd) "Getting PWD"))
	 (line (cdr result))
	 dir)
    (if (car result)
	(save-match-data
	  (and (or (string-match "\"\\([^\"]*\\)\"" line)
		   ;; Some clients cache the value and return it in
		   ;; this way without asking the server.  (Bug#15058)
		   (string-match "^Remote directory: \\(.*\\)" line)
		   (string-match " \\([^ ]+\\) " line))	; stone-age VMS servers!
	       (setq dir (match-string 1 line)))))
    (cons dir line)))
\f
;;; ------------------------------------------------------------
;;; expand-file-name and friends...which currently don't work
;;; ------------------------------------------------------------

(defun ange-ftp-expand-dir (host user dir)
  "Return the result of doing a PWD in the current FTP session.
Use the connection to machine HOST
logged in as user USER and cd'd to directory DIR."
  (let* ((host-type (ange-ftp-host-type host user))
	 ;; It is more efficient to call ange-ftp-host-type
	 ;; before binding res, because ange-ftp-host-type sometimes
	 ;; adds to the info in the expand-dir-hashtable.
	 (fix-name-func
	  (cdr (assq host-type ange-ftp-fix-name-func-alist)))
	 (key (concat host "/" user "/" dir))
	 (res (gethash key ange-ftp-expand-dir-hashtable)))
    (or res
	(progn
	  (or
	   (string-equal user "anonymous")
	   (string-equal user "ftp")
	   (not (eq host-type 'unix))
	   (let* ((ange-ftp-good-msgs (concat ange-ftp-expand-dir-regexp
					      "\\|"
					      ange-ftp-good-msgs))
		  (result (ange-ftp-send-cmd host user
					     (list 'get dir null-device)
					     (format "expanding %s" dir)))
		  (line (cdr result)))
	     (setq res
		   (if (string-match ange-ftp-expand-dir-regexp line)
		       (match-string 1 line)))))
	  (or res
	      (if (string-equal dir "~")
		  (setq res (car (ange-ftp-get-pwd host user)))
		(let ((home (ange-ftp-expand-dir host user "~")))
		  (unwind-protect
		      (and (ange-ftp-cd host user dir)
			   (setq res (car (ange-ftp-get-pwd host user))))
		    (ange-ftp-cd host user home)))))
	  (if res
	      (let ((ange-ftp-this-user user)
		    (ange-ftp-this-host host))
		(if fix-name-func
		    (setq res (funcall fix-name-func res 'reverse)))
		(puthash key res ange-ftp-expand-dir-hashtable)))
	  res))))

(defun ange-ftp-canonize-filename (n)
  "Take a string N and short-circuit //, /. and /.."
  (if (string-match "[^:]+//" n)		;don't upset Apollo users
      (setq n (substring n (1- (match-end 0)))))
  (let ((parsed (ange-ftp-ftp-name n)))
    (if parsed
	(let ((host (car parsed))
	      (user (nth 1 parsed))
	      (name (nth 2 parsed)))

	  ;; See if remote name is absolute.  If so then just expand it and
	  ;; replace the name component of the overall name.
	  (cond ((string-match "\\`/" name)
		 name)

		;; Name starts with ~ or ~user.  Resolve that part of the name
		;; making it absolute then re-expand it.
		((string-match "\\`~[^/]*" name)
		 (let* ((tilda (match-string 0 name))
			(rest (substring name (match-end 0)))
			(dir (ange-ftp-expand-dir host user tilda)))
		   (if dir
                       ;; C-x d /ftp:anonymous@ftp.gnu.org:~/ RET
                       ;; seems to cause `rest' to sometimes be empty.
                       ;; Maybe it's an error for `rest' to be empty here,
                       ;; but until we figure this out, this quick fix
                       ;; seems to do the trick.
		       (setq name (cond ((string-equal rest "") dir)
					((string-equal dir "/") rest)
					(t (concat dir rest))))
		     (error "User \"%s\" is not known"
			    (substring tilda 1)))))

		;; relative name.  Tack on homedir and re-expand.
		(t
		 (let ((dir (ange-ftp-expand-dir host user "~")))
		   (if dir
		       (setq name (concat
				   (ange-ftp-real-file-name-as-directory dir)
				   name))
		     (error "Unable to obtain CWD")))))

	  ;; If name starts with //, preserve that, for apollo system.
	  (unless (string-match "\\`//" name)
            (if (not (eq system-type 'windows-nt))
                (setq name (ange-ftp-real-expand-file-name name))
              ;; Windows UNC default dirs do not make sense for ftp.
              (setq name (if (and default-directory
				  (string-match "\\`//" default-directory))
                             (ange-ftp-real-expand-file-name name "c:/")
                           (ange-ftp-real-expand-file-name name)))
              ;; Strip off possible drive specifier.
              (if (string-match "\\`[a-zA-Z]:" name)
                  (setq name (substring name 2))))
            (if (string-match "\\`//" name)
                (setq name (substring name 1))))

	  ;; Now substitute the expanded name back into the overall filename.
	  (ange-ftp-replace-name-component n name))

      ;; non-ange-ftp name.  Just expand normally.
      (if (eq (string-to-char n) ?/)
	  (ange-ftp-real-expand-file-name n)
	(ange-ftp-real-expand-file-name
	 (ange-ftp-real-file-name-nondirectory n)
	 (ange-ftp-real-file-name-directory n))))))

(defun ange-ftp-expand-file-name (name &optional default)
  "Documented as `expand-file-name'."
  (save-match-data
    (setq default (or default default-directory))
    (cond
     ((ange-ftp-ftp-name name)
      ;; `default' is irrelevant.
      (ange-ftp-canonize-filename name))
     ((file-name-absolute-p name)
      ;; `name' is absolute but is not an ange-ftp name => not ange-ftp.
      (ange-ftp-real-expand-file-name name "/"))
     ((ange-ftp-canonize-filename
       (concat (file-name-as-directory default) name))))))
\f
;;; These are problems--they are currently not enabled.

(defvar ange-ftp-file-name-as-directory-alist nil
  "Association list of (TYPE . FUNC) pairs.
FUNC converts a filename to a directory name for the operating
system TYPE.")

(defun ange-ftp-file-name-as-directory (name)
  "Documented as `file-name-as-directory'."
  (let ((parsed (ange-ftp-ftp-name name)))
    (if parsed
	(if (string-equal (nth 2 parsed) "")
	    name
	  (funcall (or (cdr (assq
			     (ange-ftp-host-type (car parsed))
			     ange-ftp-file-name-as-directory-alist))
		       'ange-ftp-real-file-name-as-directory)
		   name))
      (ange-ftp-real-file-name-as-directory name))))

(defun ange-ftp-file-name-directory (name)
  "Documented as `file-name-directory'."
  (let ((parsed (ange-ftp-ftp-name name)))
    (if parsed
	(let ((filename (nth 2 parsed)))
	  (if (string-match-p "\\`~[^/]*\\'" filename)
	      name
	    (ange-ftp-replace-name-component
	     name
	     (ange-ftp-real-file-name-directory filename))))
      (ange-ftp-real-file-name-directory name))))

(defun ange-ftp-file-name-nondirectory (name)
  "Documented as `file-name-nondirectory'."
  (let ((parsed (ange-ftp-ftp-name name)))
    (if parsed
	(let ((filename (nth 2 parsed)))
	  (if (string-match-p "\\`~[^/]*\\'" filename)
	      ""
	    (ange-ftp-real-file-name-nondirectory filename)))
      (ange-ftp-real-file-name-nondirectory name))))

(defun ange-ftp-directory-file-name (dir)
  "Documented as `directory-file-name'."
  (let ((parsed (ange-ftp-ftp-name dir)))
    (if parsed
	(ange-ftp-replace-name-component
	 dir
	 (ange-ftp-real-directory-file-name (nth 2 parsed)))
      (ange-ftp-real-directory-file-name dir))))

\f
;;; Hooks that handle Emacs primitives.

;; Returns non-nil if should transfer FILE in binary mode.
(defun ange-ftp-binary-file (file)
  (string-match-p ange-ftp-binary-file-name-regexp file))

(defun ange-ftp-write-region
    (start end filename &optional append visit _lockname mustbenew)
  (setq filename (expand-file-name filename))
  (when mustbenew
    (ange-ftp-barf-or-query-if-file-exists
     filename "overwrite" (not (eq mustbenew 'excl))))
  (let ((parsed (ange-ftp-ftp-name filename)))
    (if parsed
	(let* ((host (nth 0 parsed))
	       (user (nth 1 parsed))
	       (name (ange-ftp-quote-string (nth 2 parsed)))
	       (temp (ange-ftp-make-tmp-name host))
	       ;; What we REALLY need here is a way to determine if the mode
	       ;; of the transfer is irrelevant, i.e. we can use binary mode
	       ;; regardless. Maybe a system-type to host-type lookup?
	       (binary (ange-ftp-binary-file filename))
	       (cmd (if append 'append 'put))
	       (abbr (ange-ftp-abbreviate-filename filename))
	       ;; we need to reset `last-coding-system-used' to its
	       ;; value immediately after calling the real write-region,
	       ;; so that `basic-save-buffer' doesn't see whatever value
	       ;; might be used when communicating with the ftp process.
	       (coding-system-used last-coding-system-used))
	  (unwind-protect
	      (progn
		(let ((filename (buffer-file-name))
		      (mod-p (buffer-modified-p)))
		  (unwind-protect
		      (progn
			(ange-ftp-real-write-region start end temp nil
						    (or visit 'quiet))
			(setq coding-system-used last-coding-system-used))
		    ;; cleanup forms
		    (setq coding-system-used last-coding-system-used)
		    (setq buffer-file-name filename)
		    (restore-buffer-modified-p mod-p)))
		(if binary
		    (ange-ftp-set-binary-mode host user))

		;; tell the process filter what size the transfer will be.
		(let ((attr (file-attributes temp)))
		  (if attr
		      (ange-ftp-set-xfer-size host user (nth 7 attr))))

		;; put or append the file.
		(let ((result (ange-ftp-send-cmd host user
						 (list cmd temp name)
						 (format "Writing %s" abbr))))
		  (or (car result)
		      (signal 'ftp-error
			      (list
			       "Opening output file"
			       (format "FTP Error: \"%s\"" (cdr result))
			       filename)))))
	    (ange-ftp-del-tmp-name temp)
	    (if binary
		(ange-ftp-set-ascii-mode host user)))
	  (if (eq visit t)
	      (progn
		(set-visited-file-modtime (ange-ftp-file-modtime filename))
		(ange-ftp-set-buffer-mode)
		(setq buffer-file-name filename)
		(set-buffer-modified-p nil)))
	  ;; ensure `last-coding-system-used' has an appropriate value
	  (setq last-coding-system-used coding-system-used)
	  (ange-ftp-message "Wrote %s" abbr)
	  (ange-ftp-add-file-entry filename))
      (ange-ftp-real-write-region start end filename append visit))))

(defun ange-ftp-insert-file-contents (filename &optional visit beg end replace)
  (barf-if-buffer-read-only)
  (setq filename (expand-file-name filename))
  (let ((parsed (ange-ftp-ftp-name filename)))
    (if parsed
	(progn
	  (if visit
	      (setq buffer-file-name filename))
	  (if (or (file-exists-p filename)
		  (progn
		    (setq ange-ftp-ls-cache-file nil)
		    (remhash (file-name-directory filename)
			     ange-ftp-files-hashtable)
		    (file-exists-p filename)))
	      (let* ((host (nth 0 parsed))
		     (user (nth 1 parsed))
		     (name (ange-ftp-quote-string (nth 2 parsed)))
		     (temp (ange-ftp-make-tmp-name host))
		     (binary (ange-ftp-binary-file filename))
		     (abbr (ange-ftp-abbreviate-filename filename))
		     (coding-system-used last-coding-system-used)
		     size)
		(unwind-protect
		    (progn
		      (if binary
			  (ange-ftp-set-binary-mode host user))
		      (let ((result (ange-ftp-send-cmd host user
					      (list 'get name temp)
					      (format "Retrieving %s" abbr))))
			(or (car result)
			    (signal 'ftp-error
				    (list
				     "Opening input file"
				     (format "FTP Error: \"%s\"" (cdr result))
				     filename))))
		      (if (or (ange-ftp-real-file-readable-p temp)
			      (sleep-for ange-ftp-retry-time)
			      ;; Wait for file to hopefully appear.
			      (ange-ftp-real-file-readable-p temp))
			  (setq
			   size
			   (nth 1 (ange-ftp-real-insert-file-contents
				   temp visit beg end replace))
			   coding-system-used last-coding-system-used)
			(signal 'ftp-error
				(list
				 "Opening input file:"
				 (format
				  "FTP Error: %s not arrived or readable"
				  filename)))))
		  (if binary
		      ;; We must keep `last-coding-system-used'
		      ;; unchanged.
		      (let (last-coding-system-used)
			(ange-ftp-set-ascii-mode host user)))
		  (ange-ftp-del-tmp-name temp))
		(if visit
		    (progn
		      (set-visited-file-modtime
                       (ange-ftp-file-modtime filename))
		      (setq buffer-file-name filename)))
		(setq last-coding-system-used coding-system-used)
		(list filename size))
	    (signal 'file-missing
		    (list
		     "Opening input file"
		     "No such file or directory"
		     filename))))
      (ange-ftp-real-insert-file-contents filename visit beg end replace))))

(defun ange-ftp-expand-symlink (file dir)
  (let ((res (if (file-name-absolute-p file)
		 (ange-ftp-replace-name-component dir file)
	       (expand-file-name file dir))))
    (if (file-symlink-p res)
	(ange-ftp-expand-symlink
	 (ange-ftp-get-file-entry res)
	 (file-name-directory (directory-file-name res)))
      res)))

(defun ange-ftp-file-symlink-p (file)
  ;; call ange-ftp-expand-file-name rather than the normal
  ;; expand-file-name to stop loops when using a package that
  ;; redefines both file-symlink-p and expand-file-name.
  (setq file (ange-ftp-expand-file-name file))
  (if (ange-ftp-ftp-name file)
      (condition-case nil
	  (let ((ent (ange-ftp-get-files (file-name-directory file))))
	    (and ent
		 (stringp (setq ent
				(gethash (ange-ftp-get-file-part file) ent)))
		 ent))
	;; If we can't read the parent directory, just assume
	;; this file is not a symlink.
	;; This makes it possible to access a directory that
	;; whose parent is not readable.
	(file-error nil))
    (ange-ftp-real-file-symlink-p file)))

(defun ange-ftp-file-regular-p (file)
  ;; Reuse Tramp's implementation.
  (if (ange-ftp-ftp-name file)
      (and (file-exists-p file)
       (eq ?- (aref (file-attribute-modes (file-attributes file)) 0)))
    (ange-ftp-real-file-regular-p file)))

(defun ange-ftp-file-exists-p (name)
  (setq name (expand-file-name name))
  (if (ange-ftp-ftp-name name)
      (if (ange-ftp-file-entry-p name)
	  (let ((file-ent (ange-ftp-get-file-entry name)))
	    (if (stringp file-ent)
		(ange-ftp-file-exists-p
		 (ange-ftp-expand-symlink file-ent
					  (file-name-directory
					   (directory-file-name name))))
	      t)))
    (ange-ftp-real-file-exists-p name)))

(defun ange-ftp-file-directory-p (name)
  (setq name (expand-file-name name))
  (if (ange-ftp-ftp-name name)
      ;; We do a file-name-as-directory on name here because some
      ;; machines (VMS) use a .DIR to indicate the filename associated
      ;; with a directory. This needs to be canonicalized.
      (let ((file-ent (ange-ftp-get-file-entry
		       (ange-ftp-file-name-as-directory name))))
	(if (stringp file-ent)
	    ;; Calling file-directory-p doesn't work because ange-ftp
	    ;; is temporarily disabled for this operation.
	    (ange-ftp-file-directory-p
	     (ange-ftp-expand-symlink file-ent
				      (file-name-directory
				       (directory-file-name name))))
	  file-ent))
    (ange-ftp-real-file-directory-p name)))

(defun ange-ftp-directory-files (directory &optional full match
					   &rest v19-args)
  (setq directory (expand-file-name directory))
  (if (ange-ftp-ftp-name directory)
      (progn
	(ange-ftp-barf-if-not-directory directory)
	(let ((tail (ange-ftp-hash-table-keys
		     (ange-ftp-get-files directory)))
	      files f)
	  (setq directory (file-name-as-directory directory))
	  (while tail
	    (setq f (car tail)
		  tail (cdr tail))
	    (if (or (not match) (string-match-p match f))
		(setq files
		      (cons (if full (concat directory f) f) files))))
	  (nreverse files)))
    (apply 'ange-ftp-real-directory-files directory full match v19-args)))

(defun ange-ftp-directory-files-and-attributes
  (directory &optional full match nosort id-format)
  (setq directory (expand-file-name directory))
  (if (ange-ftp-ftp-name directory)
      (mapcar
       (lambda (file)
	 (cons file (file-attributes (expand-file-name file directory))))
       (ange-ftp-directory-files directory full match nosort))
    (ange-ftp-real-directory-files-and-attributes
     directory full match nosort id-format)))

(defun ange-ftp-file-attributes (file &optional id-format)
  (setq file (expand-file-name file))
  (let ((parsed (ange-ftp-ftp-name file)))
    (if parsed
	(let ((part (ange-ftp-get-file-part file))
	      (files (ange-ftp-get-files (file-name-directory file))))
	  (if (ange-ftp-hash-entry-exists-p part files)
	      (let ((host (nth 0 parsed))
		    (user (nth 1 parsed))
		    (name (nth 2 parsed))
		    (dirp (gethash part files))
		    (inode (gethash file ange-ftp-inodes-hashtable)))
		(unless inode
		  (setq inode ange-ftp-next-inode-number
			ange-ftp-next-inode-number (1+ inode))
		  (puthash file inode ange-ftp-inodes-hashtable))
		(list (if (and (stringp dirp) (file-name-absolute-p dirp))
			  (ange-ftp-expand-symlink dirp
						   (file-name-directory file))
			dirp)		;0 file type
		      -1		;1 link count
		      -1		;2 uid
		      -1		;3 gid
		      '(0 0)		;4 atime
		      (ange-ftp-file-modtime file) ;5 mtime
		      '(0 0)		;6 ctime
		      (ange-ftp-file-size file)	;7 size
		      (concat (if (stringp dirp) "l" (if dirp "d" "-"))
			      "?????????") ;8 mode
		      nil		;9 gid weird
		      inode		;10 "inode number".
		      -1		;11 device number [v19 only]
		      ))))
      (if id-format
	  (ange-ftp-real-file-attributes file id-format)
	(ange-ftp-real-file-attributes file)))))

(defun ange-ftp-file-newer-than-file-p (f1 f2)
  (let ((f1-parsed (ange-ftp-ftp-name f1))
        (f2-parsed (ange-ftp-ftp-name f2)))
    (if (or f1-parsed f2-parsed)
        (let ((f1-mt (nth 5 (file-attributes f1)))
              (f2-mt (nth 5 (file-attributes f2))))
          (cond ((null f1-mt) nil)
                ((null f2-mt) t)
		(t (time-less-p f2-mt f1-mt))))
      (ange-ftp-real-file-newer-than-file-p f1 f2))))

(defun ange-ftp-file-writable-p (file)
  (let ((ange-ftp-process-verbose nil))
    (setq file (expand-file-name file))
    (if (ange-ftp-ftp-name file)
	(or (file-exists-p file)	;guess here for speed
	    (file-directory-p (file-name-directory file)))
      (ange-ftp-real-file-writable-p file))))

(defun ange-ftp-file-readable-p (file)
  (let ((ange-ftp-process-verbose nil))
    (setq file (expand-file-name file))
    (if (ange-ftp-ftp-name file)
	(file-exists-p file)
      (ange-ftp-real-file-readable-p file))))

(defun ange-ftp-file-executable-p (file)
  (let ((ange-ftp-process-verbose nil))
    (setq file (expand-file-name file))
    (if (ange-ftp-ftp-name file)
	(file-exists-p file)
      (ange-ftp-real-file-executable-p file))))

(defun ange-ftp-delete-file (file &optional trash)
  (interactive (list (read-file-name "Delete file: " nil default-directory)
		     (null current-prefix-arg)))
  (setq file (expand-file-name file))
  (let ((parsed (ange-ftp-ftp-name file)))
    (if parsed
	(let* ((host (nth 0 parsed))
	       (user (nth 1 parsed))
	       (name (ange-ftp-quote-string (nth 2 parsed)))
	       (abbr (ange-ftp-abbreviate-filename file))
	       (result (ange-ftp-send-cmd host user
					  (list 'delete name)
					  (format "Deleting %s" abbr))))
	  (or (car result)
	      (signal 'ftp-error
		      (list
		       "Removing old name"
		       (format "FTP Error: \"%s\"" (cdr result))
		       file)))
	  (ange-ftp-delete-file-entry file))
      (ange-ftp-real-delete-file file trash))))

(defun ange-ftp-file-modtime (file)
  "Return the modification time of remote file FILE.
Value is (0 0) if the modification time cannot be determined."
  (let* ((parsed (ange-ftp-ftp-name file))
	 ;; At least one FTP server (wu-ftpd) can return a "226
	 ;; Transfer complete" before the "213 MODTIME".  Let's skip
	 ;; that.
	 (ange-ftp-skip-msgs (concat ange-ftp-skip-msgs "\\|^226"))
         (res (ange-ftp-send-cmd (car parsed) (cadr parsed)
                                 (list 'quote "mdtm" (cadr (cdr parsed)))))
	 (line (cdr res))
	 (modtime '(0 0)))
    ;; MDTM should return "213 YYYYMMDDhhmmss" GMT on success
    ;; following the Internet draft for FTP extensions.
    ;; Bob@rattlesnake.com reports that is returns something different
    ;; for at least one FTP server.  So, let's use the response only
    ;; if it matches the Internet draft.
    (when (string-match-p "^213 [0-9]\\{14\\}$" line)
      (setq modtime
	    (encode-time
	     (string-to-number (substring line 16 18))
	     (string-to-number (substring line 14 16))
	     (string-to-number (substring line 12 14))
	     (string-to-number (substring line 10 12))
	     (string-to-number (substring line  8 10))
	     (string-to-number (substring line  4  8))
	     0)))
    modtime))

(defun ange-ftp-verify-visited-file-modtime (buf)
  (let ((name (buffer-file-name buf)))
    (if (and (stringp name) (ange-ftp-ftp-name name))
        (let ((file-mdtm (ange-ftp-file-modtime name))
              (buf-mdtm (with-current-buffer buf (visited-file-modtime))))
          (or (zerop (car file-mdtm))
	      (not (time-less-p buf-mdtm file-mdtm))))
      (ange-ftp-real-verify-visited-file-modtime buf))))

(defun ange-ftp-file-size (file &optional ascii-mode)
  "Return the size of remote file FILE. Return -1 if can't get it.
If ascii-mode is non-nil, return the size with the extra octets that
need to be inserted, one at the end of each line, to provide correct
end-of-line semantics for a transfer using TYPE=A. The default is nil,
so return the size on the remote host exactly. See RFC 3659."
  (let* ((parsed (ange-ftp-ftp-name file))
	 (host (nth 0 parsed))
	 (user (nth 1 parsed))
	 (name (ange-ftp-quote-string (nth 2 parsed)))
	 ;; At least one FTP server (wu-ftpd) can return a "226
	 ;; Transfer complete" before the "213 SIZE".  Let's skip
	 ;; that.
	 (ange-ftp-skip-msgs (concat ange-ftp-skip-msgs "\\|^226"))
	 (res (unwind-protect
                  (progn
                    (unless ascii-mode
                      (ange-ftp-set-binary-mode host user))
                    (ange-ftp-send-cmd host user (list 'quote "size" name)))
		(unless ascii-mode
		  (ange-ftp-set-ascii-mode host user))))
	 (line (cdr res)))
    (if (string-match "^213 \\([0-9]+\\)$" line)
	(string-to-number (match-string 1 line))
      -1)))

\f
;;;; ------------------------------------------------------------
;;;; File copying support... totally re-written 6/24/92.
;;;; ------------------------------------------------------------

(defun ange-ftp-barf-or-query-if-file-exists (absname querystring interactive)
  (if (file-exists-p absname)
      (if (not interactive)
	  (signal 'file-already-exists (list absname))
	(if (not (yes-or-no-p (format "File %s already exists; %s anyway? "
				      absname querystring)))
	    (signal 'file-already-exists (list absname))))))

;; async local copy commented out for now since I don't seem to get
;; the process sentinel called for some processes.
;;
;; (defun ange-ftp-copy-file-locally (filename newname ok-if-already-exists
;; 					    keep-date cont)
;;   "Kludge to copy a local file and call a continuation when the copy
;; finishes."
;;   ;; check to see if we can overwrite
;;   (if (or (not ok-if-already-exists)
;; 	  (numberp ok-if-already-exists))
;;       (ange-ftp-barf-or-query-if-file-exists newname "copy to it"
;; 					     (numberp ok-if-already-exists)))
;;   (let ((proc (start-process " *copy*"
;; 			     (generate-new-buffer "*copy*")
;; 			     "cp"
;; 			     filename
;; 			     newname))
;; 	res)
;;     (set-process-sentinel proc 'ange-ftp-copy-file-locally-sentinel)
;;     (process-kill-without-query proc)
;;     (with-current-buffer (process-buffer proc)
;;       (set (make-local-variable 'copy-cont) cont))))
;;
;; (defun ange-ftp-copy-file-locally-sentinel (proc status)
;;   (with-current-buffer (process-buffer proc)
;;     (let ((cont copy-cont)
;; 	  (result (buffer-string)))
;;       (unwind-protect
;; 	  (if (and (string-equal status "finished\n")
;; 		   (zerop (length result)))
;; 	      (ange-ftp-call-cont cont t nil)
;; 	    (ange-ftp-call-cont cont
;; 				nil
;; 				(if (zerop (length result))
;; 				    (substring status 0 -1)
;; 				  (substring result 0 -1))))
;; 	(kill-buffer (current-buffer))))))

;; this is the extended version of ange-ftp-copy-file-internal that works
;; asynchronously if asked nicely.
(defun ange-ftp-copy-file-internal (filename newname ok-if-already-exists
					     keep-date &optional msg cont nowait)
  (setq filename (expand-file-name filename)
	newname (expand-file-name newname))

  (or (file-exists-p filename)
      (signal 'file-missing
	      (list "Copy file" "No such file or directory" filename)))

  ;; canonicalize newname if a directory.
  (if (file-directory-p newname)
      (setq newname (expand-file-name (file-name-nondirectory filename) newname)))

  (let ((f-parsed (ange-ftp-ftp-name filename))
	(t-parsed (ange-ftp-ftp-name newname)))

    ;; local file to local file copy?
    (if (and (not f-parsed) (not t-parsed))
	(progn
	  (ange-ftp-real-copy-file filename newname ok-if-already-exists
				   keep-date)
	  (if cont
	      (ange-ftp-call-cont cont t "Copied locally")))
      ;; one or both files are remote.
      (let* ((f-host (and f-parsed (nth 0 f-parsed)))
	     (f-user (and f-parsed (nth 1 f-parsed)))
	     (f-name (and f-parsed (ange-ftp-quote-string (nth 2 f-parsed))))
	     (f-abbr (ange-ftp-abbreviate-filename filename))
	     (t-host (and t-parsed (nth 0 t-parsed)))
	     (t-user (and t-parsed (nth 1 t-parsed)))
	     (t-name (and t-parsed (ange-ftp-quote-string (nth 2 t-parsed))))
	     (t-abbr (ange-ftp-abbreviate-filename newname filename))
	     (binary (or (ange-ftp-binary-file filename)
			 (ange-ftp-binary-file newname)))
	     temp1
	     temp2)

	;; check to see if we can overwrite
	(if (or (not ok-if-already-exists)
		(numberp ok-if-already-exists))
	    (ange-ftp-barf-or-query-if-file-exists newname "copy to it"
						   (numberp ok-if-already-exists)))

	;; do the copying.
	(if f-parsed

	    ;; filename was remote.
	    (progn
	      (if (or (ange-ftp-use-gateway-p f-host)
		      t-parsed)
		  ;; have to use intermediate file if we are getting via
		  ;; gateway machine or we are doing a remote to remote copy.
		  (setq temp1 (ange-ftp-make-tmp-name f-host)))

	      (if binary
		  (ange-ftp-set-binary-mode f-host f-user))

	      (ange-ftp-send-cmd
	       f-host
	       f-user
	       (list 'get f-name (or temp1 (ange-ftp-quote-string newname)))
	       (or msg
		   (if (and temp1 t-parsed)
		       (format "Getting %s" f-abbr)
		     (format "Copying %s to %s" f-abbr t-abbr)))
	       (list 'ange-ftp-cf1
		     filename newname binary msg
		     f-parsed f-host f-user f-name f-abbr
		     t-parsed t-host t-user t-name t-abbr
		     temp1 temp2 cont nowait)
	       nowait))

	  ;; filename wasn't remote.  newname must be remote.  call the
	  ;; function which does the remainder of the copying work.
	  (ange-ftp-cf1 t nil
			filename newname binary msg
			f-parsed f-host f-user f-name f-abbr
			t-parsed t-host t-user t-name t-abbr
			nil nil cont nowait))))))

(defvar ange-ftp-waiting-flag nil)

;; next part of copying routine.
(defun ange-ftp-cf1 (result line
			    filename newname binary msg
			    f-parsed f-host f-user _f-name f-abbr
			    t-parsed t-host t-user t-name t-abbr
			    temp1 temp2 cont nowait)
  (if line
      ;; filename must have been remote, and we must have just done a GET.
      (unwind-protect
	  (or result
	      ;; GET failed for some reason.  Clean up and get out.
	      (progn
		(and temp1 (ange-ftp-del-tmp-name temp1))
		(or cont
		    (if ange-ftp-waiting-flag
			(throw 'ftp-error t)
		      (signal 'ftp-error
			      (list "Opening input file"
				    (format "FTP Error: \"%s\"" line)
				    filename))))))
	;; cleanup
	(if binary
	    (ange-ftp-set-ascii-mode f-host f-user))))

  (if result
      ;; We now have to copy either temp1 or filename to newname.
      (if t-parsed

	  ;; newname was remote.
	  (progn
	    (if (ange-ftp-use-gateway-p t-host)
		(setq temp2 (ange-ftp-make-tmp-name t-host)))

	    ;; make sure data is moved into the right place for the
	    ;; outgoing transfer.  gateway temporary files complicate
	    ;; things nicely.
	    (if temp1
		(if temp2
		    (if (string-equal temp1 temp2)
			(setq temp1 nil)
		      (ange-ftp-real-copy-file temp1 temp2 t))
		  (setq temp2 temp1 temp1 nil))
	      (if temp2
		  (ange-ftp-real-copy-file filename temp2 t)))

	    (if binary
		(ange-ftp-set-binary-mode t-host t-user))

	    ;; tell the process filter what size the file is.
	    (let ((attr (file-attributes (or temp2 filename))))
	      (if attr
		  (ange-ftp-set-xfer-size t-host t-user (nth 7 attr))))

	    (ange-ftp-send-cmd
	     t-host
	     t-user
	     (list 'put (or temp2 (ange-ftp-quote-string filename)) t-name)
	     (or msg
		 (if (and temp2 f-parsed)
		     (format "Putting %s" newname)
		   (format "Copying %s to %s" f-abbr t-abbr)))
	     (list 'ange-ftp-cf2
		   newname t-host t-user binary temp1 temp2 cont)
	     nowait)
	    (ange-ftp-add-file-entry newname))

	;; newname wasn't remote.
	(ange-ftp-cf2 t nil newname t-host t-user binary temp1 temp2 cont))

    ;; first copy failed, tell caller
    (ange-ftp-call-cont cont result line)))

;; last part of copying routine.
(defun ange-ftp-cf2 (result line newname t-host t-user binary temp1 temp2 cont)
  (unwind-protect
      (if line
	  ;; result from doing a local to remote copy.
	  (unwind-protect
	      (progn
		(or result
		    (or cont
			(if ange-ftp-waiting-flag
			    (throw 'ftp-error t)
			  (signal 'ftp-error
				  (list "Opening output file"
					(format "FTP Error: \"%s\"" line)
					newname)))))

		(ange-ftp-add-file-entry newname))

	    ;; cleanup.
	    (if binary
		(ange-ftp-set-ascii-mode t-host t-user)))

	;; newname was local.
	(if temp1
	    (ange-ftp-real-copy-file temp1 newname t)))

    ;; clean up
    (and temp1 (ange-ftp-del-tmp-name temp1))
    (and temp2 (ange-ftp-del-tmp-name temp2))
    (ange-ftp-call-cont cont result line)))

(defun ange-ftp-copy-file (filename newname &optional ok-if-already-exists
				    keep-date preserve-uid-gid
				    _preserve-selinux-context)
  (interactive "fCopy file: \nFCopy %s to file: \np")
  (ange-ftp-copy-file-internal filename
			       newname
			       ok-if-already-exists
			       keep-date
			       nil
			       nil
			       (called-interactively-p 'interactive)))

(defun ange-ftp-copy-files-async (okay-p line verbose-p files)
  "Copy some files in the background.
OKAY-P must be t, and LINE does not matter.  They are here to make this
 function a valid CONT argument for `ange-ftp-raw-send-cmd'.
If VERBOSE-P is non-nil, print progress report in the echo area.
 When all the files have been copied already, a message is shown anyway.
FILES is a list of files to copy in the form
  (from-file to-file ok-if-already-exists keep-date)
E.g.,
  (ange-ftp-copy-files-async t nil t \\='((\"a\" \"b\" t t) (\"c\" \"d\" t t)))"
  (unless okay-p (error "%s: %s" 'ange-ftp-copy-files-async line))
  (if files
      (let* ((ff (car files))
             (from-file            (nth 0 ff))
             (to-file              (nth 1 ff))
             (ok-if-already-exists (nth 2 ff))
             (keep-date            (nth 3 ff)))
        (ange-ftp-copy-file-internal
         from-file to-file ok-if-already-exists keep-date
         (and verbose-p (format "%s --> %s" from-file to-file))
         (list 'ange-ftp-copy-files-async verbose-p (cdr files))
         t))
    (message "%s: done" 'ange-ftp-copy-files-async)))

\f
;;;; ------------------------------------------------------------
;;;; File renaming support.
;;;; ------------------------------------------------------------

(defun ange-ftp-rename-remote-to-remote (filename newname f-parsed t-parsed)
  "Rename remote file FILENAME to remote file NEWNAME."
  (let ((f-host (nth 0 f-parsed))
	(f-user (nth 1 f-parsed))
	(t-host (nth 0 t-parsed))
	(t-user (nth 1 t-parsed)))
    (if (and (string-equal f-host t-host)
	     (string-equal f-user t-user))
	(let* ((f-name (ange-ftp-quote-string (nth 2 f-parsed)))
	       (t-name (ange-ftp-quote-string (nth 2 t-parsed)))
	       (cmd (list 'rename f-name t-name))
	       (fabbr (ange-ftp-abbreviate-filename filename))
	       (nabbr (ange-ftp-abbreviate-filename newname filename))
	       (result (ange-ftp-send-cmd f-host f-user cmd
					  (format "Renaming %s to %s"
						  fabbr
						  nabbr))))
	  (or (car result)
	      (signal 'ftp-error
		      (list
		       "Renaming"
		       (format "FTP Error: \"%s\"" (cdr result))
		       filename
		       newname)))
	  (ange-ftp-add-file-entry newname)
	  (ange-ftp-delete-file-entry filename))
      (ange-ftp-copy-file-internal filename newname t nil)
      (delete-file filename))))

(defun ange-ftp-rename-local-to-remote (filename newname)
  "Rename local file FILENAME to remote file NEWNAME."
  (let* ((fabbr (ange-ftp-abbreviate-filename filename))
	 (nabbr (ange-ftp-abbreviate-filename newname filename))
	 (msg (format "Renaming %s to %s" fabbr nabbr)))
    (ange-ftp-copy-file-internal filename newname t nil msg)
    (let (ange-ftp-process-verbose)
      (delete-file filename))))

(defun ange-ftp-rename-remote-to-local (filename newname)
  "Rename remote file FILENAME to local file NEWNAME."
  (let* ((fabbr (ange-ftp-abbreviate-filename filename))
	 (nabbr (ange-ftp-abbreviate-filename newname filename))
	 (msg (format "Renaming %s to %s" fabbr nabbr)))
    (ange-ftp-copy-file-internal filename newname t nil msg)
    (let (ange-ftp-process-verbose)
      (delete-file filename))))

(defun ange-ftp-rename-file (filename newname &optional ok-if-already-exists)
  (interactive "fRename file: \nFRename %s to file: \np")
  (setq filename (expand-file-name filename))
  (setq newname (expand-file-name newname))
  (let* ((f-parsed (ange-ftp-ftp-name filename))
	 (t-parsed (ange-ftp-ftp-name newname)))
    (if (and (or f-parsed t-parsed)
	     (or (not ok-if-already-exists)
		 (numberp ok-if-already-exists)))
	(ange-ftp-barf-or-query-if-file-exists
	 newname
	 "rename to it"
	 (numberp ok-if-already-exists)))
    (if f-parsed
	(if t-parsed
	    (ange-ftp-rename-remote-to-remote filename newname f-parsed
					      t-parsed)
	  (ange-ftp-rename-remote-to-local filename newname))
      (if t-parsed
	  (ange-ftp-rename-local-to-remote filename newname)
	(ange-ftp-real-rename-file filename newname ok-if-already-exists)))))
\f
;;;; ------------------------------------------------------------
;;;; File name completion support.
;;;; ------------------------------------------------------------

;; If the file entry is not a directory (nor a symlink pointing to a directory)
;; returns whether the file (or file pointed to by the symlink) is ignored
;; by completion-ignored-extensions.
;; Note that `ange-ftp-this-dir' and `ange-ftp-completion-ignored-pattern'
;; are used as free variables.
(defun ange-ftp-file-entry-not-ignored-p (symname val)
  (if (stringp val)
      (let ((file (ange-ftp-expand-symlink val ange-ftp-this-dir)))
	(or (file-directory-p file)
	    (and (file-exists-p file)
		 (not (string-match ange-ftp-completion-ignored-pattern
				    symname)))))
    (or val				; is a directory name
	(not (string-match ange-ftp-completion-ignored-pattern symname)))))

(defun ange-ftp-root-dir-p (dir)
  ;; Maybe we should use something more like
  ;; (equal dir (file-name-directory (directory-file-name dir)))  -stef
  (or (and (eq system-type 'windows-nt)
	   (string-match "\\`[a-zA-Z]:[/\\]\\'" dir))
      (string-equal "/" dir)))

(defmacro ange-ftp-ignore-errors-if-non-essential (&rest body)
  `(if non-essential
       (ignore-errors ,@body)
     (progn ,@body)))

(defun ange-ftp-file-name-all-completions (file dir)
  (let ((ange-ftp-this-dir (expand-file-name dir)))
    (if (ange-ftp-ftp-name ange-ftp-this-dir)
	(ange-ftp-ignore-errors-if-non-essential
	  (ange-ftp-barf-if-not-directory ange-ftp-this-dir)
	  (setq ange-ftp-this-dir
		(ange-ftp-real-file-name-as-directory ange-ftp-this-dir))
	  (let* ((tbl (ange-ftp-get-files ange-ftp-this-dir))
		 (completions (all-completions file tbl)))

	    ;; see whether each matching file is a directory or not...
	    (mapcar
             (lambda (file)
               (let ((ent (gethash file tbl)))
                 (if (and ent
                          (or (not (stringp ent))
                              (file-directory-p
                               (ange-ftp-expand-symlink ent
                                                        ange-ftp-this-dir))))
                     (concat file "/")
		   file)))
	     completions)))

      (if (ange-ftp-root-dir-p ange-ftp-this-dir)
	  (nconc (all-completions file (ange-ftp-generate-root-prefixes))
		 (ange-ftp-real-file-name-all-completions file
							  ange-ftp-this-dir))
	(ange-ftp-real-file-name-all-completions file ange-ftp-this-dir)))))

(defun ange-ftp-file-name-completion (file dir &optional predicate)
  (let ((ange-ftp-this-dir (expand-file-name dir)))
    (if (ange-ftp-ftp-name ange-ftp-this-dir)
	(progn
	  (ange-ftp-barf-if-not-directory ange-ftp-this-dir)
	  (if (equal file "")
	      ""
	    (setq ange-ftp-this-dir
		  (ange-ftp-real-file-name-as-directory ange-ftp-this-dir))	;real?
	    (let* ((tbl (ange-ftp-get-files ange-ftp-this-dir))
		   (ange-ftp-completion-ignored-pattern
		    (mapconcat (lambda (s) (if (stringp s)
                                          (concat (regexp-quote s) "$")
                                        "/")) ; / never in filename
			       completion-ignored-extensions
			       "\\|")))
	      (save-match-data
		(or (ange-ftp-file-name-completion-1
		     file tbl ange-ftp-this-dir
		     'ange-ftp-file-entry-not-ignored-p)
		    (ange-ftp-file-name-completion-1
		     file tbl ange-ftp-this-dir))))))

      (if (ange-ftp-root-dir-p ange-ftp-this-dir)
	  (try-completion
	   file
	   (nconc (ange-ftp-generate-root-prefixes)
		  (ange-ftp-real-file-name-all-completions
		   file ange-ftp-this-dir))
	   predicate)
	(if predicate
	    (ange-ftp-real-file-name-completion
	     file ange-ftp-this-dir predicate)
	  (ange-ftp-real-file-name-completion
	   file ange-ftp-this-dir))))))


(defun ange-ftp-file-name-completion-1 (file tbl dir &optional predicate)
  (let ((bestmatch (try-completion file tbl predicate)))
    (if bestmatch
	(if (eq bestmatch t)
	    (if (file-directory-p (expand-file-name file dir))
		(concat file "/")
	      t)
	  (if (and (eq (try-completion bestmatch tbl predicate) t)
		   (file-directory-p
		    (expand-file-name bestmatch dir)))
	      (concat bestmatch "/")
	    bestmatch)))))

;; Put these lines uncommented in your .emacs if you want C-r to refresh
;; ange-ftp's cache whilst doing filename completion.
;;
;;(define-key minibuffer-local-completion-map "\C-r" 'ange-ftp-re-read-dir)
;;(define-key minibuffer-local-must-match-map "\C-r" 'ange-ftp-re-read-dir)

;;;###autoload
(defalias 'ange-ftp-re-read-dir 'ange-ftp-reread-dir)

;;;###autoload
(defun ange-ftp-reread-dir (&optional dir)
  "Reread remote directory DIR to update the directory cache.
The implementation of remote FTP file names caches directory contents
for speed.  Therefore, when new remote files are created, Emacs
may not know they exist.  You can use this command to reread a specific
directory, so that Emacs will know its current contents."
  (interactive)
  (if dir
      (setq dir (expand-file-name dir))
    (setq dir (file-name-directory (expand-file-name (buffer-string)))))
  (if (ange-ftp-ftp-name dir)
      (progn
	(setq ange-ftp-ls-cache-file nil)
	(remhash dir ange-ftp-files-hashtable)
	(ange-ftp-get-files dir t))))
\f
(defun ange-ftp-make-directory (dir &optional parents)
  (interactive (list (expand-file-name (read-directory-name "Make directory: "))))
  (if parents
      (let ((parent (file-name-directory (directory-file-name dir))))
	(or (file-exists-p parent)
	    (ange-ftp-make-directory parent parents))))
  (if (file-exists-p dir)
      (unless parents
	(error "Cannot make directory %s: file already exists" dir))
    (let ((parsed (ange-ftp-ftp-name dir)))
      (if parsed
	  (let* ((host (nth 0 parsed))
		 (user (nth 1 parsed))
		 ;; Some ftp's on unix machines (at least on Suns)
		 ;; insist that mkdir take a filename, and not a
		 ;; directory-name name as an arg. Argh!! This is a bug.
		 ;; Non-unix machines will probably always insist
		 ;; that mkdir takes a directory-name as an arg
		 ;; (as the ftp man page says it should).
		 (name (ange-ftp-quote-string
			(if (eq (ange-ftp-host-type host) 'unix)
			    (ange-ftp-real-directory-file-name (nth 2 parsed))
			  (ange-ftp-real-file-name-as-directory
			   (nth 2 parsed)))))
		 (abbr (ange-ftp-abbreviate-filename dir))
		 (result (ange-ftp-send-cmd host user
					    (list 'mkdir name)
					    (format "Making directory %s"
						    abbr))))
	    (or (car result)
		(ange-ftp-error host user
				(format "Could not make directory %s: %s"
					dir
					(cdr result))))
	    (ange-ftp-add-file-entry dir t))
	(ange-ftp-real-make-directory dir)))))

(defun ange-ftp-delete-directory (dir &optional recursive trash)
  (if (file-directory-p dir)
      (let ((parsed (ange-ftp-ftp-name dir)))
	(if recursive
	    (mapc
	     (lambda (file)
	       (if (file-directory-p file)
		   (ange-ftp-delete-directory file recursive trash)
		 (delete-file file trash)))
	     ;; We do not want to delete "." and "..".
	     (directory-files
	      dir 'full "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*")))
	(if parsed
	    (let* ((host (nth 0 parsed))
		   (user (nth 1 parsed))
		   ;; Some ftp's on unix machines (at least on Suns)
		   ;; insist that rmdir take a filename, and not a
		   ;; directory-name name as an arg. Argh!! This is a bug.
		   ;; Non-unix machines will probably always insist
		   ;; that rmdir takes a directory-name as an arg
		   ;; (as the ftp man page says it should).
		   (name (ange-ftp-quote-string
			  (if (eq (ange-ftp-host-type host) 'unix)
			      (ange-ftp-real-directory-file-name
			       (nth 2 parsed))
			    (ange-ftp-real-file-name-as-directory
			     (nth 2 parsed)))))
		   (abbr (ange-ftp-abbreviate-filename dir))
		   (result
		    (progn
		      ;; CWD must not in this directory.
		      (ange-ftp-cd host user "/" 'noerror)
		      (ange-ftp-send-cmd host user
					 (list 'rmdir name)
					 (format "Removing directory %s"
						 abbr)))))
	      (or (car result)
		  (ange-ftp-error host user
				  (format "Could not remove directory %s: %s"
					  dir
					  (cdr result))))
	      (ange-ftp-delete-file-entry dir t))
	  (ange-ftp-real-delete-directory dir recursive trash)))
    (error "Not a directory: %s" dir)))
\f
;; Make a local copy of FILE and return its name.

(defun ange-ftp-file-local-copy (file)
  (let* ((fn1 (expand-file-name file))
	 (pa1 (ange-ftp-ftp-name fn1)))
    (if pa1
	(let ((tmp1 (ange-ftp-make-tmp-name (car pa1)
					    (file-name-extension file t))))
	  (ange-ftp-copy-file-internal fn1 tmp1 t nil
				       (format "Getting %s" fn1))
	  tmp1))))

(defun ange-ftp-file-remote-p (file &optional identification connected)
  (let* ((parsed (ange-ftp-ftp-name file))
	 (host (nth 0 parsed))
	 (user (nth 1 parsed))
	 (localname (nth 2 parsed)))
    (and (or (not connected)
	     (let ((proc (get-process (ange-ftp-ftp-process-buffer host user))))
	       (and proc (processp proc)
		    (memq (process-status proc) '(run open)))))
	 (cond
	  ((eq identification 'method) (and parsed "ftp"))
	  ((eq identification 'user) user)
	  ((eq identification 'host) host)
	  ((eq identification 'localname) localname)
	  (t (ange-ftp-replace-name-component file ""))))))

(defun ange-ftp-load (file &optional noerror nomessage nosuffix)
  (if (ange-ftp-ftp-name file)
      (let ((tryfiles (if nosuffix
			  (list file)
			(list (concat file ".elc") (concat file ".el") file)))
	    ;; make sure there are no references to temp files
	    (load-force-doc-strings t)
	    copy)
	(while (and tryfiles (not copy))
	  (catch 'ftp-error
	    (let ((ange-ftp-waiting-flag t))
	      (condition-case _error
		  (setq copy (ange-ftp-file-local-copy (car tryfiles)))
		(ftp-error nil))))
	  (setq tryfiles (cdr tryfiles)))
	(if copy
	    (unwind-protect
		(funcall 'load copy noerror nomessage nosuffix)
	      (delete-file copy))
	  (or noerror
	      (signal 'file-error (list "Cannot open load file" file)))
	  nil))
    (ange-ftp-real-load file noerror nomessage nosuffix)))

;; Calculate default-unhandled-directory for a given ange-ftp buffer.
(defun ange-ftp-unhandled-file-name-directory (_filename)
  nil)

\f
;; Need the following functions for making filenames of compressed
;; files, because some OS's (unlike UNIX) do not allow a filename to
;; have two extensions.

(defvar ange-ftp-make-compressed-filename-alist nil
  "Alist of host-type-specific functions to process file names for compression.
Each element has the form (TYPE . FUNC).
FUNC should take one argument, a file name, and return a list
of the form (COMPRESSING NEWNAME).
COMPRESSING should be t if the specified file should be compressed,
and nil if it should be uncompressed (that is, if it is a compressed file).
NEWNAME should be the name to give the new compressed or uncompressed file.")

(declare-function dired-compress-file "dired-aux" (file))

(defun ange-ftp-dired-compress-file (name)
  "Handler used by `dired-compress-file'."
  (let ((parsed (ange-ftp-ftp-name name))
	conversion-func)
    (if (and parsed
	     (setq conversion-func
		   (cdr (assq (ange-ftp-host-type (car parsed))
			      ange-ftp-make-compressed-filename-alist))))
	(let* ((decision
		(save-match-data (funcall conversion-func name)))
	       (compressing (car decision))
	       (newfile (nth 1 decision)))
	  (if compressing
	      (ange-ftp-compress name newfile)
	    (ange-ftp-uncompress name newfile)))
      (let (file-name-handler-alist)
	(dired-compress-file name)))))

;; Copy FILE to this machine, compress it, and copy out to NFILE.
(defun ange-ftp-compress (file nfile)
  (let* ((parsed (ange-ftp-ftp-name file))
	 (tmp1 (ange-ftp-make-tmp-name (car parsed)))
	 (tmp2 (ange-ftp-make-tmp-name (car parsed)))
	 (abbr (ange-ftp-abbreviate-filename file))
	 (nabbr (ange-ftp-abbreviate-filename nfile))
	 (msg1 (format "Getting %s" abbr))
	 (msg2 (format "Putting %s" nabbr)))
    (unwind-protect
	(progn
	  (ange-ftp-copy-file-internal file tmp1 t nil msg1)
	  (and ange-ftp-process-verbose
	       (ange-ftp-message "Compressing %s..." abbr))
	  (call-process-region (point)
			       (point)
			       shell-file-name
			       nil
			       t
			       nil
			       "-c"
			       (format "compress -f -c < %s > %s" tmp1 tmp2))
	  (and ange-ftp-process-verbose
	       (ange-ftp-message "Compressing %s...done" abbr))
	  (if (zerop (buffer-size))
	      (progn
		(let (ange-ftp-process-verbose)
		  (delete-file file))
		(ange-ftp-copy-file-internal tmp2 nfile t nil msg2))))
      (ange-ftp-del-tmp-name tmp1)
      (ange-ftp-del-tmp-name tmp2))))

;; Copy FILE to this machine, uncompress it, and copy out to NFILE.
(defun ange-ftp-uncompress (file nfile)
  (let* ((parsed (ange-ftp-ftp-name file))
	 (tmp1 (ange-ftp-make-tmp-name (car parsed)))
	 (tmp2 (ange-ftp-make-tmp-name (car parsed)))
	 (abbr (ange-ftp-abbreviate-filename file))
	 (nabbr (ange-ftp-abbreviate-filename nfile))
	 (msg1 (format "Getting %s" abbr))
	 (msg2 (format "Putting %s" nabbr))
;;	 ;; Cheap hack because of problems with binary file transfers from
;;	 ;; VMS hosts.
;;	 (gbinary (not (eq 'vms (ange-ftp-host-type (car parsed)))))
	 )
    (unwind-protect
	(progn
	  (ange-ftp-copy-file-internal file tmp1 t nil msg1)
	  (and ange-ftp-process-verbose
	       (ange-ftp-message "Uncompressing %s..." abbr))
	  (call-process-region (point)
			       (point)
			       shell-file-name
			       nil
			       t
			       nil
			       "-c"
			       (format "uncompress -c < %s > %s" tmp1 tmp2))
	  (and ange-ftp-process-verbose
	       (ange-ftp-message "Uncompressing %s...done" abbr))
	  (if (zerop (buffer-size))
	      (progn
		(let (ange-ftp-process-verbose)
		  (delete-file file))
		(ange-ftp-copy-file-internal tmp2 nfile t nil msg2))))
      (ange-ftp-del-tmp-name tmp1)
      (ange-ftp-del-tmp-name tmp2))))

(defun ange-ftp-find-backup-file-name (fn)
  ;; Either return the ordinary backup name, etc.,
  ;; or return nil meaning don't make a backup.
  (if ange-ftp-make-backup-files
      (ange-ftp-real-find-backup-file-name fn)))
\f
;;; Define the handler for special file names
;;; that causes ange-ftp to be invoked.

;;;###autoload
(defun ange-ftp-hook-function (operation &rest args)
  (let ((fn (get operation 'ange-ftp)))
    (if fn
	;; Catch also errors in process-filter.
	(condition-case err
	    (let ((debug-on-error t))
	      (save-match-data (apply fn args)))
	  (error (signal (car err) (cdr err))))
      (ange-ftp-run-real-handler operation args))))

;; The following code is commented out because Tramp now deals with
;; Ange-FTP filenames, too.

;;-;;; This regexp takes care of real ange-ftp file names (with a slash
;;-;;; and colon).
;;-;;; Don't allow the host name to end in a period--some systems use /.:
;;-;;;###autoload
;;-(or (assoc "^/[^/:]*[^/:.]:" file-name-handler-alist)
;;-    (setq file-name-handler-alist
;;-	  (cons '("^/[^/:]*[^/:.]:" . ange-ftp-hook-function)
;;-		file-name-handler-alist)))
;;-
;;-;;; This regexp recognizes absolute filenames with only one component,
;;-;;; for the sake of hostname completion.
;;-;;;###autoload
;;-(or (assoc "^/[^/:]*\\'" file-name-handler-alist)
;;-    (setq file-name-handler-alist
;;-	  (cons '("^/[^/:]*\\'" . ange-ftp-completion-hook-function)
;;-		file-name-handler-alist)))
;;-
;;-;;; This regexp recognizes absolute filenames with only one component
;;-;;; on Windows, for the sake of hostname completion.
;;-;;; NB. Do not mark this as autoload, because it is very common to
;;-;;; do completions in the root directory of drives on Windows.
;;-(and (memq system-type '(ms-dos windows-nt))
;;-     (or (assoc "^[a-zA-Z]:/[^/:]*\\'" file-name-handler-alist)
;;-	 (setq file-name-handler-alist
;;-	       (cons '("^[a-zA-Z]:/[^/:]*\\'" .
;;-		       ange-ftp-completion-hook-function)
;;-		     file-name-handler-alist))))

;;; The above two forms are sufficient to cause this file to be loaded
;;; if the user ever uses a file name with a colon in it.

;;; This sets the mode
(add-hook 'find-file-hook 'ange-ftp-set-buffer-mode)

;;; Now say where to find the handlers for particular operations.

(put 'file-name-directory 'ange-ftp 'ange-ftp-file-name-directory)
(put 'file-name-nondirectory 'ange-ftp 'ange-ftp-file-name-nondirectory)
(put 'file-name-as-directory 'ange-ftp 'ange-ftp-file-name-as-directory)
(put 'directory-file-name 'ange-ftp 'ange-ftp-directory-file-name)
(put 'expand-file-name 'ange-ftp 'ange-ftp-expand-file-name)
(put 'make-directory 'ange-ftp 'ange-ftp-make-directory)
(put 'delete-directory 'ange-ftp 'ange-ftp-delete-directory)
(put 'insert-file-contents 'ange-ftp 'ange-ftp-insert-file-contents)
(put 'directory-files 'ange-ftp 'ange-ftp-directory-files)
(put 'directory-files-and-attributes 'ange-ftp
     'ange-ftp-directory-files-and-attributes)
(put 'file-directory-p 'ange-ftp 'ange-ftp-file-directory-p)
(put 'file-writable-p 'ange-ftp 'ange-ftp-file-writable-p)
(put 'file-readable-p 'ange-ftp 'ange-ftp-file-readable-p)
(put 'file-executable-p 'ange-ftp 'ange-ftp-file-executable-p)
(put 'file-symlink-p 'ange-ftp 'ange-ftp-file-symlink-p)
(put 'file-regular-p 'ange-ftp 'ange-ftp-file-regular-p)
(put 'delete-file 'ange-ftp 'ange-ftp-delete-file)
(put 'verify-visited-file-modtime 'ange-ftp
     'ange-ftp-verify-visited-file-modtime)
(put 'file-exists-p 'ange-ftp 'ange-ftp-file-exists-p)
(put 'write-region 'ange-ftp 'ange-ftp-write-region)
(put 'copy-file 'ange-ftp 'ange-ftp-copy-file)
(put 'rename-file 'ange-ftp 'ange-ftp-rename-file)
(put 'file-attributes 'ange-ftp 'ange-ftp-file-attributes)
(put 'file-newer-than-file-p 'ange-ftp 'ange-ftp-file-newer-than-file-p)
(put 'file-name-all-completions 'ange-ftp 'ange-ftp-file-name-all-completions)
(put 'file-name-completion 'ange-ftp 'ange-ftp-file-name-completion)
(put 'insert-directory 'ange-ftp 'ange-ftp-insert-directory)
(put 'file-local-copy 'ange-ftp 'ange-ftp-file-local-copy)
(put 'file-remote-p 'ange-ftp 'ange-ftp-file-remote-p)
(put 'unhandled-file-name-directory 'ange-ftp
     'ange-ftp-unhandled-file-name-directory)
(put 'file-name-sans-versions 'ange-ftp 'ange-ftp-file-name-sans-versions)
(put 'dired-uncache 'ange-ftp 'ange-ftp-dired-uncache)
(put 'dired-compress-file 'ange-ftp 'ange-ftp-dired-compress-file)
(put 'load 'ange-ftp 'ange-ftp-load)
(put 'find-backup-file-name 'ange-ftp 'ange-ftp-find-backup-file-name)
(put 'set-file-modes 'ange-ftp 'ange-ftp-set-file-modes)

;; Turn off truename processing to save time.
;; Treat each name as its own truename.
(put 'file-truename 'ange-ftp 'identity)

;; We must return non-nil in order to mask our inability to do the job.
;; Otherwise there are errors when applied to the target file during
;; copying from a (localhost) Tramp file.
(put 'set-file-times 'ange-ftp 'ignore)

;; Turn off RCS/SCCS processing to save time.
;; This returns nil for any file name as argument.
(put 'vc-registered 'ange-ftp 'null)

;; We can handle process-file in a restricted way (just for chown).
;; Nothing possible for `start-file-process'.
(put 'process-file 'ange-ftp 'ange-ftp-process-file)
(put 'start-file-process 'ange-ftp 'ignore)
(put 'shell-command 'ange-ftp 'ange-ftp-shell-command)
\f
;;; Define ways of getting at unmodified Emacs primitives,
;;; turning off our handler.

(defun ange-ftp-run-real-handler-orig (operation args)
  (let ((inhibit-file-name-handlers
	 (cons 'ange-ftp-hook-function
	       (cons 'ange-ftp-completion-hook-function
		     (and (eq inhibit-file-name-operation operation)
			  inhibit-file-name-handlers))))
	(inhibit-file-name-operation operation))
    (apply operation args)))

(defalias 'ange-ftp-run-real-handler
  (if (fboundp 'tramp-run-real-handler)
      'tramp-run-real-handler 'ange-ftp-run-real-handler-orig))

(defun ange-ftp-real-file-name-directory (&rest args)
  (ange-ftp-run-real-handler 'file-name-directory args))
(defun ange-ftp-real-file-name-nondirectory (&rest args)
  (ange-ftp-run-real-handler 'file-name-nondirectory args))
(defun ange-ftp-real-file-name-as-directory (&rest args)
  (ange-ftp-run-real-handler 'file-name-as-directory args))
(defun ange-ftp-real-directory-file-name (&rest args)
  (ange-ftp-run-real-handler 'directory-file-name args))
(defun ange-ftp-real-expand-file-name (&rest args)
  (ange-ftp-run-real-handler 'expand-file-name args))
(defun ange-ftp-real-make-directory (&rest args)
  (ange-ftp-run-real-handler 'make-directory args))
(defun ange-ftp-real-delete-directory (&rest args)
  (ange-ftp-run-real-handler 'delete-directory args))
(defun ange-ftp-real-insert-file-contents (&rest args)
  (ange-ftp-run-real-handler 'insert-file-contents args))
(defun ange-ftp-real-directory-files (&rest args)
  (ange-ftp-run-real-handler 'directory-files args))
(defun ange-ftp-real-directory-files-and-attributes (&rest args)
  (ange-ftp-run-real-handler 'directory-files-and-attributes args))
(defun ange-ftp-real-file-directory-p (&rest args)
  (ange-ftp-run-real-handler 'file-directory-p args))
(defun ange-ftp-real-file-writable-p (&rest args)
  (ange-ftp-run-real-handler 'file-writable-p args))
(defun ange-ftp-real-file-readable-p (&rest args)
  (ange-ftp-run-real-handler 'file-readable-p args))
(defun ange-ftp-real-file-executable-p (&rest args)
  (ange-ftp-run-real-handler 'file-executable-p args))
(defun ange-ftp-real-file-symlink-p (&rest args)
  (ange-ftp-run-real-handler 'file-symlink-p args))
(defun ange-ftp-real-file-regular-p (&rest args)
  (ange-ftp-run-real-handler 'file-regular-p args))
(defun ange-ftp-real-delete-file (&rest args)
  (ange-ftp-run-real-handler 'delete-file args))
(defun ange-ftp-real-verify-visited-file-modtime (&rest args)
  (ange-ftp-run-real-handler 'verify-visited-file-modtime args))
(defun ange-ftp-real-file-exists-p (&rest args)
  (ange-ftp-run-real-handler 'file-exists-p args))
(defun ange-ftp-real-write-region (&rest args)
  (ange-ftp-run-real-handler 'write-region args))
(defun ange-ftp-real-backup-buffer (&rest args)
  (ange-ftp-run-real-handler 'backup-buffer args))
(defun ange-ftp-real-copy-file (&rest args)
  (ange-ftp-run-real-handler 'copy-file args))
(defun ange-ftp-real-rename-file (&rest args)
  (ange-ftp-run-real-handler 'rename-file args))
(defun ange-ftp-real-file-attributes (&rest args)
  (ange-ftp-run-real-handler 'file-attributes args))
(defun ange-ftp-real-file-newer-than-file-p (&rest args)
  (ange-ftp-run-real-handler 'file-newer-than-file-p args))
(defun ange-ftp-real-file-name-all-completions (&rest args)
  (ange-ftp-run-real-handler 'file-name-all-completions args))
(defun ange-ftp-real-file-name-completion (&rest args)
  (ange-ftp-run-real-handler 'file-name-completion args))
(defun ange-ftp-real-insert-directory (&rest args)
  (ange-ftp-run-real-handler 'insert-directory args))
(defun ange-ftp-real-file-name-sans-versions (&rest args)
  (ange-ftp-run-real-handler 'file-name-sans-versions args))
(defun ange-ftp-real-shell-command (&rest args)
  (ange-ftp-run-real-handler 'shell-command args))
(defun ange-ftp-real-load (&rest args)
  (ange-ftp-run-real-handler 'load args))
(defun ange-ftp-real-find-backup-file-name (&rest args)
  (ange-ftp-run-real-handler 'find-backup-file-name args))
\f
;; Here we support using dired on remote hosts.
;; I have turned off the support for using dired on foreign directory formats.
;; That involves too many unclean hooks.
;; It would be cleaner to support such operations by
;; converting the foreign directory format to something dired can understand;
;; something close to ls -l output.
;; The logical place to do this is in the functions ange-ftp-parse-...-listing.

;; Some of the old dired hooks would still be needed even if this is done.
;; I have preserved (and modernized) those hooks.
;; So the format conversion should be all that is needed.

;; When called from dired, SWITCHES may start with "--dired".
;; `ange-ftp-ls' handles this.

(defun ange-ftp-insert-directory (file switches &optional wildcard full)
  (if (not (ange-ftp-ftp-name (expand-file-name file)))
      (ange-ftp-real-insert-directory file switches wildcard full)
    ;; We used to follow symlinks on `file' here.  Apparently it was done
    ;; because some FTP servers react to "ls foo" by listing the symlink foo
    ;; rather than the directory it points to.  Now that ange-ftp-ls uses
    ;; "cd foo; ls" instead, this is not necessary any more.
    (let ((beg (point))
	  (end (point-marker)))
      (set-marker-insertion-type end t)
      (insert
       (cond
	(wildcard
	 (let ((default-directory (file-name-directory file)))
	   (ange-ftp-ls (file-name-nondirectory file) switches nil nil t)))
	(full
	 (ange-ftp-ls file switches 'parse))
	(t
	 ;; If `full' is nil we're going to do `ls' for a single file.
	 ;; Problem is that for various reasons, ange-ftp-ls needs to cd and
	 ;; then do an ls of current dir, which obviously won't work if we
	 ;; want to ls a file.  So instead, we get a full listing of the
	 ;; parent directory and extract the line corresponding to `file'.
	 (when (string-match "-?d\\'" switches)
	   ;; Remove "d" which dired added to `switches'.
	   (setq switches (substring switches 0 (match-beginning 0))))
	 (setq file (directory-file-name file))
	 (let* ((dirlist (ange-ftp-ls (or (file-name-directory file) ".")
				      switches 'parse))
		(filename (file-name-nondirectory file))
		(case-fold-search nil))
	   ;; FIXME: This presumes a particular output format, which is
	   ;; basically Unix.
	   (if (string-match (concat "^.+[^ ] " (regexp-quote filename)
				     "\\( -> .*\\)?[@/*=]?\n") dirlist)
	       (match-string 0 dirlist)
	     "")))))

      ;; Insert "  " for dired's alignment sanity.
      (goto-char beg)
      (while (re-search-forward "^\\(\\S-\\)" end 'move)
	(replace-match "  \\1"))

      ;; The inserted file could be from somewhere else.
      (when (and (not wildcard) (not full)
		 (search-backward
		  (if (zerop (length (file-name-nondirectory
				      (expand-file-name file))))
		      "."
		    (file-name-nondirectory file))
		  nil 'noerror))
	(replace-match (file-relative-name (expand-file-name file)) t)
	(goto-char end))

      (set-marker end nil))))

(defun ange-ftp-dired-uncache (dir)
  (if (ange-ftp-ftp-name (expand-file-name dir))
      (setq ange-ftp-ls-cache-file nil)))

(defvar ange-ftp-sans-version-alist nil
  "Alist of mapping host type into function to remove file version numbers.")

(defun ange-ftp-file-name-sans-versions (file keep-backup-version)
  (let* ((short (ange-ftp-abbreviate-filename file))
	 (parsed (ange-ftp-ftp-name short))
	 (func (if parsed (cdr (assq (ange-ftp-host-type (car parsed))
                                     ange-ftp-sans-version-alist)))))
    (if func (funcall func file keep-backup-version)
      (ange-ftp-real-file-name-sans-versions file keep-backup-version))))

;; This is the handler for shell-command.
(defun ange-ftp-shell-command (command &optional output-buffer error-buffer)
  (let* ((parsed (ange-ftp-ftp-name default-directory))
	 (host (nth 0 parsed))
	 (name (nth 2 parsed)))
    (if (not parsed)
	(ange-ftp-real-shell-command command output-buffer error-buffer)
      (if (> (length name) 0)		; else it's $HOME
	  (setq command (concat "cd " name "; " command)))
      ;; Remove port from the hostname
      (when (string-match "\\(.*\\)#" host)
	(setq host (match-string 1 host)))
      (setq command
	    (format  "%s %s \"%s\""	; remsh -l USER does not work well
					; on a hp-ux machine I tried
		     remote-shell-program host command))
      (ange-ftp-message "Remote command `%s' ..." command)
      ;; Cannot call ange-ftp-real-dired-run-shell-command here as it
      ;; would prepend "cd default-directory" --- which bombs because
      ;; default-directory is in ange-ftp syntax for remote file names.
      (ange-ftp-real-shell-command command output-buffer error-buffer))))

;;; This is the handler for process-file.
(defun ange-ftp-process-file (program infile buffer display &rest arguments)
  ;; PROGRAM is always one of those below in the cond in dired.el.
  ;; The ARGUMENTS are (nearly) always files.
  (if (ange-ftp-ftp-name default-directory)
      ;; Can't use ange-ftp-dired-host-type here because the current
      ;; buffer is *dired-check-process output*
      (condition-case oops
	  (cond ((equal (or (bound-and-true-p dired-chmod-program) "chmod")
			program)
		 (ange-ftp-call-chmod arguments))
		;; ((equal "chgrp" program))
		;; ((equal dired-chown-program program))
		(t (error "Unknown remote command: %s" program)))
	(ftp-error (insert (format "%s: %s, %s\n"
				   (nth 1 oops)
				   (nth 2 oops)
				   (nth 3 oops)))
		   ;; Caller expects nonzero value to mean failure.
		   1)
	(error (insert (format "%s\n" (nth 1 oops)))
	       1))
    (apply 'call-process program infile buffer display arguments)))

;; Handle an attempt to run chmod on a remote file
;; by using the ftp chmod command.
(defun ange-ftp-call-chmod (args)
  (if (< (length args) 2)
      (error "ange-ftp-call-chmod: missing mode and/or filename: %s" args))
  (let ((mode (car args))
	(rest (cdr args)))
    (if (equal "--" (car rest))
	(setq rest (cdr rest)))
    (mapc
     (lambda (file)
       (setq file (expand-file-name file))
       (let ((parsed (ange-ftp-ftp-name file)))
         (if parsed
             (let* ((host (nth 0 parsed))
                    (user (nth 1 parsed))
                    (name (ange-ftp-quote-string (nth 2 parsed)))
                    (abbr (ange-ftp-abbreviate-filename file))
                    (result (ange-ftp-send-cmd host user
                                               (list 'chmod mode name)
                                               (format "doing chmod %s"
                                                       abbr))))
               (or (car result)
		   (ange-ftp-error
		    host user (concat "CHMOD failed: " (cdr result))))))))
     rest))
  (setq ange-ftp-ls-cache-file nil)	;Stop confusing Dired.
  0)

(defun ange-ftp-set-file-modes (filename mode)
  (ange-ftp-call-chmod (list (format "%o" mode) filename)))
\f
;; This is turned off because it has nothing properly to do
;; with dired.  It could be reasonable to adapt this to
;; replace ange-ftp-copy-file.

;;;;; ------------------------------------------------------------
;;;;; Noddy support for async copy-file within dired.
;;;;; ------------------------------------------------------------

;;(defun ange-ftp-dired-copy-file (from to ok-flag &optional cont nowait)
;;  "Documented as original."
;;  (dired-handle-overwrite to)
;;  (ange-ftp-copy-file-internal from to ok-flag dired-copy-preserve-time nil
;;			       cont nowait))

;;(defun ange-ftp-dired-do-create-files (op-symbol file-creator operation arg
;;						 &optional marker-char op1
;;						 how-to)
;;  "Documented as original."
;;  ;; we need to let ange-ftp-dired-create-files know that we indirectly
;;  ;; called it rather than somebody else.
;;  (let ((ange-ftp-dired-do-create-files t)) ; tell who caller is
;;    (ange-ftp-real-dired-do-create-files op-symbol file-creator operation
;;					 arg marker-char op1 how-to)))

;;(defun ange-ftp-dired-create-files (file-creator operation fn-list name-constructor
;;						 &optional marker-char)
;;  "Documented as original."
;;  (if (and (boundp 'ange-ftp-dired-do-create-files)
;;	   ;; called from ange-ftp-dired-do-create-files?
;;	   ange-ftp-dired-do-create-files
;;	   ;; any files worth copying?
;;	   fn-list
;;	   ;; we only support async copy-file at the mo.
;;	   (eq file-creator 'dired-copy-file)
;;	   ;; it is only worth calling the alternative function for remote files
;;	   ;; as we tie ourself in recursive knots otherwise.
;;	   (or (ange-ftp-ftp-name (car fn-list))
;;	       ;; we can only call the name constructor for dired-do-create-files
;;	       ;; since the one for regexps starts prompting here, there and
;;	       ;; everywhere.
;;	       (ange-ftp-ftp-name (funcall name-constructor (car fn-list)))))
;;      ;; use the process-filter driven routine rather than the iterative one.
;;      (ange-ftp-dcf-1 file-creator
;;   		      operation
;; 		      fn-list
;; 		      name-constructor
;; 		      (and (boundp 'target) target)	;dynamically bound
;; 		      marker-char
;; 		      (current-buffer)
;; 		      nil	;overwrite-query
;; 		      nil	;overwrite-backup-query
;; 		      nil	;failures
;; 		      nil	;skipped
;; 		      0		;success-count
;; 		      (length fn-list) ;total
;; 		      )
;;    ;; normal case... use the interactive routine... much cheaper.
;;    (ange-ftp-real-dired-create-files file-creator operation fn-list
;;				      name-constructor marker-char)))

;;(defun ange-ftp-dcf-1 (file-creator operation fn-list name-constructor
;;		       target marker-char buffer overwrite-query
;;		       overwrite-backup-query failures skipped
;;		       success-count total)
;;  (with-current-buffer buffer
;;	  (if (null fn-list)
;;	      (ange-ftp-dcf-3 failures operation total skipped
;;			      success-count buffer)

;;	    (let* ((from (car fn-list))
;;		   (to (funcall name-constructor from)))
;;	      (if (equal to from)
;;		  (progn
;;		    (setq to nil)
;;		    (dired-log "Cannot %s to same file: %s\n"
;;			       (downcase operation) from)))
;;	      (if (not to)
;;		  (ange-ftp-dcf-1 file-creator
;;				  operation
;;				  (cdr fn-list)
;;				  name-constructor
;;				  target
;;				  marker-char
;;				  buffer
;;				  overwrite-query
;;				  overwrite-backup-query
;;				  failures
;;				  (cons (dired-make-relative from) skipped)
;;				  success-count
;;				  total)
;;		(let* ((overwrite (file-exists-p to))
;;		       (overwrite-confirmed	; for dired-handle-overwrite
;;			(and overwrite
;;			     (let ((help-form '(format "\
;;Type SPC or `y' to overwrite file `%s',
;;DEL or `n' to skip to next,
;;ESC or `q' to not overwrite any of the remaining files,
;;`!' to overwrite all remaining files with no more questions." to)))
;;			       (dired-query 'overwrite-query
;;					    "Overwrite `%s'?" to))))
;;		       ;; must determine if FROM is marked before file-creator
;;		       ;; gets a chance to delete it (in case of a move).
;;		       (actual-marker-char
;;			(cond  ((integerp marker-char) marker-char)
;;			       (marker-char (dired-file-marker from)) ; slow
;;			       (t nil))))
;;		  (condition-case err
;;		      (funcall file-creator from to overwrite-confirmed
;;			       (list 'ange-ftp-dcf-2
;;				     nil	;err
;;				     file-creator operation fn-list
;;				     name-constructor
;;				     target
;;				     marker-char actual-marker-char
;;				     buffer to from
;;				     overwrite
;;				     overwrite-confirmed
;;				     overwrite-query
;;				     overwrite-backup-query
;;				     failures skipped success-count
;;				     total)
;;			       t)
;;		    (file-error		; FILE-CREATOR aborted
;;		     (ange-ftp-dcf-2 nil ;result
;;				     nil ;line
;;				     err
;;				     file-creator operation fn-list
;;				     name-constructor
;;				     target
;;				     marker-char actual-marker-char
;;				     buffer to from
;;				     overwrite
;;				     overwrite-confirmed
;;				     overwrite-query
;;				     overwrite-backup-query
;;				     failures skipped success-count
;;				     total)))))))))

;;(defun ange-ftp-dcf-2 (result line err
;;			      file-creator operation fn-list
;;			      name-constructor
;;			      target
;;			      marker-char actual-marker-char
;;			      buffer to from
;;			      overwrite
;;			      overwrite-confirmed
;;			      overwrite-query
;;			      overwrite-backup-query
;;			      failures skipped success-count
;;			      total)
;;  (with-current-buffer buffer
;;	  (if (or err (not result))
;;	      (progn
;;		(setq failures (cons (dired-make-relative from) failures))
;;		(dired-log "%s `%s' to `%s' failed:\n%s\n"
;;			   operation from to (or err line)))
;;	    (if overwrite
;;		;; If we get here, file-creator hasn't been aborted
;;		;; and the old entry (if any) has to be deleted
;;		;; before adding the new entry.
;;		(dired-remove-file to))
;;	    (setq success-count (1+ success-count))
;;	    (message "%s: %d of %d" operation success-count total)
;;	    (dired-add-file to actual-marker-char))

;;	  (ange-ftp-dcf-1 file-creator operation (cdr fn-list)
;;			  name-constructor
;;			  target
;;			  marker-char
;;			  buffer
;;			  overwrite-query
;;			  overwrite-backup-query
;;			  failures skipped success-count
;;			  total)))

;;(defun ange-ftp-dcf-3 (failures operation total skipped success-count
;;				buffer)
;;  (with-current-buffer buffer
;;	  (cond
;;	   (failures
;;	    (dired-log-summary
;;	     (message "%s failed for %d of %d file%s %s"
;;		      operation (length failures) total
;;		      (dired-plural-s total) failures)))
;;	   (skipped
;;	    (dired-log-summary
;;	     (message "%s: %d of %d file%s skipped %s"
;;		      operation (length skipped) total
;;		      (dired-plural-s total) skipped)))
;;	   (t
;;	    (message "%s: %s file%s."
;;		     operation success-count (dired-plural-s success-count))))
;;	  (dired-move-to-filename)))
\f
;;;; -----------------------------------------------
;;;; Unix Descriptive Listing (dl) Support
;;;; -----------------------------------------------

;; This is turned off because nothing uses it currently
;; and because I don't understand what it's supposed to be for. --rms.

;;(defconst ange-ftp-dired-dl-re-dir
;;  "^. [^ /]+/[ \n]"
;;  "Regular expression to use to search for dl directories.")

;;(or (assq 'unix:dl ange-ftp-dired-re-dir-alist)
;;    (setq ange-ftp-dired-re-dir-alist
;;	  (cons (cons 'unix:dl  ange-ftp-dired-dl-re-dir)
;;		ange-ftp-dired-re-dir-alist)))

;;(defun ange-ftp-dired-dl-move-to-filename (&optional raise-error eol)
;;  "In dired, move to the first character of the filename on this line."
;;  ;; This is the Unix dl version.
;;  (or eol (setq eol (progn (end-of-line) (point))))
;;  (let (case-fold-search)
;;    (beginning-of-line)
;;    (if (looking-at ". [^ ]+ +\\([0-9]+\\|-\\|=\\) ")
;;	(goto-char (+ (point) 2))
;;      (if raise-error
;;	  (error "No file on this line")
;;	nil))))

;;(or (assq 'unix:dl ange-ftp-dired-move-to-filename-alist)
;;    (setq ange-ftp-dired-move-to-filename-alist
;;	  (cons '(unix:dl . ange-ftp-dired-dl-move-to-filename)
;;		ange-ftp-dired-move-to-filename-alist)))

;;(defun ange-ftp-dired-dl-move-to-end-of-filename (&optional no-error eol)
;;  ;; Assumes point is at beginning of filename.
;;  ;; So, it should be called only after (dired-move-to-filename t).
;;  ;; On failure, signals an error or returns nil.
;;  ;; This is the Unix dl version.
;;  (let ((opoint (point))
;;	case-fold-search hidden)
;;    (or eol (setq eol (line-end-position)))
;;    (setq hidden (and selective-display
;;		       (save-excursion
;;			 (search-forward "\r" eol t))))
;;    (if hidden
;;	(if no-error
;;	    nil
;;	  (error
;;	   (substitute-command-keys
;;	    "File line is hidden, type \\[dired-hide-subdir] to unhide")))
;;      (skip-chars-forward "^ /" eol)
;;      (if (eq opoint (point))
;;	  (if no-error
;;	      nil
;;	    (error "No file on this line"))
;;	(point)))))

;;(or (assq 'unix:dl ange-ftp-dired-move-to-end-of-filename-alist)
;;    (setq ange-ftp-dired-move-to-end-of-filename-alist
;;	  (cons '(unix:dl . ange-ftp-dired-dl-move-to-end-of-filename)
;;		ange-ftp-dired-move-to-end-of-filename-alist)))
\f
;;;; ------------------------------------------------------------
;;;; VOS support (VOS support is probably broken,
;;;; but I don't know anything about VOS.)
;;;; ------------------------------------------------------------
;
;(defun ange-ftp-fix-name-for-vos (name &optional reverse)
;  (setq name (copy-sequence name))
;  (let ((from (if reverse ?\> ?\/))
;	(to (if reverse ?\/ ?\>))
;	(i (1- (length name))))
;    (while (>= i 0)
;      (if (= (aref name i) from)
;	  (aset name i to))
;      (setq i (1- i)))
;    name))
;
;(or (assq 'vos ange-ftp-fix-name-func-alist)
;    (setq ange-ftp-fix-name-func-alist
;	  (cons '(vos . ange-ftp-fix-name-for-vos)
;		ange-ftp-fix-name-func-alist)))
;
;(or (memq 'vos ange-ftp-dumb-host-types)
;    (setq ange-ftp-dumb-host-types
;	  (cons 'vos ange-ftp-dumb-host-types)))
;
;(defun ange-ftp-fix-dir-name-for-vos (dir-name)
;  (ange-ftp-fix-name-for-vos
;   (concat dir-name
;	   (if (eq ?/ (aref dir-name (1- (length dir-name))))
;	       "" "/")
;	   "*")))
;
;(or (assq 'vos ange-ftp-fix-dir-name-func-alist)
;    (setq ange-ftp-fix-dir-name-func-alist
;	  (cons '(vos . ange-ftp-fix-dir-name-for-vos)
;		ange-ftp-fix-dir-name-func-alist)))
;
;(defvar ange-ftp-vos-host-regexp nil
;  "If a host matches this regexp then it is assumed to be running VOS.")
;
;(defun ange-ftp-vos-host (host)
;  (and ange-ftp-vos-host-regexp
;       (save-match-data
;	 (string-match ange-ftp-vos-host-regexp host))))
;
;(defun ange-ftp-parse-vos-listing ()
;  "Parse the current buffer which is assumed to be in VOS list -all
;format, and return a hashtable as the result."
;  (let ((tbl (ange-ftp-make-hashtable))
;	(type-list
;	 '(("^Files: [0-9]+ +Blocks: [0-9]+\n+" nil 40)
;	   ("^Dirs: [0-9]+\n+" t 30)))
;	type-regexp type-is-dir type-col file)
;    (goto-char (point-min))
;    (save-match-data
;      (while type-list
;	(setq type-regexp (car (car type-list))
;	      type-is-dir (nth 1 (car type-list))
;	      type-col (nth 2 (car type-list))
;	      type-list (cdr type-list))
;	(if (re-search-forward type-regexp nil t)
;	    (while (eq (char-after (point)) ? )
;	      (move-to-column type-col)
;	      (setq file (buffer-substring (point)
;					   (progn
;					     (end-of-line 1)
;					     (point))))
;	      (puthash file type-is-dir tbl)
;	      (forward-line 1))))
;      (puthash "." 'vosdir tbl)
;      (puthash ".." 'vosdir tbl))
;    tbl))
;
;(or (assq 'vos ange-ftp-parse-list-func-alist)
;    (setq ange-ftp-parse-list-func-alist
;	  (cons '(vos . ange-ftp-parse-vos-listing)
;		ange-ftp-parse-list-func-alist)))
\f
;;;; ------------------------------------------------------------
;;;; VMS support.
;;;; ------------------------------------------------------------

;; Convert NAME from UNIX-ish to VMS.  If REVERSE given then convert from VMS
;; to UNIX-ish.
(defun ange-ftp-fix-name-for-vms (name &optional reverse)
  (save-match-data
    (if reverse
	(if (string-match "\\`\\([^:]+:\\)?\\(\\[.*\\]\\)?\\([^][]*\\)\\'" name)
	    (let (drive dir file)
	      (setq drive (match-string 1 name))
	      (setq dir (match-string 2 name))
	      (setq file (match-string 3 name))
	      (and dir
		   (setq dir (subst-char-in-string
                              ?/ ?. (substring dir 1 -1) t)))
	      (concat (and drive
			   (concat "/" drive "/"))
		      dir (and dir "/")
		      file))
	  (error "name %s didn't match" name))
      (let (drive dir file tmp quote)
	(if (string-match "\\`\".+\"\\'" name)
	    (setq name (substring name 1 -1)
		  quote "\"")
	  (setq quote ""))
	(if (string-match "\\`/[^:]+:/" name)
	    (setq drive (substring name 1
				   (1- (match-end 0)))
		  name (substring name (match-end 0))))
	(setq tmp (file-name-directory name))
	(if tmp
	    (setq dir (subst-char-in-string ?/ ?. (substring tmp 0 -1) t)))
	(setq file (file-name-nondirectory name))
	(concat quote drive
		(and dir (concat "[" (if drive nil ".") dir "]"))
		file quote)))))

;; (ange-ftp-fix-name-for-vms "/PUB$:/ANONYMOUS/SDSCPUB/NEXT/Readme.txt;1")
;; (ange-ftp-fix-name-for-vms "/PUB$:[ANONYMOUS.SDSCPUB.NEXT]Readme.txt;1" t)

(or (assq 'vms ange-ftp-fix-name-func-alist)
    (setq ange-ftp-fix-name-func-alist
	  (cons '(vms . ange-ftp-fix-name-for-vms)
		ange-ftp-fix-name-func-alist)))

(or (memq 'vms ange-ftp-dumb-host-types)
    (setq ange-ftp-dumb-host-types
	  (cons 'vms ange-ftp-dumb-host-types)))

;; It is important that this function barf for directories for which we know
;; that we cannot possibly get a directory listing, such as "/" and "/DEV:/".
;; This is because it saves an unnecessary FTP error, or possibly the listing
;; might succeed, but give erroneous info. This last case is particularly
;; likely for OS's (like MTS) for which we need to use a wildcard in order
;; to list a directory.

;; Convert name from UNIX-ish to VMS ready for a DIRectory listing.
(defun ange-ftp-fix-dir-name-for-vms (dir-name)
  ;; Should there be entries for .. -> [-] and . -> [] below. Don't
  ;; think so, because expand-filename should have already short-circuited
  ;; them.
  (cond ((string-equal dir-name "/")
	 (error "Cannot get listing for fictitious \"/\" directory"))
	((string-match "\\`/[-A-Z0-9_$]+:/\\'" dir-name)
	 (error "Cannot get listing for device"))
	((ange-ftp-fix-name-for-vms dir-name))))

(or (assq 'vms ange-ftp-fix-dir-name-func-alist)
    (setq ange-ftp-fix-dir-name-func-alist
	  (cons '(vms . ange-ftp-fix-dir-name-for-vms)
		ange-ftp-fix-dir-name-func-alist)))

(defvar ange-ftp-vms-host-regexp nil)

;; Return non-nil if HOST is running VMS.
(defun ange-ftp-vms-host (host)
  (and ange-ftp-vms-host-regexp
       (string-match-p ange-ftp-vms-host-regexp host)))

;; Because some VMS ftp servers convert filenames to lower case
;; we allow a-z in the filename regexp. I'm not too happy about this.

(defconst ange-ftp-vms-filename-regexp
  (concat
   "\\(\\([_A-Za-z0-9$]?\\|[_A-Za-z0-9$][-_A-Za-z0-9$]*\\)\\."
   "[-_A-Za-z0-9$]*;+[0-9]*\\)")
  "Regular expression to match for a valid VMS file name in Dired buffer.
Stupid freaking bug!  Position of _ and $ shouldn't matter but they do.
Having [A-Z0-9$_] bombs on filename _$$CHANGE_LOG$.TXT$ and $CHANGE_LOG$.TX.
Other orders of $ and _ seem to all work just fine.")

;; These parsing functions are as general as possible because the syntax
;; of ftp listings from VMS hosts is a bit erratic. What saves us is that
;; the VMS filename syntax is so rigid. If they bomb on a listing in the
;; standard VMS Multinet format, then this is a bug. If they bomb on a listing
;; from vms.weird.net, then too bad.

;; Extract the next filename from a VMS dired-like listing.
(defun ange-ftp-parse-vms-filename ()
  (if (re-search-forward
       ange-ftp-vms-filename-regexp
       nil t)
      (match-string 0)))

;; Parse the current buffer which is assumed to be in MultiNet FTP dir
;; format, and return a hashtable as the result.
(defun ange-ftp-parse-vms-listing ()
  (let ((tbl (make-hash-table :test 'equal))
	file)
    (goto-char (point-min))
    (save-match-data
      (while (setq file (ange-ftp-parse-vms-filename))
	(if (string-match "\\.\\(DIR\\|dir\\);[0-9]+" file)
	    ;; deal with directories
	    (puthash (substring file 0 (match-beginning 0)) t tbl)
	  (puthash file nil tbl)
	  (if (string-match ";[0-9]+\\'" file) ; deal with extension
	      ;; sans extension
	      (puthash (substring file 0 (match-beginning 0)) nil tbl)))
	(forward-line 1))
      ;; Would like to look for a "Total" line, or a "Directory" line to
      ;; make sure that the listing isn't complete garbage before putting
      ;; in "." and "..", but we can't count on VMS giving us
      ;; either of these.
      (puthash "." t tbl)
      (puthash ".." t tbl))
    tbl))

(add-to-list 'ange-ftp-parse-list-func-alist
	     '(vms . ange-ftp-parse-vms-listing))

;; This version only deletes file entries which have
;; explicit version numbers, because that is all VMS allows.

;; Can the following two functions be speeded up using file
;; completion functions?

(defun ange-ftp-vms-delete-file-entry (name &optional dir-p)
  (if dir-p
      (ange-ftp-internal-delete-file-entry name t)
    (save-match-data
      (let ((file (ange-ftp-get-file-part name)))
	(if (string-match ";[0-9]+\\'" file)
	    ;; In VMS you can't delete a file without an explicit
	    ;; version number, or wild-card (e.g. FOO;*)
	    ;; For now, we give up on wildcards.
	    (let ((files (gethash (file-name-directory name)
				  ange-ftp-files-hashtable)))
	      (if files
		  (let* ((root (substring file 0
					  (match-beginning 0)))
			 (regexp (concat "^"
					 (regexp-quote root)
					 ";[0-9]+$"))
			 versions)
		    (remhash file files)
		    ;; Now we need to check if there are any
		    ;; versions left. If not, then delete the
		    ;; root entry.
		    (maphash
		     (lambda (key _val)
		       (and (string-match regexp key)
			    (setq versions t)))
		     files)
		    (or versions
			(remhash root files))))))))))

(or (assq 'vms ange-ftp-delete-file-entry-alist)
    (setq ange-ftp-delete-file-entry-alist
	  (cons '(vms . ange-ftp-vms-delete-file-entry)
		ange-ftp-delete-file-entry-alist)))

(defun ange-ftp-vms-add-file-entry (name &optional dir-p)
  (if dir-p
      (ange-ftp-internal-add-file-entry name t)
    (let ((files (gethash (file-name-directory name)
			  ange-ftp-files-hashtable)))
      (if files
	  (let ((file (ange-ftp-get-file-part name)))
	    (save-match-data
	      (if (string-match ";[0-9]+\\'" file)
		  (puthash (substring file 0 (match-beginning 0)) nil files)
		;; Need to figure out what version of the file
		;; is being added.
		(let ((regexp (concat "^"
				      (regexp-quote file)
				      ";\\([0-9]+\\)$"))
		      (version 0))
		  (maphash
		   (lambda (name val)
		     (and (string-match regexp name)
			  (setq version
				(max version
				     (string-to-number (match-string 1 name))))))
		   files)
		  (setq version (1+ version))
		  (puthash
		   (concat file ";" (int-to-string version))
		   nil files))))
	    (puthash file nil files))))))

(or (assq 'vms ange-ftp-add-file-entry-alist)
    (setq ange-ftp-add-file-entry-alist
	  (cons '(vms . ange-ftp-vms-add-file-entry)
		ange-ftp-add-file-entry-alist)))


(defun ange-ftp-add-vms-host (host)
  "Mark HOST as the name of a machine running VMS."
  (interactive
   (list (read-string "Host: "
		      (let ((name (or (buffer-file-name) default-directory)))
			(and name (car (ange-ftp-ftp-name name)))))))
  (if (not (ange-ftp-vms-host host))
      (setq ange-ftp-vms-host-regexp
	    (concat "^" (regexp-quote host) "$"
		    (and ange-ftp-vms-host-regexp "\\|")
		    ange-ftp-vms-host-regexp)
	    ange-ftp-host-cache nil)))


(defun ange-ftp-vms-file-name-as-directory (name)
  (save-match-data
    (if (string-match "\\.\\(DIR\\|dir\\)\\(;[0-9]+\\)?\\'" name)
	(setq name (substring name 0 (match-beginning 0))))
    (ange-ftp-real-file-name-as-directory name)))

(or (assq 'vms ange-ftp-file-name-as-directory-alist)
    (setq ange-ftp-file-name-as-directory-alist
	  (cons '(vms . ange-ftp-vms-file-name-as-directory)
		ange-ftp-file-name-as-directory-alist)))

;;; Tree dired support:

;; For this code I have borrowed liberally from Sebastian Kremer's
;; dired-vms.el


;;;; These regexps must be anchored to beginning of line.
;;;; Beware that the ftpd may put the device in front of the filename.

;;(defconst ange-ftp-dired-vms-re-exe "^. [^ \t.]+\\.\\(EXE\\|exe\\)[; ]"
;;  "Regular expression to use to search for VMS executable files.")

;;(defconst ange-ftp-dired-vms-re-dir "^. [^ \t.]+\\.\\(DIR\\|dir\\)[; ]"
;;  "Regular expression to use to search for VMS directories.")

;;(or (assq 'vms ange-ftp-dired-re-exe-alist)
;;    (setq ange-ftp-dired-re-exe-alist
;;	  (cons (cons 'vms  ange-ftp-dired-vms-re-exe)
;;		ange-ftp-dired-re-exe-alist)))

;;(or (assq 'vms ange-ftp-dired-re-dir-alist)
;;    (setq ange-ftp-dired-re-dir-alist
;;	  (cons (cons 'vms  ange-ftp-dired-vms-re-dir)
;;		ange-ftp-dired-re-dir-alist)))

;;(defun ange-ftp-dired-vms-insert-headerline (dir)
;;  ;; VMS inserts a headerline. I would prefer the headerline
;;  ;; to be in ange-ftp format. This version tries to
;;  ;; be careful, because we can't count on a headerline
;;  ;; over ftp, and we wouldn't want to delete anything
;;  ;; important.
;;  (save-excursion
;;    (if (looking-at "^  wildcard ")
;;	(forward-line 1))
;;    (if (looking-at "^[ \n\t]*[^\n]+\\][ \t]*\n")
;;	(delete-region (point) (match-end 0))))
;;  (ange-ftp-real-dired-insert-headerline dir))

;;(or (assq 'vms ange-ftp-dired-insert-headerline-alist)
;;    (setq ange-ftp-dired-insert-headerline-alist
;;	  (cons '(vms . ange-ftp-dired-vms-insert-headerline)
;;		ange-ftp-dired-insert-headerline-alist)))

;;(defun ange-ftp-dired-vms-move-to-filename (&optional raise-error eol)
;;  "In dired, move to first char of filename on this line.
;;Returns position (point) or nil if no filename on this line."
;;  ;; This is the VMS version.
;;  (let (case-fold-search)
;;    (or eol (setq eol (progn (end-of-line) (point))))
;;    (beginning-of-line)
;;    (if (re-search-forward ange-ftp-vms-filename-regexp eol t)
;;	(goto-char (match-beginning 1))
;;      (if raise-error
;;	  (error "No file on this line")
;;	nil))))

;;(or (assq 'vms ange-ftp-dired-move-to-filename-alist)
;;    (setq ange-ftp-dired-move-to-filename-alist
;;	  (cons '(vms . ange-ftp-dired-vms-move-to-filename)
;;		ange-ftp-dired-move-to-filename-alist)))

;;(defun ange-ftp-dired-vms-move-to-end-of-filename (&optional no-error eol)
;;  ;; Assumes point is at beginning of filename.
;;  ;; So, it should be called only after (dired-move-to-filename t).
;;  ;; case-fold-search must be nil, at least for VMS.
;;  ;; On failure, signals an error or returns nil.
;;  ;; This is the VMS version.
;;  (let (opoint hidden case-fold-search)
;;    (setq opoint (point))
;;    (or eol (setq eol (line-end-position)))
;;    (setq hidden (and selective-display
;;		      (save-excursion (search-forward "\r" eol t))))
;;    (if hidden
;;	nil
;;      (re-search-forward ange-ftp-vms-filename-regexp eol t))
;;    (or no-error
;;	(not (eq opoint (point)))
;;	(error
;;	 (if hidden
;;	     (substitute-command-keys
;;	      "File line is hidden, type \\[dired-hide-subdir] to unhide")
;;	   "No file on this line")))
;;    (if (eq opoint (point))
;;	nil
;;      (point))))

;;(or (assq 'vms ange-ftp-dired-move-to-end-of-filename-alist)
;;    (setq ange-ftp-dired-move-to-end-of-filename-alist
;;	  (cons '(vms . ange-ftp-dired-vms-move-to-end-of-filename)
;;		ange-ftp-dired-move-to-end-of-filename-alist)))

;;(defun ange-ftp-dired-vms-between-files ()
;;  (save-excursion
;;    (beginning-of-line)
;;    (or (equal (following-char) 10) ; newline
;;     (equal (following-char) 9)     ; tab
;;     (progn (forward-char 2)
;;	    (or (looking-at "Total of")
;;		(equal (following-char) 32))))))

;;(or (assq 'vms ange-ftp-dired-between-files-alist)
;;    (setq ange-ftp-dired-between-files-alist
;;	  (cons '(vms . ange-ftp-dired-vms-between-files)
;;		ange-ftp-dired-between-files-alist)))

;; Beware! In VMS filenames must be of the form "FILE.TYPE".
;; Therefore, we cannot just append a ".Z" to filenames for
;; compressed files. Instead, we turn "FILE.TYPE" into
;; "FILE.TYPE-Z". Hope that this is a reasonable thing to do.

(defun ange-ftp-vms-make-compressed-filename (name &optional _reverse)
  (cond
   ((string-match "-Z;[0-9]+\\'" name)
    (list nil (substring name 0 (match-beginning 0))))
   ((string-match ";[0-9]+\\'" name)
    (list nil (substring name 0 (match-beginning 0))))
   ((string-match "-Z\\'" name)
    (list nil (substring name 0 -2)))
   (t
    (list t
	  (if (string-match ";[0-9]+\\'" name)
	      (concat (substring name 0 (match-beginning 0))
		      "-Z")
	    (concat name "-Z"))))))

(or (assq 'vms ange-ftp-make-compressed-filename-alist)
    (setq ange-ftp-make-compressed-filename-alist
	  (cons '(vms . ange-ftp-vms-make-compressed-filename)
		ange-ftp-make-compressed-filename-alist)))

;;;; When the filename is too long, VMS will use two lines to list a file
;;;; (damn them!) This will confuse dired. To solve this, need to convince
;;;; Sebastian to use a function dired-go-to-end-of-file-line, instead of
;;;; (forward-line 1). This would require a number of changes to dired.el.
;;;; If dired gets confused, revert-buffer will fix it.

;;(defun ange-ftp-dired-vms-ls-trim ()
;;  (goto-char (point-min))
;;  (let ((case-fold-search nil))
;;    (re-search-forward  ange-ftp-vms-filename-regexp))
;;  (beginning-of-line)
;;  (delete-region (point-min) (point))
;;  (forward-line 1)
;;  (delete-region (point) (point-max)))


;;(or (assq 'vms ange-ftp-dired-ls-trim-alist)
;;    (setq ange-ftp-dired-ls-trim-alist
;;	  (cons '(vms . ange-ftp-dired-vms-ls-trim)
;;		ange-ftp-dired-ls-trim-alist)))

(defun ange-ftp-vms-sans-version (name &rest _args)
  (save-match-data
    (if (string-match ";[0-9]+\\'" name)
	(substring name 0 (match-beginning 0))
      name)))

(or (assq 'vms ange-ftp-sans-version-alist)
    (setq ange-ftp-sans-version-alist
	  (cons '(vms . ange-ftp-vms-sans-version)
		ange-ftp-sans-version-alist)))

;;(defvar ange-ftp-file-version-alist)

;;;;; The vms version of clean-directory has 2 more optional args
;;;;; than the usual dired version. This is so that it can be used by
;;;;; ange-ftp-dired-vms-flag-backup-files.

;;(defun ange-ftp-dired-vms-clean-directory (keep &optional marker msg)
;;  "Flag numerical backups for deletion.
;;Spares `dired-kept-versions' latest versions, and `kept-old-versions' oldest.
;;Positive prefix arg KEEP overrides `dired-kept-versions';
;;Negative prefix arg KEEP overrides `kept-old-versions' with KEEP made positive.

;;To clear the flags on these files, you can use \\[dired-flag-backup-files]
;;with a prefix argument."
;;;  (interactive "P") ; Never actually called interactively.
;;  (setq keep (max 1 (if keep (prefix-numeric-value keep) dired-kept-versions)))
;;  (let ((early-retention (if (< keep 0) (- keep) kept-old-versions))
;;	;; late-retention must NEVER be allowed to be less than 1 in VMS!
;;	;; This could wipe ALL copies of the file.
;;	(late-retention (max 1 (if (<= keep 0) dired-kept-versions keep)))
;;	(action (or msg "Cleaning"))
;;	(ange-ftp-trample-marker (or marker dired-del-marker))
;;	(ange-ftp-file-version-alist ()))
;;    (message (concat action
;;		     " numerical backups (keeping %d late, %d old)...")
;;	     late-retention early-retention)
;;    ;; Look at each file.
;;    ;; If the file has numeric backup versions,
;;    ;; put on ange-ftp-file-version-alist an element of the form
;;    ;; (FILENAME . VERSION-NUMBER-LIST)
;;    (dired-map-dired-file-lines 'ange-ftp-dired-vms-collect-file-versions)
;;    ;; Sort each VERSION-NUMBER-LIST,
;;    ;; and remove the versions not to be deleted.
;;    (let ((fval ange-ftp-file-version-alist))
;;      (while fval
;;	(let* ((sorted-v-list (cons 'q (sort (cdr (car fval)) '<)))
;;	       (v-count (length sorted-v-list)))
;;	  (if (> v-count (+ early-retention late-retention))
;;	      (rplacd (nthcdr early-retention sorted-v-list)
;;		      (nthcdr (- v-count late-retention)
;;			      sorted-v-list)))
;;	  (rplacd (car fval)
;;		  (cdr sorted-v-list)))
;;	(setq fval (cdr fval))))
;;    ;; Look at each file.  If it is a numeric backup file,
;;    ;; find it in a VERSION-NUMBER-LIST and maybe flag it for deletion.
;;    (dired-map-dired-file-lines
;;     'ange-ftp-dired-vms-trample-file-versions mark)
;;    (message (concat action " numerical backups...done"))))

;;(or (assq 'vms ange-ftp-dired-clean-directory-alist)
;;    (setq ange-ftp-dired-clean-directory-alist
;;	  (cons '(vms . ange-ftp-dired-vms-clean-directory)
;;		ange-ftp-dired-clean-directory-alist)))

;;(defun ange-ftp-dired-vms-collect-file-versions (fn)
;;  ;;  "If it looks like file FN has versions, return a list of the versions.
;;  ;;That is a list of strings which are file names.
;;  ;;The caller may want to flag some of these files for deletion."
;;(let ((name (nth 2 (ange-ftp-ftp-name fn))))
;;  (if (string-match ";[0-9]+$" name)
;;      (let* ((name (substring name 0 (match-beginning 0)))
;;	     (fn (ange-ftp-replace-name-component fn name)))
;;	(if (not (assq fn ange-ftp-file-version-alist))
;;	    (let* ((base-versions
;;		    (concat (file-name-nondirectory name) ";"))
;;		   (bv-length (length base-versions))
;;		   (possibilities (file-name-all-completions
;;				   base-versions
;;				   (file-name-directory fn)))
;;		   (versions (mapcar
;;			      (lambda (arg)
;;				 (if (and (string-match
;;					   "[0-9]+$" arg bv-length)
;;					  (= (match-beginning 0) bv-length))
;;				     (string-to-int (substring arg bv-length))
;;				   0))
;;			      possibilities)))
;;	      (if versions
;;		  (setq
;;		   ange-ftp-file-version-alist
;;		   (cons (cons fn versions)
;;			 ange-ftp-file-version-alist)))))))))

;;(defun ange-ftp-dired-vms-trample-file-versions (fn)
;;  (let* ((start-vn (string-match ";[0-9]+$" fn))
;;	 base-version-list)
;;    (and start-vn
;;	 (setq base-version-list	; there was a base version to which
;;	       (assoc (substring fn 0 start-vn)	; this looks like a
;;		      ange-ftp-file-version-alist))	; subversion
;;	 (not (memq (string-to-int (substring fn (1+ start-vn)))
;;		    base-version-list))	; this one doesn't make the cut
;;	 (progn (beginning-of-line)
;;		(delete-char 1)
;;		(insert ange-ftp-trample-marker)))))

;;(defun ange-ftp-dired-vms-flag-backup-files (&optional unflag-p)
;;  (let ((dired-kept-versions 1)
;;	(kept-old-versions 0)
;;	marker msg)
;;    (if unflag-p
;;	(setq marker ?\040 msg "Unflagging")
;;      (setq marker dired-del-marker msg "Cleaning"))
;;    (ange-ftp-dired-vms-clean-directory nil marker msg)))

;;(or (assq 'vms ange-ftp-dired-flag-backup-files-alist)
;;    (setq ange-ftp-dired-flag-backup-files-alist
;;	  (cons '(vms . ange-ftp-dired-vms-flag-backup-files)
;;		ange-ftp-dired-flag-backup-files-alist)))

;;(defun ange-ftp-dired-vms-backup-diff (&optional switches)
;;  (let ((file (dired-get-filename 'no-dir))
;;	bak)
;;    (if (and (string-match ";[0-9]+$" file)
;;	     ;; Find most recent previous version.
;;	     (let ((root (substring file 0 (match-beginning 0)))
;;		   (ver
;;		    (string-to-int (substring file (1+ (match-beginning 0)))))
;;		   found)
;;	       (setq ver (1- ver))
;;	       (while (and (> ver 0) (not found))
;;		 (setq bak (concat root ";" (int-to-string ver)))
;;		 (and (file-exists-p bak) (setq found t))
;;		 (setq ver (1- ver)))
;;	       found))
;;	(if switches
;;	    (diff (expand-file-name bak) (expand-file-name file) switches)
;;	  (diff (expand-file-name bak) (expand-file-name file)))
;;      (error "No previous version found for %s" file))))

;;(or (assq 'vms ange-ftp-dired-backup-diff-alist)
;;    (setq ange-ftp-dired-backup-diff-alist
;;	  (cons '(vms . ange-ftp-dired-vms-backup-diff)
;;		ange-ftp-dired-backup-diff-alist)))

\f
;;;; ------------------------------------------------------------
;;;; MTS support
;;;; ------------------------------------------------------------


;; Convert NAME from UNIX-ish to MTS. If REVERSE given then convert from
;; MTS to UNIX-ish.
(defun ange-ftp-fix-name-for-mts (name &optional reverse)
  (save-match-data
    (if reverse
	(if (string-match "\\`\\([^:]+:\\)?\\(.*\\)\\'" name)
	    (let (acct file)
	      (setq acct (match-string 1 name))
	      (setq file (match-string 2 name))
	      (concat (and acct (concat "/" acct "/"))
		      file))
	  (error "name %s didn't match" name))
      (if (string-match "\\`/\\([^:]+:\\)/\\(.*\\)\\'" name)
	  (concat (match-string 1 name) (match-string 2 name))
	;; Let's hope that mts will recognize it anyway.
	name))))

(or (assq 'mts ange-ftp-fix-name-func-alist)
    (setq ange-ftp-fix-name-func-alist
	  (cons '(mts . ange-ftp-fix-name-for-mts)
		ange-ftp-fix-name-func-alist)))

;; Convert name from UNIX-ish to MTS ready for a DIRectory listing.
;; Remember that there are no directories in MTS.
(defun ange-ftp-fix-dir-name-for-mts (dir-name)
  (if (string-equal dir-name "/")
      (error "Cannot get listing for fictitious \"/\" directory")
    (let ((dir-name (ange-ftp-fix-name-for-mts dir-name)))
      (cond
       ((string-equal dir-name "")
	"?")
       ((string-match ":\\'" dir-name)
	(concat dir-name "?"))
       (dir-name))))) ; It's just a single file.

(or (assq 'mts ange-ftp-fix-dir-name-func-alist)
    (setq ange-ftp-fix-dir-name-func-alist
	  (cons '(mts . ange-ftp-fix-dir-name-for-mts)
		ange-ftp-fix-dir-name-func-alist)))

(or (memq 'mts ange-ftp-dumb-host-types)
    (setq ange-ftp-dumb-host-types
	  (cons 'mts ange-ftp-dumb-host-types)))

(defvar ange-ftp-mts-host-regexp nil)

;; Return non-nil if HOST is running MTS.
(defun ange-ftp-mts-host (host)
  (and ange-ftp-mts-host-regexp
       (string-match-p ange-ftp-mts-host-regexp host)))

;; Parse the current buffer which is assumed to be in mts ftp dir format.
(defun ange-ftp-parse-mts-listing ()
  (let ((tbl (make-hash-table :test 'equal)))
    (goto-char (point-min))
    (save-match-data
      (while (re-search-forward directory-listing-before-filename-regexp nil t)
	(end-of-line)
	(skip-chars-backward " ")
	(let ((end (point)))
	  (skip-chars-backward "-A-Z0-9_.!")
	  (puthash (buffer-substring (point) end) nil tbl))
	(forward-line 1)))
    ;; Don't need to bother with ..
    (puthash "." t tbl)
    tbl))

(add-to-list 'ange-ftp-parse-list-func-alist
	     '(mts . ange-ftp-parse-mts-listing))

(defun ange-ftp-add-mts-host (host)
  "Mark HOST as the name of a machine running MTS."
  (interactive
   (list (read-string "Host: "
		      (let ((name (or (buffer-file-name) default-directory)))
			(and name (car (ange-ftp-ftp-name name)))))))
  (if (not (ange-ftp-mts-host host))
      (setq ange-ftp-mts-host-regexp
	    (concat "^" (regexp-quote host) "$"
		    (and ange-ftp-mts-host-regexp "\\|")
		    ange-ftp-mts-host-regexp)
	    ange-ftp-host-cache nil)))

;;; Tree dired support:

;;;; There aren't too many systems left that use MTS. This dired support will
;;;; work for the implementation of ftp on mtsg.ubc.ca. I hope other mts systems
;;;; implement ftp in the same way. If not, it might be necessary to make the
;;;; following more flexible.

;;(defun ange-ftp-dired-mts-move-to-filename (&optional raise-error eol)
;;  "In dired, move to first char of filename on this line.
;;Returns position (point) or nil if no filename on this line."
;;  ;; This is the MTS version.
;;  (or eol (setq eol (progn (end-of-line) (point))))
;;  (beginning-of-line)
;;  (if (re-search-forward
;;       ange-ftp-date-regexp eol t)
;;      (progn
;;	(skip-chars-forward " ")          ; Eat blanks after date
;;	(skip-chars-forward "0-9:" eol)   ; Eat time or year
;;	(skip-chars-forward " " eol)      ; one space before filename
;;	;; When listing an account other than the users own account it appends
;;	;; ACCT: to the beginning of the filename. Skip over this.
;;	(and (looking-at "[A-Z0-9_.]+:")
;;	     (goto-char (match-end 0)))
;;	(point))
;;    (if raise-error
;;	(error "No file on this line")
;;      nil)))

;;(or (assq 'mts ange-ftp-dired-move-to-filename-alist)
;;    (setq ange-ftp-dired-move-to-filename-alist
;;	  (cons '(mts . ange-ftp-dired-mts-move-to-filename)
;;		ange-ftp-dired-move-to-filename-alist)))

;;(defun ange-ftp-dired-mts-move-to-end-of-filename (&optional no-error eol)
;;  ;; Assumes point is at beginning of filename.
;;  ;; So, it should be called only after (dired-move-to-filename t).
;;  ;; On failure, signals an error or returns nil.
;;  ;; This is the MTS version.
;;  (let (opoint hidden case-fold-search)
;;    (setq opoint (point)
;;	  eol (line-end-position)
;;	  hidden (and selective-display
;;		      (save-excursion (search-forward "\r" eol t))))
;;    (if hidden
;;	nil
;;      (skip-chars-forward "-A-Z0-9._!" eol))
;;    (or no-error
;;	(not (eq opoint (point)))
;;	(error
;;	 (if hidden
;;	     (substitute-command-keys
;;	      "File line is hidden, type \\[dired-hide-subdir] to unhide")
;;	   "No file on this line")))
;;    (if (eq opoint (point))
;;	nil
;;      (point))))

;;(or (assq 'mts ange-ftp-dired-move-to-end-of-filename-alist)
;;    (setq ange-ftp-dired-move-to-end-of-filename-alist
;;	  (cons '(mts . ange-ftp-dired-mts-move-to-end-of-filename)
;;		ange-ftp-dired-move-to-end-of-filename-alist)))
\f
;;;; ------------------------------------------------------------
;;;; CMS support
;;;; ------------------------------------------------------------

;; Since CMS doesn't have any full file name syntax, we have to fudge
;; things with cd's. We actually send too many cd's, but it's dangerous
;; to try to remember the current minidisk, because if the connection
;; is closed and needs to be reopened, we will find ourselves back in
;; the default minidisk. This is fairly likely since CMS ftp servers
;; usually close the connection after 5 minutes of inactivity.

;; Have I got the filename character set right?

(defun ange-ftp-fix-name-for-cms (name &optional reverse)
  (save-match-data
    (if reverse
	;; Since we only convert output from a pwd in this direction,
	;; we'll assume that it's a minidisk, and make it into a
	;; directory file name. Note that the expand-dir-hashtable
	;; stores directories without the trailing /. Is this
	;; consistent?
	(concat "/" name)
      (if (string-match "\\`/\\([-A-Z0-9$*._]+\\)/\\([-A-Z0-9$._]+\\)?\\'"
			name)
	  (let ((minidisk (match-string 1 name)))
	    (if (match-beginning 2)
		(let ((file (match-string 2 name))
		      (cmd (concat "cd " minidisk))

		      ;; Note that host and user are bound in the call
		      ;; to ange-ftp-send-cmd
		      (proc (ange-ftp-get-process ange-ftp-this-host
						  ange-ftp-this-user)))

		  ;; Must use ange-ftp-raw-send-cmd here to avoid
		  ;; an infinite loop.
		  (if (car (ange-ftp-raw-send-cmd proc cmd ange-ftp-this-msg))
		      file
		    ;; failed... try ONCE more.
		    (setq proc (ange-ftp-get-process ange-ftp-this-host
						     ange-ftp-this-user))
		    (let ((result (ange-ftp-raw-send-cmd proc cmd
							 ange-ftp-this-msg)))
		      (if (car result)
			  file
			;; failed.  give up.
			(ange-ftp-error ange-ftp-this-host ange-ftp-this-user
					(format "cd to minidisk %s failed: %s"
						minidisk (cdr result)))))))
	      ;; return the minidisk
	      minidisk))
	(error "Invalid CMS filename")))))

(or (assq 'cms ange-ftp-fix-name-func-alist)
    (setq ange-ftp-fix-name-func-alist
	  (cons '(cms . ange-ftp-fix-name-for-cms)
		ange-ftp-fix-name-func-alist)))

(or (memq 'cms ange-ftp-dumb-host-types)
    (setq ange-ftp-dumb-host-types
	  (cons 'cms ange-ftp-dumb-host-types)))

;; Convert name from UNIX-ish to CMS ready for a DIRectory listing.
(defun ange-ftp-fix-dir-name-for-cms (dir-name)
  (cond
   ((string-equal "/" dir-name)
    (error "Cannot get listing for fictitious \"/\" directory"))
   ((string-match "\\`/\\([-A-Z0-9$*._]+\\)/\\([-A-Z0-9$._]+\\)?\\'" dir-name)
    (let* ((minidisk (match-string 1 dir-name))
	   ;; host and user are bound in the call to ange-ftp-send-cmd
	   (proc (ange-ftp-get-process ange-ftp-this-host ange-ftp-this-user))
	   (cmd (concat "cd " minidisk))
	   (file (if (match-beginning 2)
		     ;; it's a single file
		     (match-string 2 dir-name)
		   ;; use the wild-card
		   "*")))
      (if (car (ange-ftp-raw-send-cmd proc cmd))
	  file
	;; try again...
	(setq proc (ange-ftp-get-process ange-ftp-this-host
					 ange-ftp-this-user))
	(let ((result (ange-ftp-raw-send-cmd proc cmd)))
	  (if (car result)
	      file
	    ;; give up
	    (ange-ftp-error ange-ftp-this-host ange-ftp-this-user
			    (format "cd to minidisk %s failed: %s"
				    minidisk (cdr result))))))))
   (t (error "Invalid CMS file name"))))

(or (assq 'cms ange-ftp-fix-dir-name-func-alist)
    (setq ange-ftp-fix-dir-name-func-alist
	  (cons '(cms . ange-ftp-fix-dir-name-for-cms)
		ange-ftp-fix-dir-name-func-alist)))

(defvar ange-ftp-cms-host-regexp nil
  "Regular expression to match hosts running the CMS operating system.")

;; Return non-nil if HOST is running CMS.
(defun ange-ftp-cms-host (host)
  (and ange-ftp-cms-host-regexp
       (string-match-p ange-ftp-cms-host-regexp host)))

(defun ange-ftp-add-cms-host (host)
  "Mark HOST as the name of a CMS host."
  (interactive
   (list (read-string "Host: "
		      (let ((name (or (buffer-file-name) default-directory)))
			(and name (car (ange-ftp-ftp-name name)))))))
  (if (not (ange-ftp-cms-host host))
      (setq ange-ftp-cms-host-regexp
	    (concat "^" (regexp-quote host) "$"
		    (and ange-ftp-cms-host-regexp "\\|")
		    ange-ftp-cms-host-regexp)
	    ange-ftp-host-cache nil)))

(defun ange-ftp-parse-cms-listing ()
  ;; Parse the current buffer which is assumed to be a CMS directory listing.
  ;; If we succeed in getting a listing, then we will assume that the minidisk
  ;; exists. file is bound by the call to ange-ftp-ls. This doesn't work
  ;; because ange-ftp doesn't know that the root hashtable has only part of
  ;; the info. It will assume that if a minidisk isn't in it, then it doesn't
  ;; exist. It would be nice if completion worked for minidisks, as we
  ;; discover them.
;  (let* ((dir-file (directory-file-name file))
;	 (root (file-name-directory dir-file))
;	 (minidisk (ange-ftp-get-file-part dir-file))
;	 (root-tbl (ange-ftp-get-hash-entry root ange-ftp-files-hashtable)))
;    (if root-tbl
;	(puthash minidisk t root-tbl)
;      (setq root-tbl (ange-ftp-make-hashtable))
;      (puthash minidisk t root-tbl)
;      (puthash "." t root-tbl)
;      (ange-ftp-set-files root root-tbl)))
  ;; Now do the usual parsing
  (let ((tbl (make-hash-table :test 'equal)))
    (goto-char (point-min))
    (save-match-data
      (while
	  (re-search-forward
	   "^\\([-A-Z0-9$_]+\\) +\\([-A-Z0-9$_]+\\) +[VF] +[0-9]+ " nil t)
	(puthash (concat (match-string 1) "." (match-string 2)) nil tbl)
	(forward-line 1))
      (puthash "." t tbl))
    tbl))

(add-to-list 'ange-ftp-parse-list-func-alist
	     '(cms . ange-ftp-parse-cms-listing))

;;;;; Tree dired support:

;;(defconst ange-ftp-dired-cms-re-exe
;;  "^. [-A-Z0-9$_]+ +EXEC "
;;  "Regular expression to use to search for CMS executables.")

;;(or (assq 'cms ange-ftp-dired-re-exe-alist)
;;    (setq ange-ftp-dired-re-exe-alist
;;	  (cons (cons 'cms  ange-ftp-dired-cms-re-exe)
;;		ange-ftp-dired-re-exe-alist)))


;;(defun ange-ftp-dired-cms-insert-headerline (dir)
;;  ;; CMS has no total line, so we insert a blank line for
;;  ;; aesthetics.
;;  (insert "\n")
;;  (forward-char -1)
;;  (ange-ftp-real-dired-insert-headerline dir))

;;(or (assq 'cms ange-ftp-dired-insert-headerline-alist)
;;    (setq ange-ftp-dired-insert-headerline-alist
;;	  (cons '(cms . ange-ftp-dired-cms-insert-headerline)
;;		ange-ftp-dired-insert-headerline-alist)))

;;(defun ange-ftp-dired-cms-move-to-filename (&optional raise-error eol)
;;  "In dired, move to the first char of filename on this line."
;;  ;; This is the CMS version.
;;  (or eol (setq eol (progn (end-of-line) (point))))
;;  (let (case-fold-search)
;;    (beginning-of-line)
;;    (if (re-search-forward " [-A-Z0-9$_]+ +[-A-Z0-9$_]+ +[VF] +[0-9]+ " eol t)
;;	(goto-char (1+ (match-beginning 0)))
;;      (if raise-error
;;	  (error "No file on this line")
;;	nil))))

;;(or (assq 'cms ange-ftp-dired-move-to-filename-alist)
;;    (setq ange-ftp-dired-move-to-filename-alist
;;	  (cons '(cms . ange-ftp-dired-cms-move-to-filename)
;;		ange-ftp-dired-move-to-filename-alist)))

;;(defun ange-ftp-dired-cms-move-to-end-of-filename (&optional no-error eol)
;;  ;; Assumes point is at beginning of filename.
;;  ;; So, it should be called only after (dired-move-to-filename t).
;;  ;; case-fold-search must be nil, at least for VMS.
;;  ;; On failure, signals an error or returns nil.
;;  ;; This is the CMS version.
;;  (let ((opoint (point))
;;	case-fold-search hidden)
;;    (or eol (setq eol (line-end-position)))
;;    (setq hidden (and selective-display
;;		      (save-excursion
;;			(search-forward "\r" eol t))))
;;    (if hidden
;;	(if no-error
;;	    nil
;;	  (error
;;	   (substitute-command-keys
;;	    "File line is hidden, type \\[dired-hide-subdir] to unhide")))
;;      (skip-chars-forward "-A-Z0-9$_" eol)
;;      (skip-chars-forward " " eol)
;;      (skip-chars-forward "-A-Z0-9$_" eol)
;;      (if (eq opoint (point))
;;	  (if no-error
;;	      nil
;;	    (error "No file on this line"))
;;	(point)))))

;;(or (assq 'cms ange-ftp-dired-move-to-end-of-filename-alist)
;;    (setq ange-ftp-dired-move-to-end-of-filename-alist
;;	  (cons '(cms . ange-ftp-dired-cms-move-to-end-of-filename)
;;		ange-ftp-dired-move-to-end-of-filename-alist)))

(defun ange-ftp-cms-make-compressed-filename (name &optional _reverse)
  (if (string-match "-Z\\'" name)
      (list nil (substring name 0 -2))
    (list t (concat name "-Z"))))

(or (assq 'cms ange-ftp-make-compressed-filename-alist)
    (setq ange-ftp-make-compressed-filename-alist
	  (cons '(cms . ange-ftp-cms-make-compressed-filename)
		ange-ftp-make-compressed-filename-alist)))

;;(defun ange-ftp-dired-cms-get-filename (&optional localp no-error-if-not-filep)
;;  (let ((name (ange-ftp-real-dired-get-filename localp no-error-if-not-filep)))
;;    (and name
;;	 (if (string-match "^\\([^ ]+\\) +\\([^ ]+\\)$" name)
;;	     (concat (substring name 0 (match-end 1))
;;		     "."
;;		     (substring name (match-beginning 2) (match-end 2)))
;;	   name))))

;;(or (assq 'cms ange-ftp-dired-get-filename-alist)
;;    (setq ange-ftp-dired-get-filename-alist
;;	  (cons '(cms . ange-ftp-dired-cms-get-filename)
;;		ange-ftp-dired-get-filename-alist)))
\f
;;;; ------------------------------------------------------------
;;;; BS2000 support
;;;; ------------------------------------------------------------

;; There seems to be an error with regexps. '-' has to be the first
;; character inside of the square brackets.
(defconst ange-ftp-bs2000-short-filename-regexp
  "[-A-Z0-9$#@.]*[A-Z][-A-Z0-9$#@.]*"
  "Regular expression to match for a valid short BS2000 file name.")

(defconst ange-ftp-bs2000-fix-name-regexp-reverse
  (concat
   "^\\(" ange-ftp-bs2000-filename-pubset-regexp "\\)?"
   "\\(" ange-ftp-bs2000-filename-username-regexp "\\)?"
   "\\(" ange-ftp-bs2000-short-filename-regexp "\\)?")
  "Regular expression used in `ange-ftp-fix-name-for-bs2000'.")

(defconst ange-ftp-bs2000-fix-name-regexp
  (concat
   "/?\\(" ange-ftp-bs2000-filename-pubset-regexp "/\\)?"
   "\\(\\$[A-Z0-9]*/\\)?"
   "\\(" ange-ftp-bs2000-short-filename-regexp "\\)?")
  "Regular expression used in `ange-ftp-fix-name-for-bs2000'.")

(defcustom ange-ftp-bs2000-special-prefix
  "X"
  "Prefix used for filenames starting with `#' or `@'."
  :group 'ange-ftp
  :type 'string)

;; Convert NAME from UNIX-ish to BS2000. If REVERSE given then convert from
;; BS2000 to UNIX-ish.
(defun ange-ftp-fix-name-for-bs2000 (name &optional reverse)
  (save-match-data
    (if reverse
	(if (string-match
	     ange-ftp-bs2000-fix-name-regexp-reverse
	     name)
	    (let ((pubset (if (match-beginning 1)
			      (substring name 0 (match-end 1))))
		  (userid (if (match-beginning 2)
			      (substring name
					 (match-beginning 2)
					 (1- (match-end 2)))))
		  (filename (if (match-beginning 3)
				(substring name (match-beginning 3)))))
	      (concat
	       "/"
	       ;; we have to insert "_/" here to prevent expand-file-name to
	       ;; interpret BS2000 pubsets as the special escape prefix:
	       (and pubset (concat "_/" pubset "/"))
	       (and userid (concat userid "/"))
	       filename))
	  (error "name %s didn't match" name))
      ;; and here we (maybe) have to remove the inserted "_/" 'cause
      ;; of our prevention of the special escape prefix above:
      (if (string-match (concat "^/_/") name)
	  (setq name (substring name 2)))
      (if (string-match
	   ange-ftp-bs2000-fix-name-regexp
	   name)
	  (let ((pubset (if (match-beginning 1)
			    (substring name
				       (match-beginning 1)
				       (1- (match-end 1)))))
		(userid (if (match-beginning 2)
			    (substring name
				       (match-beginning 2)
				       (1- (match-end 2)))))
		(filename (if (match-beginning 3)
			      (substring name (match-beginning 3)))))
	    (if (and (boundp 'filename)
		     (stringp filename)
		     (string-match "[#@].+" filename))
		(setq filename (concat ange-ftp-bs2000-special-prefix
				       (substring filename 1))))
	    (upcase
	     (concat
	      pubset
	      (and userid (concat userid "."))
	      ;; change every '/' in filename to a '.', normally not necessary
	      (and filename
		   (subst-char-in-string ?/ ?. filename)))))
	;; Let's hope that BS2000 recognize this anyway:
	name))))

(or (assq 'bs2000 ange-ftp-fix-name-func-alist)
    (setq ange-ftp-fix-name-func-alist
	  (cons '(bs2000 . ange-ftp-fix-name-for-bs2000)
		ange-ftp-fix-name-func-alist)))

;; Convert name from UNIX-ish to BS2000 ready for a DIRectory listing.
;; Remember that there are no directories in BS2000.
(defun ange-ftp-fix-dir-name-for-bs2000 (dir-name)
  (if (string-equal dir-name "/")
      "*" ;; Don't use an empty string here!
    (ange-ftp-fix-name-for-bs2000 dir-name)))

(or (assq 'bs2000 ange-ftp-fix-dir-name-func-alist)
    (setq ange-ftp-fix-dir-name-func-alist
	  (cons '(bs2000 . ange-ftp-fix-dir-name-for-bs2000)
		ange-ftp-fix-dir-name-func-alist)))

(or (memq 'bs2000 ange-ftp-dumb-host-types)
    (setq ange-ftp-dumb-host-types
	  (cons 'bs2000 ange-ftp-dumb-host-types)))

(defvar ange-ftp-bs2000-host-regexp nil)
(defvar ange-ftp-bs2000-posix-host-regexp nil)

;; Return non-nil if HOST is running BS2000.
(defun ange-ftp-bs2000-host (host)
  (and ange-ftp-bs2000-host-regexp
       (string-match-p ange-ftp-bs2000-host-regexp host)))
;; Return non-nil if HOST is running BS2000 with POSIX subsystem.
(defun ange-ftp-bs2000-posix-host (host)
  (and ange-ftp-bs2000-posix-host-regexp
       (string-match-p ange-ftp-bs2000-posix-host-regexp host)))

(defun ange-ftp-add-bs2000-host (host)
  "Mark HOST as the name of a machine running BS2000."
  (interactive
   (list (read-string "Host: "
		      (let ((name (or (buffer-file-name) default-directory)))
			(and name (car (ange-ftp-ftp-name name)))))))
  (if (not (ange-ftp-bs2000-host host))
      (setq ange-ftp-bs2000-host-regexp
	    (concat "^" (regexp-quote host) "$"
		    (and ange-ftp-bs2000-host-regexp "\\|")
		    ange-ftp-bs2000-host-regexp)
	    ange-ftp-host-cache nil)))

(defun ange-ftp-add-bs2000-posix-host (host)
  "Mark HOST as the name of a machine running BS2000 with POSIX subsystem."
  (interactive
   (list (read-string "Host: "
		      (let ((name (or (buffer-file-name) default-directory)))
			(and name (car (ange-ftp-ftp-name name)))))))
  (if (not (ange-ftp-bs2000-posix-host host))
      (setq ange-ftp-bs2000-posix-host-regexp
	    (concat "^" (regexp-quote host) "$"
		    (and ange-ftp-bs2000-posix-host-regexp "\\|")
		    ange-ftp-bs2000-posix-host-regexp)
	    ange-ftp-host-cache nil))
  ;; Install CD hook to cd to posix on connecting:
  (add-hook 'ange-ftp-process-startup-hook 'ange-ftp-bs2000-cd-to-posix)
  host)

(defconst ange-ftp-bs2000-filename-regexp
  (concat
   "\\(" ange-ftp-bs2000-filename-prefix-regexp "\\)?"
   "\\(" ange-ftp-bs2000-short-filename-regexp "\\)")
  "Regular expression to match for a valid BS2000 file name.")

(defcustom ange-ftp-bs2000-additional-pubsets
  nil
  "List of additional pubsets available to all users."
  :group 'ange-ftp
  :type '(repeat string))

;; These parsing functions are as general as possible because the syntax
;; of ftp listings from BS2000 hosts is a bit erratic. What saves us is that
;; the BS2000 filename syntax is so rigid.

;; Extract the next filename from a BS2000 dired-like listing.
(defun ange-ftp-parse-bs2000-filename ()
  (if (re-search-forward ange-ftp-bs2000-filename-regexp nil t)
      (match-string 2)))

;; Parse the current buffer which is assumed to be in (some) BS2000 FTP dir
;; format, and return a hashtable as the result.
(defun ange-ftp-parse-bs2000-listing ()
  (let ((tbl (make-hash-table :test 'equal))
	pubset
	file)
    ;; get current pubset
    (goto-char (point-min))
    (if (re-search-forward ange-ftp-bs2000-filename-pubset-regexp nil t)
	(setq pubset (match-string 0)))
    ;; add files to hashtable
    (goto-char (point-min))
    (save-match-data
      (while (setq file (ange-ftp-parse-bs2000-filename))
	(puthash file nil tbl)))
    ;; add . and ..
    (puthash "." t tbl)
    (puthash ".." t tbl)
    ;; add all additional pubsets, if not listing one of them
    (if (not (member pubset ange-ftp-bs2000-additional-pubsets))
	(mapc (lambda (pubset) (puthash pubset t tbl))
	      ange-ftp-bs2000-additional-pubsets))
    tbl))

(add-to-list 'ange-ftp-parse-list-func-alist
	     '(bs2000 . ange-ftp-parse-bs2000-listing))

(defun ange-ftp-bs2000-cd-to-posix ()
  "cd to POSIX subsystem if the current host matches
`ange-ftp-bs2000-posix-host-regexp'.  All BS2000 hosts with POSIX subsystem
MUST BE EXPLICITLY SET with `ange-ftp-add-bs2000-posix-host' for they cannot
be recognized automatically (they are all valid BS2000 hosts too)."
  (if (and ange-ftp-this-host (ange-ftp-bs2000-posix-host ange-ftp-this-host))
      (progn
	;; change to POSIX:
;	(ange-ftp-raw-send-cmd proc "cd %POSIX")
	(ange-ftp-cd ange-ftp-this-host ange-ftp-this-user "%POSIX")
	;; put new home directory in the expand-dir hashtable.
	;; `ange-ftp-this-host' and `ange-ftp-this-user' are bound in
	;; ange-ftp-get-process.
	(puthash (concat ange-ftp-this-host "/" ange-ftp-this-user "/~")
		 (car (ange-ftp-get-pwd ange-ftp-this-host ange-ftp-this-user))
		 ange-ftp-expand-dir-hashtable))))

;; Not available yet:
;; ange-ftp-bs2000-delete-file-entry
;; ange-ftp-bs2000-add-file-entry
;; ange-ftp-bs2000-file-name-as-directory
;; ange-ftp-bs2000-make-compressed-filename
;; ange-ftp-bs2000-file-name-sans-versions
\f
;;;; ------------------------------------------------------------
;;;; Finally provide package.
;;;; ------------------------------------------------------------

(provide 'ange-ftp)

;;; ange-ftp.el ends here

debug log:

solving a267fc6448 ...
found a267fc6448 in https://yhetil.org/emacs-bugs/87k1v6cvv5.fsf@gmx.de/
found e62bee4499 in https://git.savannah.gnu.org/cgit/emacs.git
preparing index
index prepared:
100644 e62bee4499ebfbd6ce5d967f06392a4f6ce67119	lisp/net/ange-ftp.el

applying [1/1] https://yhetil.org/emacs-bugs/87k1v6cvv5.fsf@gmx.de/
diff --git a/lisp/net/ange-ftp.el b/lisp/net/ange-ftp.el
index e62bee4499..a267fc6448 100644

Checking patch lisp/net/ange-ftp.el...
Applied patch lisp/net/ange-ftp.el cleanly.

index at:
100644 a267fc644821f5d43ab2022ef8bddd8b6188d680	lisp/net/ange-ftp.el

(*) Git path names are given by the tree(s) the blob belongs to.
    Blobs themselves have no identifier aside from the hash of its contents.^

Code repositories for project(s) associated with this public inbox

	https://git.savannah.gnu.org/cgit/emacs.git

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).