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[ScriptBlock]]$Global:Prompt = [ScriptBlock[]]@( if(Test-Path Variable:Prompt) { $Prompt | ForEach-Object { $_ } } ) Add-MetadataConverter @{ [char] = { "'$_'" } } # [Entities]::ExtendedCharacters['FileSystem'] = [PoshCode.Pansies.Entities]::Decode("$fg:DarkGoldenrod1&nf-custom-folder_open;$fg:Clear") # [Entities]::ExtendedCharacters['RgbColor'] = [PoshCode.Pansies.Entities]::Decode("$fg:Violet&nf-fae-palette_color;$fg:Clear") # [Entities]::ExtendedCharacters['WSMan'] = [PoshCode.Pansies.Entities]::Decode("$fg:DodgerBlue4&nf-custom-folder_config;$fg:Clear") # [Entities]::ExtendedCharacters['Certificate'] = [PoshCode.Pansies.Entities]::Decode("$fg:BlueViolet&nf-mdi-certificate;$fg:Clear") # [Entities]::ExtendedCharacters['Alias'] = [PoshCode.Pansies.Entities]::Decode("&nf-mdi-guy_fawkes_mask;") # [Entities]::ExtendedCharacters['Variable'] = [PoshCode.Pansies.Entities]::Decode("$fg:Green4&nf-fa-dollar;$fg:Clear") # [Entities]::ExtendedCharacters['Function'] = [PoshCode.Pansies.Entities]::Decode("$fg:DeepPink3&nf-mdi-function;$fg:Clear") # [Entities]::ExtendedCharacters['Registry'] = [PoshCode.Pansies.Entities]::Decode("$fg:Aquamarine4&nf-ple-pixelated_squares_big;$fg:Clear") # [Entities]::ExtendedCharacters['Environment'] = [PoshCode.Pansies.Entities]::Decode("$fg:DodgerBlue4&nf-dev-terminal;$fg:Clear") #EndRegion '.\Private\_init.ps1' 25 #Region '.\Private\InitializeColor.ps1' 0 function InitializeColor { [CmdletBinding()] param( [System.Collections.Generic.List[PoshCode.Pansies.RgbColor]]$Colors = $Global:Prompt.Colors, [switch]$Passthru ) if(!$PSBoundParameters.ContainsKey("Colors")){ [System.Collections.Generic.List[PoshCode.Pansies.RgbColor]]$Colors = if($global:Prompt.Colors) { $global:Prompt.Colors } else { "Cyan","DarkCyan","Gray","DarkGray","Gray" } } if($Passthru) { $Colors } if(!(Get-Member -InputObject $Global:Prompt -Name Colors)) { Add-Member -InputObject $Global:Prompt -MemberType NoteProperty -Name Colors -Value $Colors } else { $Global:Prompt.Colors = $Colors } } #EndRegion '.\Private\InitializeColor.ps1' 26 #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="Error")] param( # The text, object, or scriptblock to show as output [Parameter(Position=0, Mandatory, ValueFromPipeline)] [Alias("Text")] $InputObject, # The position to insert the InputObject at, by default, inserts in the same place as the last one [int]$Index = -1, [Switch]$AutoRemove, # If set, adds the input to the prompt without checking if it's already there [Switch]$Force ) process { 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' 70 #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\.ffff}" [Parameter()] [string]$Format = "{0:d\d\ h\:mm\:ss\.ffff}", # If set trim leading zeros and separators off to make the string as short as possible [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) { $Result.Trim("0:d ") } else { $Result } } #EndRegion '.\Public\Get-Elapsed.ps1' 34 #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 = [ScriptBlock[]]$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'] } $Configuration.PSReadLinePromptText = (Get-PSReadLineOption).PromptText $Result = New-Object PSObject -Property $Configuration $Result.PSTypeNames.Insert(0, "PowerLine.Theme") $Result } #EndRegion '.\Public\Get-PowerLineTheme.ps1' 28 #Region '.\Public\Get-SegmentedPath.ps1' 0 function Get-SegmentedPath { <# .Synopsis Gets PowerLine Blocks for each folder in the path .Description Returns an array of hashtables which can be cast to PowerLine Blocks. Includes support for limiting the number of segments or total length of the path, but defaults to 3 segments max #> [OutputType([PoshCode.Pansies.Text[]])] [CmdletBinding(DefaultParameterSetName="Segments")] param( # The path to segment. Defaults to $pwd [Parameter(Position=0)] [string]$Path = $pwd, # The maximum number of segments. Defaults to 3 [Parameter(ParameterSetName="Segments")] [int]$SegmentLimit = 3, # The maximum length. Defaults to 0 (no max) [Parameter(ParameterSetName="Length")] [int]$LengthLimit = 0, # Show the drive name on the front [switch]$ShowDrive, # The foreground color to use when the last command succeeded [PoshCode.Pansies.RgbColor]$ForegroundColor, # The background color to use when the last command succeeded [PoshCode.Pansies.RgbColor]$BackgroundColor, # The foreground color to use when the process is elevated (running as administrator) [PoshCode.Pansies.RgbColor]$ElevatedForegroundColor, # The background color to use when the process is elevated (running as administrator) [PoshCode.Pansies.RgbColor]$ElevatedBackgroundColor, # The foreground color to use when the last command failed [PoshCode.Pansies.RgbColor]$ErrorForegroundColor, # The background color to use when the last command failed [PoshCode.Pansies.RgbColor]$ErrorBackgroundColor ) $resolved = Resolve-Path $Path $provider = $resolved.Provider $drive = $resolved.Drive.Name $Path = $resolved.Path $buffer = @() if ($Path.ToLower().StartsWith($Home.ToLower())) { $drive = '~' $Path = $Path.Substring($Home.Length) } else { $Path = Split-Path $Path -NoQualifier } $Path = $Path.Trim($provider.ItemSeparator) # Now we have a drive for the front, and we want $SegmentLimit - 1 pieces from the end # $SegmentLimit = $SegmentLimit - 1 while ($Path) { $buffer += if ($Path -eq "~") { @{ Object = $Path } } else { @{ Object = (Split-Path $Path -Leaf).Trim($provider.ItemSeparator) } } $Path = Split-Path $Path if ($PSCmdlet.ParameterSetName -eq 'Segments') { if ($Path -and $SegmentLimit -le $buffer.Count) { if ($buffer.Count -gt 1) { $buffer[-1] = @{ Object = [char]0x2026 } } else { $buffer += @{ Object = [char]0x2026 } } break } } if ($LengthLimit) { $CurrentLength = ($buffer.Object | Measure-Object Length -Sum).Sum + $buffer.Count - 1 $CurrentLength += if ($Path) { 2 } else { 0 } if ($LengthLimit -lt $CurrentLength) { if($buffer.Count -gt 1) { $buffer[-1] = @{ Object = [char]0x2026 } } else { $buffer += @{ Object = [char]0x2026 } } break } } } if ($ShowDrive -or $SegmentLimit -gt $buffer.Count) { $buffer += @{ Object = $Drive } } [Array]::Reverse($buffer) foreach($output in $buffer) { # Always set the defaults first, if they're provided if($PSBoundParameters.ContainsKey("ForegroundColor")) { $output.ForegroundColor = $ForegroundColor } if($PSBoundParameters.ContainsKey("BackgroundColor")) { $output.BackgroundColor = $BackgroundColor } # If it's elevated, and they passed the elevated color ... if(Test-Elevation) { if($PSBoundParameters.ContainsKey("ElevatedForegroundColor")) { $output.ForegroundColor = $ElevatedForegroundColor } if($PSBoundParameters.ContainsKey("ElevatedBackgroundColor")) { $output.BackgroundColor = $ElevatedBackgroundColor } } # If it failed, and they passed an error color ... if(!(Test-Success)) { if($PSBoundParameters.ContainsKey("ErrorForegroundColor")) { $output.ForegroundColor = $ErrorForegroundColor } if($PSBoundParameters.ContainsKey("ErrorBackgroundColor")) { $output.BackgroundColor = $ErrorBackgroundColor } } } [PoshCode.Pansies.Text[]]$buffer } #EndRegion '.\Public\Get-SegmentedPath.ps1' 132 #Region '.\Public\Get-ShortenedPath.ps1' 0 function Get-ShortenedPath { [CmdletBinding()] param( [Parameter(Position=0)] [string] $Path = $pwd, [Parameter()] [switch] $RelativeToHome, [Parameter()] [int] $MaximumLength = [int]::MaxValue, [Parameter()] [switch] $SingleCharacterSegment ) if ($MaximumLength -le 0) { return [string]::Empty } if ($RelativeToHome -and $Path.ToLower().StartsWith($Home.ToLower())) { $Path = '~' + $Path.Substring($Home.Length) } if (($MaximumLength -gt 0) -and ($Path.Length -gt $MaximumLength)) { $Path = $Path.Substring($Path.Length - $MaximumLength) if ($Path.Length -gt 3) { $Path = "..." + $Path.Substring(3) } } # Credit: http://www.winterdom.com/powershell/2008/08/13/mypowershellprompt.html if ($SingleCharacterSegment) { # Remove prefix for UNC paths $Path = $Path -replace '^[^:]+::', '' # handle paths starting with \\ and . correctly $Path = ($Path -replace '\\(\.?)([^\\])[^\\]*(?=\\)','\$1$2') } $Path } #EndRegion '.\Public\Get-ShortenedPath.ps1' 46 #Region '.\Public\New-PromptText.ps1' 0 function New-PromptText { <# .Synopsis Create PoshCode.Pansies.Text 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="Error")] [Alias("New-PowerLineBlock")] [Alias("New-TextFactory")] param( # The text, object, or scriptblock to show as output [Alias("Text", "Object")] [AllowNull()][EmptyStringAsNull()] [Parameter(Position=0, ValueFromPipeline, ValueFromPipelineByPropertyName)] # , Mandatory=$true $InputObject, # 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 { # Try to fix the parameter binding if($InputObject.InputObject) { $InputObject = $InputObject.InputObject } elseif($InputObject.Object) { $InputObject = $InputObject.Object }elseif($InputObject.Text) { $InputObject = $InputObject.Text } $output = [PoshCode.Pansies.Text]@{ Object = $InputObject } # Always set the defaults first, if they're provided if($PSBoundParameters.ContainsKey("ForegroundColor") -and $ForegroundColor -ne $Null) { $output.ForegroundColor = $ForegroundColor } if($PSBoundParameters.ContainsKey("BackgroundColor") -and $BackgroundColor -ne $Null) { $output.BackgroundColor = $BackgroundColor } # If it's elevated, and they passed the elevated color ... if(Test-Elevation) { if($PSBoundParameters.ContainsKey("ElevatedForegroundColor") -and $ElevatedForegroundColor -ne $Null) { $output.ForegroundColor = $ElevatedForegroundColor } if($PSBoundParameters.ContainsKey("ElevatedBackgroundColor") -and $ElevatedBackgroundColor -ne $Null) { $output.BackgroundColor = $ElevatedBackgroundColor } } # If it failed, and they passed an error color ... if(!(Test-Success)) { if($PSBoundParameters.ContainsKey("ErrorForegroundColor") -and $ErrorForegroundColor -ne $Null) { $output.ForegroundColor = $ErrorForegroundColor } if($PSBoundParameters.ContainsKey("ErrorBackgroundColor") -and $ErrorBackgroundColor -ne $Null) { $output.BackgroundColor = $ErrorBackgroundColor } } $output } } #EndRegion '.\Public\New-PromptText.ps1' 104 #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(ValueFromPipelineByPropertyName)] [System.Collections.Generic.List[ScriptBlock]]$Prompt, # One or more colors you want to use as the prompt background [Parameter(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)] [hashtable]$PowerLineCharacters, # When there's a parse error, PSReadLine changes a part of the prompt red, but ot 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 = "" ) 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[ScriptBlock]]$global:Prompt = $Local:Prompt } elseif($global:Prompt.Count -eq 0 -and $PowerLineConfig.Prompt.Count -gt 0) { [System.Collections.Generic.List[ScriptBlock]]$global:Prompt = [ScriptBlock[]]@($PowerLineConfig.Prompt) } elseif($global:Prompt.Count -eq 0) { # The default PowerLine Prompt [ScriptBlock[]]$PowerLineConfig.Prompt = { $MyInvocation.HistoryId }, { Get-SegmentedPath } [System.Collections.Generic.List[ScriptBlock]]$global:Prompt = $PowerLineConfig.Prompt } # Prefer the existing colors over the saved colors, but not over the colors parameter if($PSBoundParameters.ContainsKey("Colors")) { InitializeColor $Colors } elseif($global:Prompt.Colors) { InitializeColor $global:Prompt.Colors } elseif($PowerLineConfig.Colors) { InitializeColor $PowerLineConfig.Colors } else { InitializeColor } 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 ($PSBoundParameters.ContainsKey("PSReadLinePromptText") -and (Get-Module PSReadLine)) { Set-PSReadLineOption -PromptText $PSReadLinePromptText } # 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 } } Set-PowerLinePrompt #EndRegion '.\Public\Set-PowerLinePrompt.ps1' 226 #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() if(-not ($IsLinux -or $IsMacOS)) { [Security.Principal.WindowsIdentity]::GetCurrent().Owner.IsWellKnown("BuiltInAdministratorsSid") } else { 0 -eq (id -u) } } #EndRegion '.\Public\Test-Elevation.ps1' 14 #Region '.\Public\Test-Success.ps1' 0 function Test-Success { <# .Synopsis Get a value indicating whether the last command succeeded or not #> [CmdletBinding()] param() $script:LastSuccess } #EndRegion '.\Public\Test-Success.ps1' 11 #Region '.\Public\Write-PowerlinePrompt.ps1' 0 function Write-PowerlinePrompt { [CmdletBinding()] param() try { # FIRST, make a note if there was an error in the previous command [bool]$script:LastSuccess = $? $PromptErrors = [ordered]@{} # 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 = @( for($b = 0; $b -lt $Prompt.Count; $b++) { $block = $Global:Prompt[$b] try { $outputBlock = . { [CmdletBinding()]param() & $block } -ErrorVariable logging $buffer = $( if($outputBlock -as [PoshCode.Pansies.Text[]]) { [PoshCode.Pansies.Text[]]$outputBlock } else { [PoshCode.Pansies.Text[]][string[]]$outputBlock } ).Where{ ![string]::IsNullOrEmpty($_.Object) } # Each $buffer gets a color, if it needs one (it's not whitespace) $UniqueColorsCount += [bool]$buffer.Where({ !([string]::IsNullOrWhiteSpace($_.Object)) -and !$_.BackgroundColor -and !$_.ForegroundColor }, 1) , $buffer # Capture errors from blocks. We'll find a way to display them... if ($logging) { $PromptErrors.Add("$b {$block}", $logging) } } catch { $PromptErrors.Add("$b {$block}", $_) } } ).Where{ $_.Object } # 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 if(!$Global:Prompt.Colors) { InitializeColor } # Based on the number of text blocks, get a color gradient or the user's color choices [PoshCode.Pansies.RgbColor[]]$Colors = @( if ($Global:Prompt.Colors.Count -ge $UniqueColorsCount) { $Global:Prompt.Colors } elseif ($Global:Prompt.Colors.Count -eq 2) { Get-Gradient ($Global:Prompt.Colors[0]) ($Global:Prompt.Colors[1]) -Count $UniqueColorsCount -Flatten } else { $Global:Prompt.Colors * ([Math]::Ceiling($UniqueColorsCount/$Global:Prompt.Colors.Count)) } ) # Loop through the text blocks and set colors $ColorIndex = 0 foreach ($block in $PromptText) { $ColorUsed = $False foreach ($b in @($block)) { if (![string]::IsNullOrWhiteSpace($b.Object) -and $null -eq $b.BackgroundColor) { $b.BackgroundColor = $Colors[$ColorIndex] $ColorUsed = $True } } $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 = "" $RightAligned = $False $BufferWidth = [Console]::BufferWidth $ColorSeparator = "&ColorSeparator;" $Separator = "&Separator;" $LastBackground = $null for ($b = 0; $b -lt $Buffer.Count; $b++) { $block = $Buffer[$b] $string = $block.ToString() # Write-Debug "STEP $b of $($Buffer.Count) [$(($String -replace "\u001B.*?\p{L}").Length)] $($String -replace "\u001B.*?\p{L}" -replace "`n","{newline}" -replace "`t","{tab}")" ## Allow `t to split into (2) columns: if ($string -eq "`t") { if ($LastBackground) { ## Before the (column) break, add a cap #Write-Debug "Pre column-break, add a $LastBackground cap" $line += [PoshCode.Pansies.Text]@{ Object = "&Esc;49m$ColorSeparator&Clear;&Store;" ForegroundColor = $LastBackground BackgroundColor = $null # $Host.UI.RawUI.BackgroundColor } } $result += $line $line = "" $RightAligned = $True $ColorSeparator = "&ReverseColorSeparator;" $Separator = "&ReverseSeparator;" $LastBackground = $null ## Allow `n to create multi-line prompts } elseif ($string -in "`n", "`r`n") { if($RightAligned) { ## This is a VERY simplistic test for escape sequences $lineLength = ($line -replace "\u001B.*?\p{L}").Length $Align = "$([char]27)[$(1 + $BufferWidth - $lineLength)G" Write-Debug "The buffer is $($BufferWidth) wide, and the line is $($lineLength) long so we're aligning to $($Align)" $result += [PoshCode.Pansies.Text]::new("&Esc;$($Align)") $RightAligned = $False } else { $line += [PoshCode.Pansies.Text]@{ Object = $ColorSeparator ForegroundColor = $LastBackground BackgroundColor = if ($Host.UI.RawUI.BackgroundColor -ge 0) { $Host.UI.RawUI.BackgroundColor } else { $null } } } $extraLineCount++ $result += $line + [PoshCode.Pansies.Text]::new("&Clear;`n") $line = "" $ColorSeparator = "&ColorSeparator;" $Separator = "&Separator;" $LastBackground = $null } elseif(![string]::IsNullOrWhiteSpace($string)) { ## If the output is just color sequences, toss it if(($String -replace "\u001B.*?\p{L}").Length -eq 0) { #Write-Debug "Skip empty output, staying $LastBackground" continue } if($LastBackground -or $RightAligned) { $line += if ($RightAligned -and -not $LastBackground) { [PoshCode.Pansies.Text]@{ Object = "&Esc;49m$ColorSeparator" ForegroundColor = ($LastBackground, $block.BackgroundColor)[$RightAligned] BackgroundColor = $null } } elseif($block.BackgroundColor -ne $LastBackground) { [PoshCode.Pansies.Text]@{ Object = $ColorSeparator ForegroundColor = ($LastBackground, $block.BackgroundColor)[$RightAligned] BackgroundColor = ($block.BackgroundColor, $LastBackground)[$RightAligned] } } else { [PoshCode.Pansies.Text]@{ Object = $Separator BackgroundColor = $block.BackgroundColor ForegroundColor = $block.ForegroundColor } } } $line += $string $LastBackground = $block.BackgroundColor #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 ($RightAligned) { ## 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" $Align = "$([char]27)[$(1 + $BufferWidth - $lineLength)G" $result += [PoshCode.Pansies.Text]::new("$([char]27)[$Align") $RightAligned = $False $line += [PoshCode.Pansies.Text]::new("&Recall;") } else { $line += ([PoshCode.Pansies.Text]@{ Object = "$([char]27)[49m$ColorSeparator&Clear;" ForegroundColor = $LastBackground }) } # 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' 221 #Region '.\postfix.ps1' 0 if (Get-Module EzTheme -ErrorAction SilentlyContinue) { Get-ModuleTheme | Set-PowerLineTheme } #EndRegion '.\postfix.ps1' 4 |