Skip to content

Commit 771ff17

Browse files
committed
Merge pull request #255 from nightroman/master
Set-PSReadlineKeyHandler -Key F7: command history using Out-GridView.
2 parents 5117b23 + 57eb37b commit 771ff17

File tree

1 file changed

+47
-16
lines changed

1 file changed

+47
-16
lines changed

PSReadLine/SamplePSReadlineProfile.ps1

Lines changed: 47 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -18,28 +18,59 @@ Set-PSReadLineOption -HistorySearchCursorMovesToEnd
1818
Set-PSReadlineKeyHandler -Key UpArrow -Function HistorySearchBackward
1919
Set-PSReadlineKeyHandler -Key DownArrow -Function HistorySearchForward
2020

21-
# Being able to search the entirety of your history in a popup makes it
22-
# really easy to find a command you previously used.
23-
# Either press F7 to bring up your entire history, or type part of the
24-
# command line and then press F7 to bring up just the commands that match.
21+
# This key handler shows the entire or filtered history using Out-GridView. The
22+
# typed text is used as the substring pattern for filtering. A selected command
23+
# is inserted to the command line without invoking. Multiple command selection
24+
# is supported, e.g. selected by Ctrl + Click.
2525
Set-PSReadlineKeyHandler -Key F7 `
2626
-BriefDescription History `
27-
-LongDescription 'Show history' `
27+
-LongDescription 'Show command history' `
2828
-ScriptBlock {
29-
$history = [System.Collections.ArrayList]([System.IO.File]::ReadAllLines((Get-PSReadlineOption).HistorySavePath))
30-
$history.Reverse()
31-
32-
$line = $null
33-
$cursor = $null
34-
[Microsoft.PowerShell.PSConsoleReadline]::GetBufferState([ref]$line, [ref]$cursor)
35-
if ($line) {
36-
$history = $history -match [regex]::Escape($line)
29+
$pattern = $null
30+
[Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$pattern, [ref]$null)
31+
if ($pattern)
32+
{
33+
$pattern = [regex]::Escape($pattern)
3734
}
3835

39-
$command = $history | Get-Unique | Out-GridView -Title History -PassThru
40-
if ($command) {
36+
$history = [System.Collections.ArrayList]$(
37+
$last = ''
38+
$lines = ''
39+
foreach ($line in [System.IO.File]::ReadLines((Get-PSReadlineOption).HistorySavePath))
40+
{
41+
if ($line.EndsWith('`'))
42+
{
43+
$line = $line.Substring(0, $line.Length - 1)
44+
$lines = if ($lines)
45+
{
46+
"$lines`n$line"
47+
}
48+
else
49+
{
50+
$line
51+
}
52+
continue
53+
}
54+
55+
if ($lines)
56+
{
57+
$line = "$lines`n$line"
58+
$lines = ''
59+
}
60+
61+
if (($line -cne $last) -and (!$pattern -or ($line -match $pattern)))
62+
{
63+
($last = $line)
64+
}
65+
}
66+
)
67+
$history.Reverse()
68+
69+
$command = $history | Out-GridView -Title History -PassThru
70+
if ($command)
71+
{
4172
[Microsoft.PowerShell.PSConsoleReadLine]::RevertLine()
42-
[Microsoft.PowerShell.PSConsoleReadLine]::Insert($command)
73+
[Microsoft.PowerShell.PSConsoleReadLine]::Insert(($command -join "`n"))
4374
}
4475
}
4576

0 commit comments

Comments
 (0)