admin管理员组

文章数量:1379913

Is there a way to customize the default behavior of TabExpansion2 so that when a method with no parameters is completed, it automatically adds a closing parenthesis ) instead of leaving an opening parenthesis (?

For example, the current behavior:

''.GetT<TAB> # Completes into `''.GetType(`

And the desired behavior, because there is no overload of .GetType() that takes arguments:

''.GetT<TAB> # Completes into `''.GetType()`

Can this be achieved through a custom TabExpansion2 implementation or by modifying PowerShell's autocompletion settings?

Is there a way to customize the default behavior of TabExpansion2 so that when a method with no parameters is completed, it automatically adds a closing parenthesis ) instead of leaving an opening parenthesis (?

For example, the current behavior:

''.GetT<TAB> # Completes into `''.GetType(`

And the desired behavior, because there is no overload of .GetType() that takes arguments:

''.GetT<TAB> # Completes into `''.GetType()`

Can this be achieved through a custom TabExpansion2 implementation or by modifying PowerShell's autocompletion settings?

Share Improve this question edited Mar 30 at 17:18 Santiago Squarzon asked Mar 30 at 17:00 Santiago SquarzonSantiago Squarzon 61.6k5 gold badges24 silver badges54 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

Yes, it's possible to customize TabExpansion2 to automatically append a closing parenthesis ) when completing a method with no parameters. This answer provides 2 different ways to do it:

  1. Creating new CompletionResult objects.
  2. Updating the existing CompletionResult objects via reflection.

Before providing the options, first few clarifications:

Why .ToolTip.EndsWith('()') ?

This is sort of a hacky way to determine if a method has parameters or not, the default TabExpansion2 returns a CompletionResult object for each completion, and its .ToolTip property describes the member, including all method overloads if applicable. For methods, the overload taking no arguments, if applicable, is always listed first in the ToolTip. If a method has only a no-parameter signature, the ToolTip ends with (), making .ToolTip.EndsWith('()') a reliable check in most cases.

For example:

(TabExpansion2 "''.GetT").CompletionMatches[0]

# CompletionText ListItemText ResultType ToolTip
# -------------- ------------ ---------- -------
# GetType(       GetType      Method     type GetType()

(TabExpansion2 "''.GetT").CompletionMatches[0].ToolTip.EndsWith('()')
# True

(TabExpansion2 "''.IndexOf").CompletionMatches[0].ToolTip.EndsWith('()')
# False

What Becomes the Completion?

The CompletionText property of the CompletionResult object is what PowerShell inserts as the final completion text. Both solutions below modify this property, either by creating a new CompletionResult with an updated CompletionText or by altering the existing object's CompletionText to append the closing ).

Approach 1: Creating new objects

This approach creates a new CompletionResult object for no-parameter methods, appending the closing parenthesis. It's safer and more maintainable since it doesn’t rely on internal fields, though it may use slightly more memory.

function TabExpansion2 {
    [CmdletBinding(DefaultParameterSetName = 'ScriptInputSet')]
    [OutputType([System.Management.Automation.CommandCompletion])]
    param(
        [Parameter(ParameterSetName = 'ScriptInputSet', Mandatory = $true, Position = 0)]
        [AllowEmptyString()]
        [string] $inputScript,

        [Parameter(ParameterSetName = 'ScriptInputSet', Position = 1)]
        [int] $cursorColumn = $inputScript.Length,

        [Parameter(ParameterSetName = 'AstInputSet', Mandatory = $true, Position = 0)]
        [System.Management.Automation.Language.Ast] $ast,

        [Parameter(ParameterSetName = 'AstInputSet', Mandatory = $true, Position = 1)]
        [System.Management.Automation.Language.Token[]] $tokens,

        [Parameter(ParameterSetName = 'AstInputSet', Mandatory = $true, Position = 2)]
        [System.Management.Automation.Language.IScriptPosition] $positionOfCursor,

        [Parameter(ParameterSetName = 'ScriptInputSet', Position = 2)]
        [Parameter(ParameterSetName = 'AstInputSet', Position = 3)]
        [Hashtable] $options = $null
    )

    end {
        if ($psCmdlet.ParameterSetName -eq 'ScriptInputSet') {
            $toComplete = [System.Management.Automation.CommandCompletion]::CompleteInput(
                <#inputScript#>  $inputScript,
                <#cursorColumn#> $cursorColumn,
                <#options#>      $options)
        }
        else {
            $toComplete = [System.Management.Automation.CommandCompletion]::CompleteInput(
                <#ast#>              $ast,
                <#tokens#>           $tokens,
                <#positionOfCursor#> $positionOfCursor,
                <#options#>          $options)
        }

        for ($i = 0; $i -lt $toComplete.CompletionMatches.Count; $i++) {
            $match = $toComplete.CompletionMatches[$i]
            if ($match.ToolTip.EndsWith('()')) {
                $toComplete.CompletionMatches[$i] =
                    [System.Management.Automation.CompletionResult]::new(
                        $match.CompletionText + ')',
                        $match.ListItemText,
                        $match.ResultType,
                        $match.ToolTip)
            }
        }

        $toComplete
    }
}

Approach 2: Using Reflection

This approach uses reflection to modify the CompletionText of existing CompletionResult objects, it’s potentially more performant and memory-efficient but riskier due to reliance on private fields that could change in future PowerShell versions.

function TabExpansion2 {
    [CmdletBinding(DefaultParameterSetName = 'ScriptInputSet')]
    [OutputType([System.Management.Automation.CommandCompletion])]
    param(
        [Parameter(ParameterSetName = 'ScriptInputSet', Mandatory = $true, Position = 0)]
        [AllowEmptyString()]
        [string] $inputScript,

        [Parameter(ParameterSetName = 'ScriptInputSet', Position = 1)]
        [int] $cursorColumn = $inputScript.Length,

        [Parameter(ParameterSetName = 'AstInputSet', Mandatory = $true, Position = 0)]
        [System.Management.Automation.Language.Ast] $ast,

        [Parameter(ParameterSetName = 'AstInputSet', Mandatory = $true, Position = 1)]
        [System.Management.Automation.Language.Token[]] $tokens,

        [Parameter(ParameterSetName = 'AstInputSet', Mandatory = $true, Position = 2)]
        [System.Management.Automation.Language.IScriptPosition] $positionOfCursor,

        [Parameter(ParameterSetName = 'AstInputSet', Position = 3)]
        [Parameter(ParameterSetName = 'ScriptInputSet', Position = 2)]
        [Hashtable] $options = $null
    )

    end {
        if ($psCmdlet.ParameterSetName -eq 'ScriptInputSet') {
            $toComplete = [System.Management.Automation.CommandCompletion]::CompleteInput(
                $inputScript, $cursorColumn, $options)
        }
        else {
            $toComplete = [System.Management.Automation.CommandCompletion]::CompleteInput(
                $ast, $tokens, $positionOfCursor, $options)
        }

        # Cache the FieldInfo for performance
        if (-not $script:_fieldInfo) {
            $fieldName = 'completionText'
            if ($IsCoreCLR) {
                # In PowerShell 7 the field starts with `_`
                $fieldName = '_completionText'
            }

            $script:_fieldInfo = [System.Management.Automation.CompletionResult].GetField(
                $fieldName,
                [System.Reflection.BindingFlags] 'Instance, NonPublic')
        }

        foreach ($match in $toComplete.CompletionMatches) {
            if ($match.ToolTip.EndsWith('()')) {
                $script:_fieldInfo.SetValue($match, $match.CompletionText + ')')
            }
        }

        $toComplete
    }
}

本文标签: