From 99c693df3916272ba3f844d33f116880cf35cc4f Mon Sep 17 00:00:00 2001 From: Florian Blanchet Date: Fri, 28 Jul 2023 22:33:37 +0300 Subject: [PATCH] Add PowerShell autocompletion feature --- README.md | 2 +- completions/pyenv.pwsh | 17 +++++++++++++++++ libexec/pyenv-init | 13 ++++++++++--- 3 files changed, 28 insertions(+), 4 deletions(-) create mode 100644 completions/pyenv.pwsh diff --git a/README.md b/README.md index 74248b63..bd37bb48 100644 --- a/README.md +++ b/README.md @@ -615,7 +615,7 @@ opposed to this idea. Here's what `eval "$(pyenv init -)"` actually does: 2. **Installs autocompletion.** This is entirely optional but pretty useful. Sourcing `$(pyenv root)/completions/pyenv.bash` will set that - up. There are also completions for Zsh and Fish. + up. There are also completions for Zsh, Fish and PowerShell. 3. **Rehashes shims.** From time to time you'll need to rebuild your shim files. Doing this on init makes sure everything is up to diff --git a/completions/pyenv.pwsh b/completions/pyenv.pwsh new file mode 100644 index 00000000..f422f468 --- /dev/null +++ b/completions/pyenv.pwsh @@ -0,0 +1,17 @@ +$scriptblock = { + param($wordToComplete, $commandAst, $cursorPosition) + $words = $commandAst.ToString() + if ( $wordToComplete ) { + $matches = (($words[0..$cursorPosition] -join '') | Select-String -Pattern "\s+" -AllMatches).Matches + if ( $matches ) { + $cursorPosition = $matches[-1].Index - 1 + } + } + $words = $words[0..$cursorPosition] -join '' -split "\s+" + if ( $words.Count -ge 2 ) { + pyenv completions $words[1] | where { $_ -match $wordToComplete } + } else { + pyenv commands | where { $_ -match $wordToComplete } + } +} +Register-ArgumentCompleter -Native -CommandName pyenv -ScriptBlock $scriptblock diff --git a/libexec/pyenv-init b/libexec/pyenv-init index 98b8c48e..cf0edc25 100755 --- a/libexec/pyenv-init +++ b/libexec/pyenv-init @@ -281,7 +281,14 @@ function print_env() { function print_completion() { completion="${root}/completions/pyenv.${shell}" if [ -r "$completion" ]; then - echo "source '$completion'" + case "$shell" in + pwsh ) + echo "iex (gc $completion -Raw)" + ;; + * ) + echo "source '$completion'" + ;; + esac fi } @@ -292,7 +299,7 @@ function print_rehash() { echo '& pyenv rehash 2>/dev/null' ;; * ) - echo 'command pyenv rehash 2>/dev/null' + echo 'command pyenv rehash 2>/dev/null' ;; esac fi @@ -348,7 +355,7 @@ pyenv() { EOS ;; esac - + if [ "$shell" != "fish" ] && [ "$shell" != "pwsh" ]; then IFS="|" cat <