forked from kelleyma49/PSFzf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PSFzf.Functions.ps1
406 lines (357 loc) · 13.1 KB
/
PSFzf.Functions.ps1
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
#.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 Get-EditorLaunch() {
param($FileList, $LineNum = 0)
# HACK to check to see if we're running under Visual Studio Code.
# If so, reuse Visual Studio Code currently open windows:
$editorOptions = ''
if (-not [string]::IsNullOrEmpty($env:PSFZF_EDITOR_OPTIONS)) {
$editorOptions += ' ' + $env:PSFZF_EDITOR_OPTIONS
}
if ($null -ne $env:VSCODE_PID) {
$editor = 'code'
$editorOptions += ' --reuse-window'
}
else {
$editor = if ($ENV:VISUAL) { $ENV:VISUAL }elseif ($ENV:EDITOR) { $ENV:EDITOR }
if ($null -eq $editor) {
if (!$IsWindows) {
$editor = 'vim'
}
else {
$editor = 'code'
}
}
}
if ($editor -eq 'code' -or $editor -eq 'code-insiders' -or $editor -eq 'codium') {
if ($FileList -is [array] -and $FileList.length -gt 1) {
for ($i = 0; $i -lt $FileList.Count; $i++) {
$FileList[$i] = '"{0}"' -f $(Resolve-Path $FileList[$i].Trim('"'))
}
"$editor$editorOptions {0}" -f ($FileList -join ' ')
}
else {
"$editor$editorOptions --goto ""{0}:{1}""" -f $(Resolve-Path $FileList.Trim('"')), $LineNum
}
}
elseif ($editor -match '[gn]?vi[m]?') {
if ($FileList -is [array] -and $FileList.length -gt 1) {
for ($i = 0; $i -lt $FileList.Count; $i++) {
$FileList[$i] = '"{0}"' -f $(Resolve-Path $FileList[$i].Trim('"'))
}
"$editor$editorOptions {0}" -f ($FileList -join ' ')
}
else {
"$editor$editorOptions ""{0}"" +{1}" -f $(Resolve-Path $FileList.Trim('"')), $LineNum
}
}
elseif ($editor -eq 'nano') {
if ($FileList -is [array] -and $FileList.length -gt 1) {
for ($i = 0; $i -lt $FileList.Count; $i++) {
$FileList[$i] = '"{0}"' -f $(Resolve-Path $FileList[$i].Trim('"'))
}
"$editor$editorOptions {0}" -f ($FileList -join ' ')
}
else {
"$editor$editorOptions +{1} ""{0}""" -f $(Resolve-Path $FileList.Trim('"')), $LineNum
}
}
else {
# select the first file as we don't know if the editor supports opening multiple files from the cmd line
if ($FileList -is [array] -and $FileList.length -gt 1) {
"$editor$editorOptions ""{0}""" -f $(Resolve-Path $FileList[0].Trim('"'))
}
else {
"$editor$editorOptions ""{0}""" -f $(Resolve-Path $FileList.Trim('"'))
}
}
}
function Invoke-FuzzyEdit() {
param($Directory = ".", [switch]$Wait)
$files = @()
try {
if ( Test-Path $Directory) {
if ( (Get-Item $Directory).PsIsContainer ) {
$prevDir = $PWD.ProviderPath
cd $Directory
Invoke-Expression (Get-FileSystemCmd .) | Invoke-Fzf -Multi | ForEach-Object { $files += "$_" }
}
else {
$files += $Directory
$Directory = Split-Path -Parent $Directory
}
}
}
catch {
}
finally {
if ($prevDir) {
cd $prevDir
}
}
if ($files.Count -gt 0) {
try {
if ($Directory) {
$prevDir = $PWD.Path
cd $Directory
}
# Not sure if being passed relative or absolute path
$cmd = Get-EditorLaunch -FileList $files
Write-Host "Executing '$cmd'..."
($Editor, $Arguments) = $cmd.Split(' ')
Start-Process $Editor -ArgumentList $Arguments -Wait:$Wait -NoNewWindow
}
catch {
}
finally {
if ($prevDir) {
cd $prevDir
}
}
}
}
#.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() {
$result = Get-PickedHistory -UsePSReadLineHistory:$($null -ne $(Get-Command Get-PSReadLineOption -ErrorAction Ignore))
if ($null -ne $result) {
Write-Output "Invoking '$result'`n"
Invoke-Expression "$result" -Verbose
}
}
# needs to match helpers/GetProcessesList.ps1
function GetProcessesList() {
Get-Process | `
Where-Object { ![string]::IsNullOrEmpty($_.ProcessName) } | `
ForEach-Object {
$pmSize = $_.PM / 1MB
$cpu = $_.CPU
# make sure we display a value so we can correctly parse selections:
if ($null -eq $cpu) {
$cpu = 0.0
}
"{0,-8:n2} {1,-8:n2} {2,-8} {3}" -f $pmSize, $cpu, $_.Id, $_.ProcessName }
}
function GetProcessSelection() {
param(
[scriptblock]
$ResultAction
)
$previewScript = $(Join-Path $PsScriptRoot 'helpers/GetProcessesList.ps1')
$cmd = $($script:PowershellCmd + " -NoProfile -NonInteractive -File \""$previewScript\""")
$header = "`n" + `
"`nCTRL+R-Reload`tCTRL+A-Select All`tCTRL+D-Deselect All`tCTRL+T-Toggle All`n`n" + `
$("{0,-8} {1,-8} {2,-8} PROCESS NAME" -f "PM(M)", "CPU", "ID") + "`n" + `
"{0,-8} {1,-8} {2,-8} {3,-12}" -f "-----", "---", "--", "------------"
$result = GetProcessesList | `
Invoke-Fzf -Multi -Header $header `
-Bind "ctrl-r:reload($cmd)", "ctrl-a:select-all", "ctrl-d:deselect-all", "ctrl-t:toggle-all" `
-Preview "echo {}" -PreviewWindow """down,3,wrap""" `
-Layout reverse -Height 80%
$result | ForEach-Object {
&$ResultAction $_
}
}
#.ExternalHelp PSFzf.psm1-help.xml
function Invoke-FuzzyKillProcess() {
GetProcessSelection -ResultAction {
param($result)
$resultSplit = $result.split(' ', [System.StringSplitOptions]::RemoveEmptyEntries)
$processIdIdx = 2
$id = $resultSplit[$processIdIdx]
Stop-Process -Id $id -Verbose
}
}
#.ExternalHelp PSFzf.psm1-help.xml
function Invoke-FuzzySetLocation() {
param($Directory = $null)
if ($null -eq $Directory) { $Directory = $PWD.ProviderPath }
$result = $null
try {
Get-ChildItem $Directory -Recurse -ErrorAction Ignore | Where-Object { $_.PSIsContainer } | 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.ProviderPath
$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-FuzzyScoop() {
param(
[string]$subcommand = "install",
[string]$subcommandflags = ""
)
$result = $null
$scoopexists = Get-Command scoop -ErrorAction Ignore
if ($scoopexists) {
$apps = New-Object System.Collections.ArrayList
Get-ChildItem "$(Split-Path $scoopexists.Path)\..\buckets" | ForEach-Object {
$bucket = $_.Name
Get-ChildItem "$($_.FullName)\bucket" | ForEach-Object {
$apps.Add($bucket + '/' + ($_.Name -replace '.json', '')) > $null
}
}
$result = $apps | Invoke-Fzf -Header "Scoop Applications" -Multi -Preview "scoop info {}" -PreviewWindow wrap
}
if ($null -ne $result) {
Invoke-Expression "scoop $subcommand $($result -join ' ') $subcommandflags"
}
}
#.ExternalHelp PSFzf.psm1-help.xml
function Invoke-FuzzyGitStatus() {
Invoke-PsFzfGitFiles
}
function Invoke-PsFzfRipgrep() {
# this function is adapted from https://github.com/junegunn/fzf/blob/master/ADVANCED.md#switching-between-ripgrep-mode-and-fzf-mode
param([Parameter(Mandatory)]$SearchString, [switch]$NoEditor)
$RG_PREFIX = "rg --column --line-number --no-heading --color=always --smart-case "
$INITIAL_QUERY = $SearchString
$script:OverrideFzfDefaultCommand = [FzfDefaultCmd]::new('')
try {
if ($script:IsWindows) {
$sleepCmd = ''
$trueCmd = 'cd .'
$env:FZF_DEFAULT_COMMAND = "$RG_PREFIX ""$INITIAL_QUERY"""
}
else {
$sleepCmd = 'sleep 0.1;'
$trueCmd = 'true'
$env:FZF_DEFAULT_COMMAND = '{0} $(printf %q "{1}")' -f $RG_PREFIX, $INITIAL_QUERY
}
$fzfArguments = @{
color = "hl:-1:underline,hl+:-1:underline:reverse"
query = $INITIAL_QUERY
prompt = 'ripgrep> '
delimiter = ':'
header = '? CTRL-R (Ripgrep mode) ? CTRL -F (fzf mode) ?'
preview = 'bat --color=always {1} --highlight-line {2}'
'preview-window' = 'up,60%,border-bottom,+{2}+3/3,~3'
}
$fzfArgs = ($fzfArguments.GetEnumerator() | foreach-object { "--{0}=""{1}""" -f $_.Key, $_.Value }) -join ' '
$Bind = @(
'ctrl-r:unbind(change,ctrl-r)+change-prompt(ripgrep> )' + "+disable-search+reload($RG_PREFIX {q} || $trueCmd)+rebind(change,ctrl-f)"
)
$Bind += 'ctrl-f:unbind(change,ctrl-f)+change-prompt(fzf> )+enable-search+clear-query+rebind(ctrl-r)'
$Bind += "change:reload:$sleepCmd $RG_PREFIX {q} || $trueCmd"
$fzfArgs += ' --ansi --disabled ' + ($Bind | foreach-object { "--bind=""{0}""" -f $_ }) -join ' '
Invoke-Expression -Command $('{0} {1}' -f $script:FzfLocation, $fzfArgs) | ForEach-Object { $results += $_ }
# we need this here to prevent the editor launch from inherting FZF_DEFAULT_COMMAND from being overwritten (see #267):
if ($script:OverrideFzfDefaultCommand) {
$script:OverrideFzfDefaultCommand.Restore()
$script:OverrideFzfDefaultCommand = $null
}
if (-not [string]::IsNullOrEmpty($results)) {
$split = $results.Split(':')
$fileList = $split[0]
$lineNum = $split[1]
if ($NoEditor) {
Resolve-Path $fileList
}
else {
$cmd = Get-EditorLaunch -FileList $fileList -LineNum $lineNum
Write-Host "Executing '$cmd'..."
Invoke-Expression -Command $cmd
}
}
}
catch {
Write-Error "Error occurred: $_"
}
finally {
if ($script:OverrideFzfDefaultCommand) {
$script:OverrideFzfDefaultCommand.Restore()
$script:OverrideFzfDefaultCommand = $null
}
}
}
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 "fs" Invoke-FuzzyScoop
SetPsFzfAliasCheck "fgs" Invoke-FuzzyGitStatus
}
}