PsReadLine: execute selection

79 views Asked by At

I would like to be able to select some part of the text in my command (e.g. a path) and start it, so that explorer opens the directory, or file.

So far i have come up with the code at the end of the post, which works, but has some issues:

  1. it only works when text is selected using keyboard navigation while holding shift, not when dragging with the mouse (apparently in the latter case, psreadline doesn't recognize it as a selection?)
  2. It doesn't work for expressions that should be expanded, such as when selecting $PROFILE. How do i solve these issues?
# if there is a selection, attempt to start it (that will, for instance, open a directory or file with default explorer action)
Set-PSReadlineKeyHandler -Chord Ctrl+Shift+r `
                         -BriefDescription RunSelection `
                         -LongDescription "Run (start) the current selection" `
                         -ScriptBlock {
    param($key, $arg)

    $selectionStart = $null
    $selectionLength = $null
    [Microsoft.PowerShell.PSConsoleReadLine]::GetSelectionState([ref]$selectionStart, [ref]$selectionLength)
    if ($selectionStart -eq -1)
    {
        # no selection, nothing to do
        return
    }

    # get selected text, with quotes
    $quote = '"'
    $line = $null
    $cursor = $null
    [Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor)
    $selection = $quote + $line.SubString($selectionStart, $selectionLength) + $quote

    # start it
    &"start" $selection
}

I add quotes so that things still work when a path with spaces is selected. With or without quotes, trying to open $PROFILE gives an error.

This is Powershell 7.3.1, PSReadLine 2.2.6 and Windows Terminal 1.15.3466.0.

0

There are 0 answers