### Custom Key Handler Examples Source: https://context7.com/powershell/psreadline/llms.txt Examples of setting custom key handlers for various operations like clipboard, screen capture, word movement, history view, smart quotes, and command execution. ```APIDOC ## Custom Key Handler Examples This section demonstrates how to use `Set-PSReadLineKeyHandler` to define custom key bindings for various functionalities. ### Clipboard Operations ```powershell Set-PSReadLineKeyHandler -Key Ctrl+C -Function Copy Set-PSReadLineKeyHandler -Key Ctrl+v -Function Paste ``` ### Screen Capture ```powershell Set-PSReadLineKeyHandler -Chord 'Ctrl+d,Ctrl+c' -Function CaptureScreen ``` ### Token-based Word Movement ```powershell Set-PSReadLineKeyHandler -Key Alt+d -Function ShellKillWord Set-PSReadLineKeyHandler -Key Alt+Backspace -Function ShellBackwardKillWord Set-PSReadLineKeyHandler -Key Alt+b -Function ShellBackwardWord Set-PSReadLineKeyHandler -Key Alt+f -Function ShellForwardWord ``` ### Custom Key Handler with Script Block - F7 for History Grid View ```powershell Set-PSReadLineKeyHandler -Key F7 ` -BriefDescription 'History' ` -LongDescription 'Show command history in grid view' ` -ScriptBlock { $pattern = $null [Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$pattern, [ref]$null) if ($pattern) { $pattern = [regex]::Escape($pattern) } $history = Get-Content (Get-PSReadLineOption).HistorySavePath | Where-Object { !$pattern -or $_ -match $pattern } | Select-Object -Unique [array]::Reverse($history) $command = $history | Out-GridView -Title 'History' -PassThru if ($command) { [Microsoft.PowerShell.PSConsoleReadLine]::RevertLine() [Microsoft.PowerShell.PSConsoleReadLine]::Insert(($command -join "`n")) } } ``` ### Smart Quote Insertion ```powershell Set-PSReadLineKeyHandler -Key '"',"'" ` -BriefDescription SmartInsertQuote ` -LongDescription "Insert paired quotes if not already on a quote" ` -ScriptBlock { param($key, $arg) $line = $null $cursor = $null [Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor) if ($line.Length -gt $cursor -and $line[$cursor] -eq $key.KeyChar) { [Microsoft.PowerShell.PSConsoleReadLine]::SetCursorPosition($cursor + 1) } else { [Microsoft.PowerShell.PSConsoleReadLine]::Insert("$($key.KeyChar)" * 2) [Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor) [Microsoft.PowerShell.PSConsoleReadLine]::SetCursorPosition($cursor - 1) } } ``` ### Execute Command Without Adding to History ```powershell Set-PSReadLineKeyHandler -Key Ctrl+b ` -BriefDescription BuildCurrentDirectory ` -LongDescription "Build the current directory" ` -ScriptBlock { [Microsoft.PowerShell.PSConsoleReadLine]::RevertLine() [Microsoft.PowerShell.PSConsoleReadLine]::Insert("msbuild") [Microsoft.PowerShell.PSConsoleReadLine]::AcceptLine() } ``` ``` -------------------------------- ### Install PowerShellGet Module Source: https://github.com/powershell/psreadline/blob/master/README.md Run this command from an elevated Windows PowerShell session to install or update PowerShellGet, which is required for installing prerelease versions of PSReadLine on Windows PowerShell 5.1. ```powershell Install-Module -Name PowerShellGet -Force; exit ``` -------------------------------- ### Install PSReadLine Stable Version Source: https://github.com/powershell/psreadline/blob/master/README.md If you prefer to install only the latest stable version of PSReadLine, use this command. ```powershell Install-Module PSReadLine -Repository PSGallery -Scope CurrentUser -Force ``` -------------------------------- ### Install PSReadLine Prerelease Version Source: https://github.com/powershell/psreadline/blob/master/README.md After ensuring PowerShellGet is up-to-date, use this command to install or upgrade to the latest prerelease version of PSReadLine from the PSGallery. ```powershell Install-Module PSReadLine -Repository PSGallery -Scope CurrentUser -AllowPrerelease -Force ``` -------------------------------- ### Sample Custom Binding for Directory Change in PSReadLine Source: https://github.com/powershell/psreadline/blob/master/PSReadLine/Changes.txt An example of a custom key binding provided in SamplePSReadLineProfile.ps1 for quickly changing directories. ```powershell # Sample custom binding for quickly changing directories Set-PSReadLineKeyHandler -Key "Ctrl+G" -Function "Set-Location" ``` -------------------------------- ### Install PSReadLine Module Source: https://context7.com/powershell/psreadline/llms.txt Installs the latest stable or prerelease version of the PSReadLine module from the PowerShell Gallery. For older Windows PowerShell versions, PowerShellGet may need to be updated first. ```powershell # Install latest stable version Install-Module PSReadLine -Repository PSGallery -Scope CurrentUser -Force ``` ```powershell # Install latest prerelease version with new features Install-Module PSReadLine -Repository PSGallery -Scope CurrentUser -AllowPrerelease -Force ``` ```powershell # For Windows PowerShell 5.1, update PowerShellGet first Install-Module -Name PowerShellGet -Force; exit # Then install PSReadLine in a new session Install-Module PSReadLine -Repository PSGallery -Scope CurrentUser -Force ``` -------------------------------- ### Get Selection State in PSReadLine Source: https://context7.com/powershell/psreadline/llms.txt Retrieve the start position and length of the current text selection on the command line. The selectionStart will be -1 if no text is selected. ```powershell $selectionStart = $null $selectionLength = $null [Microsoft.PowerShell.PSConsoleReadLine]::GetSelectionState([ref]$selectionStart, [ref]$selectionLength) if ($selectionStart -ne -1) { Write-Host "Selection: start=$selectionStart, length=$selectionLength" } ``` -------------------------------- ### Build PSReadLine - Debug Configuration Source: https://github.com/powershell/psreadline/blob/master/README.md This command builds the PSReadLine project with the Debug configuration. Ensure you have .NET 6.0 or newer installed. ```powershell ./build.ps1 -Configuration Debug ``` -------------------------------- ### Add Key Binding Example: ForwardCharAndAcceptNextSuggestionWord Source: https://github.com/powershell/psreadline/blob/master/PSReadLine/Changes.txt Demonstrates how to add a key binding for the `ForwardCharAndAcceptNextSuggestionWord` function. This is useful for customizing keyboard shortcuts in PSReadLine. ```powershell Set-PSReadLineKeyHandler -Key 'Ctrl+RightArrow' -Function ForwardCharAndAcceptNextSuggestionWord ``` -------------------------------- ### Retrieve PSReadLine Options Source: https://context7.com/powershell/psreadline/llms.txt Get current PSReadLine configuration settings. The output includes all option values, and specific settings can be accessed as properties of the returned object. ```powershell # Get all current options $options = Get-PSReadLineOption $options ``` ```powershell # Output includes: # EditMode : Windows # HistoryNoDuplicates : True # MaximumHistoryCount : 4096 # HistorySavePath : C:\Users\...\PSReadLine\ConsoleHost_history.txt # PredictionSource : HistoryAndPlugin # PredictionViewStyle : InlineView # BellStyle : Audible ``` ```powershell # Check specific settings $options.EditMode $options.PredictionSource $options.HistorySavePath ``` ```powershell # Check color settings $options.CommandColor $options.StringColor $options.ErrorColor ``` -------------------------------- ### Get PSReadLine Key Handler with -Chord Parameter Source: https://github.com/powershell/psreadline/blob/master/PSReadLine/Changes.txt Demonstrates how to use the `-Chord` parameter with `Get-PSReadLineKeyHandler` to search for specific key bindings. This is useful for identifying which function is associated with a particular key combination. ```powershell Get-PSReadLineKeyHandler -Chord 'Ctrl+X' ``` -------------------------------- ### PSConsoleReadLine Public API Source: https://context7.com/powershell/psreadline/llms.txt Provides methods to manipulate the command line buffer within custom key handlers, such as getting buffer state, inserting, deleting, or replacing text. ```APIDOC ## PSConsoleReadLine Public API Use the `PSConsoleReadLine` class methods in custom key handlers to manipulate the command line buffer. ### Get Buffer State Retrieves the current text in the command line buffer and the cursor's position. ```powershell # Get current buffer state (text and cursor position) $line = $null $cursor = $null [Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor) Write-Host "Current line: $line, Cursor at: $cursor" ``` Retrieves buffer state along with Abstract Syntax Tree (AST), tokens, and parse errors for advanced analysis. ```powershell $ast = $null $tokens = $null $parseErrors = $null $cursor = $null [Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$ast, [ref]$tokens, [ref]$parseErrors, [ref]$cursor) ``` ### Insert Text Inserts specified text at the current cursor position. ```powershell # Insert text [Microsoft.PowerShell.PSConsoleReadLine]::Insert("Write-Host 'Hello'") # Insert a single character [Microsoft.PowerShell.PSConsoleReadLine]::Insert([char]'x') ``` ### Delete Text Removes characters from the buffer starting at a specified position. ```powershell # Delete text from buffer (start position, length) [Microsoft.PowerShell.PSConsoleReadLine]::Delete(0, 5) # Delete first 5 characters ``` ### Replace Text Replaces a section of text in the buffer with new text. ```powershell # Replace text in buffer (start, length, replacement) [Microsoft.PowerShell.PSConsoleReadLine]::Replace(0, 4, "Write-Output") ``` ``` -------------------------------- ### Load Locally Built PSReadLine Module Source: https://github.com/powershell/psreadline/blob/master/README.md This command sequence is used to load a locally built version of the PSReadLine module, bypassing the globally installed version. This is essential for testing local changes. ```powershell pwsh -NonInteractive -NoProfile ``` ```powershell Import-Module /bin/Debug/PSReadLine/PSReadLine.psd1 ``` -------------------------------- ### PSConsoleReadLine API: Get Buffer State Source: https://context7.com/powershell/psreadline/llms.txt Retrieve the current command line buffer's text and cursor position, or additionally get Abstract Syntax Tree (AST), tokens, and parse errors for advanced analysis. ```powershell # Get current buffer state (text and cursor position) $line = $null $cursor = $null [Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor) Write-Host "Current line: $line, Cursor at: $cursor" ``` ```powershell # Get buffer state with AST for syntax analysis $ast = $null $tokens = $null $parseErrors = $null $cursor = $null [Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$ast, [ref]$tokens, [ref]$parseErrors, [ref]$cursor) ``` -------------------------------- ### Vi Insert Mode Key Bindings Source: https://context7.com/powershell/psreadline/llms.txt Configure key bindings for Vi insert mode. These examples bind Ctrl+a to BeginningOfLine and Ctrl+e to EndOfLine. ```powershell Set-PSReadLineKeyHandler -Key Ctrl+a -Function BeginningOfLine -ViMode Insert Set-PSReadLineKeyHandler -Key Ctrl+e -Function EndOfLine -ViMode Insert ``` -------------------------------- ### Get PSReadLine Key Handler Bindings Source: https://context7.com/powershell/psreadline/llms.txt View all key bindings and their associated functions, including options to filter by bound or unbound keys, or to retrieve specific chord bindings. ```powershell # Get all bound key handlers Get-PSReadLineKeyHandler ``` ```powershell # Get only bound keys Get-PSReadLineKeyHandler -Bound ``` ```powershell # Get unbound functions (available but not mapped) Get-PSReadLineKeyHandler -Unbound ``` ```powershell # Get both bound and unbound Get-PSReadLineKeyHandler -Bound -Unbound ``` ```powershell # Get specific chord binding Get-PSReadLineKeyHandler -Chord Ctrl+r Get-PSReadLineKeyHandler -Chord 'Ctrl+x,Ctrl+e' ``` -------------------------------- ### Try Parse Argument as Integer with Default Source: https://context7.com/powershell/psreadline/llms.txt TryGetArgAsInt attempts to parse an argument as an integer, providing a default value if the argument is null or cannot be parsed. The default is 1 in this example. ```powershell $numericArg = 0 if ([Microsoft.PowerShell.PSConsoleReadLine]::TryGetArgAsInt($arg, [ref]$numericArg, 1)) { # Use $numericArg (defaults to 1 if $arg is null) } ``` -------------------------------- ### Vi Command Mode Key Handler for History Search Source: https://context7.com/powershell/psreadline/llms.txt Set-PSReadLineKeyHandler allows binding keys to specific functions in Vi editing mode. This example binds 'j' to HistorySearchForward and 'k' to HistorySearchBackward in command mode. ```powershell Set-PSReadLineKeyHandler -Key 'j' -Function HistorySearchForward -ViMode Command Set-PSReadLineKeyHandler -Key 'k' -Function HistorySearchBackward -ViMode Command ``` -------------------------------- ### Custom Vi Mode Indicator Script Source: https://context7.com/powershell/psreadline/llms.txt Use -ViModeIndicator Script with -ViModeChangeHandler to define custom visual feedback for Vi editing modes. This example changes the cursor shape based on the mode. ```powershell Set-PSReadLineOption -ViModeIndicator Script Set-PSReadLineOption -ViModeChangeHandler { param([Microsoft.PowerShell.ViMode]$Mode) if ($Mode -eq [Microsoft.PowerShell.ViMode]::Insert) { Write-Host -NoNewLine "`e[5 q" # Blinking bar cursor } else { Write-Host -NoNewLine "`e[1 q" # Blinking block cursor } } ``` -------------------------------- ### Build PSReadLine - Bootstrap Source: https://github.com/powershell/psreadline/blob/master/README.md Use this command to bootstrap the build environment for PSReadLine. This is typically the first step before building the project. ```powershell ./build.ps1 -Bootstrap ``` -------------------------------- ### View Current Key Bindings Source: https://github.com/powershell/psreadline/blob/master/README.md Run this cmdlet to display all currently configured key bindings in PSReadLine. This is useful for understanding existing configurations. ```powershell Get-PSReadLineKeyHandler ``` -------------------------------- ### Bind AcceptSuggestion and AcceptNextSuggestionWord Functions Source: https://github.com/powershell/psreadline/blob/master/PSReadLine/Changes.txt Makes the `AcceptSuggestion` and `AcceptNextSuggestionWord` functions bindable to key handlers. This allows users to trigger these suggestion acceptance actions with custom key combinations. ```powershell Set-PSReadLineKeyHandler -Key 'Tab' -Function AcceptSuggestion ``` ```powershell Set-PSReadLineKeyHandler -Key 'RightArrow' -Function AcceptNextSuggestionWord ``` -------------------------------- ### PSReadLine Completion Key Bindings Source: https://context7.com/powershell/psreadline/llms.txt Bind keys to completion functions, including tab completion, menu completion, and listing possible completions. ```powershell # Completion Set-PSReadLineKeyHandler -Key Tab -Function TabCompleteNext Set-PSReadLineKeyHandler -Key Shift+Tab -Function TabCompletePrevious Set-PSReadLineKeyHandler -Key Ctrl+Spacebar -Function MenuComplete Set-PSReadLineKeyHandler -Key Ctrl+Space -Function PossibleCompletions ``` -------------------------------- ### PSReadLine Cursor Movement Key Bindings Source: https://context7.com/powershell/psreadline/llms.txt Set key handlers for common cursor movements, such as moving to the beginning/end of the line, or moving forward/backward by word. ```powershell # Cursor movement Set-PSReadLineKeyHandler -Key Ctrl+a -Function BeginningOfLine Set-PSReadLineKeyHandler -Key Ctrl+e -Function EndOfLine Set-PSReadLineKeyHandler -Key Ctrl+LeftArrow -Function BackwardWord Set-PSReadLineKeyHandler -Key Ctrl+RightArrow -Function ForwardWord Set-PSReadLineKeyHandler -Key Home -Function BeginningOfLine Set-PSReadLineKeyHandler -Key End -Function EndOfLine ``` -------------------------------- ### Accept and Execute Current Line in PSReadLine Source: https://context7.com/powershell/psreadline/llms.txt AcceptLine executes the command currently entered on the command line. ```powershell [Microsoft.PowerShell.PSConsoleReadLine]::AcceptLine() ``` -------------------------------- ### Complete PSReadLine Profile Configuration Source: https://context7.com/powershell/psreadline/llms.txt A comprehensive PSReadLine profile configuration including editing mode, history settings, predictive IntelliSense, and color schemes. ```powershell # Import the module (usually auto-imported) Import-Module PSReadLine # Set editing mode Set-PSReadLineOption -EditMode Windows # History configuration Set-PSReadLineOption -HistoryNoDuplicates:$true Set-PSReadLineOption -HistorySearchCursorMovesToEnd Set-PSReadLineOption -MaximumHistoryCount 10000 # Enable predictive IntelliSense Set-PSReadLineOption -PredictionSource HistoryAndPlugin Set-PSReadLineOption -PredictionViewStyle ListView # Color scheme Set-PSReadLineOption -Colors @{ Command = "`e[93m" # Bright Yellow Parameter = "`e[36m" # Cyan String = "`e[32m" # Green Operator = "`e[35m" # Magenta Variable = "`e[33m" # Yellow Comment = "`e[90m" # Bright Black (Gray) Keyword = "`e[34m" # Blue Number = "`e[97m" # White Type = "`e[37m" # Gray Error = "`e[91m" # Bright Red InlinePrediction = "`e[38;5;238m" } # Smart history search with arrows Set-PSReadLineKeyHandler -Key UpArrow -Function HistorySearchBackward Set-PSReadLineKeyHandler -Key DownArrow -Function HistorySearchForward # Ctrl+r for interactive history search Set-PSReadLineKeyHandler -Key Ctrl+r -Function ReverseSearchHistory # Better word deletion Set-PSReadLineKeyHandler -Key Ctrl+Backspace -Function BackwardKillWord Set-PSReadLineKeyHandler -Key Ctrl+Delete -Function KillWord # Smart brackets/quotes insertion Set-PSReadLineKeyHandler -Key '(', '{', '[' -ScriptBlock { param($key, $arg) $closeChar = switch ($key.KeyChar) { '(' { ')'; break } '{' { '}'; break } '[' { ']'; break } } $line = $cursor = $null [Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor) [Microsoft.PowerShell.PSConsoleReadLine]::Insert("$($key.KeyChar)$closeChar") [Microsoft.PowerShell.PSConsoleReadLine]::SetCursorPosition($cursor + 1) } # Accept suggestion with right arrow at end of line Set-PSReadLineKeyHandler -Key RightArrow -ScriptBlock { param($key, $arg) $line = $cursor = $null [Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor) if ($cursor -lt $line.Length) { [Microsoft.PowerShell.PSConsoleReadLine]::ForwardChar($key, $arg) } else { [Microsoft.PowerShell.PSConsoleReadLine]::AcceptNextSuggestionWord($key, $arg) } } ``` -------------------------------- ### PSReadLine History Navigation Key Bindings Source: https://context7.com/powershell/psreadline/llms.txt Configure key handlers for navigating command history. This includes reverse and forward search, and moving between previous and next history entries. ```powershell # History navigation Set-PSReadLineKeyHandler -Key Ctrl+r -Function ReverseSearchHistory Set-PSReadLineKeyHandler -Key Ctrl+s -Function ForwardSearchHistory Set-PSReadLineKeyHandler -Key UpArrow -Function PreviousHistory Set-PSReadLineKeyHandler -Key DownArrow -Function NextHistory Set-PSReadLineKeyHandler -Key F8 -Function HistorySearchBackward Set-PSReadLineKeyHandler -Key Shift+F8 -Function HistorySearchForward ``` -------------------------------- ### Expose ViBackwardChar and ViForwardChar as Bindable Functions Source: https://github.com/powershell/psreadline/blob/master/PSReadLine/Changes.txt Exposes the `ViBackwardChar` and `ViForwardChar` functions, allowing them to be bound to specific key combinations. This enhances vi-mode customization in PSReadLine. ```powershell Set-PSReadLineKeyHandler -Key 'LeftArrow' -Function ViBackwardChar ``` ```powershell Set-PSReadLineKeyHandler -Key 'RightArrow' -Function ViForwardChar ``` -------------------------------- ### PSReadLine Selection and Clipboard Key Bindings Source: https://context7.com/powershell/psreadline/llms.txt Configure key handlers for text selection and clipboard operations, such as selecting characters or words, and selecting the entire line. ```powershell # Selection and clipboard Set-PSReadLineKeyHandler -Key Shift+LeftArrow -Function SelectBackwardChar Set-PSReadLineKeyHandler -Key Shift+RightArrow -Function SelectForwardChar Set-PSReadLineKeyHandler -Key Ctrl+Shift+LeftArrow -Function SelectBackwardWord Set-PSReadLineKeyHandler -Key Ctrl+Shift+RightArrow -Function SelectForwardWord Set-PSReadLineKeyHandler -Key Ctrl+a -Function SelectAll ``` -------------------------------- ### Accept Next Suggestion Word in PSReadLine Source: https://context7.com/powershell/psreadline/llms.txt AcceptNextSuggestionWord inserts the next word from a prediction suggestion into the command line. It takes null for the first two arguments. ```powershell [Microsoft.PowerShell.PSConsoleReadLine]::AcceptNextSuggestionWord($null, $null) ``` -------------------------------- ### Test PSReadLine - Targeting .NET 4.7.2 (Windows) Source: https://github.com/powershell/psreadline/blob/master/README.md Runs tests for PSReadLine targeting the .NET 4.7.2 framework on Windows. This is useful for ensuring compatibility with older .NET versions. ```powershell ./build.ps1 -Test -Configuration Debug -Framework net472 ``` -------------------------------- ### Configure Vi Mode Indicator Styles Source: https://context7.com/powershell/psreadline/llms.txt Set-PSReadLineOption can configure how the Vi mode indicator is displayed. Options include changing the prompt, the cursor shape in Windows Terminal, or disabling the indicator. ```powershell Set-PSReadLineOption -ViModeIndicator Prompt # Change prompt based on mode Set-PSReadLineOption -ViModeIndicator Cursor # Change cursor shape (Windows Terminal) Set-PSReadLineOption -ViModeIndicator None # No indicator ``` -------------------------------- ### Set Custom PSReadLine Key Handlers Source: https://context7.com/powershell/psreadline/llms.txt Assign custom functions or script blocks to key combinations for clipboard operations, screen capture, word movement, history grid view, smart quote insertion, and executing commands without history logging. ```powershell Set-PSReadLineKeyHandler -Key Ctrl+C -Function Copy Set-PSReadLineKeyHandler -Key Ctrl+v -Function Paste ``` ```powershell Set-PSReadLineKeyHandler -Chord 'Ctrl+d,Ctrl+c' -Function CaptureScreen ``` ```powershell Set-PSReadLineKeyHandler -Key Alt+d -Function ShellKillWord Set-PSReadLineKeyHandler -Key Alt+Backspace -Function ShellBackwardKillWord Set-PSReadLineKeyHandler -Key Alt+b -Function ShellBackwardWord Set-PSReadLineKeyHandler -Key Alt+f -Function ShellForwardWord ``` ```powershell Set-PSReadLineKeyHandler -Key F7 ` -BriefDescription 'History' ` -LongDescription 'Show command history in grid view' ` -ScriptBlock { $pattern = $null [Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$pattern, [ref]$null) if ($pattern) { $pattern = [regex]::Escape($pattern) } $history = Get-Content (Get-PSReadLineOption).HistorySavePath | Where-Object { !$pattern -or $_ -match $pattern } | Select-Object -Unique [array]::Reverse($history) $command = $history | Out-GridView -Title 'History' -PassThru if ($command) { [Microsoft.PowerShell.PSConsoleReadLine]::RevertLine() [Microsoft.PowerShell.PSConsoleReadLine]::Insert(($command -join "`n")) } } ``` ```powershell Set-PSReadLineKeyHandler -Key '"',"'" ` -BriefDescription SmartInsertQuote ` -LongDescription "Insert paired quotes if not already on a quote" ` -ScriptBlock { param($key, $arg) $line = $null $cursor = $null [Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor) if ($line.Length -gt $cursor -and $line[$cursor] -eq $key.KeyChar) { [Microsoft.PowerShell.PSConsoleReadLine]::SetCursorPosition($cursor + 1) } else { [Microsoft.PowerShell.PSConsoleReadLine]::Insert("$($key.KeyChar)" * 2) [Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor) [Microsoft.PowerShell.PSConsoleReadLine]::SetCursorPosition($cursor - 1) } } ``` ```powershell Set-PSReadLineKeyHandler -Key Ctrl+b ` -BriefDescription BuildCurrentDirectory ` -LongDescription "Build the current directory" ` -ScriptBlock { [Microsoft.PowerShell.PSConsoleReadLine]::RevertLine() [Microsoft.PowerShell.PSConsoleReadLine]::Insert("msbuild") [Microsoft.PowerShell.PSConsoleReadLine]::AcceptLine() } ``` -------------------------------- ### Configure PSReadLine Options Source: https://context7.com/powershell/psreadline/llms.txt Customize PSReadLine behavior including editing mode, history settings, colors, and prediction features. Use specific cmdlets to modify various aspects of the command-line experience. ```powershell # Set editing mode (Windows, Emacs, or Vi) Set-PSReadLineOption -EditMode Emacs ``` ```powershell # Configure history behavior Set-PSReadLineOption -HistoryNoDuplicates:$true Set-PSReadLineOption -MaximumHistoryCount 10000 Set-PSReadLineOption -HistorySavePath "$HOME/.ps_history" Set-PSReadLineOption -HistorySaveStyle SaveIncrementally ``` ```powershell # Move cursor to end when searching history Set-PSReadLineOption -HistorySearchCursorMovesToEnd ``` ```powershell # Enable predictive IntelliSense Set-PSReadLineOption -PredictionSource HistoryAndPlugin Set-PSReadLineOption -PredictionViewStyle ListView ``` ```powershell # Configure colors using a hashtable Set-PSReadLineOption -Colors @{ Command = 'Yellow' Parameter = 'Green' String = 'DarkCyan' Operator = 'Magenta' Variable = 'Green' Comment = 'DarkGreen' Keyword = 'Green' Error = 'Red' InlinePrediction = '#70A99F' ListPrediction = 'Yellow' ListPredictionSelected = "`e[48;5;238m" } ``` ```powershell # Configure bell/ding behavior Set-PSReadLineOption -BellStyle Visual Set-PSReadLineOption -DingTone 440 Set-PSReadLineOption -DingDuration 100 ``` ```powershell # Set continuation prompt for multi-line input Set-PSReadLineOption -ContinuationPrompt ">> " ``` ```powershell # Configure prompt text (shown in red on parse errors) Set-PSReadLineOption -PromptText "> ", "! " ``` ```powershell # Custom validation handler for auto-correction Set-PSReadLineOption -CommandValidationHandler { param([System.Management.Automation.Language.CommandAst]$CommandAst) switch ($CommandAst.GetCommandName()) { 'git' { $gitCmd = $CommandAst.CommandElements[1].Extent if ($gitCmd.Text -eq 'cmt') { [Microsoft.PowerShell.PSConsoleReadLine]::Replace( $gitCmd.StartOffset, $gitCmd.EndOffset - $gitCmd.StartOffset, 'commit') } } } } ``` ```powershell # Custom handler for adding to history Set-PSReadLineOption -AddToHistoryHandler { param([string]$line) # Skip short commands and those starting with space if ($line.Length -lt 4 -or $line.StartsWith(' ')) { return $false # SkipAdding } return $true # MemoryAndFile } ``` -------------------------------- ### Test PSReadLine - Targeting .NET 6.0 Source: https://github.com/powershell/psreadline/blob/master/README.md Runs tests for PSReadLine targeting the .NET 6.0 framework. This is the recommended target for modern development. ```powershell ./build.ps1 -Test -Configuration Debug -Framework net6.0 ``` -------------------------------- ### Custom Smart Insert Quote Key Binding Source: https://github.com/powershell/psreadline/blob/master/README.md This advanced configuration defines a custom key binding for inserting paired quotes. It intelligently inserts matching quotes and positions the cursor, similar to smart editors, and correctly handles undo operations. ```powershell Set-PSReadLineKeyHandler -Chord '"',"'" ` -BriefDescription SmartInsertQuote ` -LongDescription "Insert paired quotes if not already on a quote" ` -ScriptBlock { param($key, $arg) $line = $null $cursor = $null [Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor) if ($line.Length -gt $cursor -and $line[$cursor] -eq $key.KeyChar) { # Just move the cursor [Microsoft.PowerShell.PSConsoleReadLine]::SetCursorPosition($cursor + 1) } else { # Insert matching quotes, move cursor to be in between the quotes [Microsoft.PowerShell.PSConsoleReadLine]::Insert("$($key.KeyChar)" * 2) [Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor) [Microsoft.PowerShell.PSConsoleReadLine]::SetCursorPosition($cursor - 1) } } ``` -------------------------------- ### Enable Bash-style Tab Completion Source: https://github.com/powershell/psreadline/blob/master/README.md This command assigns the 'Complete' function to the Tab key, enabling bash-style command completion without activating Emacs mode. ```powershell Set-PSReadLineKeyHandler -Key Tab -Function Complete ``` -------------------------------- ### Set PSReadLine Key Handlers Source: https://context7.com/powershell/psreadline/llms.txt Assign specific functions to keyboard shortcuts for common actions like clearing the screen, canceling lines, or showing help. ```powershell Set-PSReadLineKeyHandler -Key Ctrl+l -Function ClearScreen ``` ```powershell Set-PSReadLineKeyHandler -Key Ctrl+c -Function CancelLine ``` ```powershell Set-PSReadLineKeyHandler -Key Escape -Function RevertLine ``` ```powershell Set-PSReadLineKeyHandler -Key Enter -Function AcceptLine ``` ```powershell Set-PSReadLineKeyHandler -Key Shift+Enter -Function AddLine ``` ```powershell Set-PSReadLineKeyHandler -Key F1 -Function ShowCommandHelp ``` ```powershell Set-PSReadLineKeyHandler -Key Alt+h -Function ShowParameterHelp ``` -------------------------------- ### Get-PSReadLineKeyHandler Source: https://context7.com/powershell/psreadline/llms.txt Retrieves information about PSReadLine key bindings, allowing you to view all, bound, unbound, or specific key handler configurations. ```APIDOC ## Get-PSReadLineKeyHandler Display all key bindings and their associated functions, grouped by functionality. ### Usage ```powershell # Get all bound key handlers Get-PSReadLineKeyHandler # Get only bound keys Get-PSReadLineKeyHandler -Bound # Get unbound functions (available but not mapped) Get-PSReadLineKeyHandler -Unbound # Get both bound and unbound Get-PSReadLineKeyHandler -Bound -Unbound # Get specific chord binding Get-PSReadLineKeyHandler -Chord Ctrl+r Get-PSReadLineKeyHandler -Chord 'Ctrl+x,Ctrl+e' ``` ### Output Example ``` Key Function Description --- -------- ----------- UpArrow HistorySearchBackward Search history backward Tab Complete Complete the input Ctrl+r ReverseSearchHistory Search history backwards interactively ``` ``` -------------------------------- ### Configure History Search Key Bindings Source: https://github.com/powershell/psreadline/blob/master/README.md These commands set custom key bindings for UpArrow and DownArrow to perform backward and forward history searches, respectively. This enhances the command history navigation experience. ```powershell Set-PSReadLineKeyHandler -Key UpArrow -Function HistorySearchBackward ``` ```powershell Set-PSReadLineKeyHandler -Key DownArrow -Function HistorySearchForward ``` -------------------------------- ### PSReadLine Text Editing Key Bindings Source: https://context7.com/powershell/psreadline/llms.txt Configure key handlers for various text editing operations like deleting lines, words, killing and yanking text, and undoing changes. ```powershell # Text editing Set-PSReadLineKeyHandler -Key Ctrl+u -Function BackwardDeleteLine Set-PSReadLineKeyHandler -Key Ctrl+k -Function ForwardDeleteLine Set-PSReadLineKeyHandler -Key Ctrl+w -Function BackwardKillWord Set-PSReadLineKeyHandler -Key Alt+d -Function KillWord Set-PSReadLineKeyHandler -Key Ctrl+y -Function Yank Set-PSReadLineKeyHandler -Key Ctrl+_ -Function Undo Set-PSReadLineKeyHandler -Key Ctrl+z -Function Undo Set-PSReadLineKeyHandler -Key Alt+. -Function YankLastArg ``` -------------------------------- ### Bind Ctrl+SpaceBar to MenuComplete in PSReadLine Source: https://github.com/powershell/psreadline/blob/master/PSReadLine/Changes.txt This binding adds the MenuComplete functionality, similar to an interactive completion menu, in both Windows and Emacs modes. To retain the old behavior, bind Ctrl+Spacebar to PossibleCompletions. ```powershell Set-PSReadLineKeyHandler -Key "Ctrl+Spacebar" -Function MenuComplete ``` -------------------------------- ### PSReadLine Buffer Manipulation Methods Source: https://github.com/powershell/psreadline/blob/master/README.md These are public methods of the PSConsoleReadLine class that can be used within custom key bindings to modify the command line buffer. They allow for advanced command-line editing functionalities. ```powershell [Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState ``` ```powershell [Microsoft.PowerShell.PSConsoleReadLine]::Insert ``` ```powershell [Microsoft.PowerShell.PSConsoleReadLine]::Replace ``` ```powershell [Microsoft.PowerShell.PSConsoleReadLine]::SetCursorPosition ``` -------------------------------- ### PSConsoleReadLine API: Manipulate Buffer Source: https://context7.com/powershell/psreadline/llms.txt Insert, delete, or replace text within the command line buffer at the current cursor position using the PSConsoleReadLine class methods. ```powershell # Insert text at current cursor position [Microsoft.PowerShell.PSConsoleReadLine]::Insert("Write-Host 'Hello'") ``` ```powershell # Insert a single character [Microsoft.PowerShell.PSConsoleReadLine]::Insert([char]'x') ``` ```powershell # Delete text from buffer (start position, length) [Microsoft.PowerShell.PSConsoleReadLine]::Delete(0, 5) # Delete first 5 characters ``` ```powershell # Replace text in buffer (start, length, replacement) [Microsoft.PowerShell.PSConsoleReadLine]::Replace(0, 4, "Write-Output") ``` -------------------------------- ### Configure PSReadLine Error Colors Source: https://github.com/powershell/psreadline/blob/master/PSReadLine/Changes.txt Set the foreground and background colors used when ValidateAndAcceptLine reports an error. These options are part of Set-PSReadLineOption. ```powershell Set-PSReadLineOption -ErrorForegroundColor Black -ErrorBackgroundColor Yellow ``` -------------------------------- ### Configure History Save Style and Path in PSReadLine Source: https://github.com/powershell/psreadline/blob/master/PSReadLine/Changes.txt These options control how and where command history is saved. HistorySaveStyle can be set to SaveIncrementally, SaveAtExit, or DoNotSave. HistorySavePath specifies the file path for saving history. ```powershell Set-PSReadLineOption -HistorySaveStyle SaveIncrementally -HistorySavePath "$HOME\Documents\PowerShell\PSReadLineHistory.txt" ``` -------------------------------- ### Set Emacs Edit Mode Source: https://github.com/powershell/psreadline/blob/master/README.md Use this command to enable Emacs key bindings for PSReadLine. This changes how you interact with the command line. ```powershell Set-PSReadLineOption -EditMode Emacs ``` -------------------------------- ### Bind Keys in PSReadLine Source: https://context7.com/powershell/psreadline/llms.txt Assign keyboard shortcuts to PSReadLine functions, including built-in commands or custom script blocks. This allows for keyboard-driven actions and customized editing workflows. ```powershell # Bind arrow keys to history search (search based on current input) Set-PSReadLineKeyHandler -Key UpArrow -Function HistorySearchBackward Set-PSReadLineKeyHandler -Key DownArrow -Function HistorySearchForward ``` ```powershell # Use Tab for bash-style completion Set-PSReadLineKeyHandler -Key Tab -Function Complete ``` ```powershell # Bind Ctrl+Spacebar to menu completion (IntelliSense-style) Set-PSReadLineKeyHandler -Key Ctrl+Spacebar -Function MenuComplete ``` -------------------------------- ### Remove PSReadLine Key Handler Bindings Source: https://context7.com/powershell/psreadline/llms.txt Remove custom key bindings to revert to default behavior or unbind keys. Supports removing single keys, multiple keys, chord bindings, and Vi mode specific bindings. ```powershell # Remove a single key binding Remove-PSReadLineKeyHandler -Key Ctrl+w ``` ```powershell # Remove multiple key bindings Remove-PSReadLineKeyHandler -Key Tab, Ctrl+Spacebar ``` ```powershell # Remove a chord binding Remove-PSReadLineKeyHandler -Key 'Ctrl+x,Ctrl+e' ``` ```powershell # Remove Vi mode specific binding Remove-PSReadLineKeyHandler -Key Escape -ViMode Command ``` -------------------------------- ### Bind Alt+. to YankLastArg in PSReadLine Source: https://github.com/powershell/psreadline/blob/master/PSReadLine/Changes.txt This key binding, Alt+., is added to Windows mode and is used for YankLastArg functionality. ```powershell Set-PSReadLineKeyHandler -Key "Alt+." -Function YankLastArg ``` -------------------------------- ### Enable Predictive Suggestion Feature Source: https://github.com/powershell/psreadline/blob/master/PSReadLine/Changes.txt Enables the predictive suggestion feature in PSReadLine by setting the `PredictionSource` parameter to `History`. This allows PSReadLine to offer suggestions based on command history. ```powershell Set-PSReadLineOption -PredictionSource History ``` -------------------------------- ### Revert Enter Key Behavior in PSReadLine Source: https://github.com/powershell/psreadline/blob/master/PSReadLine/Changes.txt If the new behavior for the Enter key (extra validation) is not desired, use this command to revert to the old behavior. ```powershell Set-PSReadLineKeyHandler -Key Enter -Function AcceptLine ``` -------------------------------- ### Custom Command Validation Handler in PSReadLine Source: https://github.com/powershell/psreadline/blob/master/PSReadLine/Changes.txt Assign a delegate to perform custom validation and potentially fix the command line when ValidateAndAcceptLine is used. This is configured via Set-PSReadLineOption. ```powershell Set-PSReadLineOption -CommandValidationHandler $myHandler ``` -------------------------------- ### Ring the Bell in PSReadLine Source: https://context7.com/powershell/psreadline/llms.txt Ding() plays a sound, typically a bell, to alert the user. This can be used for notifications or error indications. ```powershell [Microsoft.PowerShell.PSConsoleReadLine]::Ding() ``` -------------------------------- ### Enable Vi Editing Mode in PSReadLine Source: https://context7.com/powershell/psreadline/llms.txt Set-PSReadLineOption -EditMode Vi enables the Vi editing mode, which provides Emacs-like keybindings and command/insert modes. ```powershell Set-PSReadLineOption -EditMode Vi ``` -------------------------------- ### Clear and Replace Current Line in PSReadLine Source: https://context7.com/powershell/psreadline/llms.txt RevertLine clears the current command line, and Insert then adds new text. This is useful for replacing the entire line content. ```powershell [Microsoft.PowerShell.PSConsoleReadLine]::RevertLine() [Microsoft.PowerShell.PSConsoleReadLine]::Insert("Get-Process | Where-Object CPU -gt 100") ``` -------------------------------- ### Add Current Line to History Without Execution Source: https://context7.com/powershell/psreadline/llms.txt GetBufferState retrieves the current line content, which is then added to history using AddToHistory. RevertLine clears the buffer afterwards. ```powershell $line = $null [Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$null) [Microsoft.PowerShell.PSConsoleReadLine]::AddToHistory($line) [Microsoft.PowerShell.PSConsoleReadLine]::RevertLine() ``` -------------------------------- ### Set Cursor Position in PSReadLine Source: https://context7.com/powershell/psreadline/llms.txt Use SetCursorPosition to move the cursor to a specific column on the current line. This is useful for precise text manipulation. ```powershell [Microsoft.PowerShell.PSConsoleReadLine]::SetCursorPosition(10) ``` -------------------------------- ### Remove-PSReadLineKeyHandler Source: https://context7.com/powershell/psreadline/llms.txt Removes custom key bindings, enabling you to revert to default behavior or unbind specific keys. ```APIDOC ## Remove-PSReadLineKeyHandler Remove custom key bindings to restore default behavior or unbind keys entirely. ### Usage ```powershell # Remove a single key binding Remove-PSReadLineKeyHandler -Key Ctrl+w # Remove multiple key bindings Remove-PSReadLineKeyHandler -Key Tab, Ctrl+Spacebar # Remove a chord binding Remove-PSReadLineKeyHandler -Key 'Ctrl+x,Ctrl+e' # Remove Vi mode specific binding Remove-PSReadLineKeyHandler -Key Escape -ViMode Command ``` ``` -------------------------------- ### Invoke Prompt Redraw in PSReadLine Source: https://context7.com/powershell/psreadline/llms.txt InvokePrompt redraws the command prompt. This is useful after making changes to the command line that might affect prompt display. ```powershell [Microsoft.PowerShell.PSConsoleReadLine]::InvokePrompt() ``` -------------------------------- ### Remove PSReadLine Key Binding Source: https://github.com/powershell/psreadline/blob/master/PSReadLine/Changes.txt Use this cmdlet to remove a previously assigned key binding for a specific function in PSReadLine. ```powershell Remove-PSReadLineKeyHandler -Key "Ctrl+D" ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.