Skip to content

Commit b65141e

Browse files
authored
Add argument selection handler to sample profile (#1947)
1 parent 9f786b3 commit b65141e

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

PSReadLine/SamplePSReadLineProfile.ps1

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -600,3 +600,59 @@ Set-PSReadLineKeyHandler -Key RightArrow `
600600
[Microsoft.PowerShell.PSConsoleReadLine]::AcceptNextSuggestionWord($key, $arg)
601601
}
602602
}
603+
604+
# Cycle through arguments on current line and select the text. This makes it easier to quickly change the argument if re-running a previously run command from the history
605+
# or if using a psreadline predictor. You can also use a digit argument to specify which argument you want to select, i.e. Alt+1, Alt+a selects the first argument
606+
# on the command line.
607+
Set-PSReadLineKeyHandler -Key Alt+a `
608+
-BriefDescription SelectCommandArguments `
609+
-LongDescription "Set current selection to next command argument in the command line. Use of digit argument selects argument by position" `
610+
-ScriptBlock {
611+
param($key, $arg)
612+
613+
$ast = $null
614+
$cursor = $null
615+
[Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$ast, [ref]$null, [ref]$null, [ref]$cursor)
616+
617+
$asts = $ast.FindAll( {
618+
$args[0] -is [System.Management.Automation.Language.ExpressionAst] -and
619+
$args[0].Parent -is [System.Management.Automation.Language.CommandAst] -and
620+
$args[0].Extent.StartOffset -ne $args[0].Parent.Extent.StartOffset
621+
}, $true)
622+
623+
if ($asts.Count -eq 0) {
624+
[Microsoft.PowerShell.PSConsoleReadLine]::Ding()
625+
return
626+
}
627+
628+
$nextAst = $null
629+
630+
if ($null -ne $arg) {
631+
$nextAst = $asts[$arg - 1]
632+
}
633+
else {
634+
foreach ($ast in $asts) {
635+
if ($ast.Extent.StartOffset -ge $cursor) {
636+
$nextAst = $ast
637+
break
638+
}
639+
}
640+
641+
if ($null -eq $nextAst) {
642+
$nextAst = $asts[0]
643+
}
644+
}
645+
646+
$startOffsetAdjustment = 0
647+
$endOffsetAdjustment = 0
648+
649+
if ($nextAst -is [System.Management.Automation.Language.StringConstantExpressionAst] -and
650+
$nextAst.StringConstantType -ne [System.Management.Automation.Language.StringConstantType]::BareWord) {
651+
$startOffsetAdjustment = 1
652+
$endOffsetAdjustment = 2
653+
}
654+
655+
[Microsoft.PowerShell.PSConsoleReadLine]::SetCursorPosition($nextAst.Extent.StartOffset + $startOffsetAdjustment)
656+
[Microsoft.PowerShell.PSConsoleReadLine]::SetMark($null, $null)
657+
[Microsoft.PowerShell.PSConsoleReadLine]::SelectForwardChar($null, ($nextAst.Extent.EndOffset - $nextAst.Extent.StartOffset) - $endOffsetAdjustment)
658+
}

0 commit comments

Comments
 (0)