PowerLine.psm1
#Region '.\Private\_init.ps1' 0 #!/usr/bin/env powershell using namespace System.Management.Automation using namespace System.Collections.Generic using namespace PoshCode.Pansies # Ensure the global prompt variable exists and is typed the way we expect [System.Collections.Generic.List[PoshCode.PowerLine.Block]]$Global:Prompt = [PoshCode.PowerLine.Block[]]@( if (Test-Path Variable:Prompt) { if ($Prompt.Colors) { try { [System.Collections.Generic.List[PoshCode.Pansies.RgbColor]]$script:Colors = $Prompt.Colors } catch { Write-Warning "Couldn't use existing `$Prompt.Colors" } } $Prompt | ForEach-Object { [PoshCode.PowerLine.Block]$_ } } ) <# Add-MetadataConverter @{ PowerLineBlock = { New-PowerLineBlock @Args } [char] = { "'$_'" } [PoshCode.PowerLine.Block] = { if ($_.Object -is [PoshCode.PowerLine.Space]) { "PowerLineBlock -$($_.Object) -Separator @('$($_.Separator.Left)', '$($_.Separator.Right)') -Cap @('$($_.Cap.Left)', '$($_.Cap.Right)')" } elseif ($_.Object -is [scriptblock]) { "PowerLineBlock $("(ScriptBlock '{0}')" -f ($_.Object -replace "'", "''")) -Separator @('$($_.Separator.Left)', '$($_.Separator.Right)') -Cap @('$($_.Cap.Left)', '$($_.Cap.Right)') -ForegroundColor '$($_.ForegroundColor)' -BackgroundColor '$($_.BackgroundColor)' -ElevatedForegroundColor '$($_.ElevatedForegroundColor)' -ElevatedBackgroundColor '$($_.ElevatedBackgroundColor)' -ErrorForegroundColor '$($_.ErrorForegroundColor)' -ErrorBackgroundColor '$($_ErrorBackgroundColor)'" } else { "PowerLineBlock $(ConvertTo-Metadata $_.Object) -Separator @('$($_.Separator.Left)', '$($_.Separator.Right)') -Cap @('$($_.Cap.Left)', '$($_.Cap.Right)') -ForegroundColor '$($_.ForegroundColor)' -BackgroundColor '$($_.BackgroundColor)' -ElevatedForegroundColor '$($_.ElevatedForegroundColor)' -ElevatedBackgroundColor '$($_.ElevatedBackgroundColor)' -ErrorForegroundColor '$($_.ErrorForegroundColor)' -ErrorBackgroundColor '$($_ErrorBackgroundColor)'" } } } #> #EndRegion '.\Private\_init.ps1' 36 #Region '.\Private\SyncColor.ps1' 0 function SyncColor { <# .SYNOPSIS Synchonize the Script:Colors and Gobal:Prompt.Colors #> [CmdletBinding()] param( [System.Collections.Generic.List[PoshCode.Pansies.RgbColor]]$Colors, [switch]$Passthru ) [System.Collections.Generic.List[PoshCode.Pansies.RgbColor]]$script:Colors = # If you pass in colors, those win if ($PSBoundParameters.ContainsKey("Colors")){ $Colors # If the prompt colors are set, those win (because they're user-settable) } elseif($global:Prompt.Colors) { $global:Prompt.Colors # Otherwise, if the script colors are set (they're our cache), use those } elseif ($script:Colors) { $script:Colors } else { # Finally, here's some fallback colors "Cyan","DarkCyan","Gray","DarkGray","Gray" } if ($Passthru) { $script:Colors } # Update Prompt.Colors if (!(Get-Member -InputObject $Global:Prompt -Name Colors)) { Add-Member -InputObject $Global:Prompt -MemberType NoteProperty -Name Colors -Value $script:Colors } else { $Global:Prompt.Colors = $script:Colors } } #EndRegion '.\Private\SyncColor.ps1' 39 #Region '.\Private\WriteExceptions.ps1' 0 function WriteExceptions { [CmdletBinding()] param( # A dictionary mapping script blocks to the exceptions which threw them [System.Collections.Specialized.OrderedDictionary]$ScriptExceptions ) $ErrorString = "" if($PromptErrors.Count -gt 0) { $global:PromptErrors = [ordered]@{} + $ScriptExceptions Write-Warning "Exception thrown from prompt block. Check `$PromptErrors. To suppress this message, Set-PowerLine -HideError" #$PromptErrors.Insert(0, "0 Preview","Exception thrown from prompt block. Check `$PromptErrors:`n") if(@($Host.PrivateData.PSTypeNames)[0] -eq "Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy") { foreach($e in $ScriptExceptions.Values) { $ErrorString += [PoshCode.Pansies.Text]@{ ForegroundColor = $Host.PrivateData.ErrorForegroundColor BackgroundColor = $Host.PrivateData.ErrorBackgroundColor Object = $e } $ErrorString += "`n" } } else { foreach($e in $ScriptExceptions) { $ErrorString += [PoshCode.Pansies.Text]@{ ForegroundColor = "Red" BackgroundColor = "Black" Object = $e } $ErrorString += "`n" } } } $ErrorString } #EndRegion '.\Private\WriteExceptions.ps1' 36 #Region '.\Public\Add-PowerLineBlock.ps1' 0 function Add-PowerLineBlock { <# .Synopsis Insert text or a ScriptBlock into the $Prompt .Description This function exists primarily to ensure that modules are able to modify the prompt easily without repeating themselves. .Example Add-PowerLineBlock { "`nI ♥ PS" } Adds the classic "I ♥ PS" to your prompt on a new line. We actually recommend having a simple line in pure 16-color mode on the last line of your prompt, to ensures that PSReadLine won't mess up your colors. PSReadline overwrites your prompt line when you type -- and it can only handle 16 color mode. .Example Add-PowerLineBlock { New-PromptText { Get-Elapsed } -ForegroundColor White -BackgroundColor DarkBlue -ErrorBackground DarkRed -ElevatedForegroundColor Yellow } -Index -2 # This example uses Add-PowerLineBlock to insert a block into the prommpt _before_ the last block # It calls Get-Elapsed to show the duration of the last command as the text of the block # It uses New-PromptText to control the color so that it's highlighted in red if there is an error, but otherwise in dark blue (or yellow if it's an elevated host). #> [CmdletBinding(DefaultParameterSetName="InputObject")] param( # The text, object, or scriptblock to show as output [Parameter(Position=0, Mandatory, ValueFromPipeline, ParameterSetName = "InputObject")] [Alias("Text")] $InputObject, # The position to insert the InputObject at, by default, inserts in the same place as the last one [int]$Index = -1, # When set by a module, hooks the calling module to remove this block if the module is removed [Switch]$AutoRemove, # If set, adds the input to the prompt without checking if it's already there [Switch]$Force, # Add a line break to the prompt (the next block will start a new line) [Parameter(Mandatory, ParameterSetName = "Newline")] [Switch]$Newline, # Add a column break to the prompt (the next block will be right-aligned) [Parameter(Mandatory, ParameterSetName = "RightAlign")] [Switch]$RightAlign, # Add a zero-width space to the prompt (creates a gap between blocks) [Parameter(Mandatory, ParameterSetName = "Spacer")] [Switch]$Spacer ) process { if ($Newline) { $InputObject = { "`n" } } elseif ($RightAlign){ $InputObject = { "`t" } } elseif ($Spacer){ $InputObject = { " " } } $InputObject = switch ($InputObject) { "Azure" { { "ﴃ " + (Get-AzContext).Name } } default { $InputObject } } Write-Debug "Add-PowerLineBlock $InputObject" if(!$PSBoundParameters.ContainsKey("Index")) { $Index = $Script:PowerLineConfig.DefaultAddIndex++ } $Skip = @($Global:Prompt).ForEach{$_.ToString().Trim()} -eq $InputObject.ToString().Trim() if($Force -or !$Skip) { if($Index -eq -1 -or $Index -ge $Global:Prompt.Count) { Write-Verbose "Appending '$InputObject' to the end of the prompt" $Global:Prompt.Add($InputObject) $Index = $Global:Prompt.Count } elseif($Index -lt 0) { $Index = $Global:Prompt.Count - $Index Write-Verbose "Inserting '$InputObject' at $Index of the prompt" $Global:Prompt.Insert($Index, $InputObject) } else { Write-Verbose "Inserting '$InputObject' at $Index of the prompt" $Global:Prompt.Insert($Index, $InputObject) } $Script:PowerLineConfig.DefaultAddIndex = $Index + 1 } else { Write-Verbose "Prompt already contained the InputObject block" } if($AutoRemove) { if(($CallStack = Get-PSCallStack).Count -ge 2) { if($Module = $CallStack[1].InvocationInfo.MyCommand.Module) { $Module.OnRemove = { Remove-PowerLineBlock $InputObject }.GetNewClosure() } } } } } #EndRegion '.\Public\Add-PowerLineBlock.ps1' 100 #Region '.\Public\Export-PowerLinePrompt.ps1' 0 function Export-PowerLinePrompt { [CmdletBinding()] param() $Local:Configuration = $Script:PowerLineConfig $Configuration.Prompt = [ScriptBlock[]]$global:Prompt $Configuration.Colors = [PoshCode.Pansies.RgbColor[]]$global:Prompt.Colors @{ ExtendedCharacters = [PoshCode.Pansies.Entities]::ExtendedCharacters EscapeSequences = [PoshCode.Pansies.Entities]::EscapeSequences PowerLineConfig = $Script:PowerLineConfig } | Export-Configuration -AsHashtable } #EndRegion '.\Public\Export-PowerLinePrompt.ps1' 15 #Region '.\Public\Get-Elapsed.ps1' 0 function Get-Elapsed { <# .Synopsis Get the time span elapsed during the execution of command (by default the previous command) .Description Calls Get-History to return a single command and returns the difference between the Start and End execution time #> [OutputType([string])] [CmdletBinding()] param( # The command ID to get the execution time for (defaults to the previous command) [Parameter()] [int]$Id, # A Timespan format pattern such as "{0:ss\.fff}" [Parameter(ParameterSetName = 'SimpleFormat')] [string]$Format = "{0:d\d\ h\:mm\:ss\.fff}", # Automatically use different formats depending on the duration [Parameter(ParameterSetName = 'AutoFormat')] [switch]$Trim ) $null = $PSBoundParameters.Remove("Format") $null = $PSBoundParameters.Remove("Trim") $LastCommand = Get-History -Count 1 @PSBoundParameters if(!$LastCommand) { return "" } $Duration = $LastCommand.EndExecutionTime - $LastCommand.StartExecutionTime $Result = $Format -f $Duration if ($Trim) { if ($Duration.Days -ne 0) { "{0:d\d\ h\:mm}" -f $Duration } elseif ($Duration.Hours -ne 0) { "{0:h\:mm\:ss}" -f $Duration } elseif ($Duration.Minutes -ne 0) { "{0:m\:ss\.fff}" -f $Duration } elseif ($Duration.Seconds -ne 0) { "{0:s\.fff\s}" -f $Duration } elseif ($Duration.Milliseconds -gt 10) { ("{0:fff\m\s}" -f $Duration).Trim("0") } else { ("{0:ffffff\μ\s}" -f $Duration).Trim("0") } } else { $Result } } #EndRegion '.\Public\Get-Elapsed.ps1' 47 #Region '.\Public\Get-ErrorCount.ps1' 0 function Get-ErrorCount { <# .Synopsis Get a count of new errors from previous command .Description Detects new errors generated by previous command based on tracking last seen count of errors. MUST NOT be run inside New-PromptText. #> [CmdletBinding()] param() $global:Error.Count - $script:LastErrorCount $script:LastErrorCount = $global:Error.Count } #EndRegion '.\Public\Get-ErrorCount.ps1' 15 #Region '.\Public\Get-PowerLineTheme.ps1' 0 function Get-PowerLineTheme { <# .SYNOPSIS Get the themeable PowerLine settings #> [CmdletBinding()] param() $Local:Configuration = $Script:PowerLineConfig $Configuration.Prompt = [PoshCode.PowerLine.Block[]]$global:Prompt $Configuration.Colors = [PoshCode.Pansies.RgbColor[]]$global:Prompt.Colors $null = $Configuration.Remove("DefaultAddIndex") $Configuration.PowerLineCharacters = @{ 'ColorSeparator' = [PoshCode.Pansies.Entities]::ExtendedCharacters['ColorSeparator'] 'ReverseColorSeparator' = [PoshCode.Pansies.Entities]::ExtendedCharacters['ReverseColorSeparator'] 'Separator' = [PoshCode.Pansies.Entities]::ExtendedCharacters['Separator'] 'ReverseSeparator' = [PoshCode.Pansies.Entities]::ExtendedCharacters['ReverseSeparator'] } if (Get-Command Get-PSReadLineOption) { $PSReadLineOptions = Get-PSReadLineOption # PromptText and ContinuationPrompt can have colors in them $Configuration.PSReadLinePromptText = $PSReadLineOptions.PromptText $Configuration.PSReadLineContinuationPrompt = $PSReadLineOptions.ContinuationPrompt # If the ContinuationPrompt has color in it, this is irrelevant, but keep it anyway $Configuration.PSReadLineContinuationPromptColor = $PSReadLineOptions.ContinuationPromptColor } $Result = New-Object PSObject -Property $Configuration $Result.PSTypeNames.Insert(0, "PowerLine.Theme") $Result } #EndRegion '.\Public\Get-PowerLineTheme.ps1' 35 #Region '.\Public\Get-ShortPath.ps1' 0 function Get-ShortPath { <# .SYNOPSIS Get a shortened version of a path for human readability .DESCRIPTION Trims the length of the path using various techniques #> [CmdletBinding(DefaultParameterSetName = "Length")] param( # The path to shorten (by default, the present working directory: $pwd) [Parameter(Position=0)] [string]$Path = $pwd, # Optionally, a strict maximum length of path to display # Path will be truncated to ensure it's shorter [Parameter(Position = 1)] [int]$Length = [int]::MaxValue, # Optionally, a strict maximum number of levels of path to display # Path will be truncated to ensure it's shorter [Parameter()] [int]$Depth = [int]::MaxValue, # Show the drive name on the front. Does not count toward length [switch]$DriveName, # A character to use for $Home. Defaults to "~" # You can use "&House;" to get 🏠 if you have Pansies set to EnableEmoji! # NOTE: this is based on the provider. # By default, only the FileSystem provider has a Home, but you can set them! [string]$HomeString, # Only shows the path down to the root of git projects [switch]$GitDir, # Show only the first letter for all directories except the last one [Parameter()] [switch]$SingleLetterPath, # Show the first letter instead of truncating [Parameter()] [switch]$LeftoversAsOneLetter, # [switch]$ToRepo, # Optionally, turn it into a hyperlink to the full path. # In Windows Terminal, for instance, this makes it show the full path on hover, and open your file manager on ctrl+click [Parameter()] [switch]$AsUrl, # A decorative replacement for the path separator. Defaults to DirectorySeparatorChar [ArgumentCompleter({ [System.Collections.Generic.List[System.Management.Automation.CompletionResult]]::new( [System.Management.Automation.CompletionResult[]]@( # The Consolas-friendly block characters ▌and▐ and ╲ followed by all the extended powerline cahracters @([string[]][char[]]@(@(0xe0b0..0xe0d4) + @(0x2588..0x259b) + @(0x256d..0x2572) + @('\','/'))).ForEach({ [System.Management.Automation.CompletionResult]::new("'$_'", $_, "ParameterValue", $_) }) )) })] [string]$Separator ) # If user passes 0 (or less), I just refuse to deal with it if ($Length -le 0 -or $Depth -le 0) { return [string]::Empty } $OriginalPath = $Path $resolved = Resolve-Path $Path $provider = $resolved.Provider if (!$Separator) { $Separator = $provider.ItemSeparator } $Drive = $resolved.Drive.Name + ":" $Path = $resolved.Path $BaseHome = $Provider.Home Write-Verbose "ProviderHome: $BaseHome" if ($GitDir -and (Get-Command git)) { Push-Location $OriginalPath $toplevel = git rev-parse --show-toplevel 2>$null | Convert-Path Write-Verbose "GitDir: $TopLevel" Write-Verbose "Path: $Path" if (!$LASTEXITCODE -and $Path.StartsWith($TopLevel, "OrdinalIgnoreCase")) { $Path = $Path.SubString($TopLevel.Length) # If we're in a gitdir, we insist on showing it (using driveName logic) $Drive = Split-Path $TopLevel -Leaf $DriveName = $true $Depth = $Depth - 1 Write-Verbose "Full: $Path" } Pop-Location } if ($Path) { if ($HomeString -and $BaseHome -and $Path.StartsWith($BaseHome, "OrdinalIgnoreCase")) { # If we're in $HOME, we insist on showing it (using driveName logic) $Drive = '' $DriveName = $false $Path = $HomeString + $Path.Substring($Home.Length) } else { $Path = Split-Path $Path -NoQualifier } # Trust the provider's separator [PoshCode.Pansies.Text]$Path = $Path.Trim($provider.ItemSeparator) $Pattern = [regex]::Escape($provider.ItemSeparator) if ($SingleLetterPath) { # Remove prefix for UNC paths $Path = $Path -replace '^[^:]+::', '' $Folders = $Path -split $Pattern if ($Folders.Length -gt 1) { # Supports emoji $Folders = $Folders[0..($Folders.Count-2)].ForEach{ [System.Text.Rune]::GetRuneAt($_,0).ToString() } + @($Folders[-1]) } $Path = $Folders -join $Separator } else { $Folders = $Path -split $Pattern } $Ellipsis = [char]0x2026 if ($Path.Length -gt $Length -or $Folders.Length -gt $Depth) { [Array]::Reverse($Folders) # Start the path with just the last folder $Path, $Folders = $Folders $PathDepth = 1 # If just the last folder is too long, truncate it if ("$Path".Length + 2 -gt $Length) { Write-Verbose "$Path ($("$Path".Length) - $Length)" $Path = $Ellipsis + "$Path".Substring("$Path".Length - $Length + 1) if ($LeftoversAsOneLetter) { $Folders = $Folders.ForEach{ [System.Text.Rune]::GetRuneAt($_,0).ToString() } $Length = [int]::MaxValue } else { $Folders = @() } } while ($Folders) { $Folder, $Folders = $Folders if ($Length -gt ("$Path".Length + $Folder.Length + 3) -and $Depth -gt $PathDepth) { $Path = $Folder + $Separator + $Path } elseif ($LeftoversAsOneLetter) { # Put back the $Folder as well $Folders = @(@($Folder) + $Folders).ForEach{ [System.Text.Rune]::GetRuneAt($_,0).ToString() } + @($Drive.Trim($provider.ItemSeparator, $Separator)) $Depth = $Length = [int]::MaxValue $DriveName = $False } else { $Path = $Ellipsis + $Separator + $Path break } $PathDepth++ } } else { $Path = $Path -replace $Pattern, $Separator } } if ($DriveName) { if ($Path) { $Path = $Drive + $Separator + $Path } else { $Path = $Drive } } if ($AsUrl) { $8 = "$([char]27)]8;;" "$8{0}`a{1}$8`a" -f $OriginalPath, $Path } else { "$Path" } } #EndRegion '.\Public\Get-ShortPath.ps1' 180 #Region '.\Public\New-PromptText.ps1' 0 function New-PromptText { <# .Synopsis Create PoshCode.PowerLine.Block with variable background colors .Description Allows changing the foreground and background colors based on elevation or success. Tests elevation fist, and then whether the last command was successful, so if you pass separate colors for each, the Elevated*Color will be used when PowerShell is running as administrator and there is no error. The Error*Color will be used whenever there's an error, whether it's elevated or not. .Example New-PromptText { Get-Elapsed } -ForegroundColor White -BackgroundColor DarkBlue -ErrorBackground DarkRed -ElevatedForegroundColor Yellow This example shows the time elapsed executing the last command in White on a DarkBlue background, but switches the text to yellow if elevated, and the background to red on error. #> [CmdletBinding(DefaultParameterSetName = "InputObject")] [Alias("New-PowerLineBlock", "PowerLineBlock", "Block", "New-TextFactory")] param( # The text, object, or scriptblock to show as output [Alias("Text", "Object")] [AllowNull()][EmptyStringAsNull()] [Parameter(Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = "InputObject")] # , Mandatory=$true $InputObject, # Add a line break to the prompt (the next block will start a new line) [Parameter(Mandatory, ParameterSetName = "Newline")] [Switch]$Newline, # Add a column break to the prompt (the next block will be right-aligned) [Parameter(Mandatory, ParameterSetName = "RightAlign")] [Switch]$RightAlign, # Add a zero-width space to the prompt (creates a gap between blocks) [Parameter(Mandatory, ParameterSetName = "Spacer")] [Switch]$Spacer, # The separator character(s) are used between blocks of output by this scriptblock # Pass two characters: the first for normal (Left aligned) blocks, the second for right-aligned blocks [ArgumentCompleter({ [System.Collections.Generic.List[System.Management.Automation.CompletionResult]]::new( [System.Management.Automation.CompletionResult[]]@( # The Consolas-friendly block characters ▌and▐ and ╲ followed by all the extended powerline cahracters @([string[]][char[]]@(@(0xe0b0..0xe0d4) + @(0x2588..0x259b) + @(0x256d..0x2572))).ForEach({ [System.Management.Automation.CompletionResult]::new("'$_'", $_, "ParameterValue", $_) }) )) })] [char[]]$Separator, # The cap character(s) are used on the ends of blocks of output # Pass two characters: the first for normal (Left aligned) blocks, the second for right-aligned blocks [ArgumentCompleter({ [System.Collections.Generic.List[System.Management.Automation.CompletionResult]]::new( [System.Management.Automation.CompletionResult[]]@( # The Consolas-friendly block characters ▌and▐ and ╲ followed by all the extended powerline cahracters @([string[]][char[]]@(@(0xe0b0..0xe0d4) + @(0x2588..0x259b) + @(0x256d..0x2572))).ForEach({ [System.Management.Automation.CompletionResult]::new("'$_'", $_, "ParameterValue", $_) }) )) })] [char[]]$Cap, # The foreground color to use when the last command succeeded [Alias("Foreground", "Fg")] [Parameter(ValueFromPipelineByPropertyName)] [AllowNull()][EmptyStringAsNull()] [PoshCode.Pansies.RgbColor]$ForegroundColor, # The background color to use when the last command succeeded [Alias("Background", "Bg")] [Parameter(ValueFromPipelineByPropertyName)] [AllowNull()][EmptyStringAsNull()] [PoshCode.Pansies.RgbColor]$BackgroundColor, # The foreground color to use when the process is elevated (running as administrator) [Alias("AFg")] [Parameter(ValueFromPipelineByPropertyName)] [AllowNull()][EmptyStringAsNull()] [PoshCode.Pansies.RgbColor]$ElevatedForegroundColor, # The background color to use when the process is elevated (running as administrator) [Alias("ABg")] [Parameter(ValueFromPipelineByPropertyName)] [AllowNull()][EmptyStringAsNull()] [PoshCode.Pansies.RgbColor]$ElevatedBackgroundColor, # The foreground color to use when the last command failed [Alias("EFg")] [Parameter(ValueFromPipelineByPropertyName)] [AllowNull()][EmptyStringAsNull()] [PoshCode.Pansies.RgbColor]$ErrorForegroundColor, # The background color to use when the last command failed [Alias("EBg")] [Parameter(ValueFromPipelineByPropertyName)] [AllowNull()][EmptyStringAsNull()] [PoshCode.Pansies.RgbColor]$ErrorBackgroundColor ) process { if ($Newline -or "`n" -eq $InputObject) { $InputObject = [PoshCode.PowerLine.Space]::NewLine $null = $PSBoundParameters.Remove("Newline") } elseif ($RightAlign -or "`t" -eq $InputObject) { $InputObject = [PoshCode.PowerLine.Space]::RightAlign $null = $PSBoundParameters.Remove("RightAlign") } elseif ($Spacer -or " " -eq $InputObject) { $InputObject = [PoshCode.PowerLine.Space]::Spacer $null = $PSBoundParameters.Remove("Spacer") # Work around parameter binding } elseif ($InputObject.InputObject) { $InputObject = $InputObject.InputObject } elseif ($InputObject.Object) { $InputObject = $InputObject.Object }elseif ($InputObject.Text) { $InputObject = $InputObject.Text } $PSBoundParameters["InputObject"] = $InputObject [PoshCode.PowerLine.Block]$PSBoundParameters } } #EndRegion '.\Public\New-PromptText.ps1' 118 #Region '.\Public\Remove-PowerLineBlock.ps1' 0 function Remove-PowerLineBlock { <# .Synopsis Remove text or a ScriptBlock from the $Prompt .Description This function exists primarily to ensure that modules are able to clean up the prompt easily when they're removed .Example Remove-PowerLineBlock { New-PromptText { Get-Elapsed } -ForegroundColor White -BackgroundColor DarkBlue -ErrorBackground DarkRed -ElevatedForegroundColor Yellow } Removes the specified block. Note that it must be _exactly_ the same as when you added it. #> [CmdletBinding(DefaultParameterSetName="Error")] param( # The text, object, or scriptblock to show as output [Parameter(Position=0, Mandatory, ValueFromPipeline)] [Alias("Text")] $InputObject ) process { $Index = @($Global:Prompt).ForEach{$_.ToString().Trim()}.IndexOf($InputObject.ToString().Trim()) if($Index -ge 0) { $null = $Global:Prompt.RemoveAt($Index) } if($Index -lt $Script:PowerLineConfig.DefaultAddIndex) { $Script:PowerLineConfig.DefaultAddIndex-- } } } #EndRegion '.\Public\Remove-PowerLineBlock.ps1' 32 #Region '.\Public\Set-PowerLinePrompt.ps1' 0 function Set-PowerLinePrompt { #.Synopsis # Set the default PowerLine prompt function which uses the $Prompt variable #.Description # Overwrites the current prompt function with one that uses the $Prompt variable # Note that this doesn't try to preserve any changes already made to the prompt by modules like ZLocation #.Example # Set-PowerLinePrompt -SetCurrentDirectory # # Sets the powerline prompt and activates and option supported by this prompt function to update the .Net environment with the current directory each time the prompt runs. #.Example # Set-PowerLinePrompt -PowerLineFont # # Sets the powerline prompt using the actual PowerLine font characters, and ensuring that we're using the default characters. Note that you can still change the characters used to separate blocks in the PowerLine output after running this, by setting the static members of [PowerLine.Prompt] like Separator and ColorSeparator... #.Example # Set-PowerLinePrompt -ResetSeparators # # Sets the powerline prompt and forces the use of "safe" separator characters. You can still change the characters used to separate blocks in the PowerLine output after running this, by setting the static members of [PowerLine.Prompt] like Separator and ColorSeparator... #.Example # Set-PowerLinePrompt -FullColor # # Sets the powerline prompt and forces the assumption of full RGB color support instead of 16 color [Alias("Set-PowerLineTheme")] [CmdletBinding(DefaultParameterSetName = "PowerLine")] param( # A script which outputs a string used to update the Window Title each time the prompt is run [Parameter(ValueFromPipelineByPropertyName)] [scriptblock]$Title, # Keep the .Net Current Directory in sync with PowerShell's [Parameter(ValueFromPipelineByPropertyName)] [Alias("CurrentDirectory")] [switch]$SetCurrentDirectory, # If true, set the [PowerLine.Prompt] static members to extended characters from PowerLine fonts [Parameter(ParameterSetName = "PowerLine", ValueFromPipelineByPropertyName)] [switch]$PowerLineFont, # If true, set the [PowerLine.Prompt] static members to characters available in Consolas and Courier New [Parameter(ParameterSetName = "Reset")] [switch]$ResetSeparators, # If true, assume full color support, otherwise normalize to 16 ConsoleColor [Parameter(ValueFromPipelineByPropertyName)] [switch]$FullColor, # If true, adds ENABLE_VIRTUAL_TERMINAL_PROCESSING to the console output mode. Useful on PowerShell versions that don't restore the console [Parameter(ValueFromPipelineByPropertyName)] [switch]$RestoreVirtualTerminal, # Add a "I ♥ PS" on a line by itself to it's prompt (using ConsoleColors, to keep it safe from PSReadLine) [Parameter(ValueFromPipelineByPropertyName)] [switch]$Newline, # Add a right-aligned timestamp before the newline (implies Newline) [Parameter(ValueFromPipelineByPropertyName)] [switch]$Timestamp, # Prevent errors in the prompt from being shown (like the normal PowerShell behavior) [Parameter(ValueFromPipelineByPropertyName)] [switch]$HideErrors, # One or more scriptblocks you want to use as your new prompt [Parameter(Position = 0, ValueFromPipelineByPropertyName)] [System.Collections.Generic.List[PoshCode.PowerLine.Block]]$Prompt, # One or more colors you want to use as the prompt background [Parameter(Position = 1, ValueFromPipelineByPropertyName)] [System.Collections.Generic.List[PoshCode.Pansies.RgbColor]]$Colors, # If set, calls Export-PowerLinePrompt [Parameter()] [Switch]$Save, # A hashtable of extended characters you can use in PowerLine output (or any PANSIES output) with HTML entity syntax like "♥". By default you have the HTML named entities plus the Branch (), Lock (), Gear (⛯) and Power (⚡) icons. You can add any characters you wish, but to change the Powerline theme, you need to specify these four keys using matching pairs: # # @{ # "ColorSeparator" = "" # "ReverseColorSeparator" = "" # "Separator" = "" # "ReverseSeparator" = "" # } [Parameter(ValueFromPipelineByPropertyName)] [Alias("ExtendedCharacters")] [hashtable]$PowerLineCharacters, # When there's a parse error, PSReadLine changes a part of the prompt red, but it assumes the default prompt is just foreground color # You can use this option to override the character, OR to specify BOTH the normal and error strings. # If you specify two strings, they should both be the same length (ignoring escape sequences) [Parameter(ValueFromPipelineByPropertyName)] [string[]]$PSReadLinePromptText, # When you type a command that requires a second line (like if you type | and hit enter) # This is the prompt text. Can be an empty string. Can be anything, really. [Parameter(ValueFromPipelineByPropertyName)] [AllowEmptyString()] [string]$PSReadLineContinuationPrompt, [Parameter(ValueFromPipelineByPropertyName)] [AllowEmptyString()] [string]$PSReadLineContinuationPromptColor, # By default PowerLine caches output based on the prompt's history id # That makes if *very* fase if you hit ENTER or Ctrl+C or Ctrl+L repeatedly # But if you print the time, it wouldn't change, so you can disable that here [switch]$NoCache ) process { if ($null -eq $script:OldPrompt) { $script:OldPrompt = $function:global:prompt $MyInvocation.MyCommand.Module.OnRemove = { $function:global:prompt = $script:OldPrompt } } # These switches aren't stored in the config $null = $PSBoundParameters.Remove("Save") $null = $PSBoundParameters.Remove("Newline") $null = $PSBoundParameters.Remove("Timestamp") $Configuration = Import-Configuration # Upodate the saved PowerLinePrompt with the parameters if(!$Configuration.PowerLineConfig) { $Configuration.PowerLineConfig = @{} } $PowerLineConfig = $Configuration.PowerLineConfig | Update-Object $PSBoundParameters if($Configuration.ExtendedCharacters) { foreach($key in $Configuration.ExtendedCharacters.Keys) { [PoshCode.Pansies.Entities]::ExtendedCharacters.$key = $Configuration.ExtendedCharacters.$key } } if($Configuration.EscapeSequences) { foreach($key in $Configuration.EscapeSequences.Keys) { [PoshCode.Pansies.Entities]::EscapeSequences.$key = $Configuration.EscapeSequences.$key } } if ($Null -eq $PowerLineConfig.FullColor -and $Host.UI.SupportsVirtualTerminal) { $PowerLineConfig.FullColor = (Get-Process -Id $global:Pid).MainWindowHandle -ne 0 } # For Prompt and Colors we want to support modifying the global variable outside this function if($PSBoundParameters.ContainsKey("Prompt")) { [System.Collections.Generic.List[PoshCode.PowerLine.Block]]$global:Prompt = $Local:Prompt } elseif($global:Prompt.Count -eq 0 -and $PowerLineConfig.Prompt.Count -gt 0) { [System.Collections.Generic.List[PoshCode.PowerLine.Block]]$global:Prompt = [PoshCode.PowerLine.Block[]][ScriptBlock[]]@($PowerLineConfig.Prompt) } elseif($global:Prompt.Count -eq 0) { # The default PowerLine Prompt [ScriptBlock[]]$PowerLineConfig.Prompt = { $MyInvocation.HistoryId }, { Get-ShortPath -HomeString "~" -Depth 3 } [System.Collections.Generic.List[PoshCode.PowerLine.Block]]$global:Prompt = [PoshCode.PowerLine.Block[]]$PowerLineConfig.Prompt } # If they passed in colors, update everything if ($PSBoundParameters.ContainsKey("Colors")) { SyncColor $Colors # Otherwise, if we haven't cached the colors, and there's configured colors, use those } elseif (!$global:Prompt.Colors -and !$Script:Colors -and $PowerLineConfig.Colors) { SyncColor $PowerLineConfig.Colors } if ($ResetSeparators -or ($PSBoundParameters.ContainsKey("PowerLineFont") -and !$PowerLineFont) ) { # Use characters that at least work in Consolas and Lucida Console [PoshCode.Pansies.Entities]::ExtendedCharacters['ColorSeparator'] = [char]0x258C [PoshCode.Pansies.Entities]::ExtendedCharacters['ReverseColorSeparator'] = [char]0x2590 [PoshCode.Pansies.Entities]::ExtendedCharacters['Separator'] = [char]0x25BA [PoshCode.Pansies.Entities]::ExtendedCharacters['ReverseSeparator'] = [char]0x25C4 [PoshCode.Pansies.Entities]::ExtendedCharacters['Branch'] = [char]0x00A7 [PoshCode.Pansies.Entities]::ExtendedCharacters['Gear'] = [char]0x263C } if ($PowerLineFont) { # Make sure we're using the PowerLine custom use extended characters: [PoshCode.Pansies.Entities]::ExtendedCharacters['ColorSeparator'] = [char]0xe0b0 [PoshCode.Pansies.Entities]::ExtendedCharacters['ReverseColorSeparator'] = [char]0xe0b2 [PoshCode.Pansies.Entities]::ExtendedCharacters['Separator'] = [char]0xe0b1 [PoshCode.Pansies.Entities]::ExtendedCharacters['ReverseSeparator'] = [char]0xe0b3 [PoshCode.Pansies.Entities]::ExtendedCharacters['Branch'] = [char]0xE0A0 [PoshCode.Pansies.Entities]::ExtendedCharacters['Gear'] = [char]0x26EF } if ($PowerLineCharacters) { foreach ($key in $PowerLineCharacters.Keys) { [PoshCode.Pansies.Entities]::ExtendedCharacters["$key"] = $PowerLineCharacters[$key].ToString() } } if($null -eq $PowerLineConfig.DefaultAddIndex) { $PowerLineConfig.DefaultAddIndex = -1 } $Script:PowerLineConfig = $PowerLineConfig if($Newline -or $Timestamp) { $Script:PowerLineConfig.DefaultAddIndex = $global:Prompt.Count @( if($Timestamp) { { "`t" } { Get-Elapsed } { Get-Date -format "T" } } { "`n" } { New-PromptText { "I $(New-PromptText -Fg Red3 -EFg White "♥$([char]27)[30m") PS" } -Bg White -EBg Red3 -Fg Black } ) | Add-PowerLineBlock if (Get-Module PSReadLine) { if ($PSBoundParameters.ContainsKey("PSReadLinePromptText")) { Set-PSReadLineOption -PromptText $PSReadLinePromptText } else { Set-PSReadLineOption -PromptText @( New-PromptText -Fg Black -Bg White "I ${Fg:Red3}♥${Fg:Black} PS${Fg:White}${Bg:Clear}&ColorSeparator;" New-PromptText -Bg Red3 -Fg White "I ${Fg:White}♥${Fg:White} PS${Fg:Red3}${Bg:Clear}&ColorSeparator;" ) } } $Script:PowerLineConfig.DefaultAddIndex = @($Global:Prompt).ForEach{ $_.ToString().Trim() }.IndexOf('"`t"') } elseif ($PSBoundParameters.ContainsKey("Prompt")) { $Script:PowerLineConfig.DefaultAddIndex = -1 } if (Get-Module PSReadLine) { $Options = @{} if ($PSBoundParameters.ContainsKey("PSReadLinePromptText")) { $Options["PromptText"] = $PSReadLinePromptText } if ($PSBoundParameters.ContainsKey("PSReadLineContinuationPrompt")) { $Options["ContinuationPrompt"] = $PSReadLineContinuationPrompt } if ($PSBoundParameters.ContainsKey("PSReadLineContinuationPromptColor")) { $Options["Colors"] = @{ ContinuationPrompt = $PSReadLineContinuationPromptColor } } if ($Options) { Set-PSReadLineOption @Options } } # Finally, update the prompt function $function:global:prompt = { Write-PowerlinePrompt } [PoshCode.Pansies.RgbColor]::ResetConsolePalette() # If they asked us to save, or if there's nothing saved yet if($Save -or ($PSBoundParameters.Count -and !(Test-Path (Join-Path (Get-StoragePath) Configuration.psd1)))) { Export-PowerLinePrompt } } } #EndRegion '.\Public\Set-PowerLinePrompt.ps1' 254 #Region '.\Public\Test-Elevation.ps1' 0 function Test-Elevation { <# .Synopsis Get a value indicating whether the process is elevated (running as administrator or root) #> [CmdletBinding()] param() [PoshCode.PowerLine.State]::Elevated } #EndRegion '.\Public\Test-Elevation.ps1' 10 #Region '.\Public\Test-Success.ps1' 0 function Test-Success { <# .Synopsis Get a value indicating whether the last command succeeded or not #> [CmdletBinding()] param() [PoshCode.PowerLine.State]::LastSuccess } #EndRegion '.\Public\Test-Success.ps1' 10 #Region '.\Public\Write-PowerlinePrompt.ps1' 0 function Write-PowerlinePrompt { [CmdletBinding()] [OutputType([string])] param() try { # FIRST, make a note if there was an error in the previous command [PoshCode.PowerLine.State]::LastSuccess = $? $PromptErrors = [ordered]@{} # When someone sets $Prompt, they loose the colors. # To fix that, we cache the colors whenever we get a chance # And if it's not set, we re-initialize from the cache SyncColor # Then handle PowerLinePrompt Features: if ($Script:PowerLineConfig.Title) { try { $Host.UI.RawUI.WindowTitle = [System.Management.Automation.LanguagePrimitives]::ConvertTo( (& $Script:PowerLineConfig.Title), [string] ) } catch { $PromptErrors.Add("0 {$($Script:PowerLineConfig.Title)}", $_) Write-Error "Failed to set Title from scriptblock { $($Script:PowerLineConfig.Title) }" } } if ($Script:PowerLineConfig.SetCurrentDirectory) { try { # Make sure Windows & .Net know where we are # They can only handle the FileSystem, and not in .Net Core [System.IO.Directory]::SetCurrentDirectory( (Get-Location -PSProvider FileSystem).ProviderPath ) } catch { $PromptErrors.Add("0 { SetCurrentDirectory }", $_) Write-Error "Failed to set CurrentDirectory to: (Get-Location -PSProvider FileSystem).ProviderPath" } } if ($Script:PowerLineConfig.RestoreVirtualTerminal -and (-not $IsLinux -and -not $IsMacOS)) { [PoshCode.Pansies.NativeMethods]::EnableVirtualTerminalProcessing() } # Evaluate all the scriptblocks in $prompt $UniqueColorsCount = 0 $PromptText = @($Prompt) # Based on the number of text blocks, make up colors if we need to... [PoshCode.Pansies.RgbColor[]]$ActualColors = @( if ($Script:Colors.Count -ge $UniqueColorsCount) { $Script:Colors } elseif ($Script:Colors.Count -eq 2) { Get-Gradient ($Script:Colors[0]) ($Script:Colors[1]) -Count $UniqueColorsCount -Flatten } else { $Script:Colors * ([Math]::Ceiling($UniqueColorsCount/$Script:Colors.Count)) } ) $CacheKey = if ($Script:PowerLineConfig.NoCache) { [Guid]::NewGuid() } else { $MyInvocation.HistoryId } # Loop through the text blocks and set colors $ColorIndex = 0 foreach ($block in $PromptText) { $ColorUsed = $False foreach ($b in @($block)) { if (!$b.BackgroundColor) { if ($b.Object -isnot [PoshCode.PowerLine.Space]) { $b.BackgroundColor = $ActualColors[$ColorIndex] $ColorUsed = $True } } elseif($b.BackgroundColor -in $ActualColors) { $ActualColors = $ActualColors -ne $b.BackgroundColor } } $ColorIndex += $ColorUsed foreach ($b in @($block)) { if ($null -ne $b.BackgroundColor -and $null -eq $b.ForegroundColor) { if ($Script:PowerLineConfig.FullColor) { $b.ForegroundColor = Get-Complement $b.BackgroundColor -ForceContrast } else { $b.BackgroundColor, $b.ForegroundColor = Get-Complement $b.BackgroundColor -ConsoleColor -Passthru } } } } ## Finally, unroll all the output and join into one string (using separators and spacing) $Buffer = $PromptText | ForEach-Object { $_ } $extraLineCount = 0 $line = "" $result = "" $BufferWidth = [Console]::BufferWidth $CSI = "$([char]27)[" # Pre-invoke everything, because then we can use .Cache for ($b = 0; $b -lt $Buffer.Count; $b++) { $block = $Buffer[$b].Invoke($CacheKey) } [PoshCode.PowerLine.State]::Alignment = "Left" # $LastBackground = $null for ($b = 0; $b -lt $Buffer.Count; $b++) { $block = $Buffer[$b] # Column Separator if ($block.Object -eq [PoshCode.PowerLine.Space]::RightAlign) { [PoshCode.PowerLine.State]::Alignment = "Right" $result += $line + $Csi + "s" # STORE $line = "" # New Line } elseif ($block.Object -eq [PoshCode.PowerLine.Space]::NewLine) { if ([PoshCode.PowerLine.State]::Alignment) { [PoshCode.PowerLine.State]::Alignment = "Left" ## This is a VERY simplistic test for escape sequences $lineLength = ($line -replace "\u001B.*?\p{L}").Length # Write-Debug "The buffer is $($BufferWidth) wide, and the line is $($lineLength) long so we're aligning to $($Align)" $result += "$CSI$(1 + $BufferWidth - $lineLength)G" } $extraLineCount++ $result += $line + $CSI + "0m`n" # CLEAR $line = "" # If the cache is null, it won't draw anything } elseif ($block.Cache) { $Neighbor = $null $Direction = if ([PoshCode.PowerLine.State]::Alignment) { -1 } else { +1 } $n = $b # If this is not a spacer, it should use the color of the next non-empty block do { $n += $Direction if ($n -lt 0 -or $n -ge $Buffer.Count) { $Neighbor = $null break; } elseif ($Buffer[$n].Cache) { $Neighbor = $Buffer[$n] } } while(!$Neighbor) # If this is a spacer, it should not render at all if the next non-empty block is a spacer if ($block.Object -eq [PoshCode.PowerLine.Space]::Spacer -and $Neighbor.Object -eq [PoshCode.PowerLine.Space]::Spacer) { continue } if ($text = $block.ToLine($Neighbor.BackgroundColor, $CacheKey)) { $line += $text } #Write-Debug "Normal output ($($string -replace "\u001B.*?\p{L}")) ($($($string -replace "\u001B.*?\p{L}").Length)) on $LastBackground" } } [string]$PromptErrorString = if (-not $Script:PowerLineConfig.HideErrors) { WriteExceptions $PromptErrors } # With the latest PSReadLine, we can support ending with a right-aligned block... if ([PoshCode.PowerLine.State]::Alignment) { ## This is a VERY simplistic test for escape sequences $lineLength = ($line -replace "\u001B.*?\p{L}").Length #Write-Debug "The buffer is $($BufferWidth) wide, and the line is $($lineLength) long" $result += "$CSI$(1 + $BufferWidth - $lineLength)G" $line += $CSI + "u" # Recall [PoshCode.PowerLine.State]::Alignment = "Left" } # At the end, output everything as one single string # create the number of lines we need for output up front: ("`n" * $extraLineCount) + ("$([char]27)M" * $extraLineCount) + $PromptErrorString + $result + $line } catch { Write-Warning "Exception in PowerLinePrompt`n$_" "${PWD}>" } } #EndRegion '.\Public\Write-PowerlinePrompt.ps1' 174 #Region '.\postfix.ps1' 0 if (Get-Module EzTheme -ErrorAction SilentlyContinue) { Get-ModuleTheme | Set-PowerLineTheme } else { Set-PowerLinePrompt } #EndRegion '.\postfix.ps1' 6 |