PSReadLine icon indicating copy to clipboard operation
PSReadLine copied to clipboard

Cursor movement behavior like the cursorWordPartRight and cursorWordPartLeft commands in VSCode

Open DumbCounselor opened this issue 10 months ago • 1 comments

Prerequisites

  • [x] Write a descriptive title.

Description of the new feature/enhancement

Hello!

Will be great if PSReadline will get the cursor moving patterns similar to VSCode commands cursorWordPartRight and cursorWordPartLeft. They put the cursor into the position before the nearest capital letter to the right or left of its current position in the word.

Image

Proposed technical implementation details (optional)

No response

DumbCounselor avatar Feb 11 '25 19:02 DumbCounselor

Seems it will last too long. MVP for those who don't want to wait. Can be added to $PROFILE.

function Move-CursorWordPart {
    param (
        [string]$Direction
    )

    $line = $null
    $cursor = $null
    [Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor)
    $nextPos = $cursor
    $symbols='''",./?\|=+_-{}[]$()!@*#&^$:;%~'.ToCharArray()
    if ($Direction -eq "left") {
        while ($nextPos -gt 0) {
            $currentChar = $line[$nextPos]
            if (
                ($nextPos -lt $cursor) -and (
                    ($currentChar -in $symbols) -or
                    [char]::IsUpper($currentChar) -or
                    [char]::IsWhiteSpace($currentChar)
                )
            ) {
                break
            }
            $nextPos--
        }
    }
    elseif ($Direction -eq "right") {
        while ($nextPos -lt $line.Length) {
            $currentChar = $line[$nextPos]
            if (
                ($nextPos -gt $cursor) -and (
                    ($currentChar -in $symbols) -or
                    [char]::IsUpper($currentChar) -or
                    [char]::IsWhiteSpace($currentChar)
                )
            ) {
                break
            }
            $nextPos++
        }
    }

    [Microsoft.PowerShell.PSConsoleReadLine]::SetCursorPosition($nextPos)
}

Set-PSReadLineKeyHandler -Chord "Alt+LeftArrow" -ScriptBlock {
    Move-CursorWordPart -Direction "left"
}
Set-PSReadLineKeyHandler -Chord "Alt+RightArrow" -ScriptBlock {
    Move-CursorWordPart  -Direction "right"
}

DumbCounselor avatar Feb 28 '25 20:02 DumbCounselor