SnippetPredictor is a command-line predictor written in F#. It suggests code snippets based on the input. This module requires PowerShell 7.2 and PSReadLine 2.2.2.
This project builds upon the following article:
How to create a command-line predictor - PowerShell | Microsoft Learn
Install SnippetPredictor from the PowerShell Gallery:
PowerShell Gallery | SnippetPredictor
# Recommended: PSResourceGet (PowerShellGet 3.0)
Install-PSResource -Name SnippetPredictor
# Alternatively, if you are using PowerShellGet 2.x:
Install-Module -Name SnippetPredictor
Before using SnippetPredictor, ensure that your PowerShell PredictionSource
equals HistoryAndPlugin
1:
# PredictionSource = HistoryAndPlugin required.
Get-PSReadLineOption | Select-Object PredictionSource
#
# PredictionSource
# ----------------
# HistoryAndPlugin
Import the SnippetPredictor module and verify that the predictor loads:
Import-Module SnippetPredictor
# Confirm SnippetPredictor(Snippet) loaded.
Get-PSSubsystem -Kind CommandPredictor
#
# Kind SubsystemType IsRegistered Implementations
# ---- ------------- ------------ ---------------
# CommandPredictor ICommandPredictor True {Snippet, Windows Package Manager - WinGet}
Set the prediction view style to ListView
2:
Set-PSReadLineOption -PredictionViewStyle ListView
Refer to the following documents for detailed cmdlet help:
First, set up your ~/.snippet-predictor.json
file.
The easiest way to do this is to run the Add-Snippet
command:
Add-Snippet "echo 'hello'" -Tooltip 'say hello' -Group 'greeting'
This will create a file with the following content. You can also create the file manually if you prefer.
{
"Snippets": [
{
"Snippet": "echo 'hello'",
"Tooltip": "say hello.",
"Group": "greeting"
}
]
}
Filter snippets in your ~/.snippet-predictor.json
file using the following keywords:
- Use
:snp {input}
to search for{input}
in theSnippet
field. - Use
:tip {input}
to search for{input}
in theTooltip
field. - Use
:{group} {input}
to search for{input}
in theSnippet
field for snippets in a specifiedGroup
.- Allowed characters for the
Group
field:^[a-zA-Z0-9]+$
. (Group names must consist of alphanumeric characters.) - Typing
:
or a partial group name (e.g.,:p
) suggests matching groups like:pwsh
.
- Allowed characters for the
By default, the predictor searches snippets in a case-insensitive manner.
To enable case-sensitive search, set SearchCaseSensitive
to true
in .snippet-predictor.json
.
The default value is false
.
You can list your registered snippets with the Get-Snippet
command.
To remove a snippet, use the Remove-Snippet
command.
Remove-Snippet "echo 'hello'"
You can also delete it directly from ~/.snippet-predictor.json
.
By combining Get-Snippet
and Remove-Snippet
, you can remove snippets that match a specific pattern. Perform this in one step:
Get-Snippet | Where-Object -Property Tooltip -like *test* | Remove-Snippet