Giter Site home page Giter Site logo

poshcode / pansies Goto Github PK

View Code? Open in Web Editor NEW
144.0 9.0 14.0 2.66 MB

Powershell ANSI Escape Sequences, functions for colored output, etc.

License: MIT License

C# 96.45% PowerShell 2.99% Earthly 0.56%
powershell powershell-modules ansi ansi-escape-sequences vt

pansies's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pansies's Issues

Functions with Parameter type `RgbColor` Error on `X11ColorNames`

I was running into errors when I type'd my functions as [PoshCode.Pansies.RgbColor]

image

$p = [PoshCode.Pansies.Palettes.X11ColorName]'maroon'
New-Text 'test' -fg $p

New-Text 'test' -fg ([string]$p)

Cannot bind parameter 'ForegroundColor'. Cannot convert value "Maroon" to type "PoshCode.Pansies.RgbColor". Error: "Invalid cast from 'PoshCode.Pansies.Palettes.X11ColorName' to 'PoshCode.Pansies.RgbColor'."

Cause

New-Text from[PoshCode.Pansies.Commands.NewTextCommand] can't coerce [Palettes.X11ColorName] to [RgbColor] -- even with valid names

Fix

Wrapping [string] first, works.

-fg ( $m.X11ColorName ) Works with -fg ( [string]$m.X11ColorName )

Test Code / How to Reproduce

$m = [PoshCode.Pansies.RgbColor]'maroon'
$x11 = [RgbColor]'maroon' |  % X11ColorName

# ok
[RgbColor]'maroon'

# ok
New-Text 'test' -fg 'maroon'

# ok
New-Text -fg (  [string]$m.X11ColorName) 'test'

# error
New-Text 'test' -fg $x11
New-Text: Cannot bind parameter 'ForegroundColor'. Cannot convert value "Maroon" to type "PoshCode.Pansies.RgbColor". Error: "Invalid cast from 'PoshCode.Pansies.Palettes.X11ColorName' to 'PoshCode.Pansies.RgbColor'."
Stack Trace (Click to Expand)

Parameter Binding Trace

BIND NAMED cmd line args [New-Text]
    BIND arg [Maroon] to parameter [ForegroundColor]
        COERCE arg to [PoshCode.Pansies.RgbColor]
            Trying to convert argument value from PoshCode.Pansies.Palettes.X11ColorName to PoshCode.Pansies.RgbColor
            CONVERT arg type to param type using LanguagePrimitives.ConvertTo
            ERROR: ERROR: COERCE FAILED: arg [Maroon] could not be converted to the parameter type [PoshCode.Pansies.RgbColor]
BIND PIPELINE object to parameters: [Out-Default]
    PIPELINE object TYPE = [System.Management.Automation.ErrorRecord]
    RESTORING pipeline parameter's original values
    Parameter [InputObject] PIPELINE INPUT ValueFromPipeline NO COERCION
    BIND arg [Cannot bind parameter 'ForegroundColor'. Cannot convert value "Maroon" to type "PoshCode.Pansies.RgbColor". Error: "Invalid cast from 'PoshCode.Pansies.Palettes.X11ColorName' to 'PoshCode.Pansies.RgbColor'."] to parameter [InputObject]
        BIND arg [Cannot bind parameter 'ForegroundColor'. Cannot convert value "Maroon" to type "PoshCode.Pansies.RgbColor". Error: "Invalid cast from 'PoshCode.Pansies.Palettes.X11ColorName' to 'PoshCode.Pansies.RgbColor'."] to param [InputObject] SUCCESSFUL
BIND NAMED cmd line args [New-Text]
    BIND arg [Maroon] to parameter [ForegroundColor]
        COERCE arg to [PoshCode.Pansies.RgbColor]
            Trying to convert argument value from PoshCode.Pansies.Palettes.X11ColorName to PoshCode.Pansies.RgbColor
            CONVERT arg type to param type using LanguagePrimitives.ConvertTo
            ERROR: ERROR: COERCE FAILED: arg [Maroon] could not be converted to the parameter type [PoshCode.Pansies.RgbColor]
BIND PIPELINE object to parameters: [Out-Default]
    PIPELINE object TYPE = [System.Management.Automation.ErrorRecord]
    RESTORING pipeline parameter's original values
    Parameter [InputObject] PIPELINE INPUT ValueFromPipeline NO COERCION
    BIND arg [Cannot bind parameter 'ForegroundColor'. Cannot convert value "Maroon" to type "PoshCode.Pansies.RgbColor". Error: "Invalid cast from 'PoshCode.Pansies.Palettes.X11ColorName' to 'PoshCode.Pansies.RgbColor'."] to parameter [InputObject]
        BIND arg [Cannot bind parameter 'ForegroundColor'. Cannot convert value "Maroon" to type "PoshCode.Pansies.RgbColor". Error: "Invalid cast from 'PoshCode.Pansies.Palettes.X11ColorName' to 'PoshCode.Pansies.RgbColor'."] to param [InputObject] SUCCESSFUL
MANDATORY PARAMETER CHECK on cmdlet [Out-Default]
BIND NAMED cmd line args [Out-LineOutput]
    BIND arg [Microsoft.PowerShell.Commands.Internal.Format.ConsoleLineOutput] to parameter [LineOutput]
        COERCE arg to [System.Object]
            Parameter and arg types the same, no coercion is needed.
        BIND arg [Microsoft.PowerShell.Commands.Internal.Format.ConsoleLineOutput] to param [LineOutput] SUCCESSFUL
BIND POSITIONAL cmd line args [Out-LineOutput]
MANDATORY PARAMETER CHECK on cmdlet [Out-LineOutput]
CALLING BeginProcessing
BIND PIPELINE object to parameters: [Out-LineOutput]
    PIPELINE object TYPE = [System.Management.Automation.ErrorRecord]
    RESTORING pipeline parameter's original values
    Parameter [InputObject] PIPELINE INPUT ValueFromPipeline NO COERCION
    BIND arg [Cannot bind parameter 'ForegroundColor'. Cannot convert value "Maroon" to type "PoshCode.Pansies.RgbColor". Error: "Invalid cast from 'PoshCode.Pansies.Palettes.X11ColorName' to 'PoshCode.Pansies.RgbColor'."] to parameter [InputObject]
        BIND arg [Cannot bind parameter 'ForegroundColor'. Cannot convert value "Maroon" to type "PoshCode.Pansies.RgbColor". Error: "Invalid cast from 'PoshCode.Pansies.Palettes.X11ColorName' to 'PoshCode.Pansies.RgbColor'."] to param [InputObject] SUCCESSFUL
MANDATORY PARAMETER CHECK on cmdlet [out-lineoutput]
BIND NAMED cmd line args [Format-Default]
BIND POSITIONAL cmd line args [Format-Default]
MANDATORY PARAMETER CHECK on cmdlet [Format-Default]
CALLING BeginProcessing
BIND PIPELINE object to parameters: [Format-Default]
    PIPELINE object TYPE = [System.Management.Automation.ErrorRecord]
    RESTORING pipeline parameter's original values
    Parameter [InputObject] PIPELINE INPUT ValueFromPipeline NO COERCION
    BIND arg [Cannot bind parameter 'ForegroundColor'. Cannot convert value "Maroon" to type "PoshCode.Pansies.RgbColor". Error: "Invalid cast from 'PoshCode.Pansies.Palettes.X11ColorName' to 'PoshCode.Pansies.RgbColor'."] to parameter [InputObject]
        BIND arg [Cannot bind parameter 'ForegroundColor'. Cannot convert value "Maroon" to type "PoshCode.Pansies.RgbColor". Error: "Invalid cast from 'PoshCode.Pansies.Palettes.X11ColorName' to 'PoshCode.Pansies.RgbColor'."] to param [InputObject] SUCCESSFUL
MANDATORY PARAMETER CHECK on cmdlet [format-default]
BIND NAMED cmd line args [Set-StrictMode]
    BIND arg [True] to parameter [Off]
        COERCE arg to [System.Management.Automation.SwitchParameter]
            Parameter and arg types the same, no coercion is needed.
        BIND arg [True] to param [Off] SUCCESSFUL
BIND POSITIONAL cmd line args [Set-StrictMode]
MANDATORY PARAMETER CHECK on cmdlet [Set-StrictMode]
CALLING BeginProcessing
CALLING EndProcessing
BIND arg [Red] to parameter [color]
    Executing DATA GENERATION metadata: [System.Management.Automation.ArgumentTypeConverterAttribute]
        result returned from DATA GENERATION: Red
    BIND arg [Red] to param [color] SUCCESSFUL
BIND arg [Cyan] to parameter [color]
    Executing DATA GENERATION metadata: [System.Management.Automation.ArgumentTypeConverterAttribute]
        result returned from DATA GENERATION: Cyan
    BIND arg [Cyan] to param [color] SUCCESSFUL
BIND NAMED cmd line args [Get-Command]
    BIND arg [New-Text] to parameter [Name]
        COERCE arg to [System.String[]]
            Trying to convert argument value from System.Management.Automation.CmdletInfo to System.String[]
            ENCODING arg into collection
            Binding collection parameter Name: argument type [CmdletInfo], parameter type [System.String[]], collection type Array, element type [System.String], coerceElementType
            Creating array with element type [System.String] and 1 elements
            Argument type CmdletInfo is not IList, treating this as scalar
            Coercing scalar arg value to type System.String
            COERCE arg to [System.String]
                Trying to convert argument value from System.Management.Automation.CmdletInfo to System.String
                CONVERT arg type to param type using LanguagePrimitives.ConvertTo
                CONVERT SUCCESSFUL using LanguagePrimitives.ConvertTo: [New-Text]
            Adding scalar element of type String to array position 0
        Executing VALIDATION metadata: [System.Management.Automation.ValidateNotNullOrEmptyAttribute]
        BIND arg [System.String[]] to param [Name] SUCCESSFUL
    BIND arg [Ignore] to parameter [ErrorAction]
        COERCE arg to [System.Management.Automation.ActionPreference]
            Trying to convert argument value from System.String to System.Management.Automation.ActionPreference
            CONVERT arg type to param type using LanguagePrimitives.ConvertTo
            CONVERT SUCCESSFUL using LanguagePrimitives.ConvertTo: [Ignore]
        BIND arg [Ignore] to param [ErrorAction] SUCCESSFUL
BIND POSITIONAL cmd line args [Get-Command]
MANDATORY PARAMETER CHECK on cmdlet [Get-Command]
CALLING BeginProcessing
CALLING EndProcessing
BIND NAMED cmd line args [Set-StrictMode]
    BIND arg [1] to parameter [Version]
        Executing DATA GENERATION metadata: [Microsoft.PowerShell.Commands.SetStrictModeCommand+ArgumentToVersionTransformationAttribute]
            result returned from DATA GENERATION: 1.0
        COERCE arg to [System.Version]
            Parameter and arg types the same, no coercion is needed.
        Executing VALIDATION metadata: [Microsoft.PowerShell.Commands.SetStrictModeCommand+ValidateVersionAttribute]
        BIND arg [1.0] to param [Version] SUCCESSFUL
BIND POSITIONAL cmd line args [Set-StrictMode]
MANDATORY PARAMETER CHECK on cmdlet [Set-StrictMode]
CALLING BeginProcessing
CALLING EndProcessing
New-Text: Cannot bind parameter 'ForegroundColor'. Cannot convert value "Maroon" to type "PoshCode.Pansies.RgbColor". Error: "Invalid cast from 'PoshCode.Pansies.Palettes.X11ColorName' to 'PoshCode.Pansies.RgbColor'."
Stack Trace (Click to Expand)

Error

Type              : System.Management.Automation.ParameterBindingException
Message           : Cannot bind parameter 'ForegroundColor'. Cannot convert value "Maroon" to type "PoshCode.Pansies.RgbColor". Error: "Invalid cast from 'PoshCode.Pansies.Palettes.X11ColorName' to 'PoshCode.Pansies.RgbColor'."
ParameterName     : ForegroundColor
ParameterType     : PoshCode.Pansies.RgbColor
TypeSpecified     : PoshCode.Pansies.Palettes.X11ColorName
ErrorId           : CannotConvertArgumentNoMessage
Exception             : 
    Type              : System.Management.Automation.ParameterBindingException
    Message           : Cannot bind parameter 'ForegroundColor'. Cannot convert value "Maroon" to type "PoshCode.Pansies.RgbColor". Error: "Invalid cast from 'PoshCode.Pansies.Palettes.X11ColorName' to 'PoshCode.Pansies.RgbColor'."
    ParameterName     : ForegroundColor
    ParameterType     : PoshCode.Pansies.RgbColor
    TypeSpecified     : PoshCode.Pansies.Palettes.X11ColorName
    ErrorId           : CannotConvertArgumentNoMessage
    Line              : 1
    Offset            : 14
    CommandInvocation : 
        MyCommand        : New-Text
        ScriptLineNumber : 1
        OffsetInLine     : 1
        HistoryId        : 79
        Line             : New-Text -fg $m.X11ColorName 'test'
        PositionMessage  : At line:1 char:1
                           + New-Text -fg $m.X11ColorName 'test'
                           + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        InvocationName   : New-Text
        PipelineLength   : 1
        PipelinePosition : 1
    ErrorRecord       : 
        Exception             : 
            Type    : System.Management.Automation.ParentContainsErrorRecordException
            Message : Cannot bind parameter 'ForegroundColor'. Cannot convert value "Maroon" to type "PoshCode.Pansies.RgbColor". Error: "Invalid cast from 'PoshCode.Pansies.Palettes.X11ColorName' to 'PoshCode.Pansies.RgbColor'."
            HResult : -2146233087
        CategoryInfo          : InvalidArgument: (:) [New-Text], ParentContainsErrorRecordException
        FullyQualifiedErrorId : CannotConvertArgumentNoMessage,PoshCode.Pansies.Commands.NewTextCommand
        InvocationInfo        : 
            MyCommand        : New-Text
            ScriptLineNumber : 1
            OffsetInLine     : 14
            HistoryId        : 79
            Line             : New-Text -fg $m.X11ColorName 'test'
            PositionMessage  : At line:1 char:14
                               + New-Text -fg $m.X11ColorName 'test'
                               +              ~~~~~~~~~~~~~~~
            CommandOrigin    : Internal
        ScriptStackTrace      : at <ScriptBlock>, <No file>: line 1
    TargetSite        : 
        Name          : CoerceTypeAsNeeded
        DeclaringType : System.Management.Automation.ParameterBinderBase, System.Management.Automation, Version=7.2.0.500, Culture=neutral, PublicKeyToken=31bf3856ad364e35
        MemberType    : Method
        Module        : System.Management.Automation.dll
    Data              : System.Collections.ListDictionaryInternal
    InnerException    : 
        Type           : System.Management.Automation.PSInvalidCastException
        ErrorRecord    : 
            Exception             : 
                Type    : System.Management.Automation.ParentContainsErrorRecordException
                Message : Cannot convert value "Maroon" to type "PoshCode.Pansies.RgbColor". Error: "Invalid cast from 'PoshCode.Pansies.Palettes.X11ColorName' to 'PoshCode.Pansies.RgbColor'."
                HResult : -2146233087
            CategoryInfo          : InvalidArgument: (:) [], ParentContainsErrorRecordException
            FullyQualifiedErrorId : InvalidCastIConvertible
        TargetSite     : 
            Name          : ConvertIConvertible
            DeclaringType : System.Management.Automation.LanguagePrimitives
            MemberType    : Method
            Module        : System.Management.Automation.dll
        Message        : Cannot convert value "Maroon" to type "PoshCode.Pansies.RgbColor". Error: "Invalid cast from 'PoshCode.Pansies.Palettes.X11ColorName' to 'PoshCode.Pansies.RgbColor'."
        InnerException : 
            Type       : System.InvalidCastException
            TargetSite : 
                Name          : DefaultToType
                DeclaringType : System.Convert
                MemberType    : Method
                Module        : System.Private.CoreLib.dll
            Message    : Invalid cast from 'PoshCode.Pansies.Palettes.X11ColorName' to 'PoshCode.Pansies.RgbColor'.
            Source     : System.Private.CoreLib
            HResult    : -2147467262
            StackTrace : 
   at System.Convert.DefaultToType(IConvertible value, Type targetType, IFormatProvider provider)
   at System.Management.Automation.LanguagePrimitives.ConvertIConvertible(Object valueToConvert, Type resultType, Boolean recursion, PSObject originalValueToConvert, IFormatProvider formatProvider, TypeTable backupTable)
        Source         : System.Management.Automation
        HResult        : -2147467262
        StackTrace     : 
   at System.Management.Automation.LanguagePrimitives.ConvertIConvertible(Object valueToConvert, Type resultType, Boolean recursion, PSObject originalValueToConvert, IFormatProvider formatProvider, TypeTable backupTable)
   at System.Management.Automation.LanguagePrimitives.ConversionData`1.Invoke(Object valueToConvert, Type resultType, Boolean recurse, PSObject originalValueToConvert, IFormatProvider formatProvider, TypeTable backupTable)
   at System.Management.Automation.LanguagePrimitives.ConvertTo(Object valueToConvert, Type resultType, Boolean recursion, IFormatProvider formatProvider, TypeTable backupTypeTable)
   at System.Management.Automation.ParameterBinderBase.CoerceTypeAsNeeded(CommandParameterInternal argument, String parameterName, Type toType, ParameterCollectionTypeInformation collectionTypeInfo, Object currentValue)
    Source            : System.Management.Automation
    HResult           : -2146233087
    StackTrace        : 
   at System.Management.Automation.ParameterBinderBase.CoerceTypeAsNeeded(CommandParameterInternal argument, String parameterName, Type toType, ParameterCollectionTypeInformation collectionTypeInfo, Object currentValue)
   at System.Management.Automation.ParameterBinderBase.BindParameter(CommandParameterInternal parameter, CompiledCommandParameter parameterMetadata, ParameterBindingFlags flags)
   at System.Management.Automation.CmdletParameterBinderController.BindParameter(CommandParameterInternal argument, MergedCompiledCommandParameter parameter, ParameterBindingFlags flags)
   at System.Management.Automation.CmdletParameterBinderController.BindParameter(UInt32 parameterSets, CommandParameterInternal argument, MergedCompiledCommandParameter parameter, ParameterBindingFlags flags)
   at System.Management.Automation.CmdletParameterBinderController.BindNamedParameter(UInt32 parameterSets, CommandParameterInternal argument, MergedCompiledCommandParameter parameter)
   at System.Management.Automation.ParameterBinderController.BindNamedParameters(UInt32 parameterSets, Collection`1 arguments)
   at System.Management.Automation.CmdletParameterBinderController.BindCommandLineParametersNoValidation(Collection`1 arguments)
   at System.Management.Automation.CmdletParameterBinderController.BindCommandLineParameters(Collection`1 arguments)
   at System.Management.Automation.CommandProcessor.BindCommandLineParameters()
   at System.Management.Automation.CommandProcessor.Prepare(IDictionary psDefaultParameterValues)
   at System.Management.Automation.CommandProcessorBase.DoPrepare(IDictionary psDefaultParameterValues)
   at System.Management.Automation.Internal.PipelineProcessor.Start(Boolean incomingStream)
   at System.Management.Automation.Internal.PipelineProcessor.SynchronousExecuteEnumerate(Object input)
--- End of stack trace from previous location ---
   at System.Management.Automation.Internal.PipelineProcessor.SynchronousExecuteEnumerate(Object input)
   at System.Management.Automation.PipelineOps.InvokePipeline(Object input, Boolean ignoreInput, CommandParameterInternal[][] pipeElements, CommandBaseAst[] pipeElementAsts, CommandRedirection[][] commandRedirections, FunctionContext funcContext)
   at System.Management.Automation.Interpreter.ActionCallInstruction`6.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
CategoryInfo          : InvalidArgument: (:) [New-Text], ParameterBindingException
FullyQualifiedErrorId : CannotConvertArgumentNoMessage,PoshCode.Pansies.Commands.NewTextCommand
InvocationInfo        : 
    MyCommand        : New-Text
    ScriptLineNumber : 1
    OffsetInLine     : 14
    HistoryId        : 79
    Line             : New-Text -fg $m.X11ColorName 'test'
    PositionMessage  : At line:1 char:14
                       + New-Text -fg $m.X11ColorName 'test'
                       +              ~~~~~~~~~~~~~~~
    CommandOrigin    : Internal
ScriptStackTrace      : at <ScriptBlock>, <No file>: line 1

What COLOR class should we use?

The easy choice would be to use System.Drawing.Color

  • It converts from integers like 0xFFFF00
  • It converts from RGB strings like "255, 255, 0"
  • It converts from color names like "Yellow" or "Red"

However, it requires a reference to System.Drawing assembly, and it doesn't support xTerm's 256 color indexes (it would turn "220" into a shade of blue 0x0000dc)

A Better Way?

Since we're going to output escape sequences at the end of the day, there's no reason not to consider a custom Color class with byte R, G, B values and a ToString(bool Background) implementation that outputs escape sequences ...

It could remove the dependency on System.Drawing, and could still support all of the above conversions, and depending on the implementation, it could make calling some APIs easier.

It could handle "DarkYellow" (which isn't a named color in System.Drawing), and create more separation between "Green" and "DarkGreen" than System.Drawing.Color does, or even handle the 16 ConsoleColor names specially, resulting in the ConsoleColor ANSI sequence (which allows theming the core 16 colors, instead of using the pre-defined RGB values that System.Drawing.Color would give you)

Considerations

I don't consider supporting xTerm's colors a priority because our primary platform is Windows 10 which has full 16bit color. Older terminals that don't handle 16bit color should be fixed. However, for the sake of our xTerm and tmux using friends, I would like to support a preference variable like:

[ValidateSet("FullColor","xTerm","ConsoleColor")]$PSANSIPreference

In this situation, we should be able to down-sample from 16bit colors to the nearest xTerm 256 or ConsoleColor Color.

In fact, even when in FullColor mode, when outputting escape sequences, we will want to still support the standard ^e[0;30;44m style combinations for the console colors, so that it's possible to use our module and still get "themed" color outputs as configured in the console preferences. (see the xColors module).

Default Foreground Color Gets Borked in ConEmu with Pansies

I'm totally digging this module but seem to be running into an issue with the default color of output whenever I use it in conemu. The behavior has to do with the default host foreground color ($host.ui.rawui.foregroundcolor). If pansies is loaded I'm unable to change this value and so all output in some consoles (like conemu) get 'stuck'. Oddly enough a standard powershell console seems to render fine (as it adheres to the default colors in the registry instead of the host.ui color properties) but the underlying behavior is the same regardless which console is used, I cannot change $host.ui.rawui.foregroundcolor with this module loaded. I suspect that this may have to do with write-host being exported as a wrapper function but haven't dug into it yet.

Hide Get-GradientColor Verbose output behind some option

Since Get-Gradient is called from the prompt function, it gets very noisy when $VerbosePreference is enabled.

When a user that isn't debugging Pansies enables VerbosePreference, they likely aren't interested in the pansies

    Write-Verbose "Size: $('{0:N2}' -f $Size) ($Width x $Height) ($($Colors.Length) x $($Colors[0].Length))"
    Write-Verbose "Diff: {$StepSize}"
    Write-Verbose "From: {$Left} $($StartColor.Ordinals)"
    Write-Verbose "To:   {$Right} $($EndColor.Ordinals)"
```.

How about using some setting in the module to hide/enable this output?

PowerShell 5.1 - Pansies breaks tab completion for .net types

Steps to repro:
Windows 10 1803
PowerShell 5.1

Open new PowerShell session, type [System. and then hit Tab Tab
You will notice that PowerShell enumerates and displays all .NET types without issue.

Now, execute the following:
Install-Module Pansies -AllowClobber -AllowPrerelease -Force
Install-Module PSReadline -AllowClobber -AllowPrerelease -Force

Restart PowerShell session.

Import-Module Pansies
Import-Theme Dark

Try enumerating .NET types by typing [System. and then hit Tab Tab ...and nothing...

Any ideas?

Should be able to get default colors easily

To get this prompt:

I ๐Ÿ’Ÿ PS>

I want to be able to write:

function prompt { "I" + [TextSpan]@{ fg = "Red"; text = [char]0x2665 } + "PS>"}

But currently, the Background is required:

function prompt { "I" + [TextSpan]@{ bg = "Black"; fg = "Red"; text = [char]0x2665 } + "PS>"}

And the color doesn't reset, so PS> comes out red unless I manually call GetString, like:

function prompt { "I" + [TextSpan]::GetString("Red","Black",([char]0x2665),$true) + "PS>"}

Bug only when color code used?

I exclude my profile from loading, and the only module I import is the latest Pansies, and the odd thing is it works partially as you can see (2nd command), but when the color is introduced it barfs out what must be the behind the scenes alt codes? This is PS 5.1 on Win7x64 with DotNet 4.7.

Any help appreciated. TIA!

PS C:\> Write-Host "I $(New-Text "&hearts;" -fg "DarkRed")"
I โ†[31mโ™ฅโ†[39m
PS C:\>
PS C:\> Write-Host "I $(New-Text "&hearts;")"
I โ™ฅ

Submodules not being included

Note: I'm including ColorMine and p2f as submodules, you may need to update them with:

git submodule update --init -recursive

This does not work. PowerShell 7, Windows 10 2004, git version 2.27.0.windows.1

Use non-throwing alternative to $stepSize | Get-Member H

In

[bool]$RotatingColor = $StepSize | Get-Member H
,
throws an exception:

Cannot convert value "System.Management.Automation.PSCustomObject" to type "System.Boolean". Boolean parameters accept only Boolean values and numbers, such as $True, $False, 1 or 0

I suggest using a test like

[bool]$RotatingColor = $ColorSpace -in 'LCH', 'HSL', 'HSV', 'HSB'

or

[bool]$RotatingColor = $null -ne $StepSize.H

Unable To Download Module From PowershellGallery

Hello,

When attempting to install the Pansies module from the powershell gallery using the following syntax
Find-Module -Name "Pansies" -IncludeDependencies | Install-Module -Force -AllowClobber -Verbose

I receive the following error (I have also attached a screenshot of said error):
PackageManagement\Install-Package : The module 'Pansies' cannot be installed
or updated because it is not a properly-formed module.
At C:\Program
Files\WindowsPowerShell\Modules\PowerShellGet\1.5.0.0\PSModule.psm1:1980
char:34

  • ... $null = PackageManagement\Install-Package @PSBoundParameters
  •                  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : InvalidOperation: (Microsoft.Power....InstallPac
      kage:InstallPackage) [Install-Package], Exception
    • FullyQualifiedErrorId : InvalidManifestModule,Test-ValidManifestModule,M
      icrosoft.PowerShell.PackageManagement.Cmdlets.InstallPackage
      image

[Question] How to make Pansies full color work in ConEmu

I can't seem to get Pansies to work in ConEmu and I'm unsure why. I'm using the command [PoshCode.Pansies.RgbColor]::XTermPalette as a test and I can clearly see that the varying shades of color are all the same. I tried looking at what the "behind the scenes" powershell console is displaying and it too is not displaying full color. If I open up a normal powershell terminal, it looks correct.

Do you know if there is something I need to do to ConEmu to get it to work correctly? I figured you may know what system setting (or whatever) I would need to enable to get this working correctly. If not, I'll try over at the ConEmu page.

Thanks!

Add New-VtConsoleSequence, to provide embeddable strings and not require Pansies in distributable code

Use case: my team has ~200 powershell modules deployed to an enterprise nuget source. Our dependency trees are a little cumbersome. We don't want to add any dependencies if we can avoid it.

We do use ANSI sequences, some of which I have generated with Pansies - โ™ฅ - but I am currently doing some awkward manipulation to create strings which I can embed in our modules.

I would like to use a function New-VtConsoleSequence in development, to create those strings.

It would have a Reset switch in one parameterset, to output an ANSI reset; the other parameterset would accept any valid input to the ctor for RgbColor, e.g. ForestGreen1, ea0016.

I would also like a EscapeAsExpression switch, which would behave as follows:

> New-VtConsoleSequence ea0016 -EscapeAsExpression
$([char]27)[38;2;234;0;22m

> New-VtConsoleSequence -Reset -EscapeAsExpression
$([char]27)[39m

Then my module functions will have code like this:

$DeepSkyBlue = "$([char]27)[38;2;0;191;255m"
$Reset       = "$([char]27)[0m"
Write-Information "$DeepSkyBlue`Stuff possibly relating to other stuff.$Reset"

Import-Module Pansies fails

When I try to import Pansies i get:

Import-Module : Ein Teil des Pfades "C:\Program Files\WindowsPowerShell\Modules\UserProfile\1.0\UserProfile.Format.ps1xml" konnte
nicht gefunden werden.
In Zeile:1 Zeichen:1
+ Import-Module Pansies
+ ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (:String) [Import-Module], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException,Microsoft.PowerShell.Commands.ImportModuleCommand

roughly translates to:

Part of the path "C: \ Program Files \ WindowsPowerShell \ Modules \ UserProfile \ 1.0 \ UserProfile.Format.ps1xml" failed to be found.

I checked and well there is directory UserProfile in the Modules folder.
When should this directory and the file get created?
What can I do to fix this?

PSVersion 5.1.17134.81
PSEdition Desktop
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
BuildVersion 10.0.17134.81
CLRVersion 4.0.30319.42000
WSManStackVersion 3.0
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1

Initializing Write-Host fails?

When i load up a new Console and try to

Write-Host ">" -ForegroundColor "#222222" -BackgroundColor Gold

I get an Error

Write-Host: Cannot bind parameter 'BackgroundColor'. Cannot convert value "Gold" to type "System.ConsoleColor". Error: "Unable to match the identifier name Gold to a valid enumerator name. Specify one of the following enumerator names and try again:
Black, DarkBlue, DarkGreen, DarkCyan, DarkRed, DarkMagenta, DarkYellow, Gray, DarkGray, Blue, Green, Cyan, Red, Magenta, Yellow, White"

This is from the Legacy Write-Host command.
Once i call for example

Get-ColorWheel

I can run my first Write-Host command as expected

Terminal: Alacritty

Example:
image

Pansies Works In Powershell But Not ISE

Pansies works in Powershell 5.1 - With all the business tasks and daily stress, it is kind of fun to have this whimsy around. However, it is not working in the ISE which is really all we use these days (long live POPS).

Create a TextSpan type

We need a base class something like this, with constructor that optionally takes just the string

public class Text {
    public string Text;
    public Color? ForegroundColor;
    public Color? BackgroundColor;
    //  override to output VT ANSI escape sequence
    public override string ToString()
}

And then, a collection class which also has a constructor that optionally takes just the string, but also can cast from a that base Text class, or an array of them. It shouldn't just call the base Text object ToString(), because the key feature of this being an array is to optimize (not output extra escapes), and include a reset at the end of the output.

public class TextSpan {
    public Text[] Text;
    public Color? ForegroundColor;
    public Color? BackgroundColor;
    // this one includes a reset at the end, so text after it goes back to normal output
    public override string ToString()
}

Write-Host '&' throws exception

Calling Write-Host '&' crashes, when the end index becomes -1.

Exception             :
    Type       : System.ArgumentOutOfRangeException
    Message    : Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'startIndex')
    ParamName  : startIndex
    TargetSite :
        Name          : IndexOf
        DeclaringType : string
        MemberType    : Method
        Module        : System.Private.CoreLib.dll
    StackTrace :
   at System.String.IndexOf(Char value, Int32 startIndex, Int32 count)
   at PoshCode.Pansies.Entities.Decode(String value) in C:\Users\Jaykul\Projects\Modules\PANSIES\Source\Assembly\Entities.cs:line 36
   at PoshCode.Pansies.Text.GetString(RgbColor foreground, RgbColor background, Object object, String separator, Boolean clear, Boolean entities, Boolean persistentColor) in C:\Users\Jaykul\Projects\Modules\PANSIES\Source\Assembly\Text.cs:line 231
   at PoshCode.Pansies.Commands.WriteHostCommand.ProcessRecord() in C:\Users\Jaykul\Projects\Modules\PANSIES\Source\Assembly\Commands\WriteHostCommand.cs:line 33
   at System.Management.Automation.CommandProcessor.ProcessRecord()
    Source     : System.Private.CoreLib
    HResult    : -2146233086
CategoryInfo          : NotSpecified: (:) [Write-Host], ArgumentOutOfRangeException
FullyQualifiedErrorId : System.ArgumentOutOfRangeException,PoshCode.Pansies.Commands.WriteHostCommand
InvocationInfo        :
    MyCommand        : Write-Host
    ScriptLineNumber : 1
    OffsetInLine     : 1
    HistoryId        : 3
    Line             : Write-Host '&'
    PositionMessage  : At line:1 char:1
                       + Write-Host '&'
                       + ~~~~~~~~~~~~~~
    InvocationName   : Write-Host
    CommandOrigin    : Internal
ScriptStackTrace      : at <ScriptBlock>, <No file>: line 1

Version 2.3.0

Nerd Fonts Breaking Change

Since the nerd fonts are in the system, we need to adjust to the breaking change in Nerd Fonts 3.0 (they moved and renamed the Material Design icons).

Therefore, on the new release of Cascadia Code, Write-Host "&nf-mdi-ship_wheel; Kubernetes" doesn't work.

The character on the NerdFont cheat sheet is now named nf-md-ship_wheel and the code point was changed.

NOTE: They've moved a few things around after that, so it's frustrating to rely on some of the nerd font characters right now.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.