PSReadLine icon indicating copy to clipboard operation
PSReadLine copied to clipboard

Support restoring a previously retrieved key handler with Set-PSReadlineKeyHandler

Open mklement0 opened this issue 6 years ago • 1 comments

The [Microsoft.PowerShell.KeyHandler] instances output by Get-PSReadlineKeyHandler can currently not be used to later restore that handler (after temporarily installing a different handler), if the original handler was based on custom script block rather than a built-in function.

The reason is that the .Function property is a [string] that merely returns 'Custom' for script-block-based handlers, and the script block itself is not returned.

One option is to simply add .ScriptBlock property that contains the original script block (which would only be filled if .Function contains Custom).

Complementarily, it would be nice if Set-PSReadlineKeyHandler supported a -Handler parameter that can directly accept a previously retrieved [Microsoft.PowerShell.KeyHandler] instance.

E.g.:


# Retrieve and store the current handler.
# See also: #879
$prevEscKeyHandler = Get-PSReadLineKeyHandler | ? Key -eq Escape

# Temporarily install different handler.
Set-PSReadLineKeyHandler -Key Escape -ScriptBock { Write-Verbose -vb 'ESC pressed' }
try {
  
  # ... 
  
} finally {
  # Restore previous handler
  # WISHFUL THINKING
  Set-PSReadLineKeyHandler -Handler $prevEscKeyHandler
}


Environment data

PSReadline version: 2.0.0-beta3

mklement0 avatar Apr 05 '19 13:04 mklement0

It'd be very nice to be able to get the value of a PSReadLineKeyHandler in an invokable/resettable way. Currently, scripts can only get metadata about the current Key Handler and overwrite it - this creates unavoidable conflict if multiple scripts want to register a handler for the same key. If there was some way to get the existing key handler in an invokable way, we could at least invoke the next key handler from within our own handler if desired, giving us some way to avoid conflict.

leumasme avatar Jul 08 '23 18:07 leumasme