-
-
Save aldrichtr/f987140e090eac97ec419442ce2b4fbb to your computer and use it in GitHub Desktop.
Adds escape codes to the prompt for the shell integration
This file contains hidden or 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
| # Reference: | |
| # https://devblogs.microsoft.com/commandline/shell-integration-in-the-windows-terminal/ | |
| param | |
| ( | |
| [ValidateSet('WindowsTerminal', 'ITerm2')] | |
| [String]$TerminalProgram = 'WindowsTerminal' | |
| ) | |
| # Restore hooked functions in case this script is executed accidentally twice | |
| if ($global:shellIntegrationGlobals) { | |
| $function:global:PSConsoleHostReadLine = $global:shellIntegrationGlobals.originalPSConsoleHostReadLine | |
| $function:global:Prompt = $global:shellIntegrationGlobals.originalPrompt | |
| } | |
| $global:shellIntegrationGlobals = @{ | |
| terminalProgram = $TerminalProgram | |
| originalPSConsoleHostReadLine = $function:global:PSConsoleHostReadLine | |
| originalPrompt = $function:global:Prompt | |
| lastCommand = $null | |
| getExitCode = { | |
| param ($lastCommandStatus) | |
| if ($lastCommandStatus -eq $true) { | |
| return 0 | |
| } | |
| if ($Error[0]) { | |
| $lastHistory = Get-History -Count 1 | |
| $isPowerShellError = $Error[0].InvocationInfo.HistoryId -eq $lastHistory.Id | |
| } | |
| if ($isPowerShellError) { | |
| return 1 | |
| } | |
| else { | |
| return $LastExitCode | |
| } | |
| } | |
| } | |
| $function:global:PSConsoleHostReadLine = { | |
| $commandExecuted = "`e]133;C`a" | |
| $command = $global:shellIntegrationGlobals.originalPSConsoleHostReadLine.Invoke() | |
| $commandExecuted | Write-Host -NoNewLine | |
| $command | |
| $global:shellIntegrationGlobals.lastCommand = $command | |
| } | |
| $function:global:Prompt = { | |
| $lastCommandStatus = $? | |
| if ($global:shellIntegrationGlobals.lastCommand) { | |
| $exitCode = $global:shellIntegrationGlobals.getExitCode.Invoke($lastCommandStatus) | |
| $commandFinished = "`e]133;D;$exitCode`a" | |
| } | |
| else { | |
| $commandFinished = "`e]133;D`a" | |
| } | |
| $currentLocation = $ExecutionContext.SessionState.Path.CurrentLocation.Path | |
| switch ($global:shellIntegrationGlobals.terminalProgram) { | |
| 'WindowsTerminal' { $setWorkingDirectory = "`e]9;9;`"$currentLocation`"`a" } | |
| 'ITerm2' { $setWorkingDirectory = "`e]1337;CurrentDir=$currentLocation`a" } | |
| } | |
| $promptStarted = "`e]133;A`a" | |
| $commandStarted = "`e]133;B`a" | |
| $prompt = $global:shellIntegrationGlobals.originalPrompt.Invoke() | |
| $commandFinished + $promptStarted + $setWorkingDirectory + $prompt + $commandStarted | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment