From 11a3226fd5f6b778aa28085b733e8e5535462a93 Mon Sep 17 00:00:00 2001 From: theaquamarine Date: Sun, 12 Jan 2020 03:30:44 +0000 Subject: [PATCH] Allow InsertPairedBraces to wrap selected text Similar to SmartInsertQuote's existing ability. --- PSReadLine/SamplePSReadLineProfile.ps1 | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/PSReadLine/SamplePSReadLineProfile.ps1 b/PSReadLine/SamplePSReadLineProfile.ps1 index 89183e49..f33a3d6f 100644 --- a/PSReadLine/SamplePSReadLineProfile.ps1 +++ b/PSReadLine/SamplePSReadLineProfile.ps1 @@ -227,11 +227,24 @@ Set-PSReadLineKeyHandler -Key '(','{','[' ` <#case#> '[' { [char]']'; break } } - [Microsoft.PowerShell.PSConsoleReadLine]::Insert("$($key.KeyChar)$closeChar") + $selectionStart = $null + $selectionLength = $null + [Microsoft.PowerShell.PSConsoleReadLine]::GetSelectionState([ref]$selectionStart, [ref]$selectionLength) + $line = $null $cursor = $null [Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor) - [Microsoft.PowerShell.PSConsoleReadLine]::SetCursorPosition($cursor - 1) + + if ($selectionStart -ne -1) + { + # Text is selected, wrap it in brackets + [Microsoft.PowerShell.PSConsoleReadLine]::Replace($selectionStart, $selectionLength, $key.KeyChar + $line.SubString($selectionStart, $selectionLength) + $closeChar) + [Microsoft.PowerShell.PSConsoleReadLine]::SetCursorPosition($selectionStart + $selectionLength + 2) + } else { + # No text is selected, insert a pair + [Microsoft.PowerShell.PSConsoleReadLine]::Insert("$($key.KeyChar)$closeChar") + [Microsoft.PowerShell.PSConsoleReadLine]::SetCursorPosition($cursor + 1) + } } Set-PSReadLineKeyHandler -Key ')',']','}' `