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
pub mod list;
pub mod terminal;
pub mod fixtures;

use list::Entry;

use std::env;
use std::path::{Path, PathBuf};
use std::fs::{create_dir_all, metadata, OpenOptions};
use list::List;
use fixtures::command_assistors;
use termion::input::TermRead;
use termion::event::Key;
use termion::raw::{IntoRawMode, RawTerminal};
use std::io::{ Write, stdout, stdin, StdoutLock};
use termion::screen::AlternateScreen;
use easy_hasher::easy_hasher::*;

pub mod app {
    use super::*;

    pub fn run<P: AsRef<Path>>(path: P, all: bool, test: bool, fzf_hook_path: Option<PathBuf>, fzc_hook_path: Option<PathBuf>, fzd_hook_path: Option<PathBuf>) -> LsKey {
        if test {
            let mut path = path.as_ref().to_path_buf();
            create_dir_all(&path).expect("Failed to create directories.");
            path.push(".lsk_test_output");
            std::fs::File::create(&path).expect("failed to create lsk output file");
        }
        let path = path.as_ref();
        let mut ls_key = LsKey::new(path, all, test, fzf_hook_path.clone(), fzc_hook_path.clone(), fzd_hook_path.clone());
        ls_key.update_file_display(false);
        ls_key.run_cmd();
        let mut list = ls_key.list.clone();

        while ls_key.is_fuzzed {
            ls_key.list = list;
            let display = ls_key.display.clone();
            if let Some(fuzzy_list) = ls_key.fuzzy_list.clone() {
                let _list = ls_key.list;
                ls_key = LsKey::new(path, all, test, fzf_hook_path.clone(), fzc_hook_path.clone(), fzd_hook_path.clone());
                ls_key.list = fuzzy_list.clone();
                ls_key.display = display;
            } else if !ls_key.halt {
                let _list = ls_key.list;
                ls_key = LsKey::new(path, all, test, fzf_hook_path.clone(), fzc_hook_path.clone(), fzd_hook_path.clone());
                ls_key.list = _list;
                ls_key.display = display;
            }
            ls_key.update_file_display(false);
            ls_key.run_cmd();
            list = ls_key.list.clone();
        }

        ls_key
    }
}

#[derive(Debug, Clone, PartialEq, Default)]
pub struct LsKey {
    pub list: List,
    pub all: bool,
    pub input: Input,
    pub fuzzy_list: Option<List>,
    pub pre_fuzz_list: Option<List>,
    pub display: Option<(PathBuf, String)>,
    pub halt: bool,
    pub is_fuzzed: bool,
    pub test: bool,
    pub input_vec: Vec<String>,
    pub output_vec: Vec<String>,
    pub fzf_hook_path: Option<PathBuf>,
    pub fzc_hook_path: Option<PathBuf>,
    pub fzd_hook_path: Option<PathBuf>,
    pub default_editor: String,
    pub default_opener: String,
}

impl LsKey {
    pub fn new<P: AsRef<Path>>(path: P, all: bool, test: bool, fzf_hook_path: Option<PathBuf>, fzc_hook_path: Option<PathBuf>, fzd_hook_path: Option<PathBuf>) -> Self {
        let mut ls_key: LsKey = Default::default();
        let list = if all {
           list::List::new(path)
               .list_include_hidden()
               .unwrap()
        } else {
           list::List::new(path)
               .list_skip_hidden()
               .unwrap()
        };

        match env::var("EDITOR") {
            Ok(editor) => {
                 ls_key.default_editor = editor
            },
            Err(_) => {
                ls_key.default_editor = "nano".to_string()
            }
        };

        match env::var("LSK_FILE_OPENER") {
            Ok(editor) => {
                 ls_key.default_opener = editor
            },
            Err(_) => {
                ls_key.default_opener = "xdg-open".to_string()
            }
        };

        ls_key.list = list;
        ls_key.all = all;
        ls_key.halt = true;
        ls_key.is_fuzzed = false;
        ls_key.test = test;
        ls_key.fzf_hook_path = fzf_hook_path;
        ls_key.fzc_hook_path = fzc_hook_path;
        ls_key.fzd_hook_path = fzd_hook_path;

        ls_key
    }

    fn fuzzy_score(&mut self, mut input: String) -> list::fuzzy_score::Scores {
        let files = &self.list.files;

        let mut input_vec_str: Vec<&str> = input.split(" ").collect();

        if input_vec_str.iter().count() > 1{
            input_vec_str.pop();
            input = input_vec_str.into_iter().collect();
        }
        let score_list = |entry: Entry| {
            (
             entry.clone(),
             list::fuzzy_score::score(entry.path.to_str().unwrap(), &input)
            )
        };

        let files_score: Vec<list::fuzzy_score::Score> =
           files.iter()
               .map(|file| list::fuzzy_score::Score::Files(score_list(
                                Entry {
                                    path: file.path.to_path_buf(),
                                    file_type: file.file_type.clone(),
                                    key: file.key
                                }
                           )
                       )
                )
               .collect();

        let files = files_score;

        list::fuzzy_score::Scores {
            files,
        }
    }

    fn fuzzy_rank(&mut self, mut scores: list::fuzzy_score::Scores) -> list::fuzzy_score::Scores {
        scores.files.sort_by(|a, b| list::fuzzy_score::order(a, b));

        scores
    }

    // Filter out no-scores.
    fn fuzzy_filter(&mut self, scores: list::fuzzy_score::Scores) -> list::fuzzy_score::Scores {
         let mut files_vec: Vec<list::fuzzy_score::Score> = vec![];
         for score in scores.files.iter() {
             let path = score.score().0;
             let score = score.score().1;

             let thing = (path, score.clone());

             if score.is_some() {
                  files_vec.push(list::fuzzy_score::Score::Files(thing));
             }
         }

         list::fuzzy_score::Scores {
             files: files_vec,
         }
    }

    pub fn fuzzy_update(&mut self, input: String) -> Self {
        let scores = self.fuzzy_score(input);
        let scores = self.fuzzy_rank(scores);
        let scores = self.fuzzy_filter(scores);
        let list = self.scores_to_list(scores);
        self.update_file_display(false);
        self.fuzzy_list = Some(list);

        self.clone()
    }


    pub fn scores_to_list(&mut self, scores: list::fuzzy_score::Scores) -> list::List {
        let files_list: Vec<Entry> = scores.files.iter().map(|score|
            Entry {
                path: score.score().0.path,
                file_type: score.score().0.file_type,
                key: score.score().0.key
            }
        ).collect();

        self.list.files = files_list;

        self.list.clone()
    }

    pub fn update(&mut self, list: List) {
            let list = if self.all {
                   list
                   .list_include_hidden()
                   .unwrap()
            } else {
                   list
                   .list_skip_hidden()
                   .unwrap()
            };

            self.list = list;
    }

   pub fn update_file_display(&mut self, mut filter: bool) {
            let mut go = true;
            let entries_count = self.list.files.iter().count();
            let mut start = 0;
            let mut end = entries_count;
            if let Some(ls) = &self.list.filter {
                start = ls.clone().into_iter().nth(0).unwrap();
                end = *ls.into_iter().last().unwrap();
            } else {
            }
            while go {
                let entries = self.list.order_and_sort_list(true, filter);
                let mut entries_keyed: Vec<String> = list::key_entries(entries.clone());
                if end  < entries_count {
                    let last = format!("[{}...{}]", end, entries_count);
                    entries_keyed.push(last);
                }
                let res = terminal::input_n_display::grid(entries_keyed.clone());
                if let Some(r) = res {
                    let grid = r.0;
                    let width = r.1;
                    let height = r.2;
                    let display: terminal::input_n_display::Display;
                    let _display = grid.fit_into_width(width);
                    let pad: usize;
                    if _display.is_some() && !self.test {
                         display = _display.unwrap(); // Safe to unwrap.
                         pad = 4;
                    } else {
                         display = grid.fit_into_columns(1);
                         pad = 5;
                    }
                    let grid_row_count = display.row_count();
                    if (grid_row_count + pad) > height {
                        //panic!("Can't fit list into screen.");
                        //

                        let mut filter_vec: Vec<usize> = vec![];

                        let diff = (grid_row_count + pad).checked_sub(height).unwrap_or(1);

                        end = end.checked_sub(diff).unwrap_or(end);
                        let range = start..end;

                        range.into_iter().for_each(|i|
                            filter_vec.push(i)
                        );

                        self.list.filter = Some(filter_vec);
                        filter = true;


                    } else {
                       go = false;
                    }

                    self.display = Some((self.list.parent_path.clone(), display.to_string()));
                } else {
                    go = false;
                }
            }
    }

    fn return_file_by_key_mode(&mut self, input: Input, is_fuzzed: bool) {
        let get_file = |key_string: String| {
             let key: usize = key_string.parse().unwrap();
             self.list.get_file_by_key(key, !is_fuzzed).unwrap()
        };

        let mut n = 0;
        let mut format_cmd = |key: PathBuf| {
                    n +=1;
                    let file_string = get_file(key.to_str().unwrap().to_string()).to_str().unwrap().to_string();
                    let file_string = file_string.replace(" ", r"\ ");
                   format!(r#"{}={}"#, n, file_string)
        };

        if let Some (r) = input.args {
            let _output_vec: Vec<std::process::Output> =
                r.iter()
                    .map(|key|
                         format_cmd(PathBuf::from(key))
                    ).map(|statement|
                        format!(r#""$(printf '{} \n ')""#, statement)
                    ).map(|cmd|
                        terminal::parent_shell::type_text(
                            cmd,
                            0
                        )
                    ).collect();
        } else {
            ()
        }
    }

    pub fn filter_mode(&mut self, list: List) {
        let input_string: String = self.input.display.iter().collect();
        let mut input_vec_str: Vec<&str> = input_string.split("-").collect();
        let mut key_vec: Vec<usize> = vec![];

        // Does it end in "-"?
        let last = input_vec_str.iter().last();
        let mut open_range = false;
        if let Some(l) = last {
            if l == &"" {
                open_range = true;
           }
        }

        // Only want to deal with integers if it's an open range.
        if open_range {
           input_vec_str.pop();
        }

        // Make sure it'sall integers.
        for i in input_vec_str.into_iter() {
            let key: Result<usize, std::num::ParseIntError> = i.parse();
            if key.is_ok() {
                key_vec.push(key.unwrap());
            }

        }

        let end: usize;
        let start = key_vec.clone().into_iter().nth(0).unwrap();

        if open_range {
            end =  list.files.iter().count() + 1;
        } else {
            end = key_vec.clone().into_iter().nth(1).unwrap() + 1;
        }

        let range = start..end;

        let mut filter_vec: Vec<usize> = vec![];

        range.into_iter().for_each(|i|
            filter_vec.push(i)
        );

        self.list.filter = Some(filter_vec);
        self.update_file_display(true);
        self.run_cmd()
    }

    pub fn key_mode(&mut self, list: List, input: Input, is_fuzzed: bool) {
        let key: usize = input.cmd.unwrap().parse().unwrap();
        match key {
            0 => {
                 self.list.parent_path.pop();
                 let file_pathbuf = self.list.parent_path.clone();
                 self.list.parent_path.pop();
                 let list = self.list.clone().update(file_pathbuf);
                 self.update(list);
                 self.halt = false;
                 let halt = self.list.filter.is_some();
                 self.update_file_display(halt);
                 if !halt {
                     self.run_cmd();
                 }
            },
            _ => {
                  let file_pathbuf = list.get_file_by_key(key, !is_fuzzed).unwrap();
                  if metadata(file_pathbuf.clone()).unwrap().is_dir() {
                      let list = self.list.clone().update(file_pathbuf);
                      self.update(list);
                      self.halt = false;
                      let halt = self.list.filter.is_some();
                      self.update_file_display(halt);
                      if !halt {
                          self.run_cmd();
                      }
                  } else {
                      let file_path =
                          file_pathbuf
                          .to_str().unwrap()
                          .to_string();
                      terminal::shell::spawn(self.default_editor.clone(), vec![file_path]);
                      self.halt = true;
                      self.update_file_display(self.halt);
                      self.run_cmd();
                  }
            }
        }
    }

    fn cmd_mode(&mut self, input: Input) {
         let args = input.args;
         if let Some(a) = args {
             let args = a;
             // Unwrap is safe because is_key is not None and there are args.
             let cmd = input.cmd.unwrap();
             let list_parent_path = self.list.parent_path.clone();
             let mut path_cache = command_assistors::PathCache::new(
                 list_parent_path.as_path()
             );
             path_cache.switch();
             match cmd.as_str() {
                 //"fzf" => {
                 //    //Split cmd ('fzf')
                 //    let split: Vec<&str> = input.as_read.split("fzf").collect();
                 //    let cmd = split.iter().last().unwrap();
                 //    let cmd = format!(r#"fzf {}"#, cmd);
                 //    let output = terminal::shell::cmd(cmd.clone());
                 //    let file_path = output.unwrap();
                 //    terminal::shell::spawn("vim".to_string(), vec![file_path]);
                 //},
                 //"fzc" => {
                 //    //let split: Vec<&str> = input.as_read.split("fzc").collect();
                 //    let fzc_pathbuf = self.fzc_hook_path.as_ref().expect("fzc fail: no fzc hook path specified");
                 //    let fzc_path_string = fzc_pathbuf.clone().into_os_string().into_string().unwrap();
                 //    let output = terminal::shell::output("sh".to_string(), vec![fzc_path_string]).expect("fail to get output from fzc hook script");
                 //    let cmd = String::from_utf8_lossy(&output.stdout).to_string();
                 //    let mut input = Input::new();
                 //    let input = input.parse(cmd);
                 //    assert!(input.args.is_some());
                 //    self.cmd_mode(input);
                 //},
                 _ => {
                      terminal::shell::spawn(cmd.to_string(), args);
                 }
             }
             path_cache.switch_back();
         } else {
             let as_read = input.as_read.as_str();
             match as_read {
                 "q" => (),
                 "fzf" => {
                     let mut path_cache = command_assistors::PathCache::new(
                         self.list.parent_path.as_path()
                     );
                     path_cache.switch();
                     let fzf_pathbuf = self.fzf_hook_path.as_ref().expect("fzf fail: no fzf hook path specified");
                     let fzf_path_string = fzf_pathbuf.clone().into_os_string().into_string().unwrap();
                     let file_path = terminal::shell::cmd(fzf_path_string).unwrap();
                     //assert!(input.args.is_some());
                     //let cmd_res = terminal::shell::cmd(cmd_path).unwrap();
                     terminal::shell::spawn(self.default_editor.clone(), vec![file_path]);
                     path_cache.switch_back();
                 },
                 "fzc" => {
                     let mut path_cache = command_assistors::PathCache::new(
                         self.list.parent_path.as_path()
                     );
                     path_cache.switch();
                     let fzc_pathbuf = self.fzc_hook_path.as_ref().expect("fzc fail: no fzc hook path specified");
                     let fzc_path_string = fzc_pathbuf.clone().into_os_string().into_string().unwrap();
                     let cmd = terminal::shell::cmd(fzc_path_string).unwrap();
                     let input = Input::new();
                     let input = input.parse(cmd);
                     //assert!(input.args.is_some());
                     //let cmd_res = terminal::shell::cmd(cmd_path).unwrap();
                     path_cache.switch_back();
                     self.cmd_mode(input);
                 },
                 "fzd" => {
                     let list_parent_path = self.list.parent_path.clone();
                     let mut path_cache = command_assistors::PathCache::new(
                         list_parent_path.as_path()
                     );
                     path_cache.switch();
                     let fzd_pathbuf = self.fzd_hook_path.as_ref().expect("fzd fail: no fzd hook path specified");
                     let fzd_path_string = fzd_pathbuf.clone().into_os_string().into_string().unwrap();
                     let dir = terminal::shell::cmd(fzd_path_string).unwrap();
                     let mut dir_pathbuf = PathBuf::from(dir);
                     let mut pathbuf_vec: Vec<PathBuf> = vec![];
                     if metadata(dir_pathbuf.clone()).unwrap().is_dir() {
                         loop {
                             if dir_pathbuf != PathBuf::from("") {
                                 if dir_pathbuf != PathBuf::from("/") {
                                     pathbuf_vec.push(dir_pathbuf.clone());
                                 } else {
                                     break
                                 }
                             } else {
                                 break
                             }
                             dir_pathbuf.pop();
                         }
                         for dir_pathbuf in pathbuf_vec.iter().rev() {
                             let list = self.list.clone().update(dir_pathbuf);
                             self.update(list);
                         }
                         self.halt = false;
                         let halt = self.list.filter.is_some();
                         self.update_file_display(halt);
                     }
                     path_cache.switch_back();
                 },
                 "zsh" => {
                     let mut path_cache = command_assistors::PathCache::new(
                         self.list.parent_path.as_path()
                     );
                     path_cache.switch();
                     //Split cmd ('zsh')
                     //let split: Vec<&str> = input.as_read.split("zsh").collect();
                     //let cmd = split.iter().last().unwrap();
                     //let cmd = format!(r#"zsh {}"#, cmd);
                     terminal::shell::spawn("zsh".to_string(), vec![]);
                     path_cache.switch_back();
                 },
                 _ => {
                     let mut path_cache = command_assistors::PathCache::new(
                         self.list.parent_path.as_path()
                     );
                     path_cache.switch();
                     let _output = terminal::shell::cmd(as_read.to_string()).unwrap();
                     path_cache.switch_back();
                 }
             }
        }
    }

    fn open_file_by_key_mode(&mut self, input: Input, is_fuzzed: bool) {
        let get_file = |key_string: String| {
             let key: usize = key_string.parse().unwrap();
             self.list.get_file_by_key(key, !is_fuzzed).unwrap()
        };

        //let mut n = 0;
        //let mut format_cmd = |key: PathBuf| {
        //            n +=1;
        //            let file_string = get_file(key.to_str().unwrap().to_string()).to_str().unwrap().to_string();
        //            let file_string = file_string.replace(" ", r"\ ");
        //           format!(r#"{}={}"#, n, file_string)
        //};

        if let Some (r) = input.args {
            let _output_vec: Vec<String> =
                r.iter()
                    .map(|key|
                         get_file(key.to_string())
                    ).map(|file|
                        terminal::shell::cmd(format!("{:?} {:?}", self.default_opener, file)).unwrap()
                    ).collect();
        } else {
            ()
        }

        self.halt = false;
        let halt = self.list.filter.is_some();
        self.update_file_display(halt);
        if !halt {
            self.run_cmd();
        }
    }

    fn key_related_mode(&mut self, input: Result<Option<String>, std::io::Error>, is_fuzzed: bool) {
        match input {
            Ok(t) =>  {
                if let Some(i) = t {
                    let input = Input::new();
                    let input = input.parse(i);
                    // Safe to unwrap.
                    //
                    match input.clone().cmd_type.unwrap() {
                        CmdType::SingleKey => {
                            self.key_mode(self.list.clone(), input, is_fuzzed);
                        },
                        CmdType::OpenKeys => {
                            self.open_file_by_key_mode(input, is_fuzzed);
                        },
                        CmdType::MultipleKeys => {
                            /*
                                * get_file_by_key for each key
                                * let text_vec = vec![r#"printf '1=file1; 2=file2;...'; \n "#]
                                * then type_text_spawn(text_vec);
                            */
                            self.return_file_by_key_mode(input, is_fuzzed);
                        },
                        CmdType::FilterKeys => {
                            self.filter_mode(self.list.clone());
                        },
                        _ => ()
                    }
                } else {
                    ()
                }
            },
            Err(_) => ()
        }
    }

    // If you want to return the output of a commands, see fzf example below.
    // The commmand 'vim', without any args, is a special case handled by
    // ls-key. If the non-built in command doesn't return output and enters
    // into a child process (e.g. vim), then shell::cmd cannot be used, to my
    // understanding.
    fn run_cmd(&mut self) {
        //If the is a fuzzy re-entry, we must reset is_fuzzed and halt to default.
        let mut execute = false;
        while !execute {
           let (input,_execute) = self.read_process_chars();
            execute = _execute;
           if execute && !self.input.full_backspace {
               self.key_related_mode(Ok(input), self.is_fuzzed);
           } else if !execute && self.input.full_backspace {
           } else {
               break
           }
           self.input.full_backspace = false;
        }
    }

    fn test_data_update(&mut self, input: Option<String>) {
        if self.test == true {
            if input.is_some() {
                let hash = sha256(&input.clone().unwrap());
                let original_dir = self.clone().list.path_history.into_iter().nth(0);
                if original_dir.is_some() {
                    let mut original_dir = original_dir.unwrap();
                    //file.write_all(stuff.as_bytes()).unwrap();
                    original_dir.push(".lsk_test_output");
                    let mut file = OpenOptions::new()
                       .write(true)
                       .append(true)
                       .open(original_dir.clone().into_os_string().into_string().unwrap())
                       .unwrap();

                   if let Err(e) = writeln!(file, "{}", hash.to_hex_string()) {
                       eprintln!("Couldn't write to file: {}", e);
                   }
                }
            }
            if self.display.is_some() {
                let hash = sha256(&self.display.clone().unwrap().1);
                let original_dir = self.clone().list.path_history.into_iter().nth(0);

                if original_dir.is_some() {
                    let mut original_dir = original_dir.unwrap();
                    //file.write_all(stuff.as_bytes()).unwrap();
                    original_dir.push(".lsk_test_output");
                    let mut file = OpenOptions::new()
                       .write(true)
                       .append(true)
                       .open(original_dir.clone().into_os_string().into_string().unwrap())
                       .unwrap();

                   if let Err(e) = writeln!(file, "{}", hash.to_hex_string()) {
                       eprintln!("Couldn't write to file: {}", e);
                   }
                }
            }
        }
    }

    fn read_process_chars(&mut self) -> (Option<String>, bool) {
        self.input = Input::new();
        let stdin = stdin();
        let stdout = stdout();
        let stdout = stdout.lock().into_raw_mode().unwrap();
        let mut screen: AlternateScreen<RawTerminal<StdoutLock>> = AlternateScreen::from(stdout);
        let stdin = stdin.lock();
        let mut result: Option<String> =  None;
        let mut is_fuzzed = false;
        let orig_ls_key = self.clone();

        clear_display(&mut screen);

        let input_string: String = self.input.display.iter().collect();
        self.test_data_update(Some(input_string));
        display_files(self.clone(), b"", &mut screen, (0, 3));

        for c in stdin.keys() {
            self.input.full_backspace;
            clear_display(&mut screen);
            let c = c.unwrap();

            self.input.match_event(c);
            let mut input_string: String = self.input.display.iter().collect();
            let input = self.input.clone();
            let first = input.display.iter().nth(0);
            let input = self.input.clone();
            let last = input.display.iter().last();
            let mut _input = self.input.clone();

            let place = (0, 1);
            if let Some(_) = first {

                if self.input.unwiddle {
                    self.fuzzy_list = self.pre_fuzz_list.clone();
                    if let Some(x) = self.pre_fuzz_list.clone() {
                        self.list = x;
                    }
                    if self.input.full_backspace {
                       *self = orig_ls_key.clone();
                       is_fuzzed = false;
                    }
                }
                self.test_data_update(Some(input_string.clone()));
                display_input(input_string.clone(), &mut screen, place);

                let some_mode = self.mode_parse(input_string.clone());

                if let Some(mode) = some_mode {
                    match mode {
                        Mode::Cmd(_) => {
                             if &last == &Some(&'\n') {
                                 self.cmd_read();

                                 //Clear the command from the lsk console after executing.
                                 input_string = "".to_string();
                                 self.input.display = input_string.chars().collect();
                                 clear_display(&mut screen);
                             }
                        },
                        Mode::Work => {
                             if &last == &Some(&'\n') {
                                 let path = self.list.parent_path.clone();
                                 let path = path.to_str().unwrap();
                                 let cmd = format!(r#""$(printf 'cd {} \n ')""#, path).to_string();
                                 terminal::parent_shell::type_text(cmd, 0);
                                 self.is_fuzzed = false;
                                 break
                            } else {

                            }
                        },
                        Mode::Fuzzy(fuzzy_mode_input) => {
                            if !is_fuzzed {
                                self.pre_fuzz_list = Some(self.list.clone());
                            }
                            let _show = self.display.clone();
                            let some_keys = parse_keys(fuzzy_mode_input.as_str());

                            if let Some(keys) = some_keys {
                                input_string = keys;
                                self.input.display = input_string.chars().collect();
                            } else {

                                if self.input.unwiddle {
                                    self.fuzzy_list = self.pre_fuzz_list.clone();
                                    if let Some(x) = self.pre_fuzz_list.clone() {
                                        self.list = x;
                                    }
                                }

                                if self.input.display.iter().last() != Some(&'\n') {
                                    self.fuzzy_update(fuzzy_mode_input);
                                }
                            }

                            is_fuzzed = true;
                        }
                    }
                }
            }

            //if self.input.unwiddle {
            //    self.fuzzy_list = self.pre_fuzz_list.clone();
            //    if let Some(x) = self.pre_fuzz_list.clone() {
            //        self.list = x;
            //    }
            //    if self.input.full_backspace {
            //       *self = orig_ls_key.clone();
            //       is_fuzzed = false;
            //    }
            //}


            if self.input.full_backspace {
               *self = orig_ls_key.clone();
               is_fuzzed = false;
            }
            self.test_data_update(Some(input_string.clone()));
            display_files(self.clone(), b"", &mut screen, (0, 3));

            if self.input.display.iter().last() == Some(&'\n') {
                self.input.display.pop();
                let input_string: String = self.input.display.iter().collect();
                result = Some(input_string);
                self.is_fuzzed = is_fuzzed;
                if self.is_fuzzed {
                }
                break
            }
        }

        write!(screen, "{}", termion::cursor::Show).unwrap();

        (result, self.input.execute)
    }

    pub fn mode_parse(&mut self, mut input: String) -> Option<Mode> {
        let len = input.len();
        let mode = if len >= 2 {
             let mode = input.as_str();
             if mode == "w\n" {
                 Some(Mode::Work)
             } else {
                  let mode: String = input.drain(..2).collect();
                  let mode = mode.as_str();
                  match mode {
                      "s " => Some(Mode::Fuzzy(input.clone())),
                      "c " => Some(Mode::Cmd(input.clone())),
                      _ => None
                  }
             }
        } else {
            None
        };

        mode
    }

    fn cmd_read(&mut self) -> String {
         self.input.display.pop();
         let input_string: String = self.input.display.iter().collect();
         let cmd_mode = self.mode_parse(input_string.clone()).unwrap(); //safe

         match cmd_mode {
             Mode::Cmd(cmd_mode_input) => {
                 let input = Input::new();
                 let input = input.parse(cmd_mode_input);

                 match input.clone().cmd_type.unwrap() {
                     CmdType::Cmd => {
                         self.cmd_mode(input);
                     },
                     _ => {}
                 }
                 //break
             }
             _ => { }
         }

        input_string
    }
}


fn clear_display(screen: &mut AlternateScreen<RawTerminal<StdoutLock>>) {
    write!(
        screen,
        "{}",
        termion::clear::All
    ).unwrap();
    screen.flush().unwrap();
}

fn display_input(input_string: String, screen: &mut AlternateScreen<RawTerminal<StdoutLock>>, position: (u16, u16)) {
    write!(screen,
        "{}{}{}{}", format!("{}", input_string.as_str()
        ),
       termion::clear::AfterCursor,
       termion::cursor::Goto(position.0, position.1 + 1),
       termion::cursor::Hide,
    ).unwrap();
    screen.flush().unwrap();
}

fn display_files(ls_key: LsKey, some_stuff: &[u8], screen: &mut AlternateScreen<RawTerminal<StdoutLock>>, position: (u16, u16)) {
     let show = ls_key.clone().display;
     if let Some(x) = show {
         if x.0 == ls_key.list.parent_path {
              //into_raw_mode requires carriage returns.
              let display = str::replace(x.1.as_str(), "\n", "\n\r");
              write!(
                  screen,
                  "{}{}{}\n", format!("{}", std::str::from_utf8(&some_stuff).unwrap()),
                  termion::cursor::Goto(position.0, position.1),
                  termion::cursor::Hide,

              ).unwrap();
              screen.flush().unwrap();

              write!(screen,
                  "{}{}{}{}", format!("{}", display.as_str()
                  ),
                 termion::clear::AfterCursor,
                 termion::cursor::Goto(position.0, position.1 + 1),
                 termion::cursor::Hide,
              ).unwrap();
              screen.flush().unwrap();

              write!(
                  screen,
                  "{}",
                  termion::cursor::Goto(0, 3),
              ).unwrap();
              screen.flush().unwrap();
         }
     }
}

#[derive(Debug, Clone, PartialEq)]
pub enum CmdType {
    SingleKey,
    MultipleKeys,
    OpenKeys,
    FilterKeys,
    Cmd,
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Input {
    pub cmd: Option<String>,
    pub args: Option<Vec<String>>,
    pub as_read: String,
    pub cmd_type: Option<CmdType>,
    pub display: Vec<char>,
    pub execute: bool,
    pub unwiddle: bool, //i.e. backspacing
    pub full_backspace: bool,
}



impl Input {
    pub fn new() -> Self {
        let mut input: Input = Default::default();
        input.execute = true;
        input.unwiddle = false;
        input.full_backspace = false;

        input
    }

    pub fn match_event(&mut self, c: termion::event::Key) {
            self.unwiddle = false;
            match c {
                Key::Char(c) => {
                    match c {
                        _ => {
                            self.display.push(c);
                        }
                    }
                }
                Key::Alt(c) => println!("^{}", c),
                Key::Ctrl(c) => println!("*{}", c),
                Key::Esc => println!("ESC"),
                Key::Left => println!("←"),
                Key::Right => println!("→"),
                Key::Up => println!("↑"),
                Key::Down => println!("↓"),
                Key::Backspace => {
                    self.unwiddle = true;
                    if self.display.pop().is_some() {
                        let count = self.display.iter().count();
                        if count  == 0 {
                            self.execute = false;
                            self.full_backspace = true;
                        }
                    }

                },
                _ => {}
            }
    }

    fn defang_args(&self, args: Vec<String>) -> Option<Vec<String>> {
        let count = args.clone().iter().count();
        let empty_item = args.clone().iter().any(|x| *x == "".to_string());
        let is_valid = if empty_item && count <= 1 {
            false
        } else {
            true
        };

        if is_valid && count != 0 {
            Some(args)
        } else {
            None
        }
    }

    pub fn parse(mut self, input: String) -> Self {
        let (cmd, args) = self.parse_cmd(input.clone());
        let is_key = if args == None {
            let key: Result<usize, std::num::ParseIntError> = cmd.clone().unwrap().parse();
            match key {
                Ok(_) => Some(true),
                Err(_) => Some(false)
            }
        } else {
            Some(false)
        };

        let is_filter = {
            let mut res = false;
            let mut input_vec_str: Vec<&str> = input.split("-").collect();

            // Make sure it's more than one item (it's range of values).
            if input_vec_str.iter().count() > 1 {
                res = true;
            }

            if res {
                // Does it end in "-"?
                let last = input_vec_str.iter().last();
                let mut open_range = false;
                if let Some(l) = last {
                    if l == &"" {
                        open_range = true;
                   }
                }

                // Only want to deal with integers if it's an open range.
                if open_range {
                   input_vec_str.pop();
                }

                // Make sure it'sall integers.
                for i in input_vec_str.into_iter() {
                    let key: Result<usize, std::num::ParseIntError> = i.parse();
                    if !key.is_ok() {
                        res = false;
                        break;
                    } else {
                        res = true;
                    }
                }
            } // if res

            res
        };


        let are_all_keys = if let Some(c) = cmd.clone() {
             if c == "r".to_string() {
                 let _args = args.clone();
                 if let Some(a) = _args {
                      self.are_all_keys(a)
                 }
                 else {
                     false
                 }
             } else {
                 false
             }
        } else {
            false
        };

        let are_all_keys_open = if let Some(c) = cmd.clone() {
             if c == "o".to_string() {
                 let _args = args.clone();
                 if let Some(a) = _args {
                      self.are_all_keys(a)
                 }
                 else {
                     false
                 }
             } else {
                 false
             }
        } else {
            false
        };

        let cmd_type = if are_all_keys {
            CmdType::MultipleKeys
        } else if are_all_keys_open {
            CmdType::OpenKeys
        } else if is_filter {
            CmdType::FilterKeys
        } else if let Some(k) = is_key {
            if k {
                CmdType::SingleKey
            } else {
                CmdType::Cmd
            }
        } else if is_filter {
            CmdType::FilterKeys
        } else {
            CmdType::Cmd
        };

            //if cmd_type == CmdType::FilterKeys {
            //    let few_ms = std::time::Duration::from_millis(1000);
            //    std::thread::sleep(few_ms);
            //}

        self.cmd = cmd;
        self.args = args;
        self.as_read = input;
        self.cmd_type = Some(cmd_type);

        self
    }

    fn parse_cmd(&self, input: String) -> (Option<String>, Option<Vec<String>>) {
        let mut input: Vec<String> = input.clone().split(" ").map(|s| s.to_string()).collect();
        let cmd = input.remove(0);

        let args = self.defang_args(input);
        (Some(cmd), args)
     }

     fn are_all_keys(&self, input: Vec<String>) -> bool {
        let is_num = |x: &str| {
            let res: Result<usize, std::num::ParseIntError> = x.parse();
            match res {
                Ok(_) => true,
                Err(_) => false
            }
        };
        let is_all_nums = !input.iter().any(|x| !is_num(x.as_str()));

        is_all_nums
     }

     //fn is_key(&self, input: &Vec<String>) -> bool {
     //   if input.iter().count() == 1 {
     //       let key: Result<usize, std::num::ParseIntError> = input.iter().next().unwrap().parse();
     //       match key {
     //           Ok(_) => true,
     //           Err(_) => false
     //       }
     //   } else {
     //       false
     //   }
     //}
}

#[derive(Debug, Clone, PartialEq)]
pub enum Mode {
    Fuzzy(String),
    Cmd(String),
    Work,
}

fn parse_keys(input: &str) -> Option<String> {
    let x = input;
    let mut y: Vec<&str> = x.split(" ").collect();
    let mut count = y.iter().count();

    let some = if count > 1 {
        y.remove(0);

        let mut n = 0;
        let single_key: bool;
        if count == 2 {
            single_key = true;
        } else {
            single_key = false;
        }
        loop {
            y.insert(n, " ");
            count = count - 1;
            n = n + 2;
            if count == 1 {
                break
            }
        }

        if single_key {
           y.remove(0);
        }

        let z: String = y.into_iter().collect();

        if z == "".to_string() {
            None
        } else {
            Some(z)
        }

    } else {
        None
    };

    some
}

#[cfg(test)]
mod app_test {
    use std::fs::metadata;
    use std::path::{Path, PathBuf};
    use std::process::Command;
    use fixtures::{Fixture, command_assistors};
    use termion::terminal_size;
    use super::{Input, LsKey, CmdType, Mode};
    use super::*;

    macro_rules! test {
        (
            $test_mode_bool: expr, // If false, tests are screen-size sensitive.
            $list_all_bool: expr, // lk -a would be true
            $name:ident,
            $test_file_path :expr, // We write text to a file so we know it's it when it's opened in test.
            $delay: expr, // Delay in each character typed.
            $input1: expr,
            $input2: expr,
            $input3: expr,
            $input4: expr,
            $input5: expr,
            $input6: expr,
            $input7: expr,
            $sub_path: expr, //We test all of this in a specific path. This'll create a sub-dir under that test-path.
            $intent: expr, //Explain what will happen in the test so tester can visually verify.
            $file_hash: expr,
            $test_macro: ident //We want to ignore the tests when we want and run when we want.
        ) => {

            #[test]
            #[$test_macro]
            fn $name() {
                let path = format!("/tmp/lsk_tests/{}/", $sub_path);

                let mut fixture = Fixture::new()
                    .add_dirpath(path.clone())
                    .add_dirpath(format!("{}basilides/", path.clone()))
                    .add_dirpath(format!("{}cyrinus/", path.clone()))
                    .add_dirpath(format!("{}nabor/", path.clone()))
                    .add_dirpath(format!("{}nazarius/", path.clone()))
                    .add_dirpath(format!("{}primus/", path.clone()))
                    .add_dirpath(format!("{}felician/", path.clone()))
                    .add_dirpath(format!("{}marcelinus/", path.clone()))
                    .add_dirpath(format!("{}isidore/", path.clone()))
                    .add_dirpath(format!("{}margaret/", path.clone()))
                    .add_dirpath(format!("{}angela/", path.clone()))
                    .add_dirpath(format!("{}francis/", path.clone()))
                    .add_dirpath(format!("{}gregory/", path.clone()))
                    .add_dirpath(format!("{}joseph/", path.clone()))
                    .add_dirpath(format!("{}anne/", path.clone()))
                    .add_dirpath(format!("{}joachim/", path.clone()))
                    .add_dirpath(format!("{}faustina/", path.clone()))
                    .add_dirpath(format!("{}john/", path.clone()))
                    .add_dirpath(format!("{}peter/", path.clone()))
                    .add_dirpath(format!("{}cecilia/", path.clone()))
                    .add_dirpath(format!("{}rita/", path.clone()))
                    .add_dirpath(format!("{}magdelene/", path.clone()))
                    .add_dirpath(format!("{}expeditus/", path.clone()))
                    .add_dirpath(format!("{}sebastian/", path.clone()))
                    .add_dirpath(format!("{}gabriel/", path.clone()))
                    .add_dirpath(format!("{}michael/", path.clone()))
                    .add_dirpath(format!("{}jude/", path.clone()))
                    .add_dirpath(format!("{}anthony/", path.clone()))
                    .add_dirpath(format!("{}nicholaus/", path.clone()))
                    .add_dirpath(format!("{}teresa/", path.clone()))
                    .build();

                let path_path = Path::new(path.clone().as_str()).to_path_buf();

                let mut sample_files_files = PathBuf::from(".fixtures");
                sample_files_files.push("sample_files");

                let mut path_test = path_path.clone();
                path_test.push("sample_files");

                let md = metadata(path_test.clone());
                let test_path_string = path_test.clone().into_os_string().into_string().unwrap();

                if !md.is_ok() {
                    fixture.build();
                    Command::new("cp")
                        .arg("-r".to_string())
                        .arg(sample_files_files.clone().into_os_string().into_string().unwrap())
                        .arg(test_path_string.clone())
                        .output()
                        .expect("failed to execute lsk process");
                }

                let mut path_cache = command_assistors::PathCache::new(&path_test);
                // Changing directories.
                path_cache.switch();

                println!("");
                let text_vec = vec![
                     format!(r#""{}""#, $input1),
                     format!(r#""{}""#, $input2),
                     format!(r#""{}""#, $input3),
                     format!(r#""{}""#, $input4),
                     format!(r#""{}""#, $input5),
                     format!(r#""{}""#, $input6),
                     format!(r#""{}""#, $input7),
                ];

                //println!("\n\n\nNew case intent:\n{}", $intent);
                //let few_ms = std::time::Duration::from_millis(5000);
                //std::thread::sleep(few_ms);


                if !$test_mode_bool {
                    let term_size = terminal_size().unwrap();
                    let term_width = term_size.0;
                    let term_height = term_size.1;

                    assert_eq!(term_width, 31);
                    assert_eq!(term_height, 15);
                }

                let spawn = super::terminal::parent_shell::type_text_spawn(text_vec, $delay);
                let fzf = PathBuf::from("/home/me/.fzf.sh");
                let fzc = PathBuf::from("/home/me/.fzc.sh");
                let fzd = PathBuf::from("/home/me/.fzd.sh");
                let _ls_key = super::app::run(test_path_string.clone(), $list_all_bool, true, Some(fzf), Some(fzc), Some(fzd));
                spawn.join().expect("failed to spawn thread");

                let mut test_output_path = path_path.clone();
                test_output_path.push("sample_files");
                test_output_path.push(".lsk_test_output");
                let test_output_path_string = test_output_path.clone().into_os_string().into_string().unwrap();
                let output_mv_to_path_string = path_path.clone().into_os_string().into_string().unwrap();

                Command::new("mv")
                    .arg(test_output_path_string)
                    .arg(output_mv_to_path_string.clone())
                    .output()
                    .expect("failed to execute lsk process");

                let few_ms = std::time::Duration::from_millis(100);
                std::thread::sleep(few_ms);

                let mut output_mv_to_path = path_path.clone();
                output_mv_to_path.push(".lsk_test_output");
                let output_mv_to_path_string = output_mv_to_path.clone().into_os_string().into_string().unwrap();

                println!("\npath:\n{}", output_mv_to_path_string.clone());

                let file256 = file_sha256(output_mv_to_path_string.clone());

                match file256 {
                    Ok(h) => {
                        assert_eq!(
                            h.to_hex_string(),
                            $file_hash.to_string()
                        )
                    },
                    Err(..) => assert!(false)
                }

                path_cache.switch_back();

                std::fs::remove_file(output_mv_to_path_string).unwrap();
            }
        };
    }

    test!(
          true, // test_mode_bool
          false, //list_all_bool
          macro_fzc_enter_file,
          "Makefile",
          100,               //$delay in milleseconds
          "$(printf 'c fzc\r')", //$input1
          "$(printf 'vimread\r')",//$input2
          "$(printf ':q\r')", //$input3
          "$(printf 'q\r')", //$input4
          "",                //$input5
          "",                //$input6
          "",                //$input7
          "macro_fzc_enter_file",
          ">Run lsk\n>Open file using vim with fzc hook\n>Quite vim\n>Quite lsk",
          "64e1b450ebdc532da6ebd5b11df4347d67b48405aa166b05800180e1a1136bf2",
          ignore/*macro_use*/
    );

    test!(
          false, // test_mode_bool
          false, //list_all_bool
          macro_term_size_enter_file,
          "Makefile",
          100,               //$delay in milleseconds
          "$(printf '5\r')", //$input1
          "$(printf ':q\r')",//$input2
          "$(printf 'q\r')", //$input3
          "",                //$input4
          "",                //$input5
          "",                //$input6
          "",                //$input7
          "macro_enter_file",
          ">Run lsk\n>Open file by key (2)\n>Quite vim\n>Quite lsk",
         "dab8010a2c67e6986aa511180b41132058be77ad72a9c9c5fc076e371dccf584",
         ignore/*host_term_size_dependent*/
    );

    test!(
          true, // test_mode_bool
          false, //list_all_bool
          macro_enter_file,
          "Makefile",
          100,               //$delay in milleseconds
          "$(printf '5\r')", //$input1
          "$(printf ':q\r')",//$input2
          "$(printf 'q\r')", //$input3
          "",                //$input4
          "",                //$input5
          "",                //$input6
          "",                //$input7
          "macro_enter_file",
          ">Run lsk\n>Open file by key (2)\n>Quite vim\n>Quite lsk",
          "99150c8a4c5960ee34cfbbb8393a65a9fe1c544394c1d02bf6a0a5cf0ad9b6a9",
          ignore/*macro_use*/
    );

    test!(
          true, // test_mode_bool
          true, //list_all_bool
          macro_enter_file_list_all,
          ".eternal",
          100,               //$delay in milleseconds
          "$(printf '2\r')", //$input1
          "$(printf ':q\r')",//$input2
          "$(printf 'q\r')", //$input3
          "",                //$input4
          "",                //$input5
          "",                //$input6
          "",                //$input7
          "macro_enter_file_list_all",
          ">Run lsk\n>Open hidden file by key (2)\n>Quite vim\n>Quite lsk",
          "e539e2c5a37d677c59fd71ca1739ae398ed467fc9dd506ec2512533f5d070ae4",
          ignore/*macro_use*/
    );

    test!(
          true, // test_mode_bool
          false,
          macro_fuzzy_enter_file,
          "intercession",
          100,               //$delay in milleseconds
          "$(printf 's boo\r')",
          "$(printf '4\r')",
          "$(printf ':q\r')",
          "$(printf 'q\r')",
          "",
          "",
          "",
          "macro_fuzzy_enter_file",
          ">Run lsk\n>Fuzzy widdle\n>Open file by key (1)\n>Quite vim\n>Quite lsk",
          "d7e51ab94b12bcb1773b2a92d0b4dec550c38f845add73850347a8bd03cc8f49",
          ignore/*macro_use*/
    );

    test!(
          true, // test_mode_bool
          false,
          macro_fuzzy_enter_dir,
          "a-file",
          100,               //inrease 200 => 500 ms to see better.
          "$(printf 's ins\r')",
          "$(printf '4\r')",
          "$(printf 'q\r')",
          "",
          "",
          "",
          "",
          "macro_fuzzy_enter_dir",
          ">Run lsk\n>Fuzzy widdle\n>Open dir by key (1)\n>Quite vim\n>Quite lsk",
          "9127fec0401b363161da1931c49795066cb21a98fd025be9816655019be48b2f",
          ignore/*macro_use*/
    );

    test!(
          true, // test_mode_bool
          false,
          macro_fuzzy_enter_dir_go_back_then_repeat,
          "a-file",
          100,               //inrease 200 => 500 ms to see better.
          "$(printf 's do\r')",
          "$(printf '2\r')",
          "$(printf '0\r')",
          "$(printf 's do\r')",
          "$(printf '2\r')",
          "$(printf 'q\r')",
          "",
          "macro_fuzzy_enter_dir",
          ">Run lsk\n>Fuzzy widdle\n>Open dir by key (1)\n>Go back (0) and repeat\n>Quite vim\n>Quite lsk",
          "27a1709e1aaa369079a83d411e082c22bccca5987b008d71865e091864264e9f",
          ignore/*macro_use*/
    );

    test!(
          true, // test_mode_bool
          false,
          macro_go_back_fuzzy_enter_back_into_dir,
          "a-file",
          100,               //inrease 200 => 500 ms to see better.
          "$(printf '0\r')",
          "$(printf 's sa\r')",
          "$(printf '2\r')",
          "$(printf 'q\r')",
          "",
          "",
          "",
          "macro_go_back_fuzzy_enter_back_into_dir",
          ">Run lsk\n>Go back (0)\n>Fuzzy widdle\n>Open back into original dir by key (2)\n>\n>Quite lsk",
          "399976731f562f608d1d4c04afc1fa4f8f3530acf8683c39917d8771afebe5d1",
          ignore/*macro_use*/
    );

    test!(
          true, // test_mode_bool
          false,
          macro_walk_in_park,
          "a-file",
          100,               //inrease 200 => 500 ms to see better.
          "$(printf '24\r')",
          "$(printf '1\r')",
          "$(printf 's con\r')",
          "$(printf '2\r')",
          "$(printf ':q\r')",
          "$(printf 'q\r')",
          "",
          "macro_walk_in_park",
          ">Run lsk\n>Go back (0)\n>Fuzzy widdle\n>Open back into original dir by key (2)\n>\n>Quite lsk",
          "668f2e7980c6260f572e837375b1e4a2beea20d3683b5293f0b968f00a4e68b0",
          ignore/*macro_use*/
    );

     test!(
           true, // test_mode_bool
           false, //list_all_bool
           macro_fuzzy_backspace,
           "Makefile",
           100,
           "s itf",
           "BackSpace",
           "BackSpace",
           "BackSpace",
           "BackSpace",
           "BackSpace",
           "q\r",
           "macro_fuzzy_backspace",
           ">Run lsk\n>OFuzzy widdle (2)\n>Backspace fully (bad behavior)\n>Quite lsk",
           "ee86f4888a18c074a2df32a467ee94027ea5f437d0fede8125e3526e07ee8147",
           ignore/*macro_use*/
     );

     test!(
           true, // test_mode_bool
           false, //list_all_bool
           macro_bad_fuzzy_backspace_enter,
           "Makefile",
           100,
           "s itf",
           "BackSpace",
           "BackSpace",
           "",
           "",
           "\r",
           "q\r",
           "macro_bad_fuzzy_backspace_enter",
           ">Run lsk\n>OFuzzy widdle (2)\n>Backspace partially (bad behavior)\n>Quite lsk",
           "83f5005ed89aca8834f69b3e064afca283c3ec6f90000e6e902473e1a582d11c",
           ignore/*macro_use*/
     );

     test!(
           true, // test_mode_bool
           false, //list_all_bool
           macro_file_range,
           "Makefile",
           100,
           "20-25\r",
           "24\r",
           "1\r",
           "11\r",
           "",
           ":q\r",
           "q\r",
           "macro_file_range",
           ">Run lsk\n>List range 20-25\n>Enter rust dir\nEnter redox dir\n>Open filesystem.toml\n>Quite Vim\n>Quite lsk",
           "f5f1e7f641b5f348080ca2f86c0dffa8530cfab308cd9ec61d4cb9b8fa4cf3b7",
           ignore/*macro_use*/
     );

     test!(
           true, // test_mode_bool
           true, //list_all_bool
           macro_list_all_fuzzy_file_range,
           "Makefile",
           100,
           "s m\r",
           "1-10\r",
           "10\r",
           "9\r",
           ":q\r",
           "0\r",
           "q\r",
           "macro_list_all_all_file_range",
           ">Run lsk\n>List all\n>Fuzzy search 'm'\n>List range 1-10\n>Enter mk dir\n>Open qemu.mk\n>Quite Vim\n>Go back/up a dir level\n>Quite lsk",
           "0eea81e276ad3766422bf859f4d9d3e76b84ef11e9d5233fe1aa206f8115e4f8",
           ignore/*macro_use*/
     );

     test!(
           true, // test_mode_bool
           true, //list_all_bool
           macro_list_all_fuzzy_undo_open_range,
           "Makefile",
           100,
           "s i\r",
           "5-17\n",
           "7-\r",
           "17\r",
           ":q\r",
           "1-\n",
           "q\r",
           "macro_list_all_fuzzy_undo_open_range",
           ">Run lsk\n>List all\n>Fuzzy search 'i'\n>List range 5 - 17.\n>List range 7 open-ended\n>Open last one, key 17\n>Quite Vim\n>List entire range, 1-\n>Quite lsk",
           "83796531204cd54871410774f6858b0e79b2e291eb7c0a77b06a1314bca8ebd7",
           ignore/*macro_use*/
     );

     test!(
           true, // test_mode_bool
           true, //list_all_bool
           macro_list_all_fuzzy_dir,
           "Makefile",
           100,
           "s i\r",
           "c fzd\r",
           "redoxgitl\r",
           "1\r",
           "1\r",
           ":q\r",
           "q\r",
           "macro_list_all_fuzzy_dir",
           ">Run lsk\n>List all\n>Fuzzy search 'i'\n>List range 5 - 17.\n>List range 7 open-ended\n>Open rust-toolchain fie  with command vim\n>Quite Vim\n>List entire range, 1-\n>Quite lsk",
           "20fc38f75c6739dbce70e86974cc2b7f58f8212279c47f05fe29f639ab1977f7",
           ignore/*macro_use*/
     );

     // It's good if this test is broken. For some reason, and bin/<file> doesn't show up when
     // running fzd.
     test!(
           true, // test_mode_bool
           true, //list_all_bool
           macro_bad_list_all_fuzzy_dir,
           "Makefile",
           100,
           "s i\r",
           "7-\n",
           "c fzd\r",
           "bin\r",
           "1\r",
           ":q\r",
           "q\r",
           "macro_list_all_fuzzy_dir",
           ">Run lsk\n>List all\n>Fuzzy search 'i'\n>List range 5 - 17.\n>List range 7 open-ended\n>Open bind dir fzd command, but main.rs doesn't show.\n>Quite lsk",
           "9d2896a092c094c6073fe65408d38aa5d672dccf3f34597174774d8098194075",
           ignore/*macro_use*/
     );


    #[test]
    #[ignore]//docker
    fn parse() {
        let input = Input::new();
        let input = input.parse("vim Cargo.toml".to_string());

        assert_eq!(
           Some(CmdType::Cmd),
           input.cmd_type
        );

        assert_eq!(
           Some("vim".to_string()),
           input.cmd
        );

        assert_eq!(
           Some(vec!["Cargo.toml".to_string()]),
           input.args
        );
    }

    #[test]
    #[ignore]//docker
    fn parse_long() {
        let input = Input::new();
        let input = input.parse("git clone https://github.com/7db9a/ls-key --depth 1".to_string());

        assert_eq!(
           Some(CmdType::Cmd),
           input.cmd_type
        );

        //vec!["clone".to_string(), "https://github.com/7db9a/ls-key".to_string(), "--depth".to_string(), "1".to_string()]

        assert_eq!(
           Some("git".to_string()),
           input.cmd
        );

        assert_eq!(
           Some(vec![
                "clone".to_string(),
                "https://github.com/7db9a/ls-key".to_string(),
                "--depth".to_string(),
                "1".to_string()
           ]),
           input.args
        );
    }

    #[test]
    #[ignore]//docker
    fn parse_single_cmd() {
        let input = Input::new();
        let input = input.parse("vim".to_string());

        assert_eq!(
           Some(CmdType::Cmd),
           input.cmd_type
        );

        assert_eq!(
           Some("vim".to_string()),
           input.cmd
        );

        assert_eq!(
           None,
           input.args
        );
    }

    #[test]
    #[ignore]//docker
    fn parse_key() {
        let input = Input::new();
        let input = input.parse("33".to_string());

        assert_eq!(
           Some(CmdType::SingleKey),
           input.cmd_type
        );

        assert_eq!(
           Some("33".to_string()),
           input.cmd
        );

        assert_eq!(
           None,
           input.args
        );
    }

    #[test]
    #[ignore]//docker
    fn parse_bad() {
        let input = Input::new();
        let input = input.parse(" vim Cargo.toml".to_string());

        assert_eq!(
           Some(CmdType::Cmd),
           input.cmd_type
        );

        assert_eq!(
           Some("".to_string()),
           input.cmd
        );

        assert_eq!(
           None,
           input.args
        );
    }

    #[test]
    #[ignore]//docker
    fn parse_cmd() {
        let input = Input::new();
        let (cmd, args) = input.parse_cmd("vim Cargo.toml".to_string());

        assert_eq!(
            cmd,
            Some("vim".to_string())
        );

        assert_eq!(
            args,
            Some(vec!["Cargo.toml".to_string()])
        )
    }

    //#[test]
    //fn shell_spawn_vim() {
    //    super::terminal::shell::spawn("vim".to_string(), vec!["-c".to_string(), "vsplit README.md".to_string(), "dev.sh".to_string()]);
    //}

    //#[test]
    //fn shell_pipe_cmd() {
    //    super::terminal::shell::cmd(r#"du -ah . | sort -hr | head -n 10"#.to_string());
    //}

    //#[test]
    //fn shell_cat_cmd() {
    //    super::terminal::shell::cmd("cat Cargo.toml".to_string());
    //}

    //#[test]
    //fn shell_cat() {
    //    super::terminal::shell::spawn("cat".to_string(), vec!["Cargo.toml".to_string()]);
    //}

     #[test]
     #[ignore]//docker
     fn test_mode_parse() {
        let mut ls_key = LsKey::new("/tmp", false, false, None, None, None);
        let input_single = "s something".to_string();
        let some_fuzzy_search_single = ls_key.mode_parse(input_single.clone());

        let input_multi = "s something and more".to_string();
        let some_fuzzy_search_multi = ls_key.mode_parse(input_multi.clone());

        let input_invalid = "sd".to_string();
        let some_fuzzy_search_invalid = ls_key.mode_parse(input_invalid.clone());

        let input_lack_more = "s".to_string();
        let some_fuzzy_search_lack_more = ls_key.mode_parse(input_lack_more.clone());

        let input_wrong = "d something".to_string();
        let some_fuzzy_search_wrong = ls_key.mode_parse(input_wrong.clone());

        assert_eq!(
            some_fuzzy_search_invalid,
            None
        );

        assert_eq!(
            some_fuzzy_search_lack_more,
            None
        );

        assert_eq!(
            some_fuzzy_search_single,
            Some(Mode::Fuzzy("something".to_string()))
        );

        assert_eq!(
            some_fuzzy_search_multi,
            Some(Mode::Fuzzy("something and more".to_string()))

        );

        assert_eq!(
            some_fuzzy_search_wrong,
            None
        );
     }

     #[test]
     #[ignore]//docker
     fn test_bad_mode_parse() {
        let mut ls_key = LsKey::new("/tmp", false, false, None, None, None);

        let input_lack = "s ".to_string();
        let some_fuzzy_search_lack = ls_key.mode_parse(input_lack.clone());

        assert_eq!(
            some_fuzzy_search_lack,
            None
        );
     }
}