-
Notifications
You must be signed in to change notification settings - Fork 9
/
Colors.ps1
424 lines (346 loc) · 11.3 KB
/
Colors.ps1
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
function Write-Colorized
{
<#
.SYNOPSIS
Output object to stdout with specific color
.DESCRIPTION
Prints an object contents colorized in a specific color. Makes the output
more readable on a console screen and the output can be still redirected
as a regular stdout.
.PARAMETER Color
Name of the color to be used for coloring.
Use Get-Colors command to output all available colors.
.PARAMETER Object
Object to be outputted to stdout.
.EXAMPLE
Write-Colorized green "=)", "test"
Prints all items in passed string array to stdout with green color
used in your console.
.LINK
Get-Colors
#>
param
(
[Parameter(Mandatory = $true)]
[string] $Color,
[Parameter(Mandatory = $true)]
[object] $Object
)
$previous, [Console]::ForegroundColor = [Console]::ForegroundColor, [ConsoleColor]::$color
$object
[Console]::ForegroundColor = $previous
}
function Show-Highlight
{
<#
.SYNOPSIS
Highlight portion of some text to make it visually
easier to find something in the text
.DESCRIPTION
Uses regex to find some some portion in the input text send via pipe.
Matching text is highlighted with the color specified.
Without regex specified this function would highlight code examples
in the Powershell build in help.
alias: hl
.PARAMETER Regex
Regular expression used to match interesting part of the input text.
By default: regex that would match code snippets in the help examples.
.PARAMETER Color
Color that would be used to highlight matching text.
By default: dark magenta
.PARAMETER DropUnmatched
If line doesn't match regex, don't return it.
By default: unmatched lines are returned without highlighting
.PARAMETER Interactive
Render output as soon as it is received.
By default: Out-String is called after all the input is received.
.PARAMETER JSON
Use pre-defined regex for JSON output.
If user specifies $regex or color explicitly they take precedence.
.EXAMPLE
"test tee, please", "tee" | Show-Highlight e+ red
Highlights all 'e' chars in the input with red.
.EXAMPLE
man hl -Examples | hl
Highlights code snippets in Show-Highlight examples help.
.EXAMPLE
tracert bing.com | hl "[a-f0-9]+:[a-f0-9:]+" green -int
Highlights IPv6 addresses from tracert output with green color.
Output us rendered as soon as it is available.
.EXAMPLE
ls | hl ps1 -drop
Highlights files or folders from ls output that match 'ps1' regex.
If a line is not matching, it is dropped.
.EXAMPLE
Get-TimeZone | ConvertTo-Json | hl -JSON
Highlights JSON syntax chars making output a bit more readable.
.LINK
Get-Colors
#>
param
(
[string] $Regex = "^\s*PS\s+.*>.+",
[ConsoleColor] $Color = "Blue",
[switch] $DropUnmatched,
[switch] $Interactive,
[switch] $JSON
)
begin
{
function Get-Markup
{
$start = 0
$sections = [Regex]::Matches($line, $regex, "IgnoreCase") | select Index, Length, Value
foreach( $section in $sections )
{
[ordered] @{ type = "text"; start = $start; end = $section.Index - 1 }
[ordered] @{ type = "high"; start = $section.Index; end = $section.Index + $section.Length - 1 }
$start = $section.Index + $section.Length
}
[ordered] @{ type = "text"; start = $start; end = $line.Length - 1 }
}
function Use-Markup
{
foreach( $line in ($lines | Out-String | foreach TrimEnd) -split "`r?`n" )
{
if( $line -notmatch $regex )
{
if( -not $dropUnmatched )
{
$line
}
continue
}
foreach( $info in (Get-Markup | where{ $psitem.start -le $psitem.end }) )
{
$text = $line.Substring($info.start, $info.end - $info.start + 1)
$foreground = if( $info.type -eq "text" ) { [Console]::ForegroundColor } else { $color }
Write-Host $text -ForegroundColor $foreground -NoNewline
}
Write-Host ""
}
}
$lines = @()
if( $JSON )
{
if( (-not $Regex) -or ($Regex -eq "^\s*PS\s+.*>.+") )
{
$regex = '["{}/:,]'
}
}
}
process
{
$lines += $psitem
if( $interactive )
{
Use-Markup
$lines = @()
}
}
end
{
if( -not $interactive )
{
Use-Markup
}
}
}
function Get-Colors
{
<#
.SYNOPSIS
Print all console host colors to the console in color
.DESCRIPTION
Possible color names taken from '[ConsoleColor] | gm -Static' are:
Blue | DarkBlue
Cyan | DarkCyan
Gray | DarkGray
Green | DarkGreen
Magenta | DarkMagenta
Red | DarkRed
Yellow | DarkYellow
White | Black
.EXAMPLE
Get-Colors
Would output all colors to the console output.
#>
function color( $name )
{
[Console]::ForegroundColor = [ConsoleColor]::$name
}
$previous = [Console]::ForegroundColor
color Blue
[Console]::Out.Write("Blue")
color DarkBlue
[Console]::Out.WriteLine(" DarkBlue")
color Cyan
[Console]::Out.Write("Cyan")
color DarkCyan
[Console]::Out.WriteLine(" DarkCyan")
color Gray
[Console]::Out.Write("Gray")
color DarkGray
[Console]::Out.WriteLine(" DarkGray")
color Green
[Console]::Out.Write("Green")
color DarkGreen
[Console]::Out.WriteLine(" DarkGreen")
color Magenta
[Console]::Out.Write("Magenta")
color DarkMagenta
[Console]::Out.WriteLine(" DarkMagenta")
color Red
[Console]::Out.Write("Red")
color DarkRed
[Console]::Out.WriteLine(" DarkRed")
color Yellow
[Console]::Out.Write("Yellow")
color DarkYellow
[Console]::Out.WriteLine(" DarkYellow")
color White
[Console]::Out.Write("White")
color Black
[Console]::Out.WriteLine(" Black")
[Console]::ForegroundColor = $previous
}
function Get-Source
{
<#
.SYNOPSIS
Print source code of a command or script in color
.DESCRIPTION
Gets sources of a command, a script or an alias and outputs
them with syntax highlighting to the host.
Alias: source
.PARAMETER CommandName
Command name or alias name or path to a Powershell script file.
.EXAMPLE
Get-Source hl
Get sources of the command that is resolved from hl alias in color.
#>
param
(
[string] $CommandName
)
function Get-CommandSource
{
# Getting corresponding command object
$command = Get-Command $commandName | select -First 1
if( $command.CommandType -eq "Alias" )
{
$command = Get-Command $command.Definition
}
# Fixing shortcomings of $command.Definition - it truncates
# function start for some reason
$firstFix = $false
$command.Definition -split "`r?`n" | foreach `
{
if( (-not $firstFix) -and ($psitem -match "^\S") )
{
""
" " + $psitem
$firstFix = $true
}
else
{
$psitem
}
}
}
# Getting source code of the command
if( Test-Path $commandName )
{
$source = Get-Content $commandName
}
else
{
$source = Get-CommandSource
}
# Rendering sources in color
Show-ColorizedContent $source
}
function Show-ColorizedContent
{
param
(
$content = $(throw "Powershell script must be specified"),
$highlightRanges = @(),
[System.Management.Automation.SwitchParameter] $excludeLineNumbers
)
$replacementColours =
@{
Attribute = "DarkCyan"
Command = "DarkCyan"
CommandParameter = "DarkMagenta"
CommandArgument = "Gray"
Comment = "DarkGreen"
Grouper = "DarkCyan"
Keyword = "Gray"
Member = "DarkCyan"
Number = "DarkGray"
Operator = "DarkRed"
Property = "Gray"
StatementSeparator = "DarkCyan"
String = "DarkYellow"
Type = "DarkCyan"
Variable = "DarkGray"
}
$highlightColor = "Green"
$highlightCharacter = ">"
# Read the text of the file, and parse it
$content = $content | Out-String
$parsed = [Management.Automation.PsParser]::Tokenize($content, [ref] $null) | sort StartLine, StartColumn
function WriteFormattedLine($formatString, [int] $line)
{
if($excludeLineNumbers) { return }
$hColor = "Gray"
$separator = "|"
if($highlightRanges -contains $line) { $hColor = $highlightColor; $separator = $highlightCharacter }
Write-Host -NoNewLine -Fore $hColor ($formatString -f $line, $separator)
}
Write-Host
WriteFormattedLine "{0:D3} {1} " 1
$column = 1
foreach($token in $parsed)
{
$color = "Gray"
# Determine the highlighting colour
$color = $replacementColours[[string]$token.Type]
if(-not $color) { $color = "Gray" }
# Now output the token
if(($token.Type -eq "NewLine") -or ($token.Type -eq "LineContinuation"))
{
$column = 1
Write-Host
WriteFormattedLine "{0:D3} {1} " ($token.StartLine + 1)
}
else
{
# Do any indenting
if($column -lt $token.StartColumn)
{
Write-Host -NoNewLine (" " * ($token.StartColumn - $column))
}
# See where the token ends
$tokenEnd = $token.Start + $token.Length - 1
# Handle the line numbering for multi-line strings
$lineCounter = $token.StartLine
$stringLines = $( -join $content[$token.Start..$tokenEnd] -split "`r`n")
foreach($stringLine in $stringLines)
{
if($lineCounter -gt $token.StartLine)
{
WriteFormattedLine "$([Environment]::NewLine){0:D3} {1}" $lineCounter
}
Write-Host -NoNewLine -Fore $color $stringLine
$lineCounter++
}
# Update our position in the column
$column = $token.EndColumn
}
}
Write-Host ([Environment]::NewLine)
}