0
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

posted at

updated at

Powershellでpecoをショートカットキーで呼び出す

ここに書くまでもない程簡単にできたけど、意外とドンピシャの記事は見つからなかったので書き記しておく。
PowerShell 7.1.2で確認。

  • Ctrl+Tで$HOME\.snippetsに配置したワンライナー集をpeco
  • Ctrl+Shift+Tでプロンプト上の1行を.snippetsに追加
  • Ctrl+Rでコマンド履歴をpeco
Microsoft.PowerShell_profile.ps1
Set-PSReadLineKeyHandler -Key Ctrl+t -BriefDescription "snipetts" -LongDescription "peco .snippets" -ScriptBlock {
    $snipet = Get-Content $HOME\.snippets | peco

    [Microsoft.PowerShell.PSConsoleReadLine]::ClearScreen()
    [Microsoft.PowerShell.PSConsoleReadLine]::RevertLine()
    if($snipet -eq $null){return}
    [Microsoft.PowerShell.PSConsoleReadLine]::Insert($snipet)
}

Set-PSReadLineKeyHandler -Key Ctrl+Shift+t -BriefDescription SaveInHistory -LongDescription "Add line to .snippets" -ScriptBlock {
    param($key, $arg)

    $line = $null
    $cursor = $null
    [Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor)
    if($cursor -eq 0){return}
    Add-Content $HOME\.snippets $line
    [Microsoft.PowerShell.PSConsoleReadLine]::RevertLine()
}
Set-PSReadLineKeyHandler -Key Ctrl+r -BriefDescription History -LongDescription 'peco history' -ScriptBlock {
    $hist = @(Get-Content $(Get-PSReadLineOption).HistorySavePath)
    $command = ($hist)[$hist.length..0] | peco

    [Microsoft.PowerShell.PSConsoleReadLine]::ClearScreen()
    [Microsoft.PowerShell.PSConsoleReadLine]::RevertLine()
    if($command -eq $null){return}
    [Microsoft.PowerShell.PSConsoleReadLine]::Insert($command)
}

日本語が混じると微妙な感じになるけど、使い道としてそんなに混じることは無いので妥協した。

Register as a new user and use Qiita more conveniently

  1. You can follow users and tags
  2. you can stock useful information
  3. You can make editorial suggestions for articles
What you can do with signing up
0
Help us understand the problem. What are the problem?