Skip to content

Instantly share code, notes, and snippets.

@mdgrs-mei
Last active May 12, 2024 03:36
Show Gist options
  • Save mdgrs-mei/1599cb07ef5bc67125ebffba9c8f1e37 to your computer and use it in GitHub Desktop.
Save mdgrs-mei/1599cb07ef5bc67125ebffba9c8f1e37 to your computer and use it in GitHub Desktop.
Adds escape codes to the prompt for the shell integration
# 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
}
@mdgrs-mei
Copy link
Author

Supported iTerm2 on macOS.

& 'PathTo/ShellIntegration.ps1' -TerminalProgram ITerm2

ITerm2ShellIntegration

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment