Codebase list fish / debian/2.1.1.dfsg-2 expand.cpp
debian/2.1.1.dfsg-2

Tree @debian/2.1.1.dfsg-2 (Download .tar.gz)

expand.cpp @debian/2.1.1.dfsg-2raw · history · blame

   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
/**\file expand.c

String expansion functions. These functions perform several kinds of
parameter expansion.

*/

#include "config.h"

#include <stdlib.h>
#include <stdio.h>
#include <wchar.h>
#include <string.h>
#include <wctype.h>
#include <errno.h>
#include <pwd.h>
#include <unistd.h>
#include <limits.h>
#include <sys/param.h>
#include <sys/types.h>
#ifdef HAVE_SYS_SYSCTL_H
#include <sys/sysctl.h>
#endif
#include <termios.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#include <signal.h>
#include <algorithm>

#include <assert.h>
#include <vector>

#ifdef SunOS
#include <procfs.h>
#endif

#include "fallback.h"
#include "util.h"

#include "common.h"
#include "wutil.h"
#include "env.h"
#include "proc.h"
#include "parser.h"
#include "expand.h"
#include "wildcard.h"
#include "exec.h"
#include "signal.h"
#include "tokenizer.h"
#include "complete.h"

#include "parse_util.h"

/**
   Error issued on invalid variable name
*/
#define COMPLETE_VAR_DESC _( L"The '$' character begins a variable name. The character '%lc', which directly followed a '$', is not allowed as a part of a variable name, and variable names may not be zero characters long. To learn more about variable expansion in fish, type 'help expand-variable'.")

/**
   Error issued on $?
*/
#define COMPLETE_YOU_WANT_STATUS _( L"$? is not a valid variable in fish. If you want the exit status of the last command, try $status.")

/**
   Error issued on invalid variable name
*/
#define COMPLETE_VAR_NULL_DESC _( L"The '$' begins a variable name. It was given at the end of an argument. Variable names may not be zero characters long. To learn more about variable expansion in fish, type 'help expand-variable'.")

/**
   Error issued on invalid variable name
*/
#define COMPLETE_VAR_BRACKET_DESC _( L"Did you mean %ls{$%ls}%ls? The '$' character begins a variable name. A bracket, which directly followed a '$', is not allowed as a part of a variable name, and variable names may not be zero characters long. To learn more about variable expansion in fish, type 'help expand-variable'." )

/**
   Error issued on invalid variable name
*/
#define COMPLETE_VAR_PARAN_DESC _( L"Did you mean (COMMAND)? In fish, the '$' character is only used for accessing variables. To learn more about command substitution in fish, type 'help expand-command-substitution'.")

/**
   Description for child process
*/
#define COMPLETE_CHILD_PROCESS_DESC _( L"Child process")

/**
   Description for non-child process
*/
#define COMPLETE_PROCESS_DESC _( L"Process")

/**
   Description for long job
*/
#define COMPLETE_JOB_DESC _( L"Job")

/**
   Description for short job. The job command is concatenated
*/
#define COMPLETE_JOB_DESC_VAL _( L"Job: %ls")

/**
   Description for the shells own pid
*/
#define COMPLETE_SELF_DESC _( L"Shell process")

/**
   Description for the shells own pid
*/
#define COMPLETE_LAST_DESC _( L"Last background job")

/**
   String in process expansion denoting ourself
*/
#define SELF_STR L"self"

/**
   String in process expansion denoting last background job
*/
#define LAST_STR L"last"

/**
   Characters which make a string unclean if they are the first
   character of the string. See \c expand_is_clean().
*/
#define UNCLEAN_FIRST L"~%"
/**
   Unclean characters. See \c expand_is_clean().
*/
#define UNCLEAN L"$*?\\\"'({})"

static void remove_internal_separator(wcstring &s, bool conv);

int expand_is_clean(const wchar_t *in)
{

    const wchar_t * str = in;

    CHECK(in, 1);

    /*
      Test characters that have a special meaning in the first character position
    */
    if (wcschr(UNCLEAN_FIRST, *str))
        return 0;

    /*
      Test characters that have a special meaning in any character position
    */
    while (*str)
    {
        if (wcschr(UNCLEAN, *str))
            return 0;
        str++;
    }

    return 1;
}

/**
   Return the environment variable value for the string starting at \c in.
*/
static env_var_t expand_var(const wchar_t *in)
{
    if (!in)
        return env_var_t::missing_var();
    return env_get_string(in);
}

/**
   Test if the specified string does not contain character which can
   not be used inside a quoted string.
*/
static int is_quotable(const wchar_t *str)
{
    switch (*str)
    {
        case 0:
            return 1;

        case L'\n':
        case L'\t':
        case L'\r':
        case L'\b':
        case L'\x1b':
            return 0;

        default:
            return is_quotable(str+1);
    }
    return 0;

}

static int is_quotable(const wcstring &str)
{
    return is_quotable(str.c_str());
}

wcstring expand_escape_variable(const wcstring &in)
{

    wcstring_list_t lst;
    wcstring buff;

    tokenize_variable_array(in, lst);

    switch (lst.size())
    {
        case 0:
            buff.append(L"''");
            break;

        case 1:
        {
            const wcstring &el = lst.at(0);

            if (el.find(L' ') != wcstring::npos && is_quotable(el))
            {
                buff.append(L"'");
                buff.append(el);
                buff.append(L"'");
            }
            else
            {
                buff.append(escape_string(el, 1));
            }
            break;
        }
        default:
        {
            for (size_t j=0; j<lst.size(); j++)
            {
                const wcstring &el = lst.at(j);
                if (j)
                    buff.append(L"  ");

                if (is_quotable(el))
                {
                    buff.append(L"'");
                    buff.append(el);
                    buff.append(L"'");
                }
                else
                {
                    buff.append(escape_string(el, 1));
                }
            }
        }
    }
    return buff;
}

/**
   Tests if all characters in the wide string are numeric
*/
static int iswnumeric(const wchar_t *n)
{
    for (; *n; n++)
    {
        if (*n < L'0' || *n > L'9')
        {
            return 0;
        }
    }
    return 1;
}

/**
   See if the process described by \c proc matches the commandline \c
   cmd
*/
static bool match_pid(const wcstring &cmd,
                      const wchar_t *proc,
                      int flags,
                      size_t *offset)
{
    /* Test for a direct match. If the proc string is empty (e.g. the user tries to complete against %), then return an offset pointing at the base command. That ensures that you don't see a bunch of dumb paths when completing against all processes. */
    if (proc[0] != L'\0' && wcsncmp(cmd.c_str(), proc, wcslen(proc)) == 0)
    {
        if (offset)
            *offset = 0;
        return true;
    }

    /* Get the command to match against. We're only interested in the last path component. */
    const wcstring base_cmd = wbasename(cmd);

    bool result = string_prefixes_string(proc, base_cmd);
    if (result)
    {
        /* It's a match. Return the offset within the full command. */
        if (offset)
            *offset = cmd.size() - base_cmd.size();
    }
    return result;
}

/** Helper class for iterating over processes. The names returned have been unescaped (e.g. may include spaces) */
#ifdef KERN_PROCARGS2

/* BSD / OS X process completions */

class process_iterator_t
{
    std::vector<pid_t> pids;
    size_t idx;

    wcstring name_for_pid(pid_t pid);

public:
    process_iterator_t();
    bool next_process(wcstring *str, pid_t *pid);
};

wcstring process_iterator_t::name_for_pid(pid_t pid)
{
    wcstring result;
    int mib[4], maxarg = 0, numArgs = 0;
    size_t size = 0;
    char *args = NULL, *stringPtr = NULL;

    mib[0] = CTL_KERN;
    mib[1] = KERN_ARGMAX;

    size = sizeof(maxarg);
    if (sysctl(mib, 2, &maxarg, &size, NULL, 0) == -1)
    {
        return result;
    }

    args = (char *)malloc(maxarg);
    if (args == NULL)
    {
        return result;
    }

    mib[0] = CTL_KERN;
    mib[1] = KERN_PROCARGS2;
    mib[2] = pid;

    size = (size_t)maxarg;
    if (sysctl(mib, 3, args, &size, NULL, 0) == -1)
    {
        free(args);
        return result;;
    }

    memcpy(&numArgs, args, sizeof(numArgs));
    stringPtr = args + sizeof(numArgs);
    result = str2wcstring(stringPtr);
    free(args);
    return result;
}

bool process_iterator_t::next_process(wcstring *out_str, pid_t *out_pid)
{
    wcstring name;
    pid_t pid = 0;
    bool result = false;
    while (idx < pids.size())
    {
        pid = pids.at(idx++);
        name = name_for_pid(pid);
        if (! name.empty())
        {
            result = true;
            break;
        }
    }
    if (result)
    {
        *out_str = name;
        *out_pid = pid;
    }
    return result;
}

process_iterator_t::process_iterator_t() : idx(0)
{
    int                 err;
    struct kinfo_proc * result;
    bool                done;
    static const int    name[] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0 };
    // Declaring name as const requires us to cast it when passing it to
    // sysctl because the prototype doesn't include the const modifier.
    size_t              length;


    // We start by calling sysctl with result == NULL and length == 0.
    // That will succeed, and set length to the appropriate length.
    // We then allocate a buffer of that size and call sysctl again
    // with that buffer.  If that succeeds, we're done.  If that fails
    // with ENOMEM, we have to throw away our buffer and loop.  Note
    // that the loop causes use to call sysctl with NULL again; this
    // is necessary because the ENOMEM failure case sets length to
    // the amount of data returned, not the amount of data that
    // could have been returned.

    result = NULL;
    done = false;
    do
    {
        assert(result == NULL);

        // Call sysctl with a NULL buffer.

        length = 0;
        err = sysctl((int *) name, (sizeof(name) / sizeof(*name)) - 1,
                     NULL, &length,
                     NULL, 0);
        if (err == -1)
        {
            err = errno;
        }

        // Allocate an appropriately sized buffer based on the results
        // from the previous call.

        if (err == 0)
        {
            result = (struct kinfo_proc *)malloc(length);
            if (result == NULL)
            {
                err = ENOMEM;
            }
        }

        // Call sysctl again with the new buffer.  If we get an ENOMEM
        // error, toss away our buffer and start again.

        if (err == 0)
        {
            err = sysctl((int *) name, (sizeof(name) / sizeof(*name)) - 1,
                         result, &length,
                         NULL, 0);
            if (err == -1)
            {
                err = errno;
            }
            if (err == 0)
            {
                done = true;
            }
            else if (err == ENOMEM)
            {
                assert(result != NULL);
                free(result);
                result = NULL;
                err = 0;
            }
        }
    }
    while (err == 0 && ! done);

    // Clean up and establish post conditions.
    if (err == 0 && result != NULL)
    {
        for (size_t idx = 0; idx < length / sizeof(struct kinfo_proc); idx++)
            pids.push_back(result[idx].kp_proc.p_pid);
    }

    if (result)
        free(result);
}

#else

/* /proc style process completions */
class process_iterator_t
{
    DIR *dir;

public:
    process_iterator_t();
    ~process_iterator_t();

    bool next_process(wcstring *out_str, pid_t *out_pid);
};

process_iterator_t::process_iterator_t(void)
{
    dir = opendir("/proc");
}

process_iterator_t::~process_iterator_t(void)
{
    if (dir)
        closedir(dir);
}

bool process_iterator_t::next_process(wcstring *out_str, pid_t *out_pid)
{
    wcstring cmd;
    pid_t pid = 0;
    while (cmd.empty())
    {
        wcstring name;
        if (! dir || ! wreaddir(dir, name))
            break;

        if (!iswnumeric(name.c_str()))
            continue;

        wcstring path = wcstring(L"/proc/") + name;
        struct stat buf;
        if (wstat(path, &buf))
            continue;

        if (buf.st_uid != getuid())
            continue;

        /* remember the pid */
        pid = fish_wcstoi(name.c_str(), NULL, 10);

        /* the 'cmdline' file exists, it should contain the commandline */
        FILE *cmdfile;
        if ((cmdfile=wfopen(path + L"/cmdline", "r")))
        {
            wcstring full_command_line;
            fgetws2(&full_command_line, cmdfile);

            /* The command line needs to be escaped */
            cmd = tok_first(full_command_line.c_str());
        }
#ifdef SunOS
        else if ((cmdfile=wfopen(path + L"/psinfo", "r")))
        {
            psinfo_t info;
            if (fread(&info, sizeof(info), 1, cmdfile))
            {
                /* The filename is unescaped */
                cmd = str2wcstring(info.pr_fname);
            }
        }
#endif
        if (cmdfile)
            fclose(cmdfile);
    }

    bool result = ! cmd.empty();
    if (result)
    {
        *out_str = cmd;
        *out_pid = pid;
    }
    return result;
}

#endif

std::vector<wcstring> expand_get_all_process_names(void)
{
    wcstring name;
    pid_t pid;
    process_iterator_t iterator;
    std::vector<wcstring> result;
    while (iterator.next_process(&name, &pid))
    {
        result.push_back(name);
    }
    return result;
}

/**
   Searches for a job with the specified job id, or a job or process
   which has the string \c proc as a prefix of its commandline.

   If the ACCEPT_INCOMPLETE flag is set, the remaining string for any matches
   are inserted.

   Otherwise, any job matching the specified string is matched, and
   the job pgid is returned. If no job matches, all child processes
   are searched. If no child processes match, and <tt>fish</tt> can
   understand the contents of the /proc filesystem, all the users
   processes are searched for matches.
*/

static int find_process(const wchar_t *proc,
                        expand_flags_t flags,
                        std::vector<completion_t> &out)
{
    int found = 0;

    if (!(flags & EXPAND_SKIP_JOBS))
    {
        ASSERT_IS_MAIN_THREAD();
        const job_t *j;

        // do the empty param check first, because an empty string passes our 'numeric' check
        if (wcslen(proc)==0)
        {
            /*
              This is an empty job expansion: '%'
              It expands to the last job backgrounded.
            */
            job_iterator_t jobs;
            while ((j = jobs.next()))
            {
                if (!j->command_is_empty())
                {
                    append_completion(out, to_string<long>(j->pgid));
                    break;
                }
            }
            /*
              You don't *really* want to flip a coin between killing
              the last process backgrounded and all processes, do you?
              Let's not try other match methods with the solo '%' syntax.
            */
            found = 1;
        }
        else if (iswnumeric(proc))
        {
            /*
              This is a numeric job string, like '%2'
            */

            if (flags & ACCEPT_INCOMPLETE)
            {
                job_iterator_t jobs;
                while ((j = jobs.next()))
                {
                    wchar_t jid[16];
                    if (j->command_is_empty())
                        continue;

                    swprintf(jid, 16, L"%d", j->job_id);

                    if (wcsncmp(proc, jid, wcslen(proc))==0)
                    {
                        wcstring desc_buff = format_string(COMPLETE_JOB_DESC_VAL, j->command_wcstr());
                        append_completion(out,
                                          jid+wcslen(proc),
                                          desc_buff,
                                          0);
                    }
                }
            }
            else
            {
                int jid;
                wchar_t *end;

                errno = 0;
                jid = fish_wcstoi(proc, &end, 10);
                if (jid > 0 && !errno && !*end)
                {
                    j = job_get(jid);
                    if ((j != 0) && (j->command_wcstr() != 0) && (!j->command_is_empty()))
                    {
                        append_completion(out, to_string<long>(j->pgid));
                    }
                }
            }
            /*
               Stop here so you can't match a random process name
               when you're just trying to use job control.
            */
            found = 1;
        }
        if (found)
            return 1;

        job_iterator_t jobs;
        while ((j = jobs.next()))
        {

            if (j->command_is_empty())
                continue;

            size_t offset;
            if (match_pid(j->command(), proc, flags, &offset))
            {
                if (flags & ACCEPT_INCOMPLETE)
                {
                    append_completion(out,
                                      j->command_wcstr() + offset + wcslen(proc),
                                      COMPLETE_JOB_DESC,
                                      0);
                }
                else
                {
                    append_completion(out, to_string<long>(j->pgid));
                    found = 1;
                }
            }
        }

        if (found)
        {
            return 1;
        }

        jobs.reset();
        while ((j = jobs.next()))
        {
            process_t *p;
            if (j->command_is_empty())
                continue;
            for (p=j->first_process; p; p=p->next)
            {
                if (p->actual_cmd.empty())
                    continue;

                size_t offset;
                if (match_pid(p->actual_cmd, proc, flags, &offset))
                {
                    if (flags & ACCEPT_INCOMPLETE)
                    {
                        append_completion(out,
                                          wcstring(p->actual_cmd, offset + wcslen(proc)),
                                          COMPLETE_CHILD_PROCESS_DESC,
                                          0);
                    }
                    else
                    {
                        append_completion(out,
                                          to_string<long>(p->pid),
                                          L"",
                                          0);
                        found = 1;
                    }
                }
            }
        }

        if (found)
        {
            return 1;
        }
    }

    /* Iterate over all processes */
    wcstring process_name;
    pid_t process_pid;
    process_iterator_t iterator;
    while (iterator.next_process(&process_name, &process_pid))
    {
        size_t offset;
        if (match_pid(process_name, proc, flags, &offset))
        {
            if (flags & ACCEPT_INCOMPLETE)
            {
                append_completion(out,
                                  process_name.c_str() + offset + wcslen(proc),
                                  COMPLETE_PROCESS_DESC,
                                  0);
            }
            else
            {
                append_completion(out, to_string<long>(process_pid));
            }
        }
    }

    return 1;
}

/**
   Process id expansion
*/
static int expand_pid(const wcstring &instr_with_sep,
                      expand_flags_t flags,
                      std::vector<completion_t> &out)
{

    /* expand_string calls us with internal separators in instr...sigh */
    wcstring instr = instr_with_sep;
    remove_internal_separator(instr, false);

    if (instr.empty() || instr.at(0) != PROCESS_EXPAND)
    {
        append_completion(out, instr);
        return 1;
    }

    const wchar_t * const in = instr.c_str();

    if (flags & ACCEPT_INCOMPLETE)
    {
        if (wcsncmp(in+1, SELF_STR, wcslen(in+1))==0)
        {
            append_completion(out,
                              &SELF_STR[wcslen(in+1)],
                              COMPLETE_SELF_DESC,
                              0);
        }
        else if (wcsncmp(in+1, LAST_STR, wcslen(in+1))==0)
        {
            append_completion(out,
                              &LAST_STR[wcslen(in+1)],
                              COMPLETE_LAST_DESC,
                              0);
        }
    }
    else
    {
        if (wcscmp((in+1), SELF_STR)==0)
        {

            append_completion(out, to_string<long>(getpid()));

            return 1;
        }
        if (wcscmp((in+1), LAST_STR)==0)
        {
            if (proc_last_bg_pid > 0)
            {
                append_completion(out, to_string<long>(proc_last_bg_pid));
            }

            return 1;
        }
    }

    size_t prev = out.size();
    if (!find_process(in+1, flags, out))
        return 0;

    if (prev ==  out.size())
    {
        if (!(flags & ACCEPT_INCOMPLETE))
        {
            return 0;
        }
    }

    return 1;
}


void expand_variable_error(parser_t &parser, const wchar_t *token, size_t token_pos, int error_pos)
{
    size_t stop_pos = token_pos+1;

    switch (token[stop_pos])
    {
        case BRACKET_BEGIN:
        {
            wchar_t *cpy = wcsdup(token);
            *(cpy+token_pos)=0;
            wchar_t *name = &cpy[stop_pos+1];
            wchar_t *end = wcschr(name, BRACKET_END);
            wchar_t *post;
            int is_var=0;
            if (end)
            {
                post = end+1;
                *end = 0;

                if (!wcsvarname(name))
                {
                    is_var = 1;
                }
            }

            if (is_var)
            {
                parser.error(SYNTAX_ERROR,
                             error_pos,
                             COMPLETE_VAR_BRACKET_DESC,
                             cpy,
                             name,
                             post);
            }
            else
            {
                parser.error(SYNTAX_ERROR,
                             error_pos,
                             COMPLETE_VAR_BRACKET_DESC,
                             L"",
                             L"VARIABLE",
                             L"");
            }
            free(cpy);

            break;
        }

        case INTERNAL_SEPARATOR:
        {
            parser.error(SYNTAX_ERROR,
                         error_pos,
                         COMPLETE_VAR_PARAN_DESC);
            break;
        }

        case 0:
        {
            parser.error(SYNTAX_ERROR,
                         error_pos,
                         COMPLETE_VAR_NULL_DESC);
            break;
        }

        default:
        {
            wchar_t token_stop_char = token[stop_pos];
            // Unescape (see http://github.com/fish-shell/fish-shell/issues/50)
            if (token_stop_char == ANY_CHAR)
                token_stop_char = L'?';
            else if (token_stop_char == ANY_STRING || token_stop_char == ANY_STRING_RECURSIVE)
                token_stop_char = L'*';

            parser.error(SYNTAX_ERROR,
                         error_pos,
                         (token_stop_char == L'?' ? COMPLETE_YOU_WANT_STATUS : COMPLETE_VAR_DESC),
                         token_stop_char);
            break;
        }
    }
}

/**
   Parse an array slicing specification
 */
static int parse_slice(const wchar_t *in, wchar_t **end_ptr, std::vector<long> &idx, size_t array_size)
{
    wchar_t *end;

    const long size = (long)array_size;
    size_t pos = 1; //skip past the opening square bracket

    //  debug( 0, L"parse_slice on '%ls'", in );

    while (1)
    {
        long tmp;

        while (iswspace(in[pos]) || (in[pos]==INTERNAL_SEPARATOR))
            pos++;

        if (in[pos] == L']')
        {
            pos++;
            break;
        }

        errno=0;
        tmp = wcstol(&in[pos], &end, 10);
        if ((errno) || (end == &in[pos]))
        {
            return 1;
        }
        //    debug( 0, L"Push idx %d", tmp );

        long i1 = tmp>-1 ? tmp : (long)array_size+tmp+1;
        pos = end-in;
        while (in[pos]==INTERNAL_SEPARATOR)
            pos++;
        if (in[pos]==L'.' && in[pos+1]==L'.')
        {
            pos+=2;
            while (in[pos]==INTERNAL_SEPARATOR)
                pos++;
            long tmp1 = wcstol(&in[pos], &end, 10);
            if ((errno) || (end == &in[pos]))
            {
                return 1;
            }
            pos = end-in;

            // debug( 0, L"Push range %d %d", tmp, tmp1 );
            long i2 = tmp1>-1 ? tmp1 : size+tmp1+1;
            // debug( 0, L"Push range idx %d %d", i1, i2 );
            short direction = i2<i1 ? -1 : 1 ;
            for (long jjj = i1; jjj*direction <= i2*direction; jjj+=direction)
            {
                // debug(0, L"Expand range [subst]: %i\n", jjj);
                idx.push_back(jjj);
            }
            continue;
        }

        // debug( 0, L"Push idx %d", tmp );
        idx.push_back(i1);
    }

    if (end_ptr)
    {
        //    debug( 0, L"Remainder is '%ls', slice def was %d characters long", in+pos, pos );

        *end_ptr = (wchar_t *)(in+pos);
    }
    //  debug( 0, L"ok, done" );

    return 0;
}



/**
   Expand all environment variables in the string *ptr.

   This function is slow, fragile and complicated. There are lots of
   little corner cases, like $$foo should do a double expansion,
   $foo$bar should not double expand bar, etc. Also, it's easy to
   accidentally leak memory on array out of bounds errors an various
   other situations. All in all, this function should be rewritten,
   split out into multiple logical units and carefully tested. After
   that, it can probably be optimized to do fewer memory allocations,
   fewer string scans and overall just less work. But until that
   happens, don't edit it unless you know exactly what you are doing,
   and do proper testing afterwards.
*/
static int expand_variables_internal(parser_t &parser, wchar_t * const in, std::vector<completion_t> &out, long last_idx);

static int expand_variables2(parser_t &parser, const wcstring &instr, std::vector<completion_t> &out, long last_idx)
{
    wchar_t *in = wcsdup(instr.c_str());
    int result = expand_variables_internal(parser, in, out, last_idx);
    free(in);
    return result;
}

static int expand_variables_internal(parser_t &parser, wchar_t * const in, std::vector<completion_t> &out, long last_idx)
{
    int is_ok= 1;
    int empty=0;

    wcstring var_tmp;
    std::vector<long> var_idx_list;

    //  CHECK( out, 0 );

    for (long i=last_idx; (i>=0) && is_ok && !empty; i--)
    {
        const wchar_t c = in[i];
        if ((c == VARIABLE_EXPAND) || (c == VARIABLE_EXPAND_SINGLE))
        {
            long start_pos = i+1;
            long stop_pos;
            long var_len;
            int is_single = (c==VARIABLE_EXPAND_SINGLE);

            stop_pos = start_pos;

            while (1)
            {
                if (!(in[stop_pos ]))
                    break;
                if (!(iswalnum(in[stop_pos]) ||
                        (wcschr(L"_", in[stop_pos])!= 0)))
                    break;

                stop_pos++;
            }

            /*      printf( "Stop for '%c'\n", in[stop_pos]);*/

            var_len = stop_pos - start_pos;

            if (var_len == 0)
            {
                expand_variable_error(parser, in, stop_pos-1, -1);

                is_ok = 0;
                break;
            }

            var_tmp.append(in + start_pos, var_len);
            env_var_t var_val = expand_var(var_tmp.c_str());

            if (! var_val.missing())
            {
                int all_vars=1;
                wcstring_list_t var_item_list;

                if (is_ok)
                {
                    tokenize_variable_array(var_val.c_str(), var_item_list);

                    if (in[stop_pos] == L'[')
                    {
                        wchar_t *slice_end;
                        all_vars=0;

                        if (parse_slice(in + stop_pos, &slice_end, var_idx_list, var_item_list.size()))
                        {
                            parser.error(SYNTAX_ERROR,
                                         -1,
                                         L"Invalid index value");
                            is_ok = 0;
                            break;
                        }
                        stop_pos = (slice_end-in);
                    }

                    if (!all_vars)
                    {
                        wcstring_list_t string_values(var_idx_list.size());

                        for (size_t j=0; j<var_idx_list.size(); j++)
                        {
                            long tmp = var_idx_list.at(j);
                            /*
                                           Check that we are within array
                                           bounds. If not, truncate the list to
                                           exit.
                                           */
                            if (tmp < 1 || (size_t)tmp > var_item_list.size())
                            {
                                parser.error(SYNTAX_ERROR,
                                             -1,
                                             ARRAY_BOUNDS_ERR);
                                is_ok=0;
                                var_idx_list.resize(j);
                                break;
                            }
                            else
                            {
                                /* Replace each index in var_idx_list inplace with the string value at the specified index */
                                //al_set( var_idx_list, j, wcsdup((const wchar_t *)al_get( &var_item_list, tmp-1 ) ) );
                                string_values.at(j) = var_item_list.at(tmp-1);
                            }
                        }

                        // string_values is the new var_item_list
                        var_item_list.swap(string_values);
                    }
                }

                if (is_ok)
                {

                    if (is_single)
                    {
                        in[i]=0;
                        wcstring res = in;
                        res.push_back(INTERNAL_SEPARATOR);

                        for (size_t j=0; j<var_item_list.size(); j++)
                        {
                            const wcstring &next = var_item_list.at(j);
                            if (is_ok)
                            {
                                if (j != 0)
                                    res.append(L" ");
                                res.append(next);
                            }
                        }
                        res.append(in + stop_pos);
                        is_ok &= expand_variables2(parser, res, out, i);
                    }
                    else
                    {
                        for (size_t j=0; j<var_item_list.size(); j++)
                        {
                            const wcstring &next = var_item_list.at(j);
                            if (is_ok && (i == 0) && (!in[stop_pos]))
                            {
                                append_completion(out, next);
                            }
                            else
                            {

                                if (is_ok)
                                {
                                    wcstring new_in;

                                    if (start_pos > 0)
                                        new_in.append(in, start_pos - 1);

                                    // at this point new_in.size() is start_pos - 1
                                    if (start_pos>1 && new_in[start_pos-2]!=VARIABLE_EXPAND)
                                    {
                                        new_in.push_back(INTERNAL_SEPARATOR);
                                    }
                                    new_in.append(next);
                                    new_in.append(in + stop_pos);
                                    is_ok &= expand_variables2(parser, new_in, out, i);
                                }
                            }

                        }
                    }
                }

                return is_ok;
            }
            else
            {
                /*
                         Expand a non-existing variable
                         */
                if (c == VARIABLE_EXPAND)
                {
                    /*
                               Regular expansion, i.e. expand this argument to nothing
                               */
                    empty = 1;
                }
                else
                {
                    /*
                               Expansion to single argument.
                               */
                    wcstring res;
                    in[i] = 0;
                    res.append(in);
                    res.append(in + stop_pos);

                    is_ok &= expand_variables2(parser, res, out, i);
                    return is_ok;
                }
            }


        }
    }

    if (!empty)
    {
        append_completion(out, in);
    }

    return is_ok;
}

/**
   Perform bracket expansion
*/
static int expand_brackets(parser_t &parser, const wcstring &instr, int flags, std::vector<completion_t> &out)
{
    bool syntax_error = false;
    int bracket_count=0;

    const wchar_t *bracket_begin = NULL, *bracket_end = NULL;
    const wchar_t *last_sep = NULL;

    const wchar_t *item_begin;
    size_t length_preceding_brackets, length_following_brackets, tot_len;

    const wchar_t * const in = instr.c_str();

    /* Locate the first non-nested bracket pair */
    for (const wchar_t *pos = in; (*pos) && !syntax_error; pos++)
    {
        switch (*pos)
        {
            case BRACKET_BEGIN:
            {
                if (bracket_count == 0)
                    bracket_begin = pos;
                bracket_count++;
                break;

            }
            case BRACKET_END:
            {
                bracket_count--;
                if (bracket_count < 0)
                {
                    syntax_error = true;
                }
                else if (bracket_count == 0)
                {
                    bracket_end = pos;
                    break;
                }

            }
            case BRACKET_SEP:
            {
                if (bracket_count == 1)
                    last_sep = pos;
            }
        }
    }

    if (bracket_count > 0)
    {
        if (!(flags & ACCEPT_INCOMPLETE))
        {
            syntax_error = true;
        }
        else
        {
            /* The user hasn't typed an end bracket yet; make one up and append it, then expand that. */
            wcstring mod;
            if (last_sep)
            {
                mod.append(in, bracket_begin-in+1);
                mod.append(last_sep+1);
                mod.push_back(BRACKET_END);
            }
            else
            {
                mod.append(in);
                mod.push_back(BRACKET_END);
            }

            return expand_brackets(parser, mod, 1, out);
        }
    }

    if (syntax_error)
    {
        parser.error(SYNTAX_ERROR,
                     -1,
                     _(L"Mismatched brackets"));
        return 0;
    }

    if (bracket_begin == NULL)
    {
        append_completion(out, instr);
        return 1;
    }

    length_preceding_brackets = (bracket_begin-in);
    length_following_brackets = wcslen(bracket_end)-1;
    tot_len = length_preceding_brackets+length_following_brackets;
    item_begin = bracket_begin+1;
    for (const wchar_t *pos =(bracket_begin+1); true; pos++)
    {
        if (bracket_count == 0)
        {
            if ((*pos == BRACKET_SEP) || (pos==bracket_end))
            {
                assert(pos >= item_begin);
                size_t item_len = pos-item_begin;

                wcstring whole_item;
                whole_item.reserve(tot_len + item_len + 2);
                whole_item.append(in, length_preceding_brackets);
                whole_item.append(item_begin, item_len);
                whole_item.append(bracket_end + 1);
                expand_brackets(parser, whole_item, flags, out);

                item_begin = pos+1;
                if (pos == bracket_end)
                    break;
            }
        }

        if (*pos == BRACKET_BEGIN)
        {
            bracket_count++;
        }

        if (*pos == BRACKET_END)
        {
            bracket_count--;
        }
    }
    return 1;
}

/**
 Perform cmdsubst expansion
 */
static int expand_cmdsubst(parser_t &parser, const wcstring &input, std::vector<completion_t> &outList)
{
    wchar_t *paran_begin=0, *paran_end=0;
    std::vector<wcstring> sub_res;
    size_t i, j;
    wchar_t *tail_begin = 0;

    const wchar_t * const in = input.c_str();

    int parse_ret;
    switch (parse_ret = parse_util_locate_cmdsubst(in, &paran_begin, &paran_end, false))
    {
        case -1:
            parser.error(SYNTAX_ERROR,
                         -1,
                         L"Mismatched parenthesis");
            return 0;
        case 0:
            outList.push_back(completion_t(input));
            return 1;
        case 1:

            break;
    }

    const wcstring subcmd(paran_begin + 1, paran_end-paran_begin - 1);

    if (exec_subshell(subcmd, sub_res, true /* do apply exit status */) == -1)
    {
        parser.error(CMDSUBST_ERROR, -1, L"Unknown error while evaulating command substitution");
        return 0;
    }

    tail_begin = paran_end + 1;
    if (*tail_begin == L'[')
    {
        std::vector<long> slice_idx;
        wchar_t *slice_end;

        if (parse_slice(tail_begin, &slice_end, slice_idx, sub_res.size()))
        {
            parser.error(SYNTAX_ERROR, -1, L"Invalid index value");
            return 0;
        }
        else
        {
            std::vector<wcstring> sub_res2;
            tail_begin = slice_end;
            for (i=0; i < slice_idx.size(); i++)
            {
                long idx = slice_idx.at(i);
                if (idx < 1 || (size_t)idx > sub_res.size())
                {
                    parser.error(SYNTAX_ERROR,
                                 -1,
                                 ARRAY_BOUNDS_ERR);
                    return 0;
                }
                idx = idx-1;

                sub_res2.push_back(sub_res.at(idx));
                //        debug( 0, L"Pushing item '%ls' with index %d onto sliced result", al_get( sub_res, idx ), idx );
                //sub_res[idx] = 0; // ??
            }
            sub_res = sub_res2;
        }
    }


    /*
       Recursively call ourselves to expand any remaining command
       substitutions. The result of this recursive call using the tail
       of the string is inserted into the tail_expand array list
       */
    std::vector<completion_t> tail_expand;
    expand_cmdsubst(parser, tail_begin, tail_expand);

    /*
       Combine the result of the current command substitution with the
       result of the recursive tail expansion
       */
    for (i=0; i<sub_res.size(); i++)
    {
        wcstring sub_item = sub_res.at(i);
        wcstring sub_item2 = escape_string(sub_item, 1);

        for (j=0; j < tail_expand.size(); j++)
        {

            wcstring whole_item;

            wcstring tail_item = tail_expand.at(j).completion;

            //sb_append_substring( &whole_item, in, len1 );
            whole_item.append(in, paran_begin-in);

            //sb_append_char( &whole_item, INTERNAL_SEPARATOR );
            whole_item.push_back(INTERNAL_SEPARATOR);

            //sb_append_substring( &whole_item, sub_item2, item_len );
            whole_item.append(sub_item2);

            //sb_append_char( &whole_item, INTERNAL_SEPARATOR );
            whole_item.push_back(INTERNAL_SEPARATOR);

            //sb_append( &whole_item, tail_item );
            whole_item.append(tail_item);

            //al_push( out, whole_item.buff );
            outList.push_back(completion_t(whole_item));
        }
    }

    return 1;
}

/**
   Wrapper around unescape funtion. Issues an error() on failiure.
*/
__attribute__((unused))
static wchar_t *expand_unescape(parser_t &parser, const wchar_t * in, int escape_special)
{
    wchar_t *res = unescape(in, escape_special);
    if (!res)
        parser.error(SYNTAX_ERROR, -1, L"Unexpected end of string");
    return res;
}

static wcstring expand_unescape_string(const wcstring &in, int escape_special)
{
    wcstring tmp = in;
    unescape_string(tmp, escape_special);
    /* Need to detect error here */
    return tmp;
}

/* Given that input[0] is HOME_DIRECTORY or tilde (ugh), return the user's name. Return the empty string if it is just a tilde. Also return by reference the index of the first character of the remaining part of the string (e.g. the subsequent slash) */
static wcstring get_home_directory_name(const wcstring &input, size_t *out_tail_idx)
{
    const wchar_t * const in = input.c_str();
    assert(in[0] == HOME_DIRECTORY || in[0] == L'~');
    size_t tail_idx;

    const wchar_t *name_end = wcschr(in, L'/');
    if (name_end)
    {
        tail_idx = name_end - in;
    }
    else
    {
        tail_idx = wcslen(in);
    }
    *out_tail_idx = tail_idx;
    return input.substr(1, tail_idx - 1);
}

/** Attempts tilde expansion of the string specified, modifying it in place. */
static void expand_home_directory(wcstring &input)
{
    if (! input.empty() && input.at(0) == HOME_DIRECTORY)
    {
        size_t tail_idx;
        wcstring username = get_home_directory_name(input, &tail_idx);

        bool tilde_error = false;
        wcstring home;
        if (username.empty())
        {
            /* Current users home directory */
            home = env_get_string(L"HOME");
            tail_idx = 1;
        }
        else
        {
            /* Some other users home directory */
            std::string name_cstr = wcs2string(username);
            struct passwd *userinfo = getpwnam(name_cstr.c_str());
            if (userinfo == NULL)
            {
                tilde_error = true;
                input[0] = L'~';
            }
            else
            {
                home = str2wcstring(userinfo->pw_dir);
            }
        }

        if (! tilde_error)
        {
            input.replace(input.begin(), input.begin() + tail_idx, home);
        }
    }
}

void expand_tilde(wcstring &input)
{
    // Avoid needless COW behavior by ensuring we use const at
    const wcstring &tmp = input;
    if (! tmp.empty() && tmp.at(0) == L'~')
    {
        input.at(0) = HOME_DIRECTORY;
        expand_home_directory(input);
    }
}

static void unexpand_tildes(const wcstring &input, std::vector<completion_t> *completions)
{
    // If input begins with tilde, then try to replace the corresponding string in each completion with the tilde
    // If it does not, there's nothing to do
    if (input.empty() || input.at(0) != L'~')
        return;

    // We only operate on completions that replace their contents
    // If we don't have any, we're done.
    // In particular, empty vectors are common.
    bool has_candidate_completion = false;
    for (size_t i=0; i < completions->size(); i++)
    {
        if (completions->at(i).flags & COMPLETE_REPLACES_TOKEN)
        {
            has_candidate_completion = true;
            break;
        }
    }
    if (! has_candidate_completion)
        return;

    size_t tail_idx;
    wcstring username_with_tilde = L"~";
    username_with_tilde.append(get_home_directory_name(input, &tail_idx));

    // Expand username_with_tilde
    wcstring home = username_with_tilde;
    expand_tilde(home);

    // Now for each completion that starts with home, replace it with the username_with_tilde
    for (size_t i=0; i < completions->size(); i++)
    {
        completion_t &comp = completions->at(i);
        if ((comp.flags & COMPLETE_REPLACES_TOKEN) && string_prefixes_string(home, comp.completion))
        {
            comp.completion.replace(0, home.size(), username_with_tilde);

            // And mark that our tilde is literal, so it doesn't try to escape it
            comp.flags |= COMPLETE_DONT_ESCAPE_TILDES;
        }
    }
}

/**
   Remove any internal separators. Also optionally convert wildcard characters to
   regular equivalents. This is done to support EXPAND_SKIP_WILDCARDS.
*/
static void remove_internal_separator(wcstring &str, bool conv)
{
    /* Remove all instances of INTERNAL_SEPARATOR */
    str.erase(std::remove(str.begin(), str.end(), (wchar_t)INTERNAL_SEPARATOR), str.end());

    /* If conv is true, replace all instances of ANY_CHAR with '?', ANY_STRING with '*', ANY_STRING_RECURSIVE with '*' */
    if (conv)
    {
        for (size_t idx = 0; idx < str.size(); idx++)
        {
            switch (str.at(idx))
            {
                case ANY_CHAR:
                    str.at(idx) = L'?';
                    break;
                case ANY_STRING:
                case ANY_STRING_RECURSIVE:
                    str.at(idx) = L'*';
                    break;
            }
        }
    }
}


int expand_string(const wcstring &input, std::vector<completion_t> &output, expand_flags_t flags)
{
    parser_t parser(PARSER_TYPE_ERRORS_ONLY, true /* show errors */);

    size_t i;
    int res = EXPAND_OK;

    if ((!(flags & ACCEPT_INCOMPLETE)) && expand_is_clean(input.c_str()))
    {
        output.push_back(completion_t(input));
        return EXPAND_OK;
    }

    std::vector<completion_t> clist1, clist2;
    std::vector<completion_t> *in = &clist1, *out = &clist2;

    if (EXPAND_SKIP_CMDSUBST & flags)
    {
        wchar_t *begin, *end;

        if (parse_util_locate_cmdsubst(input.c_str(), &begin, &end, true) != 0)
        {
            parser.error(CMDSUBST_ERROR, -1, L"Command substitutions not allowed");
            return EXPAND_ERROR;
        }
        in->push_back(completion_t(input));
    }
    else
    {
        int cmdsubst_ok = expand_cmdsubst(parser, input, *in);
        if (! cmdsubst_ok)
            return EXPAND_ERROR;
    }

    for (i=0; i < in->size(); i++)
    {
        /*
         We accept incomplete strings here, since complete uses
         expand_string to expand incomplete strings from the
         commandline.
         */
        int unescape_flags = UNESCAPE_SPECIAL | UNESCAPE_INCOMPLETE;
        wcstring next = expand_unescape_string(in->at(i).completion, unescape_flags);

        if (EXPAND_SKIP_VARIABLES & flags)
        {
            for (size_t i=0; i < next.size(); i++)
            {
                if (next.at(i) == VARIABLE_EXPAND)
                {
                    next[i] = L'$';
                }
            }
            out->push_back(completion_t(next));
        }
        else
        {
            if (!expand_variables2(parser, next, *out, next.size() - 1))
            {
                return EXPAND_ERROR;
            }
        }
    }

    in->clear();
    std::swap(in, out); // note: this swaps the pointers only (last output is next input)

    for (i=0; i < in->size(); i++)
    {
        wcstring next = in->at(i).completion;

        if (!expand_brackets(parser, next, flags, *out))
        {
            return EXPAND_ERROR;
        }
    }
    in->clear();
    std::swap(in, out); // note: this swaps the pointers only (last output is next input)

    for (i=0; i < in->size(); i++)
    {
        wcstring next = in->at(i).completion;

        if (!(EXPAND_SKIP_HOME_DIRECTORIES & flags))
            expand_home_directory(next);


        if (flags & ACCEPT_INCOMPLETE)
        {
            if (next[0] == PROCESS_EXPAND)
            {
                /*
                 If process expansion matches, we are not
                 interested in other completions, so we
                 short-circuit and return
                 */
                if (!(flags & EXPAND_SKIP_PROCESS))
                    expand_pid(next, flags, output);
                return EXPAND_OK;
            }
            else
            {
                out->push_back(completion_t(next));
            }
        }
        else
        {
            if (!(flags & EXPAND_SKIP_PROCESS) && ! expand_pid(next, flags, *out))
            {
                return EXPAND_ERROR;
            }
        }
    }

    in->clear();
    std::swap(in, out); // note: this swaps the pointers only (last output is next input)

    for (i=0; i < in->size(); i++)
    {
        wcstring next_str = in->at(i).completion;
        int wc_res;

        remove_internal_separator(next_str, (EXPAND_SKIP_WILDCARDS & flags) ? true : false);
        const wchar_t *next = next_str.c_str();
        
        const bool has_wildcard = wildcard_has(next, 1);
        
        if (has_wildcard && (flags & EXECUTABLES_ONLY))
        {
            // Don't do wildcard expansion for executables. See #785. So do nothing here.
        }
        else if (((flags & ACCEPT_INCOMPLETE) && (!(flags & EXPAND_SKIP_WILDCARDS))) ||
                has_wildcard)
        {
            const wchar_t *start, *rest;

            if (next[0] == '/')
            {
                start = L"/";
                rest = &next[1];
            }
            else
            {
                start = L"";
                rest = next;
            }

            std::vector<completion_t> expanded;
            wc_res = wildcard_expand_string(rest, start, flags, expanded);
            if (flags & ACCEPT_INCOMPLETE)
            {
                out->insert(out->end(), expanded.begin(), expanded.end());
            }
            else
            {
                switch (wc_res)
                {
                    case 0:
                    {
                        if (res == EXPAND_OK)
                            res = EXPAND_WILDCARD_NO_MATCH;
                        break;
                    }

                    case 1:
                    {
                        res = EXPAND_WILDCARD_MATCH;
                        std::sort(expanded.begin(), expanded.end(), completion_t::is_alphabetically_less_than);
                        out->insert(out->end(), expanded.begin(), expanded.end());
                        break;
                    }

                    case -1:
                    {
                        return EXPAND_ERROR;
                    }

                }
            }
        }
        else
        {
            if (!(flags & ACCEPT_INCOMPLETE))
            {
                out->push_back(completion_t(next_str));
            }
        }
    }

    // Hack to un-expand tildes (see #647)
    if (!(flags & EXPAND_SKIP_HOME_DIRECTORIES))
    {
        unexpand_tildes(input, out);
    }

    // Return our output
    output.insert(output.end(), out->begin(), out->end());

    return res;
}

bool expand_one(wcstring &string, expand_flags_t flags)
{
    std::vector<completion_t> completions;
    bool result = false;

    if ((!(flags & ACCEPT_INCOMPLETE)) &&  expand_is_clean(string.c_str()))
    {
        return true;
    }

    if (expand_string(string, completions, flags))
    {
        if (completions.size() == 1)
        {
            string = completions.at(0).completion;
            result = true;
        }
    }
    return result;
}


/*

https://github.com/fish-shell/fish-shell/issues/367

With them the Seed of Wisdom did I sow,
And with my own hand labour'd it to grow:
And this was all the Harvest that I reap'd---
"I came like Water, and like Wind I go."

*/

static std::string escape_single_quoted_hack_hack_hack_hack(const char *str)
{
    std::string result;
    size_t len = strlen(str);
    result.reserve(len + 2);
    result.push_back('\'');
    for (size_t i=0; i < len; i++)
    {
        char c = str[i];
        // Escape backslashes and single quotes only
        if (c == '\\' || c == '\'')
            result.push_back('\\');
        result.push_back(c);
    }
    result.push_back('\'');
    return result;
}

bool fish_xdm_login_hack_hack_hack_hack(std::vector<std::string> *cmds, int argc, const char * const *argv)
{
    bool result = false;
    if (cmds && cmds->size() == 1)
    {
        const std::string &cmd = cmds->at(0);
        if (cmd == "exec \"${@}\"" || cmd == "exec \"$@\"")
        {
            /* We're going to construct a new command that starts with exec, and then has the remaining arguments escaped */
            std::string new_cmd = "exec";
            for (int i=1; i < argc; i++)
            {
                const char *arg = argv[i];
                if (arg)
                {
                    new_cmd.push_back(' ');
                    new_cmd.append(escape_single_quoted_hack_hack_hack_hack(arg));
                }
            }

            cmds->at(0) = new_cmd;
            result = true;
        }
    }
    return result;
}

bool fish_openSUSE_dbus_hack_hack_hack_hack(std::vector<completion_t> *args)
{
    static signed char isSUSE = -1;
    if (isSUSE == 0)
        return false;

    bool result = false;
    if (args && ! args->empty())
    {
        const wcstring &cmd = args->at(0).completion;
        if (cmd.find(L"DBUS_SESSION_BUS_") != wcstring::npos)
        {
            /* See if we are SUSE */
            if (isSUSE < 0)
            {
                struct stat buf = {};
                isSUSE = (0 == stat("/etc/SuSE-release", &buf));
            }

            if (isSUSE)
            {
                /* Look for an equal sign */
                size_t where = cmd.find(L'=');
                if (where != wcstring::npos)
                {
                    /* Oh my. It's presumably of the form foo=bar; find the = and split */
                    const wcstring key = wcstring(cmd, 0, where);

                    /* Trim whitespace and semicolon */
                    wcstring val = wcstring(cmd, where+1);
                    size_t last_good = val.find_last_not_of(L"\n ;");
                    if (last_good != wcstring::npos)
                        val.resize(last_good + 1);

                    args->clear();
                    args->push_back(completion_t(L"set"));
                    if (key == L"DBUS_SESSION_BUS_ADDRESS")
                        args->push_back(completion_t(L"-x"));
                    args->push_back(completion_t(key));
                    args->push_back(completion_t(val));
                    result = true;
                }
                else if (string_prefixes_string(L"export DBUS_SESSION_BUS_ADDRESS;", cmd))
                {
                    /* Nothing, we already exported it */
                    args->clear();
                    args->push_back(completion_t(L"echo"));
                    args->push_back(completion_t(L"-n"));
                    result = true;
                }
            }
        }
    }
    return result;
}

bool expand_abbreviation(const wcstring &src, wcstring *output)
{
    if (src.empty())
        return false;

    /* Get the abbreviations. Return false if we have none */
    env_var_t var = env_get_string(USER_ABBREVIATIONS_VARIABLE_NAME);
    if (var.missing_or_empty())
        return false;

    bool result = false;
    wcstring line;
    wcstokenizer tokenizer(var, ARRAY_SEP_STR);
    while (tokenizer.next(line))
    {
        /* Line is expected to be of the form 'foo=bar'. Parse out the first =. Be forgiving about spaces, but silently skip on failure (no equals, or equals at the end or beginning). Try to avoid copying any strings until we are sure this is a match. */
        size_t equals = line.find(L'=');
        if (equals == wcstring::npos || equals == 0 || equals + 1 == line.size())
            continue;

        /* Find the character just past the end of the command. Walk backwards, skipping spaces. */
        size_t cmd_end = equals;
        while (cmd_end > 0 && iswspace(line.at(cmd_end - 1)))
            cmd_end--;

        /* See if this command matches */
        if (line.compare(0, cmd_end, src) == 0)
        {
            /* Success. Set output to everythign past the end of the string. */
            if (output != NULL)
                output->assign(line, equals + 1, wcstring::npos);

            result = true;
            break;
        }
    }
    return result;
}