Skip to content

TabExpansion2

Roman Kuzmin edited this page Dec 31, 2022 · 5 revisions

PowerShell v3+ provides powerful code completion tools and ability to customize and extend them even though official guidelines are seemingly missing. One way is to replace the native function TabExpansion2 with a slightly modified.

TabExpansion2.ps1

TabExpansion2.ps1 defines the custom function TabExpansion2 and functions registering three kind of completers. TabExpansion2.ps1 (with the extension) should be called in the beginning of an interactive session, for example in a profile. This is not expensive because completers are not searched and registered at this point.

One or more completer registrations are normally placed in special scripts named like *ArgumentCompleter.ps1. Such scripts in the path are found and invoked automatically on the first actual completion, i.e. when the custom TabExpansion2 is called the first time.

Other scripts with completers, i.e. not in the path or named differently, can be used as well. They may be invoked any time after TabExpansion2.ps1.

Registration and completers

Register-ArgumentCompleter

This command registers standard argument completers that can be also used with v5 native and TabExpansionPlusPlus Register-ArgumentCompleter.

A completer is a script block with the following parameters

param($commandName, $parameterName, $wordToComplete, $commandAst, $boundParameters)

It outputs one or more completion result objects created as

New-Object System.Management.Automation.CompletionResult <completionText> [, <listItemText>, <resultType>, <toolTip>]

For console completers the constructor with one argument is enough. For the fine tuned results in graphical hosts like ISE use all arguments.

The result type is enum [System.Management.Automation.CompletionResultType]. In ISE this value defines icons shown in the drop down completion list.

Text,
History,
Command,
ProviderItem,
ProviderContainer,
Property,
Method,
ParameterName,
ParameterValue,
Variable,
Namespace,
Type,
Keyword,
DynamicKeyword

Register-InputCompleter

This command registers special completers which intercept the input and may produce their own completion instead of standard.

A completer is a script block with the following parameters

param($ast, $tokens, $positionOfCursor, $options)

It should return either nothing or [System.Management.Automation.CommandCompletion] which is used as the final result and other completers are not invoked.

Register-ResultCompleter

This command registers special completers which may alter the results produced by previously invoked completers.

A completer is a script block with the following parameters

param($result, $ast, $tokens, $positionOfCursor, $options)

It should not output anything. Instead, it should process the input and alter the $result, i.e. add, remove, or change items.

Examples