WieldingAnsi.psm1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233

# \033[38;2;<r>;<g>;<b>m #Select RGB foreground color
# \033[48;2;<r>;<g>;<b>m #Select RGB background color

class WansiConfig {
    [string]$UnderlineOn = "`e[4m"
    [string]$UnderlineOff = "`e[24m"
    [string]$BoldOn = "`e[1m"
    [string]$BoldOff = "`e[22m"    
    [string]$InverseOn = "`e[7m"
    [string]$InverseOff = "`e[27m"        
    [string]$R = "`e[0m"
    [bool]$Enabled = $true
}

class AnsiString {
    [int]$Length
    [int]$NakedLength
    [int]$InvisibleLength
    [string]$Value
}

$Wansi = New-Object -TypeName WansiConfig

function Get-WieldingAnsiInfo {
    $moduleName = (Get-ChildItem "$PSScriptRoot/*.psd1").Name

    Import-PowerShellDataFile -Path "$PSScriptRoot/$moduleName"
}

function Update-AnsiCodes() {
    <#
 .SYNOPSIS
    Builds the color attributes for the AnsiCodes class
 
 .DESCRIPTION
    Builds the color attributes for the AnsiCodes class
 
 .NOTES
    It is not generally necessary to call this function unless you want to reset
    the $Wansi class values after they have been altered in some way.
#>
    
    $esc = $([char]27)
    foreach ($fb in 38, 48) {
        foreach ($color in 0..255) {
            Add-Member -InputObject $Wansi -MemberType NoteProperty -Name "$(if ($fb -eq 38) {"F"} Else {"B"})$color" -Value "$esc[$fb;5;${color}m" -Force
        }
    }    
}
function Show-AnsiCodes() {
    <#
     .SYNOPSIS
        Displays the supported ANSI values
     
     .DESCRIPTION
        Displays the supported ANSI values
 
     .EXAMPLE
        Show-AnsiCodes
        Displays the ANSI code table
    #>
        

    $output = ""
    $output += (ConvertTo-AnsiString "`n{:UnderlineOn:}Styles{:R:}`n").Value
    $output += (ConvertTo-AnsiString "{:BoldOn:}Bold '`$Wansi.BoldOn'{:BoldOff:} : Bold Off '`$Wansi.BoldOff'{:R:}`n").Value
    $output += (ConvertTo-AnsiString "{:UnderlineOn:}Underline '`$Wansi.UnderlineOn'{:UnderlineOff:} : Underline Off '`$Wansi.UnderlineOff'{:R:}`n").Value
    $output += (ConvertTo-AnsiString "{:InverseOn:}Inverse '`$Wansi.InverseOn'{:InverseOff:} : Inverse Off '`$Wansi.InverseOff'{:R:}`n").Value
    $output += (ConvertTo-AnsiString "{:InverseOn:}{:UnderlineOn:}{:BoldOn:}Everything On {:R:}: Reset `$(`$Wansi.R)`n" ).Value
    
    $output += (ConvertTo-AnsiString "`n{:UnderlineOn:}Foreground(`$Wansi.F`#), Background(`$Wansi.B`#){:R:}`n").Value

    foreach ($color in 0..255) {
        $fg = ConvertTo-AnsiString " $color" -PadRight 5
        $bg = ConvertTo-AnsiString "{`:B$color`:}" -PadRight 5
        $temp = "{0, -5}{1}{2}" -f $fg.Value, "{:F0:}", $bg.Value
        $output += (ConvertTo-AnsiString "$temp{:R:}").Value
        if ( (($color + 1) % 6) -eq 4 ) { $output += "`n" }
    }

    $output
}

function Expand-Tokens {
    param (
        [string]$Value
    )

    $result = $Value

    $captures = [regex]::Matches($Value, "\{\{(\w+\+?)\}\}").Groups.captures
    foreach ($capture in $captures) {
        if ($null -ne $capture.Groups) {
            $appendSpace = $false
            $token = $capture.Groups[0].Value
            $property =$capture.Groups[1].Value
            if ($property -match '\+$') {
                $appendSpace = $true
            }

            if ($appendSpace) {
                $property = $property.SubString(0, $property.Length - 1)
            }

            $code = $Wansi.PSObject.Properties.Item($property).Value

            if ($appendSpace -and $code.Length -gt 0) {
                $code = $code + " "
            }

            $result = $result.Replace($token, $code)
        }
    }

    $result

}

function ConvertTo-AnsiString {
    <#
 .SYNOPSIS
    Converts input string with Wansi tokens
 
 .DESCRIPTION
    Converts input string with Wansi tokens to a string with embedded ANSI escape codes.
 
 .PARAMETER Value
    The string containing Wansi tokens to be converted
 
 .EXAMPLE
    Write-Wansi "{:F3:}{:B4:}Test{:R:}`n"
    Writes the word 'Test' to the console with a Red foreground and Blue background.
 
 .OUTPUTS
    an AnsiString object with Length, NakedLength and Value properties.
#>
            
    param (
        [string]$Value,
        [int]$PadRight,
        [int]$PadLeft
    )

    $result = Expand-Tokens $Value    
    $naked = $result

    $captures = [regex]::Matches($result, "\{:(\w+):\}").Groups.captures
    $tokensLength = 0

    foreach ($capture in $captures) {
        if ($null -ne $capture.Groups) {
            $token = $capture.Groups[0].Value
            $property =$capture.Groups[1].Value
            $naked = $naked.Replace($capture.Groups[0].Value, "")


            if ([bool]($Wansi.PSObject.Properties.name.Contains($property))) {
                $code = $Wansi.PSObject.Properties.Item($property).Value
                $tokensLength += $code.Length
                if ($Wansi.Enabled) {
                    $result = $result.Replace($token, $code)
                }  else {
                    $result = $result.Replace($token, "")
                }
            }            
        }
    }

    $padLength = 0

    if (-not $Wansi.Enabled) {
        $tokensLength = 0;
    }

    if ($PadLeft -ne 0) {        
        $originalLength = $result.Length
        $result = $result.PadLeft($PadLeft + $tokensLength, " ")
        $padLength += ($result.Length - $originalLength)
    }

    if ($PadRight -ne 0) {
        $originalLength = $result.Length
        $result = $result.PadRight($PadRight + $tokensLength, " ")
        $padLength += ($result.Length - $originalLength)
    }
   
    $ansiString = New-Object -TypeName AnsiString
    $ansiString.Value = $result
    $ansiString.NakedLength = $naked.Length + $padLength
    $ansiString.Length = $result.Length
    if ($Wansi.Enabled) {
        $ansiString.InvisibleLength = $tokensLength
    } else {
        $ansiString.InvisibleLength = 0
        $ansiString.NakedLength = $result.Length
    }

    return $ansiString
}

function Write-Wansi() {
    <#
 .SYNOPSIS
    Displays passed string containing Wansi tokens to the console.
 
 .DESCRIPTION
    Displays provided string containing Wansi tokens to the console after
    converting the tokens to ANSI escape sequences
 
  .PARAMETER Value
    The string value to convert Wansi tokens to ansi codes and write to console
     
  .NOTES
    This function does not produce a newline character so the caller must supply one
    with an escape sequence or produce one when the function returns if desired.
#>
            
    param (
        [string]$Value
    )

    Write-Output $(ConvertTo-AnsiString $Value).Value
}

Update-AnsiCodes

Export-ModuleMember -Function Out-Default, 'Get-WieldingAnsiInfo'
Export-ModuleMember -Function Out-Default, 'Show-AnsiCodes'
Export-ModuleMember -Function Out-Default, 'Update-AnsiCodes'
Export-ModuleMember -Function Out-Default, 'Expand-Tokens'
Export-ModuleMember -Function Out-Default, 'ConvertTo-AnsiString'
Export-ModuleMember -Function Out-Default, 'Write-Wansi'
Export-ModuleMember -Variable 'Wansi'