From af1308e94fbbce16292da943a1953de65b01eebc Mon Sep 17 00:00:00 2001 From: twobiers <22715034+twobiers@users.noreply.github.com> Date: Fri, 8 Jul 2022 16:44:45 +0200 Subject: [PATCH] Add PowerShell ArgumentCompleter --- templates/powershell.txt | 46 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/templates/powershell.txt b/templates/powershell.txt index e134ab1..58ceb3d 100644 --- a/templates/powershell.txt +++ b/templates/powershell.txt @@ -144,6 +144,52 @@ function global:__zoxide_zi { Set-Alias -Name {{cmd}} -Value __zoxide_z -Option AllScope -Scope Global -Force Set-Alias -Name {{cmd}}i -Value __zoxide_zi -Option AllScope -Scope Global -Force +filter __zoxide_escapeStringWithSpecialChars { + $_ -replace '\s|#|@|\$|;|,|''|\{|\}|\(|\)|"|`|\||<|>|&','`$&' +} + +Register-ArgumentCompleter -Native -CommandName "{{cmd}}" -ScriptBlock { + param( + $WordToComplete, + $CommandAst, + $CursorPosition + ) + + # Get the current command line and convert into a string + $Command = $CommandAst.CommandElements + $Command = "$Command" + + # The user could have moved the cursor backwards on the command-line. + # We only show completions when the cursor is at the end of the line + if ($Command.Length -gt $CursorPosition) { + return + } + + $Program,$Arguments = $Command.Split(" ",2) + + # If we don't have any parameter, just use the default completion (Which is Set-Location) + if([string]::IsNullOrEmpty($Arguments)) { + return + } + + $QueryArgs = $Arguments.Split(" ") + + # If the last parameter is complete (there is a space following it) + if ($WordToComplete -eq "" -And ( -Not $IsEqualFlag )) { + # Normally, we would invoke the interactive query. Unfortunally it is not possible to invoke an + # interactive command in a powershell argument completer. Therefore, we just return in that case to the + # default completion strategy. + # zoxide query -i -- @QueryArgs + return + } else { + $result = zoxide query --exclude "$(__zoxide_pwd)" -l -- @QueryArgs + } + + $result | ForEach-Object { + [System.Management.Automation.CompletionResult]::new($($_ | __zoxide_escapeStringWithSpecialChars), "$($_)", 'ParameterValue', "$($_)") + } +} + {%- when None %} {{ not_configured }}