Created
January 28, 2024 12:00
-
-
Save GhostOps77/92b75d44e31c341d867179f1368c5cf7 to your computer and use it in GitHub Desktop.
My powershell config
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using namespace System.Management.Automation | |
using namespace System.Management.Automation.Language | |
using namespace Microsoft.PowerShell.PSConsoleReadLine | |
if ($host.Name -eq 'ConsoleHost') { | |
Import-Module PSReadLine | |
} | |
Import-Module -Name Terminal-Icons | |
oh-my-posh --init --shell pwsh --config "C:\Users\Mouhsen\Documents\oh my posh config\oh-my-posh-config.json" | Invoke-Expression | |
# PowerShell parameter completion shim for the winget | |
Register-ArgumentCompleter -Native -CommandName winget -ScriptBlock { | |
param($wordToComplete, $commandAst, $cursorPosition) | |
[Console]::InputEncoding = [Console]::OutputEncoding = $OutputEncoding = [System.Text.Utf8Encoding]::new() | |
$Local:word = $wordToComplete.Replace('"', '""') | |
$Local:ast = $commandAst.ToString().Replace('"', '""') | |
winget complete --word="$Local:word" --commandline "$Local:ast" --position $cursorPosition | ForEach-Object { | |
[CompletionResult]::new($_) | |
} | |
} | |
# PowerShell parameter completion shim for the dotnet CLI | |
Register-ArgumentCompleter -Native -CommandName dotnet -ScriptBlock { | |
param($commandName, $wordToComplete, $cursorPosition) | |
dotnet complete --position $cursorPosition "$wordToComplete" | ForEach-Object { | |
[System.Management.Automation.CompletionResult]::new($_) | |
} | |
} | |
# --- | |
# Set-PSReadLineKeyHandler -Chord Tab -Function ForwardWord | |
Set-PSReadlineKeyHandler -Chord 'Ctrl+Spacebar' -Function PossibleCompletions | |
Set-PSReadlineKeyHandler -Key Tab -Function MenuComplete | |
Set-PSReadLineKeyHandler -Key UpArrow -Function HistorySearchBackward | |
Set-PSReadLineKeyHandler -Key DownArrow -Function HistorySearchForward | |
Set-PSReadLineKeyHandler -Key F7 ` | |
-BriefDescription History ` | |
-LongDescription 'Show command history' ` | |
-ScriptBlock { | |
$pattern = $null | |
[Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$pattern, [ref]$null) | |
if ($pattern) { | |
$pattern = [regex]::Escape($pattern) | |
} | |
$history = [System.Collections.ArrayList]@( | |
$last = '' | |
$lines = '' | |
foreach ($line in [System.IO.File]::ReadLines((Get-PSReadLineOption).HistorySavePath)) { | |
if ($line.EndsWith('`')) { | |
$line = $line.Substring(0, $line.Length - 1) | |
$lines = if ($lines) { | |
"$lines`n$line" | |
} else { $line } | |
continue | |
} | |
if ($lines) { | |
$line = "$lines`n$line" | |
$lines = '' | |
} | |
if (($line -cne $last) -and (!$pattern -or ($line -match $pattern))) { | |
$last = $line | |
$line | |
} | |
} | |
) | |
$history.Reverse() | |
$command = $history | Out-GridView -Title History -PassThru | |
if ($command) { | |
[Microsoft.PowerShell.PSConsoleReadLine]::RevertLine() | |
[Microsoft.PowerShell.PSConsoleReadLine]::Insert(($command -join "`n")) | |
} | |
} | |
Set-PSReadLineKeyHandler -Chord 'Ctrl+d,Ctrl+c' -Function CaptureScreen | |
Set-PSReadLineKeyHandler -Key Alt+d -Function ShellKillWord | |
Set-PSReadLineKeyHandler -Key Alt+Backspace -Function ShellBackwardKillWord | |
Set-PSReadLineKeyHandler -Key Alt+b -Function ShellBackwardWord | |
Set-PSReadLineKeyHandler -Key Alt+f -Function ShellForwardWord | |
Set-PSReadLineKeyHandler -Key Alt+B -Function SelectShellBackwardWord | |
Set-PSReadLineKeyHandler -Key Alt+F -Function SelectShellForwardWord | |
# region Smart Insert/Delete | |
Set-PSReadLineKeyHandler -Key '"',"'" ` | |
-BriefDescription SmartInsertQuote ` | |
-LongDescription "Insert paired quotes if not already on a quote" ` | |
-ScriptBlock { | |
param($key, $arg) | |
$quote = $key.KeyChar | |
$selectionStart = $null | |
$selectionLength = $null | |
[Microsoft.PowerShell.PSConsoleReadLine]::GetSelectionState([ref]$selectionStart, [ref]$selectionLength) | |
$line = $null | |
$cursor = $null | |
[Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor) | |
# If text is selected, just quote it without any smarts | |
if ($selectionStart -ne -1) { | |
[Microsoft.PowerShell.PSConsoleReadLine]::Replace($selectionStart, $selectionLength, $quote + $line.SubString($selectionStart, $selectionLength) + $quote) | |
[Microsoft.PowerShell.PSConsoleReadLine]::SetCursorPosition($selectionStart + $selectionLength + 2) | |
return | |
} | |
$ast = $null | |
$tokens = $null | |
$parseErrors = $null | |
[Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$ast, [ref]$tokens, [ref]$parseErrors, [ref]$null) | |
function FindToken { | |
param($tokens, $cursor) | |
foreach ($token in $tokens) { | |
if ($cursor -lt $token.Extent.StartOffset) { continue } | |
if ($cursor -lt $token.Extent.EndOffset) { | |
$result = $token | |
$token = $token -as [StringExpandableToken] | |
if ($token) { | |
$nested = FindToken $token.NestedTokens $cursor | |
if ($nested) { $result = $nested } | |
} | |
return $result | |
} | |
} | |
return $null | |
} | |
$token = FindToken $tokens $cursor | |
# If we're on or inside a **quoted** string token (so not generic), we need to be smarter | |
if ($token -is [StringToken] -and $token.Kind -ne [TokenKind]::Generic) { | |
# If we're at the start of the string, assume we're inserting a new string | |
if ($token.Extent.StartOffset -eq $cursor) { | |
[Microsoft.PowerShell.PSConsoleReadLine]::Insert("$quote$quote ") | |
[Microsoft.PowerShell.PSConsoleReadLine]::SetCursorPosition($cursor + 1) | |
return | |
} | |
# If we're at the end of the string, move over the closing quote if present. | |
if ($token.Extent.EndOffset -eq ($cursor + 1) -and $line[$cursor] -eq $quote) { | |
[Microsoft.PowerShell.PSConsoleReadLine]::SetCursorPosition($cursor + 1) | |
return | |
} | |
} | |
if ($null -eq $token -or | |
$token.Kind -eq [TokenKind]::RParen -or $token.Kind -eq [TokenKind]::RCurly -or $token.Kind -eq [TokenKind]::RBracket) { | |
if ($line[0..$cursor].Where{$_ -eq $quote}.Count % 2 -eq 1) { | |
# Odd number of quotes before the cursor, insert a single quote | |
[Microsoft.PowerShell.PSConsoleReadLine]::Insert($quote) | |
} else { | |
# Insert matching quotes, move cursor to be in between the quotes | |
[Microsoft.PowerShell.PSConsoleReadLine]::Insert("$quote$quote") | |
[Microsoft.PowerShell.PSConsoleReadLine]::SetCursorPosition($cursor + 1) | |
} | |
return | |
} | |
# If cursor is at the start of a token, enclose it in quotes. | |
if ($token.Extent.StartOffset -eq $cursor) { | |
if ($token.Kind -eq [TokenKind]::Generic -or $token.Kind -eq [TokenKind]::Identifier -or | |
$token.Kind -eq [TokenKind]::Variable -or $token.TokenFlags.hasFlag([TokenFlags]::Keyword)) { | |
$end = $token.Extent.EndOffset | |
$len = $end - $cursor | |
[Microsoft.PowerShell.PSConsoleReadLine]::Replace($cursor, $len, $quote + $line.SubString($cursor, $len) + $quote) | |
[Microsoft.PowerShell.PSConsoleReadLine]::SetCursorPosition($end + 2) | |
return | |
} | |
} | |
# We failed to be smart, so just insert a single quote | |
[Microsoft.PowerShell.PSConsoleReadLine]::Insert($quote) | |
} | |
Set-PSReadLineKeyHandler -Key '(','{','[' ` | |
-BriefDescription InsertPairedBraces ` | |
-LongDescription "Insert matching braces" ` | |
-ScriptBlock { | |
param($key, $arg) | |
$closeChar = switch ($key.KeyChar) { | |
<#case#> '(' { [char]')'; break } | |
<#case#> '{' { [char]'}'; break } | |
<#case#> '[' { [char]']'; break } | |
} | |
$selectionStart = $null | |
$selectionLength = $null | |
[Microsoft.PowerShell.PSConsoleReadLine]::GetSelectionState([ref]$selectionStart, [ref]$selectionLength) | |
$line = $null | |
$cursor = $null | |
[Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor) | |
if ($selectionStart -ne -1) { | |
# Text is selected, wrap it in brackets | |
[Microsoft.PowerShell.PSConsoleReadLine]::Replace($selectionStart, $selectionLength, $key.KeyChar + $line.SubString($selectionStart, $selectionLength) + $closeChar) | |
[Microsoft.PowerShell.PSConsoleReadLine]::SetCursorPosition($selectionStart + $selectionLength + 2) | |
} else { | |
# No text is selected, insert a pair | |
[Microsoft.PowerShell.PSConsoleReadLine]::Insert("$($key.KeyChar)$closeChar") | |
[Microsoft.PowerShell.PSConsoleReadLine]::SetCursorPosition($cursor + 1) | |
} | |
} | |
Set-PSReadLineKeyHandler -Key ')',']','}' ` | |
-BriefDescription SmartCloseBraces ` | |
-LongDescription "Insert closing brace or skip" ` | |
-ScriptBlock { | |
param($key, $arg) | |
$line = $null | |
$cursor = $null | |
[Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor) | |
if ($line[$cursor] -eq $key.KeyChar) { | |
[Microsoft.PowerShell.PSConsoleReadLine]::SetCursorPosition($cursor + 1) | |
} else { | |
[Microsoft.PowerShell.PSConsoleReadLine]::Insert("$($key.KeyChar)") | |
} | |
} | |
Set-PSReadLineKeyHandler -Key Backspace ` | |
-BriefDescription SmartBackspace ` | |
-LongDescription "Delete previous character or matching quotes/parens/braces" ` | |
-ScriptBlock { | |
param($key, $arg) | |
$line = $null | |
$cursor = $null | |
[Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor) | |
if ($cursor -gt 0) { | |
$toMatch = $null | |
if ($cursor -lt $line.Length) { | |
switch ($line[$cursor]) { | |
<#case#> '"' { $toMatch = '"'; break } | |
<#case#> "'" { $toMatch = "'"; break } | |
<#case#> ')' { $toMatch = '('; break } | |
<#case#> ']' { $toMatch = '['; break } | |
<#case#> '}' { $toMatch = '{'; break } | |
} | |
} | |
if ($toMatch -ne $null -and $line[$cursor-1] -eq $toMatch) { | |
[Microsoft.PowerShell.PSConsoleReadLine]::Delete($cursor - 1, 2) | |
} else { | |
[Microsoft.PowerShell.PSConsoleReadLine]::BackwardDeleteChar($key, $arg) | |
} | |
} | |
} | |
# endregion Smart Insert/Delete | |
Set-PSReadLineKeyHandler -Key Alt+w ` | |
-BriefDescription SaveInHistory ` | |
-LongDescription "Save current line in history but do not execute" ` | |
-ScriptBlock { | |
param($key, $arg) | |
$line = $null | |
$cursor = $null | |
[Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor) | |
[Microsoft.PowerShell.PSConsoleReadLine]::AddToHistory($line) | |
[Microsoft.PowerShell.PSConsoleReadLine]::RevertLine() | |
} | |
# Insert text from the clipboard as a here string | |
Set-PSReadLineKeyHandler -Key Ctrl+V ` | |
-BriefDescription PasteAsHereString ` | |
-LongDescription "Paste the clipboard text as a here string" ` | |
-ScriptBlock { | |
param($key, $arg) | |
Add-Type -Assembly PresentationCore | |
if ([System.Windows.Clipboard]::ContainsText()) { | |
# Get clipboard text - remove trailing spaces, convert \r\n to \n, and remove the final \n. | |
$text = ([System.Windows.Clipboard]::GetText() -replace "\p{Zs}*`r?`n","`n").TrimEnd() | |
[Microsoft.PowerShell.PSConsoleReadLine]::Insert("@'`n$text`n'@") | |
} else { | |
[Microsoft.PowerShell.PSConsoleReadLine]::Ding() | |
} | |
} | |
Set-PSReadLineKeyHandler -Key 'Alt+(' ` | |
-BriefDescription ParenthesizeSelection ` | |
-LongDescription "Put parenthesis around the selection or entire line and move the cursor to after the closing parenthesis" ` | |
-ScriptBlock { | |
param($key, $arg) | |
$selectionStart = $null | |
$selectionLength = $null | |
[Microsoft.PowerShell.PSConsoleReadLine]::GetSelectionState([ref]$selectionStart, [ref]$selectionLength) | |
$line = $null | |
$cursor = $null | |
[Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor) | |
if ($selectionStart -ne -1) { | |
[Microsoft.PowerShell.PSConsoleReadLine]::Replace($selectionStart, $selectionLength, '(' + $line.SubString($selectionStart, $selectionLength) + ')') | |
[Microsoft.PowerShell.PSConsoleReadLine]::SetCursorPosition($selectionStart + $selectionLength + 2) | |
} else { | |
[Microsoft.PowerShell.PSConsoleReadLine]::Replace(0, $line.Length, '(' + $line + ')') | |
[Microsoft.PowerShell.PSConsoleReadLine]::EndOfLine() | |
} | |
} | |
Set-PSReadLineKeyHandler -Key "Alt+'" ` | |
-BriefDescription ToggleQuoteArgument ` | |
-LongDescription "Toggle quotes on the argument under the cursor" ` | |
-ScriptBlock { | |
param($key, $arg) | |
$ast = $null | |
$tokens = $null | |
$errors = $null | |
$cursor = $null | |
[Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$ast, [ref]$tokens, [ref]$errors, [ref]$cursor) | |
$tokenToChange = $null | |
foreach ($token in $tokens) { | |
$extent = $token.Extent | |
if ($extent.StartOffset -le $cursor -and $extent.EndOffset -ge $cursor) { | |
$tokenToChange = $token | |
# If the cursor is at the end (it's really 1 past the end) of the previous token, | |
# we only want to change the previous token if there is no token under the cursor | |
if ($extent.EndOffset -eq $cursor -and $foreach.MoveNext()) { | |
$nextToken = $foreach.Current | |
if ($nextToken.Extent.StartOffset -eq $cursor) { | |
$tokenToChange = $nextToken | |
} | |
} | |
break | |
} | |
} | |
if ($tokenToChange -ne $null) { | |
$extent = $tokenToChange.Extent | |
$tokenText = $extent.Text | |
if ($tokenText[0] -eq '"' -and $tokenText[-1] -eq '"') { | |
# Switch to no quotes | |
$replacement = $tokenText.Substring(1, $tokenText.Length - 2) | |
} | |
elseif ($tokenText[0] -eq "'" -and $tokenText[-1] -eq "'") { | |
# Switch to double quotes | |
$replacement = '"' + $tokenText.Substring(1, $tokenText.Length - 2) + '"' | |
} | |
else { | |
# Add single quotes | |
$replacement = "'" + $tokenText + "'" | |
} | |
[Microsoft.PowerShell.PSConsoleReadLine]::Replace( | |
$extent.StartOffset, $tokenText.Length, $replacement | |
) | |
} | |
} | |
Set-PSReadLineKeyHandler -Key "Alt+%" ` | |
-BriefDescription ExpandAliases ` | |
-LongDescription "Replace all aliases with the full command" ` | |
-ScriptBlock { | |
param($key, $arg) | |
$ast = $null | |
$tokens = $null | |
$errors = $null | |
$cursor = $null | |
[Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$ast, [ref]$tokens, [ref]$errors, [ref]$cursor) | |
$startAdjustment = 0 | |
foreach ($token in $tokens) { | |
if ($token.TokenFlags -band [TokenFlags]::CommandName) { | |
$alias = $ExecutionContext.InvokeCommand.GetCommand($token.Extent.Text, 'Alias') | |
if ($alias -ne $null) { | |
$resolvedCommand = $alias.ResolvedCommandName | |
if ($resolvedCommand -ne $null) { | |
$extent = $token.Extent | |
$length = $extent.EndOffset - $extent.StartOffset | |
[Microsoft.PowerShell.PSConsoleReadLine]::Replace( | |
$extent.StartOffset + $startAdjustment, | |
$length, | |
$resolvedCommand | |
) | |
# Our copy of the tokens won't have been updated, so we need to | |
# adjust by the difference in length | |
$startAdjustment += ($resolvedCommand.Length - $length) | |
} | |
} | |
} | |
} | |
} | |
Set-PSReadLineKeyHandler -Key F1 ` | |
-BriefDescription CommandHelp ` | |
-LongDescription "Open the help window for the current command" ` | |
-ScriptBlock { | |
param($key, $arg) | |
$ast = $null | |
$tokens = $null | |
$errors = $null | |
$cursor = $null | |
[Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$ast, [ref]$tokens, [ref]$errors, [ref]$cursor) | |
$commandAst = $ast.FindAll( { | |
$node = $args[0] | |
$node -is [CommandAst] -and | |
$node.Extent.StartOffset -le $cursor -and | |
$node.Extent.EndOffset -ge $cursor | |
}, $true) | Select-Object -Last 1 | |
if ($commandAst -ne $null) { | |
$commandName = $commandAst.GetCommandName() | |
if ($commandName -ne $null) { | |
$command = $ExecutionContext.InvokeCommand.GetCommand($commandName, 'All') | |
if ($command -is [AliasInfo]) { | |
$commandName = $command.ResolvedCommandName | |
} | |
if ($commandName -ne $null) { | |
Get-Help $commandName -ShowWindow | |
} | |
} | |
} | |
} | |
# Ctrl+Shift+j then type a key to mark the current directory. | |
# Ctrl+j then the same key will change back to that directory without | |
# needing to type cd and won't change the command line. | |
$global:PSReadLineMarks = @{} | |
Set-PSReadLineKeyHandler -Key Ctrl+J ` | |
-BriefDescription MarkDirectory ` | |
-LongDescription "Mark the current directory" ` | |
-ScriptBlock { | |
param($key, $arg) | |
$key = [Console]::ReadKey($true) | |
$global:PSReadLineMarks[$key.KeyChar] = $pwd | |
} | |
Set-PSReadLineKeyHandler -Key Ctrl+j ` | |
-BriefDescription JumpDirectory ` | |
-LongDescription "Goto the marked directory" ` | |
-ScriptBlock { | |
param($key, $arg) | |
$key = [Console]::ReadKey() | |
$dir = $global:PSReadLineMarks[$key.KeyChar] | |
if ($dir) { | |
cd $dir | |
[Microsoft.PowerShell.PSConsoleReadLine]::InvokePrompt() | |
} | |
} | |
Set-PSReadLineKeyHandler -Key Alt+j ` | |
-BriefDescription ShowDirectoryMarks ` | |
-LongDescription "Show the currently marked directories" ` | |
-ScriptBlock { | |
param($key, $arg) | |
$global:PSReadLineMarks.GetEnumerator() | % { | |
[PSCustomObject]@{Key = $_.Key; Dir = $_.Value} } | | |
Format-Table -AutoSize | Out-Host | |
[Microsoft.PowerShell.PSConsoleReadLine]::InvokePrompt() | |
} | |
# Auto correct 'git cmt' to 'git commit' | |
Set-PSReadLineOption -CommandValidationHandler { | |
param([CommandAst]$CommandAst) | |
switch ($CommandAst.GetCommandName()) { | |
'git' { | |
$gitCmd = $CommandAst.CommandElements[1].Extent | |
switch ($gitCmd.Text) { | |
'cmt' { | |
[Microsoft.PowerShell.PSConsoleReadLine]::Replace( | |
$gitCmd.StartOffset, $gitCmd.EndOffset - $gitCmd.StartOffset, 'commit' | |
) | |
} | |
} | |
} | |
} | |
} | |
# `ForwardChar` accepts the entire suggestion text when the cursor is at the end of the line. | |
# This custom binding makes `RightArrow` behave similarly - accepting the next word instead of the entire suggestion text. | |
Set-PSReadLineKeyHandler -Key RightArrow ` | |
-BriefDescription ForwardCharAndAcceptNextSuggestionWord ` | |
-LongDescription "Move cursor one character to the right in the current editing line and accept the next word in suggestion when it's at the end of current editing line" ` | |
-ScriptBlock { | |
param($key, $arg) | |
$line = $null | |
$cursor = $null | |
[Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor) | |
if ($cursor -lt $line.Length) { | |
[Microsoft.PowerShell.PSConsoleReadLine]::ForwardChar($key, $arg) | |
} else { | |
[Microsoft.PowerShell.PSConsoleReadLine]::AcceptNextSuggestionWord($key, $arg) | |
} | |
} | |
# 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 | |
# 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 | |
# on the command line. | |
Set-PSReadLineKeyHandler -Key Alt+a ` | |
-BriefDescription SelectCommandArguments ` | |
-LongDescription "Set current selection to next command argument in the command line. Use of digit argument selects argument by position" ` | |
-ScriptBlock { | |
param($key, $arg) | |
$ast = $null | |
$cursor = $null | |
[Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$ast, [ref]$null, [ref]$null, [ref]$cursor) | |
$asts = $ast.FindAll( { | |
$args[0] -is [ExpressionAst] -and | |
$args[0].Parent -is [CommandAst] -and | |
$args[0].Extent.StartOffset -ne $args[0].Parent.Extent.StartOffset | |
}, $true) | |
if ($asts.Count -eq 0) { | |
[Microsoft.PowerShell.PSConsoleReadLine]::Ding() | |
return | |
} | |
$nextAst = $null | |
if ($null -ne $arg) { | |
$nextAst = $asts[$arg - 1] | |
} else { | |
foreach ($ast in $asts) { | |
if ($ast.Extent.StartOffset -ge $cursor) { | |
$nextAst = $ast | |
break | |
} | |
} | |
if ($null -eq $nextAst) { | |
$nextAst = $asts[0] | |
} | |
} | |
$startOffsetAdjustment = 0 | |
$endOffsetAdjustment = 0 | |
if ($nextAst -is [StringConstantExpressionAst] -and | |
$nextAst.StringConstantType -ne [StringConstantType]::BareWord) { | |
$startOffsetAdjustment = 1 | |
$endOffsetAdjustment = 2 | |
} | |
[Microsoft.PowerShell.PSConsoleReadLine]::SetCursorPosition($nextAst.Extent.StartOffset + $startOffsetAdjustment) | |
[Microsoft.PowerShell.PSConsoleReadLine]::SetMark($null, $null) | |
[Microsoft.PowerShell.PSConsoleReadLine]::SelectForwardChar($null, ($nextAst.Extent.EndOffset - $nextAst.Extent.StartOffset) - $endOffsetAdjustment) | |
} | |
Set-PSReadLineOption -PredictionSource HistoryAndPlugin | |
Set-PSReadLineOption -PredictionViewStyle ListView | |
# Set-PSReadLineOption -EditMode Windows | |
# powershell completion for oh-my-posh command | |
function __oh-my-posh_debug { | |
if ($env:BASH_COMP_DEBUG_FILE) { | |
"$args" | Out-File -Append -FilePath "$env:BASH_COMP_DEBUG_FILE" | |
} | |
} | |
filter __oh-my-posh_escapeStringWithSpecialChars { | |
$_ -replace '[\s#@$;,{}()`|<>&"]|''','`$&' | |
} | |
Register-ArgumentCompleter -CommandName 'oh-my-posh' -ScriptBlock { | |
param($WordToComplete, $CommandAst, $CursorPosition) | |
# Get the current command line and convert into a string | |
$Command = $CommandAst.CommandElements | |
$Command = "$Command" | |
__oh-my-posh_debug "" | |
__oh-my-posh_debug "========= starting completion logic ==========" | |
__oh-my-posh_debug "WordToComplete: $WordToComplete Command: $Command CursorPosition: $CursorPosition" | |
# The user could have moved the cursor backwards on the command-line. | |
# We need to trigger completion from the $CursorPosition location, so we need | |
# to truncate the command-line ($Command) up to the $CursorPosition location. | |
# Make sure the $Command is longer then the $CursorPosition before we truncate. | |
# This happens because the $Command does not include the last space. | |
if ($Command.Length -gt $CursorPosition) { | |
$Command=$Command.Substring(0,$CursorPosition) | |
} | |
__oh-my-posh_debug "Truncated command: $Command" | |
$ShellCompDirectiveError=1 | |
$ShellCompDirectiveNoSpace=2 | |
$ShellCompDirectiveNoFileComp=4 | |
$ShellCompDirectiveFilterFileExt=8 | |
$ShellCompDirectiveFilterDirs=16 | |
$ShellCompDirectiveKeepOrder=32 | |
# Prepare the command to request completions for the program. | |
# Split the command at the first space to separate the program and arguments. | |
$Program,$Arguments = $Command.Split(" ",2) | |
$RequestComp="$Program __complete $Arguments" | |
__oh-my-posh_debug "RequestComp: $RequestComp" | |
# we cannot use $WordToComplete because it | |
# has the wrong values if the cursor was moved | |
# so use the last argument | |
if ($WordToComplete -ne "" ) { | |
$WordToComplete = $Arguments.Split(" ")[-1] | |
} | |
__oh-my-posh_debug "New WordToComplete: $WordToComplete" | |
# Check for flag with equal sign | |
$IsEqualFlag = ($WordToComplete -Like "--*=*" ) | |
if ( $IsEqualFlag ) { | |
__oh-my-posh_debug "Completing equal sign flag" | |
# Remove the flag part | |
$Flag,$WordToComplete = $WordToComplete.Split("=",2) | |
} | |
if ( $WordToComplete -eq "" -And ( -Not $IsEqualFlag )) { | |
# If the last parameter is complete (there is a space following it) | |
# We add an extra empty parameter so we can indicate this to the go method. | |
__oh-my-posh_debug "Adding extra empty parameter" | |
# PowerShell 7.2+ changed the way how the arguments are passed to executables, | |
# so for pre-7.2 or when Legacy argument passing is enabled we need to use | |
# `"`" to pass an empty argument, a "" or '' does not work!!! | |
if ($PSVersionTable.PsVersion -lt [version]'7.2.0' -or | |
($PSVersionTable.PsVersion -lt [version]'7.3.0' -and -not [ExperimentalFeature]::IsEnabled("PSNativeCommandArgumentPassing")) -or | |
(($PSVersionTable.PsVersion -ge [version]'7.3.0' -or [ExperimentalFeature]::IsEnabled("PSNativeCommandArgumentPassing")) -and | |
$PSNativeCommandArgumentPassing -eq 'Legacy')) { | |
$RequestComp="$RequestComp" + ' `"`"' | |
} else { | |
$RequestComp="$RequestComp" + ' ""' | |
} | |
} | |
__oh-my-posh_debug "Calling $RequestComp" | |
# First disable ActiveHelp which is not supported for Powershell | |
${env:OH_MY_POSH_ACTIVE_HELP}=0 | |
#call the command store the output in $out and redirect stderr and stdout to null | |
# $Out is an array contains each line per element | |
Invoke-Expression -OutVariable out "$RequestComp" 2>&1 | Out-Null | |
# get directive from last line | |
[int]$Directive = $Out[-1].TrimStart(':') | |
if ($Directive -eq "") { | |
# There is no directive specified | |
$Directive = 0 | |
} | |
__oh-my-posh_debug "The completion directive is: $Directive" | |
# remove directive (last element) from out | |
$Out = $Out | Where-Object { $_ -ne $Out[-1] } | |
__oh-my-posh_debug "The completions are: $Out" | |
if (($Directive -band $ShellCompDirectiveError) -ne 0 ) { | |
# Error code. No completion. | |
__oh-my-posh_debug "Received error from custom completion go code" | |
return | |
} | |
$Longest = 0 | |
[Array]$Values = $Out | ForEach-Object { | |
#Split the output in name and description | |
$Name, $Description = $_.Split("`t",2) | |
__oh-my-posh_debug "Name: $Name Description: $Description" | |
# Look for the longest completion so that we can format things nicely | |
if ($Longest -lt $Name.Length) { | |
$Longest = $Name.Length | |
} | |
# Set the description to a one space string if there is none set. | |
# This is needed because the CompletionResult does not accept an empty string as argument | |
if (-Not $Description) { | |
$Description = " " | |
} | |
@{Name="$Name";Description="$Description"} | |
} | |
$Space = " " | |
if (($Directive -band $ShellCompDirectiveNoSpace) -ne 0 ) { | |
# remove the space here | |
__oh-my-posh_debug "ShellCompDirectiveNoSpace is called" | |
$Space = "" | |
} | |
if ((($Directive -band $ShellCompDirectiveFilterFileExt) -ne 0 ) -or | |
(($Directive -band $ShellCompDirectiveFilterDirs) -ne 0 )) { | |
__oh-my-posh_debug "ShellCompDirectiveFilterFileExt ShellCompDirectiveFilterDirs are not supported" | |
# return here to prevent the completion of the extensions | |
return | |
} | |
$Values = $Values | Where-Object { | |
# filter the result | |
$_.Name -like "$WordToComplete*" | |
# Join the flag back if we have an equal sign flag | |
if ( $IsEqualFlag ) { | |
__oh-my-posh_debug "Join the equal sign flag back to the completion value" | |
$_.Name = $Flag + "=" + $_.Name | |
} | |
} | |
# we sort the values in ascending order by name if keep order isn't passed | |
if (($Directive -band $ShellCompDirectiveKeepOrder) -eq 0 ) { | |
$Values = $Values | Sort-Object -Property Name | |
} | |
if (($Directive -band $ShellCompDirectiveNoFileComp) -ne 0 ) { | |
__oh-my-posh_debug "ShellCompDirectiveNoFileComp is called" | |
if ($Values.Length -eq 0) { | |
# Just print an empty string here so the shell does not start to complete paths. | |
# We cannot use CompletionResult here because it does not accept an empty string as argument. | |
"" | |
return | |
} | |
} | |
# Get the current mode | |
$Mode = (Get-PSReadLineKeyHandler | Where-Object {$_.Key -eq "Tab" }).Function | |
__oh-my-posh_debug "Mode: $Mode" | |
$Values | ForEach-Object { | |
# store temporary because switch will overwrite $_ | |
$comp = $_ | |
# switch ($Mode) { | |
# # bash like | |
# "Complete" { | |
# if ($Values.Length -eq 1) { | |
# __oh-my-posh_debug "Only one completion left" | |
# # insert space after value | |
# [System.Management.Automation.CompletionResult]::new( | |
# $($comp.Name | __oh-my-posh_escapeStringWithSpecialChars) + $Space, | |
# "$($comp.Name)", | |
# 'ParameterValue', | |
# "$($comp.Description)" | |
# ) | |
# } else { | |
# # Add the proper number of spaces to align the descriptions | |
# while($comp.Name.Length -lt $Longest) { | |
# $comp.Name = $comp.Name + " " | |
# } | |
# # Check for empty description and only add parentheses if needed | |
# if ($($comp.Description) -eq " " ) { | |
# $Description = "" | |
# } else { | |
# $Description = " ($($comp.Description))" | |
# } | |
# [System.Management.Automation.CompletionResult]::new("$($comp.Name)$Description") | |
# } | |
# } | |
# # zsh like | |
# "MenuComplete" { | |
# # insert space after value MenuComplete will automatically show the ToolTip of | |
# # the highlighted value at the bottom of the suggestions. | |
# [System.Management.Automation.CompletionResult]::new( | |
# $($comp.Name | __oh-my-posh_escapeStringWithSpecialChars) + $Space, | |
# "$($comp.Name)", | |
# 'ParameterValue', | |
# "$($comp.Description)" | |
# ) | |
# } | |
# # TabCompleteNext and in case we get something unknown | |
# Default { | |
# # Like MenuComplete but we don't want to add a space here because | |
# # the user need to press space anyway to get the completion. | |
# # Description will not be shown because that's not possible with TabCompleteNext | |
# [System.Management.Automation.CompletionResult]::new( | |
# $($comp.Name | __oh-my-posh_escapeStringWithSpecialChars), | |
# "$($comp.Name)", | |
# 'ParameterValue', | |
# "$($comp.Description)" | |
# ) | |
# } | |
# } | |
[System.Management.Automation.CompletionResult]::new( | |
$($comp.Name | __oh-my-posh_escapeStringWithSpecialChars) + $Space, | |
"$($comp.Name)", | |
'ParameterValue', | |
"$($comp.Description)" | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment