pip icon indicating copy to clipboard operation
pip copied to clipboard

Fix/improve argument completion for PowerShell 7.4+

Open BinToss opened this issue 2 years ago • 2 comments

What's the problem this feature will solve?

The current implementation hooks the legacy PowerShell function TabExpansion. This function does not exist in Powershell 7.4 and later. image The function was replaced by TabExpansion2. Completion/suggestion implementations are recommended to use the Register-ArgumentCompleter API which is in Windows PowerShell (5.1) and PowerShell Core (6.0 and later).

Describe the solution you'd like

The Register-ArgumentCompleter function can be leveraged like so:

Register-ArgumentCompleter -Native -CommandName 'pip' -ScriptBlock {
    param(
        [string]$wordToComplete,
        [System.Management.Automation.Language.CommandAst]$commandAst,
        $cursorPosition
    )
    $Env:COMP_WORDS = $commandAst.ToString()
    $Env:COMP_CWORD = $commandAst.ToString().Split().Length - 1
    $Env:PIP_AUTO_COMPLETE = 1
    (& pip).Split() | ForEach-Object {
        [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)
    }
    Remove-Item Env:COMP_WORDS
    Remove-Item Env:COMP_CWORD
    Remove-Item Env:PIP_AUTO_COMPLETE
}

This can be appended to the user's $PROFILE script as-is, as a string executed by Invoke-Expression, or as a dot-sourced command invoking a script file (e.g. . path/to/pip-completion.ps1).

Unlike the old implementation, this does not override any built-in functions. The currently-unused $cursorPosition parameter can be leveraged for completion/suggestion at the cursor's position instead of only the last word in the CommandAst.

Known Issues

  • PowerShell assumes the returned completion(s) should replace the word at the cursor instead of the last word in the command. I'm not sure how to fix that without adding a position environment variable to the implementation in https://github.com/pypa/pip/blob/main/src/pip/_internal/cli/autocompletion.py

Alternative Solutions

The provided solution works well enough for now. Additional functionality can be implemented later.

Additional context

Improves upon #9025

Code of Conduct

BinToss avatar Dec 18 '23 09:12 BinToss

hey @BinToss can i work on it ?

tomaswoj-eth avatar May 30 '25 14:05 tomaswoj-eth

@tomaswoj-eth feel free to write and submit a PR! Autocompletion is the sort of thing we rely on community contributions for. I'll note that there is very little review capacity at the moment, so don't expect a quick review.

ichard26 avatar May 30 '25 14:05 ichard26

hey @BinToss can i work on it ?

Be my guest!

BinToss avatar Jul 13 '25 02:07 BinToss

i've created the PR for this issue #13577

meet-vasita avatar Sep 12 '25 17:09 meet-vasita

closing in favor of #13577

BinToss avatar Oct 14 '25 06:10 BinToss