Search code examples
powershellpsreadline

In powershell with psreadline -EditMode VI how to ensure the cursor starts at the end of the line when going through history


I'm using the powershell VI mode via

Set-PSReadlineOption -EditMode vi

It is awsome to be able to edit the line using VI commands however there is one thing that is annoying. When using the up and down arrows to navigate history the cursor always starts at the start of the line instead of at the end. ie: if I had the following command in my history

svn help x-shelve --list

then I would want the cursor (represented by the pipe | ) to be like

svn help x-shelve --list|

rather than

|svn help x-shelve --list

is there a way to set this?


Solution

  • You can use the Set-PSReadLineKeyHandler cmdlet:

    Set-PSReadLineKeyHandler -Key UpArrow `
       -ScriptBlock {
         param($key, $arg)
    
         $line=$null
         $cursor=$null
         [Microsoft.PowerShell.PSConsoleReadLine]::HistorySearchBackward()
         [Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor)
         [Microsoft.PowerShell.PSConsoleReadLine]::SetCursorPosition($line.Length)
    }
    
    
    Set-PSReadLineKeyHandler -Key DownArrow `
       -ScriptBlock {
         param($key, $arg)
    
         $line=$null
         $cursor=$null
         [Microsoft.PowerShell.PSConsoleReadLine]::HistorySearchForward()
         [Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor)
         [Microsoft.PowerShell.PSConsoleReadLine]::SetCursorPosition($line.Length)
    }