#Do not accept line in closed pairs

8 messages · Page 1 of 1 (latest)

young coral
#

My habit when working with pwsh session is to type a full pair of braces and edit inside it, but pwsh will accept the line when I hit enter. Is it possible to disable this behavior? I want enter to always start a new line and use ctrl+enter to accept the line

ps> function foo {|} # pwsh accept on enter which I dislike
ps> function bar {
>> # by default it starts a new line when brace is not closed
digital mountain
#

Why would you want to disable the behaviour and instead not just work how the shell is designed? I might be miss-understanding the question here...

Why would you not just leave the closing bracket, enter the lines you want then close the bracket to say to the shell "Hey, I am ready for you to process this now"

How would you expect entering {} into a live shell to know you know what you mean? In an ISE where you can have things like tooltips, shortcuts and so on to avoid ambiguity, sure, but not in a bog standard shell

burnt vector
#

You can.
Set-PSReadLineKeyHandler -Chord Enter -Function AddLine
Set-PSReadLineKeyHandler -Chord Ctrl+Enter -Function AcceptLine

#

note Ctrl+Enter is by default bound to InsertLineAbove so you may want to remove that or change it to Shift+Enter or something

#

Get-PSReadLineKeyHandler to view all the currently configured keybinds

woven kelp
#
  • to AddLine, InsertAlineAbove/Below, etc.

Some split the text at the cursor position, like this. Others just add a new line before or after, without breaking the current line.

ps> function foo {
   | # cursor
}

There's a bunch of options: https://learn.microsoft.com/en-us/powershell/module/psreadline/about/about_psreadline_functions?view=powershell-7.5

woven kelp
young coral
#

thanks for all these info! I am able to do this with experience enhancement for braces

$script:braces = ('"', '"'), ("'", "'"), ('(', ')'), ('[', ']'), ('{', '}'), ('<', '>')
Set-PSReadLineKeyHandler -Chord Enter -ScriptBlock {
    $line = $pos = $null
    [Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$pos)

    $inMiddleOfBraces = foreach ($pair in $script:braces) {
        if ($pair[0] -eq $line[$pos - 1] -and $pair[1] -eq $line[$pos]) {
            $true
            break
        }
    }

    if ($line.Contains([System.Environment]::NewLine) -or $inMiddleOfBraces) {
        [Microsoft.PowerShell.PSConsoleReadLine]::AddLine()
        if ($inMiddleOfBraces) {
            [Microsoft.PowerShell.PSConsoleReadLine]::InsertLineAbove()
        }
    } else {
        [Microsoft.PowerShell.PSConsoleReadLine]::AcceptLine()
    }
}

Set-PSReadLineKeyHandler -Chord 'Ctrl+Enter' -Function AcceptLine