PSFzf.psm1

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
# AUTOGENERATED - DO NOT EDIT

# PSFzf.Base.ps1
param(
    [parameter(Position=0,Mandatory=$false)][string]$PSReadlineChordProvider = 'Ctrl+t',
    [parameter(Position=1,Mandatory=$false)][string]$PSReadlineChordReverseHistory = 'Ctrl+r',
    [parameter(Position=2,Mandatory=$false)][string]$PSReadlineChordSetLocation = 'Alt+c',
    [parameter(Position=3,Mandatory=$false)][string]$PSReadlineChordReverseHistoryArgs = 'Alt+a')

$script:IsWindows = ($PSVersionTable.PSVersion.Major -le 5) -or $IsWindows
if ($script:IsWindows) {    
    $script:ShellCmd = 'cmd.exe /S /C {0}'    
    $script:DefaultFileSystemCmd = @"
dir /s/b "{0}"
"@
 
} else {
    $script:ShellCmd = '/bin/sh -c "{0}"'
    $script:DefaultFileSystemCmd = @"
find {0} -path '*/\.*' -prune -o -type f -print -o -type l -print 2> /dev/null
"@

}

$script:RunningInWindowsTerminal = [bool]($env:WT_Session)
if ($script:RunningInWindowsTerminal) {
    $script:DefaultFileSystemFdCmd = "fd.exe --color always . {0}"    
} else {
    $script:DefaultFileSystemFdCmd = "fd.exe . {0}"    
}

$script:UseFd = $false

function Get-FileSystemCmd
{
    param($dir, [switch]$dirOnly = $false)
    if ([string]::IsNullOrWhiteSpace($env:FZF_DEFAULT_COMMAND)) {
        if ($script:UseFd) {
            # need to quote if there's spaces in the path name:
            if ($dir.Contains(' ')) {
                $strDir = """$dir""" 
            } else {
                $strDir = $dir
            }
            if ($dirOnly) {
                ($script:DefaultFileSystemFdCmd -f '--type directory {0}') -f $strDir
            } else {
                $script:DefaultFileSystemFdCmd -f $strDir
            }
        } else {
            $script:ShellCmd -f ($script:DefaultFileSystemCmd -f $dir)
        }
    } else {
        $script:ShellCmd -f ($env:FZF_DEFAULT_COMMAND -f $dir)
    }
}

function FixCompletionResult($str) 
{
    if ($str.Contains(" ") -or $str.Contains("`t")) {
        return "'{0}'" -f $str.Replace("`r`n","").Trim(@('''','"'))
    } else {
        return $str.Replace("`r`n","")
    }
}

$script:FzfLocation = $null
$script:PSReadlineHandlerChords = @()
$script:TabContinuousTrigger = [IO.Path]::DirectorySeparatorChar.ToString()

$MyInvocation.MyCommand.ScriptBlock.Module.OnRemove =
{
    $PsReadlineShortcuts.Values | Where-Object Chord | ForEach-Object { 
        Remove-PSReadlineKeyHandler $_.Chord
    }
    RemovePsFzfAliases

    RemoveGitKeyBindings
}

# if the quoted string ends with a '\', and we need to escape it for Windows:
function script:PrepareArg($argStr) {
    if (-not $argStr.EndsWith("\\") -and $argStr.EndsWith('\')) {
        return $argStr + '\'
    } else {
        return $argStr
    }
}
function Set-PsFzfOption{
    param(
        [switch]
        $TabExpansion,
        [string]
        $PSReadlineChordProvider,
        [string]
        $PSReadlineChordReverseHistory,
        [string]
        $PSReadlineChordSetLocation,
        [string]
        $PSReadlineChordReverseHistoryArgs,
        [switch]
        $GitKeyBindings,
        [switch]
        $EnableAliasFuzzyEdit,
        [switch]
        $EnableAliasFuzzyFasd,
        [switch]
        $EnableAliasFuzzyHistory,
        [switch]
        $EnableAliasFuzzyKillProcess,
        [switch]
        $EnableAliasFuzzySetLocation,
        [switch]
        $EnableAliasFuzzySetEverything,
        [switch]
        $EnableAliasFuzzyZLocation,
        [switch]
        $EnableAliasFuzzyGitStatus,
        [switch]
        $EnableFd
    )
    if ($PSBoundParameters.ContainsKey('TabExpansion')) {
        SetTabExpansion $TabExpansion
    }

    if ($PSBoundParameters.ContainsKey('GitKeyBindings')) {
        SetGitKeyBindings $GitKeyBindings
    }

    $PsReadlineShortcuts.GetEnumerator() | ForEach-Object {
        if ($PSBoundParameters.ContainsKey($_.key)) {
            $info = $_.value
            $newChord = $PSBoundParameters[$_.key]
            $result = SetPsReadlineShortcut $newChord -Override $info.BriefDesc $info.Desc $info.ScriptBlock
            if ($result) {
                if (($null -ne $info.Chord) -and ($info.Chord.ToLower() -ne $newChord.ToLower())) {
                    Remove-PSReadLineKeyHandler $info.Chord
                }
                $info.Chord = $newChord
            }
        }    
    }

    if ($EnableAliasFuzzyEdit)             { SetPsFzfAlias "fe"      Invoke-FuzzyEdit}
    if ($EnableAliasFuzzyFasd)             { SetPsFzfAlias "ff"      Invoke-FuzzyFasd}
    if ($EnableAliasFuzzyHistory)         { SetPsFzfAlias "fh"      Invoke-FuzzyHistory }
    if ($EnableAliasFuzzyKillProcess)     { SetPsFzfAlias "fkill"   Invoke-FuzzyKillProcess }
    if ($EnableAliasFuzzySetLocation)     { SetPsFzfAlias "fd"      Invoke-FuzzySetLocation }
    if ($EnableAliasFuzzyZLocation)     { SetPsFzfAlias "fz"      Invoke-FuzzyZLocation }
    if ($EnableAliasFuzzyGitStatus)     { SetPsFzfAlias "fgs"     Invoke-FuzzyGitStatus }
    if ($EnableAliasFuzzySetEverything) {
        if (${function:Set-LocationFuzzyEverything}) {
            SetPsFzfAlias "cde" Set-LocationFuzzyEverything 
        }
    }
    if ($PSBoundParameters.ContainsKey('EnableFd')) {
        $script:UseFd = $EnableFd
    }
    if ($PSBoundParameters.ContainsKey('TabContinuousTrigger')) {
        $script:TabContinuousTrigger = $TabContinuousTrigger
    }
}

function Stop-Pipeline {
    # borrowed from https://stackoverflow.com/a/34800670:
    (Add-Type -Passthru -TypeDefinition '
    using System.Management.Automation;
    namespace PSFzf.IO {
      public static class CustomPipelineStopper {
        public static void Stop(Cmdlet cmdlet) {
          throw (System.Exception) System.Activator.CreateInstance(typeof(Cmdlet).Assembly.GetType("System.Management.Automation.StopUpstreamCommandsException"), cmdlet);
        }
      }
    }'
)::Stop($PSCmdlet)
}

function Invoke-Fzf {
    param( 
            # Search
            [Alias("x")]
            [switch]$Extended,
            [Alias('e')]
              [switch]$Exact,
            [Alias('i')]
              [switch]$CaseInsensitive,
              [switch]$CaseSensitive,
              [Alias('d')]
              [string]$Delimiter,
              [switch]$NoSort,
            [Alias('tac')]
            [switch]$ReverseInput,
            [switch]$Phony,
              [ValidateSet('length','begin','end','index')]
              [string]
              $Tiebreak = $null,

            # Interface
            [Alias('m')]
              [switch]$Multi,
            [switch]$NoMouse,
            [string]$Bind,
            [switch]$Cycle,
            [switch]$KeepRight,
            [switch]$NoHScroll,
            [switch]$FilepathWord,

            # Layout
            [ValidatePattern("^[1-9]+[0-9]+$|^[1-9][0-9]?%?$|^100%?$")]
            [string]$Height,
            [ValidateRange(1,[int]::MaxValue)]
            [int]$MinHeight,
            [ValidateSet('default','reverse','reverse-list')]
            [string]$Layout = $null,
            [switch]$Border,
            [ValidateSet('rounded','sharp','horizontal')]
            [string]$BorderStyle,
            [ValidateSet('default','inline','hidden')]
            [string]$Info = $null,
            [string]$Prompt,
            [string]$Pointer,
            [string]$Marker,
            [string]$Header,
            [int]$HeaderLines = -1,

            # Display
            [switch]$Ansi,
            [int]$Tabstop = 8,
            [switch]$NoBold,

            # History
            [string]$History,
            [int]$HistorySize = -1,
            
            #Preview
            [string]$Preview,
            [string]$PreviewWindow,

            # Scripting
            [Alias('q')]
            [string]$Query,
            [Alias('s1')]
            [switch]$Select1,
            [Alias('e0')]
            [switch]$Exit0,
            [Alias('f')]
            [string]$Filter,
            [switch]$PrintQuery,
            [string]$Expect,
            
              [Parameter(ValueFromPipeline=$True)]
            [object[]]$Input
    )

    Begin {
        # process parameters:
        $arguments = ''
        if ($PSBoundParameters.ContainsKey('Extended') -and $Extended)                                             { $arguments += '--extended '}
        if ($PSBoundParameters.ContainsKey('Exact') -and $Exact)                                                 { $arguments += '--exact '}
        if ($PSBoundParameters.ContainsKey('CaseInsensitive') -and $CaseInsensitive)                             { $arguments += '-i '}
        if ($PSBoundParameters.ContainsKey('CaseSensitive') -and $CaseSensitive)                                 { $arguments += '+i '}
        if ($PSBoundParameters.ContainsKey('Delimiter') -and ![string]::IsNullOrWhiteSpace($Delimiter))         { $arguments += "--delimiter=$Delimiter "}
        if ($PSBoundParameters.ContainsKey('NoSort') -and $NoSort)                                                 { $arguments += '--no-sort '}
        if ($PSBoundParameters.ContainsKey('ReverseInput') -and $ReverseInput)                                     { $arguments += '--tac '}
        if ($PSBoundParameters.ContainsKey('Phony') -and $Phony)                                                { $arguments += '--phony '}
        if ($PSBoundParameters.ContainsKey('Tiebreak') -and ![string]::IsNullOrWhiteSpace($Tiebreak))            { $arguments += "--tiebreak=$Tiebreak "}
        if ($PSBoundParameters.ContainsKey('Multi') -and $Multi)                                                 { $arguments += '--multi '}
        if ($PSBoundParameters.ContainsKey('NoMouse') -and $NoMouse)                                             { $arguments += '--no-mouse '}
        if ($PSBoundParameters.ContainsKey('Bind') -and ![string]::IsNullOrWhiteSpace($Bind))                    { $arguments += "--bind=$Bind "}
        if ($PSBoundParameters.ContainsKey('Reverse') -and $Reverse)                                             { $arguments += '--reverse '}
        if ($PSBoundParameters.ContainsKey('Cycle') -and $Cycle)                                                 { $arguments += '--cycle '}
        if ($PSBoundParameters.ContainsKey('KeepRight') -and $KeepRight)                                         { $arguments += '--keep-right '}
        if ($PSBoundParameters.ContainsKey('NoHScroll') -and $NoHScroll)                                         { $arguments += '--no-hscroll '}
        if ($PSBoundParameters.ContainsKey('FilepathWord') -and $FilepathWord)                                    { $arguments += '--filepath-word '}
        if ($PSBoundParameters.ContainsKey('Height') -and ![string]::IsNullOrWhiteSpace($Height))                { $arguments += "--height=$height "}
        if ($PSBoundParameters.ContainsKey('MinHeight') -and $MinHeight -ge 0)                                    { $arguments += "--min-height=$MinHeight "}
        if ($PSBoundParameters.ContainsKey('Layout') -and ![string]::IsNullOrWhiteSpace($Layout))                { $arguments += "--layout=$Layout "}
        if ($PSBoundParameters.ContainsKey('Border') -and $Border)                                                { $arguments += '--border '}
        if ($PSBoundParameters.ContainsKey('BorderStyle') -and ![string]::IsNullOrWhiteSpace($BorderStyle))        { $arguments += "--border=$BorderStyle "}
        if ($PSBoundParameters.ContainsKey('Info') -and ![string]::IsNullOrWhiteSpace($Info))                     { $arguments += "--info=$Info "}
        if ($PSBoundParameters.ContainsKey('Prompt') -and ![string]::IsNullOrWhiteSpace($Prompt))                 { $arguments += "--prompt='$Prompt' "}
        if ($PSBoundParameters.ContainsKey('Pointer') -and ![string]::IsNullOrWhiteSpace($Pointer))             { $arguments += "--pointer='$Pointer' "}
        if ($PSBoundParameters.ContainsKey('Marker') -and ![string]::IsNullOrWhiteSpace($Marker))                 { $arguments += "--marker='$Marker' "}
        if ($PSBoundParameters.ContainsKey('Header') -and ![string]::IsNullOrWhiteSpace($Header))                 { $arguments += "--header=""$Header"" "}
        if ($PSBoundParameters.ContainsKey('HeaderLines') -and $HeaderLines -ge 0)                                    { $arguments += "--header-lines=$HeaderLines "}
        if ($PSBoundParameters.ContainsKey('Ansi') -and $Ansi)                                                    { $arguments += '--ansi '}
        if ($PSBoundParameters.ContainsKey('Tabstop') -and $Tabstop -ge 0)                                        { $arguments += "--tabstop=$Tabstop "}
        if ($PSBoundParameters.ContainsKey('NoBold') -and $NoBold)                                                { $arguments += '--no-bold '}
        if ($PSBoundParameters.ContainsKey('History') -and $History)                                             { $arguments += "--history='$History' "}
        if ($PSBoundParameters.ContainsKey('HistorySize') -and $HistorySize -ge 1)                                { $arguments += "--history-size=$HistorySize "}
        if ($PSBoundParameters.ContainsKey('Preview') -and ![string]::IsNullOrWhiteSpace($Preview))             { $arguments += "--preview=""$Preview"" "}
        if ($PSBoundParameters.ContainsKey('PreviewWindow') -and ![string]::IsNullOrWhiteSpace($PreviewWindow)) { $arguments += "--preview-window=""$PreviewWindow"" "}
        if ($PSBoundParameters.ContainsKey('Query') -and ![string]::IsNullOrWhiteSpace($Query))                    { $arguments += "--query=""{0}"" " -f $(PrepareArg $Query)}
        if ($PSBoundParameters.ContainsKey('Select1') -and $Select1)                                            { $arguments += '--select-1 '}
        if ($PSBoundParameters.ContainsKey('Exit0') -and $Exit0)                                                { $arguments += '--exit-0 '}
        if ($PSBoundParameters.ContainsKey('Filter') -and ![string]::IsNullOrEmpty($Filter))                    { $arguments += "--filter=$Filter " }
        if ($PSBoundParameters.ContainsKey('PrintQuery') -and $PrintQuery)                                        { $arguments += '--print-query '}
        if ($PSBoundParameters.ContainsKey('Expect') -and ![string]::IsNullOrWhiteSpace($Expect))                    { $arguments += "--expect=""$Expect"" "}
     
        if ($script:UseHeightOption -and [string]::IsNullOrWhiteSpace($Height) -and `
              ([string]::IsNullOrWhiteSpace($env:FZF_DEFAULT_OPTS) -or (-not $env:FZF_DEFAULT_OPTS.Contains('--height')))) {
            $arguments += "--height=40% "
        }
        
        if ($Border -eq $true -and -not [string]::IsNullOrWhiteSpace($BorderStyle)) {
            throw '-Border and -BorderStyle are mutally exclusive'
        }
        if ($script:UseFd -and $script:RunningInWindowsTerminal -and -not $arguments.Contains('--ansi')) {
            $arguments += "--ansi "
        }

        # prepare to start process:
        $process = New-Object System.Diagnostics.Process
        $process.StartInfo.FileName = $script:FzfLocation
        $process.StartInfo.Arguments = $arguments
        $process.StartInfo.StandardOutputEncoding = [System.Text.Encoding]::UTF8
        $process.StartInfo.RedirectStandardInput = $true
        $process.StartInfo.RedirectStandardOutput = $true
        $process.StartInfo.UseShellExecute = $false
        if ($pwd.Provider.Name -eq 'FileSystem') {
            $process.StartInfo.WorkingDirectory = $pwd.Path
        }
        
        # Adding event handers for stdout:
        $stdOutEventId = "PsFzfStdOutEh-" + [System.Guid]::NewGuid()
        $stdOutEvent = Register-ObjectEvent -InputObject $process `
            -EventName 'OutputDataReceived' `
            -SourceIdentifier $stdOutEventId

        $processHasExited = new-object psobject -property @{flag = $false}
        # register on exit:
        $scriptBlockExited = {
            $Event.MessageData.flag = $true
        }
        $exitedEventId = "PsFzfExitedEh-" + [System.Guid]::NewGuid()
        $exitedEvent = Register-ObjectEvent -InputObject $process `
            -Action $scriptBlockExited -EventName 'Exited' `
            -SourceIdentifier $exitedEventId `
            -MessageData $processHasExited

        $process.Start() | Out-Null
        $process.BeginOutputReadLine() | Out-Null

        $utf8Encoding = New-Object System.Text.UTF8Encoding -ArgumentList $false
        $utf8Stream = New-Object System.IO.StreamWriter -ArgumentList $process.StandardInput.BaseStream, $utf8Encoding

        $cleanup = [scriptblock] {
            try {
                   $process.StandardInput.Close() | Out-Null
                $process.WaitForExit()
                $utf8Stream = $null
            } catch {
                # do nothing
            }

            try {
                #$stdOutEventId,$exitedEventId | ForEach-Object {
                # Unregister-Event $_ -ErrorAction SilentlyContinue
                #}
    
                $stdOutEvent,$exitedEvent | ForEach-Object {
                    Stop-Job $_  -ErrorAction SilentlyContinue
                    Remove-Job $_ -Force  -ErrorAction SilentlyContinue
                }    
            } catch {

            }

            # events seem to be generated out of order - thereforce, we need sort by time created. For examp`le,
            # -print-query and -expect and will be outputted first if specified on the command line.
            Get-Event -SourceIdentifier $stdOutEventId | `
                Sort-Object -Property TimeGenerated | `
                Where-Object { $null -ne $_.SourceEventArgs.Data } | ForEach-Object {
                    Write-Output $_.SourceEventArgs.Data
                    Remove-Event -EventIdentifier $_.EventIdentifier
                }
        }
    }

    Process {
        $hasInput = $PSBoundParameters.ContainsKey('Input')
        
        # handle no piped input:
        if (!$hasInput) {
            # optimization for filesystem provider:
            if ($PWD.Provider.Name -eq 'FileSystem') {
                Invoke-Expression (Get-FileSystemCmd $PWD.Path) | ForEach-Object { 
                    $utf8Stream.WriteLine($_)
                    if ($processHasExited.flag -or $process.HasExited) {
                        $utf8Stream = $null
                        & $cleanup
                        Stop-Pipeline
                    }
                }
            }
            else {
                Get-ChildItem . -Recurse -ErrorAction SilentlyContinue | ForEach-Object {
                    $item = $_ 
                    if ($item -is [System.String]) {
                        $str = $item
                    } else {
                        # search through common properties:
                        $str = $item.FullName
                        if ($null -eq $str) {
                            $str = $item.Name
                            if ($null -eq $str) {
                                $str = $item.ToString()
                            }
                        }
                    }
                    if (![System.String]::IsNullOrWhiteSpace($str)) {
                        $utf8Stream.WriteLine($str)
                    }

                    if ($processHasExited.flag -or $process.HasExited) {
                        $utf8Stream = $null
                        & $cleanup
                        Stop-Pipeline
                    }
                }
            }
                
        } else {
            foreach ($item in $Input) {
                if ($item -is [System.String]) {
                $str = $item
                } else {
                    # search through common properties:
                    $str = $item.FullName
                    if ($null -eq $str) {
                        $str = $item.Name
                        if ($null -eq $str) {
                            $str = $item.ToString()
                        }
                    }
                }
                if (![System.String]::IsNullOrWhiteSpace($str)) {
                    $utf8Stream.WriteLine($str)
                }
                if ($processHasExited.flag -or $process.HasExited) {
                    & $cleanup
                    Stop-Pipeline
                    #return
                }
            }
        }
        if ($utf8Stream -ne $null) {
            $utf8Stream.Flush()
        }
    }

    End {
        & $cleanup
    }
}

function Find-CurrentPath {
    param([string]$line,[int]$cursor,[ref]$leftCursor,[ref]$rightCursor)
    
    if ($line.Length -eq 0) {
        $leftCursor.Value = $rightCursor.Value = 0
        return $null
    }

    if ($cursor -ge $line.Length) {
        $leftCursorTmp = $cursor - 1
    } else {
        $leftCursorTmp = $cursor
    }
    :leftSearch for (;$leftCursorTmp -ge 0;$leftCursorTmp--) {
        if ([string]::IsNullOrWhiteSpace($line[$leftCursorTmp])) {
            if (($leftCursorTmp -lt $cursor) -and ($leftCursorTmp -lt $line.Length-1)) {
                $leftCursorTmpQuote = $leftCursorTmp - 1
                $leftCursorTmp = $leftCursorTmp + 1
            } else {
                $leftCursorTmpQuote = $leftCursorTmp
            }
            for (;$leftCursorTmpQuote -ge 0;$leftCursorTmpQuote--) {
                if (($line[$leftCursorTmpQuote] -eq '"') -and (($leftCursorTmpQuote -le 0) -or ($line[$leftCursorTmpQuote-1] -ne '"'))) {
                    $leftCursorTmp = $leftCursorTmpQuote
                    break leftSearch
                }
                elseif (($line[$leftCursorTmpQuote] -eq "'") -and (($leftCursorTmpQuote -le 0) -or ($line[$leftCursorTmpQuote-1] -ne "'"))) {
                    $leftCursorTmp = $leftCursorTmpQuote
                    break leftSearch
                }
            }
            break leftSearch
        }
    }
    :rightSearch for ($rightCursorTmp = $cursor;$rightCursorTmp -lt $line.Length;$rightCursorTmp++) {
        if ([string]::IsNullOrWhiteSpace($line[$rightCursorTmp])) {
            if ($rightCursorTmp -gt $cursor) {
                $rightCursorTmp = $rightCursorTmp - 1
            }
            for ($rightCursorTmpQuote = $rightCursorTmp+1;$rightCursorTmpQuote -lt $line.Length;$rightCursorTmpQuote++) {
                if (($line[$rightCursorTmpQuote] -eq '"') -and (($rightCursorTmpQuote -gt $line.Length) -or ($line[$rightCursorTmpQuote+1] -ne '"'))) {
                    $rightCursorTmp = $rightCursorTmpQuote
                    break rightSearch
                }
                elseif (($line[$rightCursorTmpQuote] -eq "'") -and (($rightCursorTmpQuote -gt $line.Length) -or ($line[$rightCursorTmpQuote+1] -ne "'"))) {
                    $rightCursorTmp = $rightCursorTmpQuote
                    break rightSearch
                }
            }
            break rightSearch
        }
    }
    if ($leftCursorTmp -lt 0 -or $leftCursorTmp -gt $line.Length-1) { $leftCursorTmp = 0}
    if ($rightCursorTmp -ge $line.Length) { $rightCursorTmp = $line.Length-1 }
    $leftCursor.Value = $leftCursorTmp
    $rightCursor.Value = $rightCursorTmp
    $str = -join ($line[$leftCursorTmp..$rightCursorTmp])
    return $str.Trim("'").Trim('"')
}

function Invoke-FzfPsReadlineHandlerProvider {
    $leftCursor = $null
    $rightCursor = $null
    $line = $null
    $cursor = $null
    [Microsoft.PowerShell.PSConsoleReadline]::GetBufferState([ref]$line, [ref]$cursor)
    $currentPath = Find-CurrentPath $line $cursor ([ref]$leftCursor) ([ref]$rightCursor)
    $addSpace = $null -ne $currentPath -and $currentPath.StartsWith(" ")
    if ([String]::IsNullOrWhitespace($currentPath) -or !(Test-Path $currentPath)) {
        $currentPath = $PWD
    }

    $result = @()
    try 
    {
        $prevDefaultOpts = $env:FZF_DEFAULT_OPTS
        $env:FZF_DEFAULT_OPTS = $env:FZF_DEFAULT_OPTS + ' ' + $env:FZF_CTRL_T_OPTS
        if (-not [System.String]::IsNullOrWhiteSpace($env:FZF_CTRL_T_COMMAND)) {
            Invoke-Expression ($env:FZF_CTRL_T_COMMAND) | Invoke-Fzf -Multi | ForEach-Object { $result += $_ }
        } else {
            if ([string]::IsNullOrWhiteSpace($currentPath)) {
                Invoke-Fzf -Multi | ForEach-Object { $result += $_ }
            } else {
                $resolvedPath = Resolve-Path $currentPath -ErrorAction SilentlyContinue
                $providerName = $null
                if ($null -ne $resolvedPath) {
                    $providerName = $resolvedPath.Provider.Name 
                }
                switch ($providerName) {
                    # Get-ChildItem is way too slow - we optimize for the FileSystem provider by
                    # using batch commands:
                    'FileSystem'    { Invoke-Expression (Get-FileSystemCmd $resolvedPath.ProviderPath) | Invoke-Fzf -Multi | ForEach-Object { $result += $_ } }
                    'Registry'      { Get-ChildItem $currentPath -Recurse -ErrorAction SilentlyContinue | Select-Object Name -ExpandProperty Name | Invoke-Fzf -Multi | ForEach-Object { $result += $_ } }
                    $null           { Get-ChildItem $currentPath -Recurse -ErrorAction SilentlyContinue | Select-Object FullName -ExpandProperty FullName | Invoke-Fzf -Multi | ForEach-Object { $result += $_ } }
                    Default         {}
                }
            }
        }
    }
    catch 
    {
        # catch custom exception
    }
    finally 
    {
        $env:FZF_DEFAULT_OPTS = $prevDefaultOpts
    }
    
    #HACK: workaround for fact that PSReadLine seems to clear screen
    # after keyboard shortcut action is executed:
    [Microsoft.PowerShell.PSConsoleReadLine]::InvokePrompt()

    if ($null -ne $result) {
        # quote strings if we need to:
        if ($result -is [system.array]) {
            for ($i = 0;$i -lt $result.Length;$i++) {
                $result[$i] = FixCompletionResult $result[$i]
            }
        } else {
            $result = FixCompletionResult $result
        }
        
        $str = $result -join ','
        if ($addSpace) {
            $str = ' ' + $str
        }
        $replaceLen = $rightCursor - $leftCursor
        if ($rightCursor -eq 0 -and $leftCursor -eq 0) {
            [Microsoft.PowerShell.PSConsoleReadLine]::Insert($str)
        } else {
            [Microsoft.PowerShell.PSConsoleReadLine]::Replace($leftCursor,$replaceLen+1,$str)
        }        
    }
}
function Invoke-FzfPsReadlineHandlerHistory {
    $result = $null
    try
    {
        $prevDefaultOpts = $env:FZF_DEFAULT_OPTS
        $env:FZF_DEFAULT_OPTS = $env:FZF_DEFAULT_OPTS + ' ' + $env:FZF_CTRL_R_OPTS 

        $line = $null
        $cursor = $null    
        [Microsoft.PowerShell.PSConsoleReadline]::GetBufferState([ref]$line, [ref]$cursor)

        $reader = New-Object PSFzf.IO.ReverseLineReader -ArgumentList $((Get-PSReadlineOption).HistorySavePath)

        $fileHist = @{}
        $reader.GetEnumerator() | ForEach-Object {
            if (-not $fileHist.ContainsKey($_)) {
                $fileHist.Add($_,$true)
                $_
            }
        } | Invoke-Fzf -NoSort -Query "$line" -Bind ctrl-r:toggle-sort | ForEach-Object { $result = $_ }
    }
    catch
    {
        # catch custom exception
    }
    finally 
    {
        $env:FZF_DEFAULT_OPTS = $prevDefaultOpts
        # ensure that stream is closed:
        $reader.Dispose()
    }

    #HACK: workaround for fact that PSReadLine seems to clear screen
    # after keyboard shortcut action is executed:
    [Microsoft.PowerShell.PSConsoleReadLine]::InvokePrompt()

    if (-not [string]::IsNullOrEmpty($result)) {
        [Microsoft.PowerShell.PSConsoleReadLine]::Replace(0,$line.Length,$result)
    }
}

function Invoke-FzfPsReadlineHandlerHistoryArgs {    
    try 
    {
        $line = $null
        $cursor = $null
        [Microsoft.PowerShell.PSConsoleReadline]::GetBufferState([ref]$line, [ref]$cursor)
        $line = $line.Insert($cursor,"{}") # add marker for fzf
        
        $contentTable = @{}
        $reader = New-Object PSFzf.IO.ReverseLineReader -ArgumentList $((Get-PSReadlineOption).HistorySavePath)
        
        $fileHist = @{}
        $reader.GetEnumerator() | ForEach-Object {
            if (-not $fileHist.ContainsKey($_)) {
                $fileHist.Add($_,$true)
                [System.Management.Automation.PsParser]::Tokenize($_, [ref] $null) 
            }  
        } | Where-Object {$_.type -eq "commandargument" -or $_.type -eq "string"} | 
                ForEach-Object { 
                    if (!$contentTable.ContainsKey($_.Content)) { $_.Content ; $contentTable[$_.Content] = $true } 
                } | Invoke-Fzf -NoSort -Preview "echo $line" -PreviewWindow "up:20%" | ForEach-Object { $result = $_ }
    }
    catch 
    {
        # catch custom exception
    }
    finally
    {
        $reader.Dispose()
    }
    
    #HACK: workaround for fact that PSReadLine seems to clear screen
    # after keyboard shortcut action is executed:
    [Microsoft.PowerShell.PSConsoleReadLine]::InvokePrompt()

    if (-not [string]::IsNullOrEmpty($result)) {
        # add quotes:
        if ($result.Contains(" ") -or $result.Contains("`t")) {
            $result = "'{0}'" -f $result.Replace("'","''")
        }
        [Microsoft.PowerShell.PSConsoleReadLine]::Replace($cursor,0,$result)
    }
}

function Invoke-FzfPsReadlineHandlerSetLocation {
    $result = $null
    try 
    {
        $prevDefaultOpts = $env:FZF_DEFAULT_OPTS
        $env:FZF_DEFAULT_OPTS = $env:FZF_DEFAULT_OPTS + ' ' + $env:FZF_ALT_C_OPTS
        if ($null -eq $env:FZF_ALT_C_COMMAND) {
            Invoke-Expression (Get-FileSystemCmd . -dirOnly) | Invoke-Fzf | ForEach-Object { $result = $_ }
        } else {
            Invoke-Expression ($env:FZF_ALT_C_COMMAND) | Invoke-Fzf | ForEach-Object { $result = $_ }
        }
    } 
    catch 
    {
        # catch custom exception
    }
    finally 
    {
        $env:FZF_DEFAULT_OPTS = $prevDefaultOpts
    }
    if (-not [string]::IsNullOrEmpty($result)) {
        Set-Location $result
        [Microsoft.PowerShell.PSConsoleReadLine]::AcceptLine()
    } else {
        #HACK: workaround for fact that PSReadLine seems to clear screen
        # after keyboard shortcut action is executed:
        [Microsoft.PowerShell.PSConsoleReadLine]::InvokePrompt()
    }
}

function SetPsReadlineShortcut($Chord,[switch]$Override,$BriefDesc,$Desc,[scriptblock]$scriptBlock)
{
    if ([string]::IsNullOrEmpty($Chord)) {
        return $false
    }
    if ((Get-PSReadlineKeyHandler -Bound | Where-Object {$_.Key.ToLower() -eq $Chord}) -and -not $Override) {
        return $false
    } else {
        Set-PSReadlineKeyHandler -Key $Chord -Description $Desc -BriefDescription $BriefDesc -ScriptBlock $scriptBlock
        return $true
    } 
}


function FindFzf()
{
    if ($script:IsWindows) {
        $AppNames = @('fzf-*-windows_*.exe','fzf.exe')
    } else {
        if ($IsMacOS) {
            $AppNames = @('fzf-*-darwin_*','fzf')
        } elseif ($IsLinux) {
            $AppNames = @('fzf-*-linux_*','fzf')
        } else {
            throw 'Unknown OS'
        }
    }

    # find it in our path:
    $script:FzfLocation = $null
    $AppNames | ForEach-Object {
        if ($null -eq $script:FzfLocation) {
            $result = Get-Command $_ -ErrorAction SilentlyContinue
            $result | ForEach-Object {
                $script:FzfLocation = Resolve-Path $_.Source   
            }
        }
    }
    
    if ($null -eq $script:FzfLocation) {
        throw 'Failed to find fzf binary in PATH. You can download a binary from this page: https://github.com/junegunn/fzf/releases' 
    }
}

$PsReadlineShortcuts = @{
    PSReadlineChordProvider = [PSCustomObject]@{
        'Chord' = "$PSReadlineChordProvider" 
        'BriefDesc' = 'Fzf Provider Select' 
        'Desc' = 'Run fzf for current provider based on current token' 
        'ScriptBlock' = { Invoke-FzfPsReadlineHandlerProvider } };
    PSReadlineChordReverseHistory = [PsCustomObject]@{
        'Chord' = "$PSReadlineChordReverseHistory" 
        'BriefDesc' = 'Fzf Reverse History Select' 
        'Desc' = 'Run fzf to search through PSReadline history' 
        'ScriptBlock' = { Invoke-FzfPsReadlineHandlerHistory } };
    PSReadlineChordSetLocation = @{
        'Chord' = "$PSReadlineChordSetLocation"
        'BriefDesc' = 'Fzf Set Location'
        'Desc' = 'Run fzf to select directory to set current location' 
        'ScriptBlock' = { Invoke-FzfPsReadlineHandlerSetLocation } };
    PSReadlineChordReverseHistoryArgs = @{
        'Chord' = "$PSReadlineChordReverseHistoryArgs"
        'BriefDesc' = 'Fzf Reverse History Arg Select'
        'Desc' = 'Run fzf to search through command line arguments in PSReadline history' 
        'ScriptBlock' = { Invoke-FzfPsReadlineHandlerHistoryArgs } };
    PSReadlineChordTabCompletion = [PSCustomObject]@{
        'Chord' = "Tab"
        'BriefDesc' = 'Fzf Tab Completion'
        'Desc' = 'Invoke Fzf for tab completion'
        'ScriptBlock' = { Invoke-TabCompletion } };    
}
if (Get-Module -ListAvailable -Name PSReadline) {
    $PsReadlineShortcuts.GetEnumerator() | ForEach-Object {
        $info = $_.Value
        $result = SetPsReadlineShortcut $info.Chord -Override:$PSBoundParameters.ContainsKey($_.Key) $info.BriefDesc $info.Desc $info.ScriptBlock
        # store that the chord is not activated:
        if (-not $result) {
            $info.Chord = $null
        }
    } 
} else {
    Write-Warning "PSReadline module not found - keyboard handlers not installed" 
}

FindFzf

try 
{
    $fzfVersion = $(& $script:FzfLocation --version).Replace(' (devel)','').Split('.') 
    $script:UseHeightOption = $fzfVersion.length -ge 2 -and `
                              ([int]$fzfVersion[0] -gt 0 -or `
                              [int]$fzfVersion[1] -ge 21) -and `
                              $script:RunningInWindowsTerminal     
}
catch 
{
    # continue
}
# PSFzf.Functions.ps1
#.ExternalHelp PSFzf.psm1-help.xml

$addedAliases = @()

function script:SetPsFzfAlias {
    param($Name,$Function)

    New-Alias -Name $Name -Scope Global -Value $Function -ErrorAction Ignore
    $addedAliases += $Name
}
function script:SetPsFzfAliasCheck {
    param($Name,$Function)

    # prevent Get-Command from loading PSFzf
    $script:PSModuleAutoLoadingPreferencePrev=$PSModuleAutoLoadingPreference
    $PSModuleAutoLoadingPreference='None'

    if (-not (Get-Command -Name $Name -ErrorAction Ignore)) {
        SetPsFzfAlias $Name $Function
    }    

    # restore module auto loading
    $PSModuleAutoLoadingPreference=$script:PSModuleAutoLoadingPreferencePrev
}

function script:RemovePsFzfAliases {
    $addedAliases | ForEach-Object {
        Remove-Item -Path Alias:$_
    }
}
function Invoke-FuzzyEdit()
{
    param($Directory=$null)

    $files = @()
    try {
        if ($Directory) {
            $prevDir = $PWD.Path
            cd $Directory
        }
        Invoke-Expression (Get-FileSystemCmd .) | Invoke-Fzf -Multi | ForEach-Object { $files += """$_""" }
    } catch {
    }
    finally {
        if ($prevDir) {
            cd $prevDir
        }
    }

    # HACK to check to see if we're running under Visual Studio Code.
    # If so, reuse Visual Studio Code currently open windows:
    $editorOptions = ''
    if ($null -ne $env:VSCODE_PID) {
        $editor = 'code'
        $editorOptions += '--reuse-window'
    } else {
        $editor = $env:EDITOR
        if ($null -eq $editor) {
            if (!$IsWindows) {
                $editor = 'vim'
            } else {
                $editor = 'code'
            }
        }
    }
    
    if ($null -ne $files) {
        $fileList = ''
        $files | ForEach-Object {
            if ($Directory) {
                $fileList += (Join-Path $Directory $_) + ' '
            } else {
                $fileList += $_ + ' '
            }
        }
        Invoke-Expression -Command ("$editor $editorOptions $fileList") 
    }
}


    #.ExternalHelp PSFzf.psm1-help.xml
function Invoke-FuzzyFasd() {
    $result = $null
    try {
        if (Get-Command Get-Frecents -ErrorAction Ignore) {
            Get-Frecents | ForEach-Object { $_.FullPath } | Invoke-Fzf -ReverseInput -NoSort | ForEach-Object { $result = $_ }
        } elseif (Get-Command fasd -ErrorAction Ignore) {
            fasd -l | Invoke-Fzf -ReverseInput -NoSort | ForEach-Object { $result = $_ }
        } 
    } catch {
        
    }
    if ($null -ne $result) {
        # use cd in case it's aliased to something else:
        cd $result
    }
}


#.ExternalHelp PSFzf.psm1-help.xml
function Invoke-FuzzyHistory() {
    if (Get-Command Get-PSReadLineOption -ErrorAction SilentlyContinue) {
        $result = Get-Content (Get-PSReadLineOption).HistorySavePath | Invoke-Fzf -Reverse -NoSort
    } else {
        $result = Get-History | ForEach-Object { $_.CommandLine } | Invoke-Fzf -Reverse -NoSort
    }
    if ($null -ne $result) {
        Write-Output "Invoking '$result'`n"
        Invoke-Expression "$result" -Verbose
    }
}

#.ExternalHelp PSFzf.psm1-help.xml

function GetProcessSelection() {
    param(
        [scriptblock]
        $ResultAction
    )
    $header = "`n" + $("{0,-8} PROCESS NAME" -f "ID") + "`n"
    $result = Get-Process | Where-Object { ![string]::IsNullOrEmpty($_.ProcessName) } | ForEach-Object { "{0,-8} {1}" -f $_.Id,$_.ProcessName } | Invoke-Fzf -Multi -Header $header
    $result | ForEach-Object {
        &$ResultAction $_
    }
}
function Invoke-FuzzyKillProcess() {
    GetProcessSelection -ResultAction {
        param($result) 
        $id = $result -replace "([0-9]+)(.*)",'$1' 
        Stop-Process $id -Verbose
    }
}

#.ExternalHelp PSFzf.psm1-help.xml
function Invoke-FuzzySetLocation() {
    param($Directory=$null)

    if ($null -eq $Directory) { $Directory = $PWD.Path }
    $result = $null
    try {
        if ([string]::IsNullOrWhiteSpace($env:FZF_DEFAULT_COMMAND)) {
            Get-ChildItem $Directory -Recurse -ErrorAction Ignore | Where-Object{ $_.PSIsContainer } | Invoke-Fzf | ForEach-Object { $result = $_ }
        } else {
            Invoke-Fzf | ForEach-Object { $result = $_ }
        }
    } catch {
        
    }

    if ($null -ne $result) {
        Set-Location $result
    } 
}

if ((-not $IsLinux) -and (-not $IsMacOS)) {
    #.ExternalHelp PSFzf.psm1-help.xml
    function Set-LocationFuzzyEverything() {
        param($Directory=$null)
        if ($null -eq $Directory) {
            $Directory = $PWD.Path
            $Global = $False
        } else {
            $Global = $True
        }
        $result = $null
        try {
            Search-Everything -Global:$Global -PathInclude $Directory -FolderInclude @('') | Invoke-Fzf | ForEach-Object { $result = $_ }
        } catch {
            
        }
        if ($null -ne $result) {
            # use cd in case it's aliased to something else:
            cd $result
        }
    }
}

#.ExternalHelp PSFzf.psm1-help.xml
function Invoke-FuzzyZLocation() {
    $result = $null
    try {
        (Get-ZLocation).GetEnumerator() | Sort-Object { $_.Value } -Descending | ForEach-Object{ $_.Key } | Invoke-Fzf -NoSort | ForEach-Object { $result = $_ }
    } catch {
        
    }
    if ($null -ne $result) {
        # use cd in case it's aliased to something else:
        cd $result
    }
}


#.ExternalHelp PSFzf.psm1-help.xml
function Invoke-FuzzyGitStatus() {
    $result = @()
    try {
        $headerStrings = Get-HeaderStrings
        $gitRoot = git rev-parse --show-toplevel
        git status --porcelain | 
        Invoke-Fzf -Multi -Bind $headerStrings[1] -Header $headerStrings[0] | ForEach-Object { 
            $result += Join-Path $gitRoot $('{0}' -f $_.Substring('?? '.Length)) 
        }
    } catch {
        # do nothing
    }
    if ($null -ne $result) {
        $result
    }
}

function Enable-PsFzfAliases()
{
    # set aliases:
    if (-not $DisableAliases) {
        SetPsFzfAliasCheck "fe"      Invoke-FuzzyEdit
        SetPsFzfAliasCheck "fh"      Invoke-FuzzyHistory
        SetPsFzfAliasCheck "ff"      Invoke-FuzzyFasd
        SetPsFzfAliasCheck "fkill"   Invoke-FuzzyKillProcess
        SetPsFzfAliasCheck "fd"      Invoke-FuzzySetLocation
        if (${function:Set-LocationFuzzyEverything}) {
            SetPsFzfAliasCheck "cde" Set-LocationFuzzyEverything 
        }
        SetPsFzfAliasCheck "fz"      Invoke-FuzzyZLocation
        SetPsFzfAliasCheck "fgs"     Invoke-FuzzyGitStatus
    }     
}
# PSFzf.Git.ps1

$script:GitKeyHandlers = @()

$script:gitPath = $null
$script:bashPath = $null
$script:gitPathLong = $null

function SetGitKeyBindings($enable)
{
    if ($IsLinux -or $IsMacOS) {
        Write-Error "Failed to register git key bindings - git bindings aren't supported on non-Windows platforms"
    }

    if ($enable)
    {
        if ($null -eq $gitPath) {
            $gitInfo = Get-Command git.exe -ErrorAction SilentlyContinue
            if ($null -ne $gitInfo) {
                $script:gitPathLong = Split-Path (Split-Path $gitInfo.Source -Parent) -Parent  

                $a = New-Object -ComObject Scripting.FileSystemObject 
                $f = $a.GetFolder($script:gitPathLong) 
                $script:gitPath = $f.ShortPath
                $script:bashPath = $(Join-Path $script:gitPath "bin\bash.exe")
                $script:bashPath = Resolve-Path $script:bashPath  
            } else {
                Write-Error "Failed to register git key bindings - git executable not found"
                return
            }
        }
        if (Get-Command Set-PSReadLineKeyHandler -ErrorAction SilentlyContinue) {
            @('ctrl+g,ctrl+f','Select Git Files', {Invoke-PsFzfGitFiles}), `
            @('ctrl+g,ctrl+s','Select Git Hashes', {Invoke-PsFzfGitHashes}), `
            @('ctrl+g,ctrl+b','Select Git Branches', {Invoke-PsFzfGitBranches}) | ForEach-Object {
                $script:GitKeyHandlers += $_[0]
                Set-PSReadLineKeyHandler -Chord $_[0] -Description $_[1] -ScriptBlock $_[2]
            }
        } else {
            Write-Error "Failed to register git key bindings - PSReadLine module not loaded"
            return
        }
    }
}

function RemoveGitKeyBindings()
{
    $script:GitKeyHandlers | ForEach-Object {
        Remove-PSReadLineKeyHandler -Chord $_
    }
}

function IsInGitRepo()
{
    git rev-parse HEAD 2>&1 | Out-Null
    return $?
}

function Get-ColorAlways()
{
    if ($RunningInWindowsTerminal) {
        ' --color=always'
    } else {
        ''
    }
}

function Get-HeaderStrings() {
    if ($RunningInWindowsTerminal) {
        $header = "`n`e[7mCTRL+A`e[0m Select All`t`e[7mCTRL+D`e[0m Deselect All`t`e[7mCTRL+T`e[0m Toggle All"
    } else {
        $header = "`nCTRL+A-Select All`tCTRL+D-Deselect All`tCTRL+T-Toggle All"
    }

    $keyBinds = 'ctrl-a:select-all,ctrl-d:deselect-all,ctrl-t:toggle-all'
    return $Header, $keyBinds
}
function Invoke-PsFzfGitFiles() {
    if (-not (IsInGitRepo)) {
        return
    }

    $previewCmd = "${script:bashPath} \""" + $(Join-Path $PsScriptRoot 'helpers/PsFzfGitFiles-Preview.sh') + "\"" {-1}" + $(Get-ColorAlways) + " \""$pwd\"""
    $result = @()
   
    $headerStrings = Get-HeaderStrings

    git status --short | `
        Invoke-Fzf -Multi -Ansi `
            -Preview "$previewCmd" -Header $headerStrings[0] -Bind $headerStrings[1] | foreach-object { 
                $result += $_.Substring('?? '.Length) 
            } 
    [Microsoft.PowerShell.PSConsoleReadLine]::InvokePrompt()
    if ($result.Length -gt 0) {
        $result = $result -join " "
        [Microsoft.PowerShell.PSConsoleReadLine]::Insert($result)
    }
}
function Invoke-PsFzfGitHashes() {
    if (-not (IsInGitRepo)) {
        return
    }

    $previewCmd = "${script:bashPath} \""" + $(Join-Path $PsScriptRoot 'helpers/PsFzfGitHashes-Preview.sh') + "\"" {}" + $(Get-ColorAlways) + " \""$pwd\"""
    $result = @()
    
    & git log --date=short --format="%C(green)%C(bold)%cd %C(auto)%h%d %s (%an)" $(Get-ColorAlways).Trim()  | `
        Invoke-Fzf -Ansi -NoSort -Multi -Bind ctrl-s:toggle-sort `
        -Header 'Press CTRL-S to toggle sort' `
        -Preview "$previewCmd" | ForEach-Object {
            if ($_ -match '\d\d-\d\d-\d\d\s+([a-f0-9]+)\s+') {
                $result += $Matches.1
            }
        }

    [Microsoft.PowerShell.PSConsoleReadLine]::InvokePrompt()
    if ($result.Length -gt 0) {
        $result = $result -join " "
        [Microsoft.PowerShell.PSConsoleReadLine]::Insert($result)
    }
 }

 function Invoke-PsFzfGitBranches() {
    if (-not (IsInGitRepo)) {
        return
    }

    $previewCmd = "${script:bashPath} \""" + $(Join-Path $PsScriptRoot 'helpers/PsFzfGitBranches-Preview.sh') + "\"" {}" + $(Get-ColorAlways) + " \""$pwd\"""
    $result = @()
    git branch -a | & "${script:gitPathLong}\usr\bin\grep.exe" -v '/HEAD\s' | 
        ForEach-Object { $_.Substring('* '.Length) } | Sort-Object | `
                Invoke-Fzf -Ansi -Multi -PreviewWindow "right:70%" -Preview "$previewCmd" | ForEach-Object {
                        $result += $_
                }

    [Microsoft.PowerShell.PSConsoleReadLine]::InvokePrompt()
    if ($result.Length -gt 0) {
        $result = $result -join " "
        [Microsoft.PowerShell.PSConsoleReadLine]::Insert($result)
    }
 }

# gb() {
# is_in_git_repo || return
# git branch -a --color=always | grep -v '/HEAD\s' | sort |
# fzf-down --ansi --multi --tac --preview-window right:70% \
# --preview 'git log --oneline --graph --date=short --color=always --pretty="format:%C(auto)%cd %h%d %s" $(sed s/^..// <<< {} | cut -d" " -f1) | head -'$LINES |
# sed 's/^..//' | cut -d' ' -f1 |
# sed 's#^remotes/##'
# }
# PSFzf.TabExpansion.ps1
# borrowed from https://github.com/dahlbyk/posh-git/blob/f69efd9229029519adb32e37a464b7e1533a372c/src/GitTabExpansion.ps1#L81
filter script:quoteStringWithSpecialChars {
    if ($_ -and ($_ -match '\s+|#|@|\$|;|,|''|\{|\}|\(|\)')) {
        $str = $_ -replace "'", "''"
        "'$str'"
    }
    else {
        $_
    }
}

# taken from https://github.com/dahlbyk/posh-git/blob/2ad946347e7342199fd4bb1b42738833f68721cd/src/GitUtils.ps1#L407
function script:Get-AliasPattern($cmd) {
    $aliases = @($cmd) + @(Get-Alias | Where-Object { $_.Definition -eq $cmd } | Select-Object -Exp Name)
   "($($aliases -join '|'))"
}

function Expand-GitWithFzf($lastBlock) {
    $gitResults = Expand-GitCommand $lastBlock
    # if no results, invoke filesystem completion:
    if ($null -eq $gitResults) {
        $results = Invoke-Fzf -Multi | script:quoteStringWithSpecialChars
    } else {
        $results = $gitResults | Invoke-Fzf -Multi | script:quoteStringWithSpecialChars
    }

    if ($results.Count -gt 1) {
        $results -join ' '
    } else {
        if (-not $null -eq $results) {
            $results
        } else {
            '' # output something to prevent default tab expansion
        }
    }

    #HACK: workaround for fact that PSReadLine seems to clear screen
    # after keyboard shortcut action is executed:
    [Microsoft.PowerShell.PSConsoleReadLine]::InvokePrompt()
}

function Expand-FileDirectoryPath($lastWord) {
    # find dir and file pattern connected to the trigger:
    $lastWord = $lastWord.Substring(0, $lastWord.Length - 2)
    if ($lastWord.EndsWith('\')) {
        $dir = $lastWord.Substring(0, $lastWord.Length - 1)
        $file = $null    
    } elseif (-not [string]::IsNullOrWhiteSpace($lastWord)) {
        $dir = Split-Path $lastWord -Parent
        $file = Split-Path $lastWord -Leaf    
    }
    if (-not [System.IO.Path]::IsPathRooted($dir)) {
        $dir = Join-Path $PWD.Path $dir
    }
    $prevPath = $Pwd.Path
    try {
        if (-not [string]::IsNullOrEmpty($dir)) {
            Set-Location $dir
        }
        if (-not [string]::IsNullOrEmpty($file)) {
            Invoke-Fzf -Query $file
        }
        else {
            Invoke-Fzf
        }
    }
    finally {
        Set-Location $prevPath
    }

    #HACK: workaround for fact that PSReadLine seems to clear screen
    # after keyboard shortcut action is executed:
    [Microsoft.PowerShell.PSConsoleReadLine]::InvokePrompt()
}

$script:TabExpansionEnabled = $false
function SetTabExpansion($enable)
{
    if ($enable) {
        if (-not $script:TabExpansionEnabled) {
                $script:TabExpansionEnabled = $true

                RegisterBuiltinCompleters

                Register-ArgumentCompleter -CommandName git,tgit,gitk -Native -ScriptBlock {
                    param($wordToComplete, $commandAst, $cursorPosition)
                
                    # The PowerShell completion has a habit of stripping the trailing space when completing:
                    # git checkout <tab>
                    # The Expand-GitCommand expects this trailing space, so pad with a space if necessary.
                    $padLength = $cursorPosition - $commandAst.Extent.StartOffset
                    $textToComplete = $commandAst.ToString().PadRight($padLength, ' ').Substring(0, $padLength)
                
                    Expand-GitCommandPsFzf $textToComplete
                }
                
        }
    } else {
        if ($script:TabExpansionEnabled) {
            $script:TabExpansionEnabled = $false
        }
    }   
}

function CheckFzfTrigger {
    param($commandName, $parameterName, $wordToComplete, $commandAst, $cursorPosition,$action)
    if ([string]::IsNullOrWhiteSpace($env:FZF_COMPLETION_TRIGGER)) {
        $completionTrigger = '**'
    } else {
        $completionTrigger = $env:FZF_COMPLETION_TRIGGER
    }
    if ($wordToComplete.EndsWith($completionTrigger)) {
        $wordToComplete = $wordToComplete.Substring(0, $wordToComplete.Length - $completionTrigger.Length)
        $wordToComplete
    }
}


function GetServiceSelection() {
    param(
        [scriptblock]
        $ResultAction
    )
    $header = [System.Environment]::NewLine + $("{0,-24} NAME" -f "DISPLAYNAME") + [System.Environment]::NewLine
    $result = Get-Service | Where-Object { ![string]::IsNullOrEmpty($_.Name) } | ForEach-Object { 
        "{0,-24} {1}" -f $_.DisplayName.Substring(0,[System.Math]::Min(24,$_.DisplayName.Length)),$_.Name } | Invoke-Fzf -Multi -Header $header
    $result | ForEach-Object {
        &$ResultAction $_
    }
}

function RegisterBuiltinCompleters {
    $processIdOrNameScriptBlock = {
        param($commandName, $parameterName, $wordToComplete, $commandAst, $cursorPosition, $action)
        $wordToComplete = CheckFzfTrigger $commandName $parameterName $wordToComplete $commandAst $cursorPosition
        if ($null -ne $wordToComplete)
        {
            if ($parameterName -eq 'Name') {
                $group = '$2'
            } elseif ($parameterName -eq 'Id') {
                $group = '$1'
            }

            $script:resultArr = @()
            GetProcessSelection -ResultAction {
                param($result) 
                $script:resultArr += $result -replace "([0-9]+)\s*(.*)",$group
            }

            if ($script:resultArr.Length -ge 1) {
                $script:resultArr -join ', '
            }
            
            #HACK: workaround for fact that PSReadLine seems to clear screen
            # after keyboard shortcut action is executed:
            [Microsoft.PowerShell.PSConsoleReadLine]::InvokePrompt()
        } else {
            # don't return anything - let normal tab completion work
        }
    }

    'Get-Process','Stop-Process' | ForEach-Object {
        Register-ArgumentCompleter -CommandName $_ -ParameterName "Name" -ScriptBlock $processIdOrNameScriptBlock
        Register-ArgumentCompleter -CommandName $_ -ParameterName "Id" -ScriptBlock $processIdOrNameScriptBlock            
    }

    $serviceNameScriptBlock = {
        param($commandName, $parameterName, $wordToComplete, $commandAst, $cursorPosition,$action)
        $wordToComplete = CheckFzfTrigger $commandName $parameterName $wordToComplete $commandAst $cursorPosition
        if ($null -ne $wordToComplete)
        {
            if ($parameterName -eq 'Name') {
                $group = '$2'
            } elseif ($parameterName -eq 'DisplayName') {
                $group = '$1'
            }

            $script:resultArr = @()
            GetServiceSelection -ResultAction {
                param($result) 
                $script:resultArr += $result.Substring(24+1)
            }

            if ($script:resultArr.Length -ge 1) {
                $script:resultArr -join ', '
            }
            #HACK: workaround for fact that PSReadLine seems to clear screen
            # after keyboard shortcut action is executed:
            [Microsoft.PowerShell.PSConsoleReadLine]::InvokePrompt()
        } else {
            # don't return anything - let normal tab completion work
        }
    }

    'Get-Service','Start-Service','Stop-Service' | ForEach-Object {
        Register-ArgumentCompleter -CommandName $_ -ParameterName "Name" -ScriptBlock $serviceNameScriptBlock
        Register-ArgumentCompleter -CommandName $_ -ParameterName "DisplayName" -ScriptBlock $serviceNameScriptBlock            
    }
}


function Expand-GitCommandPsFzf($lastWord) {
    if ([string]::IsNullOrWhiteSpace($env:FZF_COMPLETION_TRIGGER)) {
        $completionTrigger = '**'
    }
    else {
        $completionTrigger = $env:FZF_COMPLETION_TRIGGER
    }
    if ($lastWord.EndsWith($completionTrigger)) {
            $lastWord = $lastWord.Substring(0, $lastWord.Length - $completionTrigger.Length)
            Expand-GitWithFzf $lastWord
    } else {
        Expand-GitCommand $lastWord
    }
}


function Invoke-FzfTabCompletion()
{
    $script:continueCompletion = $true
    do 
    {
        $script:continueCompletion = script:Invoke-FzfTabCompletionInner
    }
    while ($script:continueCompletion)
}
function script:Invoke-FzfTabCompletionInner()
{
    $script:result = @()

    [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Management.Automation") 
    $line = $null
    $cursor = $null
    [Microsoft.PowerShell.PSConsoleReadline]::GetBufferState([ref]$line, [ref]$cursor)

    if ($cursor -lt 0 -or [string]::IsNullOrWhiteSpace($line)) { 
        return $false
    }
    $completions = [System.Management.Automation.CommandCompletion]::CompleteInput($line, $cursor, @{})
    
    $completionMatches = $completions.CompletionMatches 
    if ($completionMatches.Count -le 0) {
        return $false
    }
    $script:continueCompletion = $false

    $addSpace = $null -ne $currentPath -and $currentPath.StartsWith(" ")

    if ($completionMatches.Count -eq 1) {                
        $script:result = $completionMatches[0].CompletionText
    } elseif ($completionMatches.Count -gt 1) {
        $helpers = New-Object PSFzf.IO.CompletionHelpers
        $ambiguous = $false
        $addSpace  = $false
        $prefix = $helpers.GetUnambiguousPrefix($completionMatches,[ref]$ambiguous)
        
        $script:result = @()
        $script:checkCompletion = $true
        $expectTrigger = $script:TabContinuousTrigger
        # need to escape the key if it's a forward slash:
        if ($expectTrigger -eq '\') {
            $expectTrigger += $expectTrigger 
        }

        # normalize so path works correctly for Windows:
        $path = $PWD.Path.Replace('\','/')
        
        $previewScript = $(Join-Path $PsScriptRoot 'helpers/PsFzfTabExpansion-Preview.ps1')
        $additionalCmd = @{ Preview=$("pwsh -NoProfile -NonInteractive -File \""$previewScript\"" \""" + $path + "\"" {}") } 

        $script:fzfOutput = @()
        $completionMatches | ForEach-Object { $_.CompletionText } | Invoke-Fzf `
            -Layout reverse `
            -Expect $expectTrigger `
            -Query "$prefix" `
            -PrintQuery `
            -Bind 'tab:down,btab:up' `
            @additionalCmd | ForEach-Object {
                if ($null -eq $_) {
                    $script:fzfOutput += ""
                } else {
                    $script:fzfOutput += $_
                }
            }

        # check if there's a selection:
        if ($script:fzfOutput.Length -gt 2) {
            $script:result = $script:fzfOutput[2..($script:fzfOutput.Length-1)]
        }
        # or just complete with the query string:
        else {
            $script:result = $script:fzfOutput[0]
        }    

        # check if we should continue completion:
        $script:continueCompletion = $script:fzfOutput[1] -eq $script:TabContinuousTrigger
    
        #HACK: workaround for fact that PSReadLine seems to clear screen
        # after keyboard shortcut action is executed:
        [Microsoft.PowerShell.PSConsoleReadLine]::InvokePrompt()
    }    

    $result = $script:result
    if ($null -ne $result) {
        # quote strings if we need to:
        if ($result -is [system.array]) {
            for ($i = 0;$i -lt $result.Length;$i++) {
                $result[$i] = FixCompletionResult $result[$i]
            }
            $str = $result -join ','
        } else {
            $str = FixCompletionResult $result
        }
        
        if ($script:continueCompletion) {
            $isQuoted = $str.EndsWith("'")
            $resultTrimmed = $str.Trim(@('''','"')) 
            if (Test-Path "$resultTrimmed"  -PathType Container) {
                if ($isQuoted) {
                    $str = "'{0}{1}'" -f "$resultTrimmed",$script:TabContinuousTrigger
                } else {
                    $str = "$resultTrimmed" + $script:TabContinuousTrigger
                }
            } else {
                # no more paths to complete, so let's stop completion:
                $str += ' ' 
                $script:continueCompletion = $false
            }
        }

        if ($addSpace) {
            $str = ' ' + $str
        }
    
        $leftCursor = $completions.ReplacementIndex
        $replacementLength = $completions.ReplacementLength
        if ($leftCursor -le 0 -and $replacementLength -le 0) {
            [Microsoft.PowerShell.PSConsoleReadLine]::Insert($str)
        } else {
            [Microsoft.PowerShell.PSConsoleReadLine]::Replace($leftCursor,$replacementLength,$str)
        }
        
    }

    return $script:continueCompletion
}