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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351

# \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
}

class FormatOptions {
    [string]$Value
    [bool]$Prefix
    [string]$PrefixValue
    [bool]$Append 
    [string]$Appendvalue
    [bool]$Attribute
    [string]$AttributeValue
}

$Wansi = New-Object -TypeName WansiConfig

function Get-FormatOptions {
    param (
        $Token
    )

    $f = New-Object -TypeName FormatOptions 
    $f.AppendValue = ""
    $f.PrefixValue = ""

    if (-not ($Token -match "\|")) {
        $f.Value = $Token
        return $f
    }

    $spec = $Token.SubString($Token.IndexOf("|") + 1)

    $f.Value = $Token.SubString(0, $Token.IndexOf("|"))

    if ($spec.Length -lt 1) {
        return $f
    }

    $escapeNext = $false
    $capture = ""
    
    $spec.ToCharArray() | ForEach-Object {

        $c = $_

        switch -Wildcard ($c) {
            "\" {
                $escapeNext = $true; Break
            }
            ">" {
                if (-not $escapeNext) {
                    $capture = "A"
                    $f.Append = $true
                    Break
                }                
            }
            "<" {
                if (-not $escapeNext) {
                    $capture = "P"
                    $f.Prefix = $true
                    Break
                }
            }
            "*" {
                $escapeNext = $false
                switch ($capture) {
                    "P" {
                        $f.PrefixValue += $c
                        Break
                    }

                    "A" {
                        $f.AppendValue += $c
                        Break                        
                    }
                }
                

            }
            # default {
            # }
        }

    }

    $f

}
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 Set-WansiToken {
    param (
        [string]$Name,
        [string]$Value
    )

    Add-Member -InputObject $Wansi -MemberType NoteProperty -Name $Name -Value $Value -Force

}

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

    $result = $Value

    # "\{\{(\w+[<>](.)?[<>]?(.))\}\}"

    $captures = [regex]::Matches($Value, "\{\{([^\}]*)\}\}").Groups.captures
    foreach ($capture in $captures) {
        if ($null -ne $capture.Groups) {
            $token = $capture.Groups[0].Value


            $property = $capture.Groups[1].Value

            $fmt = Get-FormatOptions $property

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

            if ($code.Length -gt 0) {

                if ($fmt.Prefix) {
                    if ($fmt.PrefixValue.Length -lt 1) {
                        $fmt.PrefixValue = " "
                    }

                    if ($fmt.PrefixValue[0] -eq "@") {
                        $fmt.PrefixValue = "{:$($fmt.PrefixValue.SubString(1)):}"
                    }

                    $code = $fmt.PrefixValue + $code
                }

                if ($fmt.Append) {

                    if ($fmt.AppendValue.Length -lt 1) {
                        $fmt.AppendValue = " "
                    }

                    if ($fmt.AppendValue[0] -eq "@") {
                        $fmt.AppendValue = "{:$($fmt.AppendValue.SubString(1)):}"
                    }

                    $code = $code + $fmt.AppendValue
                }
            }

            $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, 'Set-WansiToken'
Export-ModuleMember -Function Out-Default, 'Get-FormatOptions'
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'