-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
ShowDemo.format.ps1xml
1468 lines (1351 loc) · 57.3 KB
/
ShowDemo.format.ps1xml
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?xml version="1.0" encoding="utf-16"?>
<!-- Generated with EZOut 2.0.5: Install-Module EZOut or https://github.com/StartAutomating/EZOut -->
<Configuration>
<Controls>
<Control>
<Name>DemoViewer</Name>
<CustomControl>
<CustomEntries>
<CustomEntry>
<CustomItem>
<ExpressionBinding>
<ItemSelectionCondition>
<ScriptBlock>
# If the demo has not started yet
-not $_.DemoStarted
</ScriptBlock>
</ItemSelectionCondition>
<ScriptBlock>$moduleName = 'ShowDemo'
do {
$lm = Get-Module -Name $moduleName -ErrorAction Ignore
if (-not $lm) { continue }
if ($lm.FormatPartsLoaded) { break }
$wholeScript = @(foreach ($formatFilePath in $lm.exportedFormatFiles) {
foreach ($partNodeName in Select-Xml -LiteralPath $formatFilePath -XPath "/Configuration/Controls/Control/Name[starts-with(., '$')]") {
$ParentNode = $partNodeName.Node.ParentNode
"$($ParentNode.Name)={
$($ParentNode.CustomControl.CustomEntries.CustomEntry.CustomItem.ExpressionBinding.ScriptBlock)}"
}
}) -join [Environment]::NewLine
New-Module -Name "${ModuleName}.format.ps1xml" -ScriptBlock ([ScriptBlock]::Create(($wholeScript + ';Export-ModuleMember -Variable *'))) |
Import-Module -Global
$onRemove = [ScriptBlock]::Create("Remove-Module '${ModuleName}.format.ps1xml'")
if (-not $lm.OnRemove) {
$lm.OnRemove = $onRemove
} else {
$lm.OnRemove = [ScriptBlock]::Create($onRemove.ToString() + '' + [Environment]::NewLine + $lm.OnRemove)
}
$lm | Add-Member NoteProperty FormatPartsLoaded $true -Force
} while ($false)
$demo = $_
if ($demo.RecordDemo) {
$startRecordingCommand = $ExecutionContext.SessionState.InvokeCommand.GetCommand('Start-Recording','Function,Alias')
if ($startRecordingCommand) {
$null = Start-Recording
} else {
Write-Warning "Start-Recording was not found. Have you installed/imported obs-powershell?"
}
}
# Start the demo.
$demo.Start()
# Then, create a message indicating we've started.
if ($demo.StartMessage) {
$demoStartMessage =
& ${ShowDemo_Format-RichText} -ForegroundColor Warning -InputObject (
$demo.StartMessage +
([Environment]::NewLine * 2)
) -Italic
# If the demo is being run interactively,
if ($demo.Interactive) {
# write that message to the host.
$demoStartMessage | Out-Host
""
}
# Otherwise, as long as we are not outputting markdown
elseif (-not $demo.Markdown) {
# output the demo started message.
($demoStartMessage -join '') + [Environment]::NewLine
} else {
''
}
}
if ($demo.Interactive) {
[Console]::OutputEncoding = $OutputEncoding
}
</ScriptBlock>
</ExpressionBinding>
<ExpressionBinding>
<ItemSelectionCondition>
<ScriptBlock>
# If the demo has started, is interactive, and not markdown
$_.DemoStarted -and $_.Interactive -and -not $_.Markdown
</ScriptBlock>
</ItemSelectionCondition>
<ScriptBlock>
# attempt to to change the window title.
$Duration = [DateTime]::Now - $_.DemoStarted
$Host.UI.RawUI.WindowTitle = "{0}[{1}m, {2}s] {2}" -f $_.Name, [int]$Duration.TotalMinutes, [int]$Duration.Seconds
""
</ScriptBlock>
</ExpressionBinding>
<ExpressionBinding>
<ItemSelectionCondition>
<ScriptBlock>
# If we do not have a current chapter
-not $_.CurrentChapter
</ScriptBlock>
</ItemSelectionCondition>
<ScriptBlock>
# pick the first chapter and modify the object.
$firstChapter = $_.Chapters[0]
$_ | Add-Member NoteProperty CurrentChapter $firstChapter -Force
$_ | Add-Member NoteProperty CurrentStep 0 -Force
""
</ScriptBlock>
</ExpressionBinding>
<ExpressionBinding>
<ItemSelectionCondition>
<ScriptBlock>
# If we do not have a current step
-not $_.CurrentStep
</ScriptBlock>
</ItemSelectionCondition>
<ScriptBlock>
# Start the chapter
$_.StartChapter()
$demo = $_
# and get the first step
$stepToRun = $demo.CurrentChapter.Steps[$demo.CurrentStep - 1]
# while the step is hidden
while ($stepToRun.HiddenStep) {
$stepToRun.Invoke() # run it
$demo.NextStep() # and move onto the next step.
$stepToRun = $demo.CurrentChapter.Steps[$demo.CurrentStep - 1]
}
# declare a chapter heading
$chapterHeading =
$demo.CurrentChapter.Number +
' ' +
$demo.CurrentChapter.Name + ([Environment]::NewLine * 2)
$ChapterHeadingSplat = [Ordered]@{ForegroundColor='Verbose';InputObject=$chapterHeading;Underline=$true}
# and get a rich text version of that heading
$null = New-Event -SourceIdentifier Demo.WriteChapterName -Sender $demo -MessageData ([Ordered]@{} + $ChapterHeadingSplat)
$currentChapterText =
& ${ShowDemo_Format-RichText} @ChapterHeadingSplat
# If we are running interactively
if ($_.Interactive) {
# output that message now
$currentChapterText | Out-Host
''
} elseif ($demo.Markdown) {
# otherwise, if we are generating markdown,
# determine the heading size.
$headingSize = [int][math]::max($demo.HeadingSize, 3)
# use Format-Markdown
(& ${ShowDemo_Format-Markdown} -HeadingSize $headingSize -InputObject $chapterHeading)
} else {
# if we are not running interactively, output the rich text from our formatter.
($currentChapterText -join '') + [Environment]::NewLine
}
</ScriptBlock>
</ExpressionBinding>
<ExpressionBinding>
<ItemSelectionCondition>
<ScriptBlock>
# If there is a current step
$_.CurrentStep
</ScriptBlock>
</ItemSelectionCondition>
<ScriptBlock>
$demo = $_
# set step to run
$stepToRun = $demo.CurrentChapter.Steps[$demo.CurrentStep - 1]
# while the step is hidden
while ($stepToRun.HiddenStep) {
$stepToRun.Invoke() # run it
$demo.NextStep() # and move onto the next step.
$stepToRun = $demo.CurrentChapter.Steps[$demo.CurrentStep - 1]
}
</ScriptBlock>
</ExpressionBinding>
<ExpressionBinding>
<ItemSelectionCondition>
<ScriptBlock>
$_.StepToRun -and
$_.ShowPrompt -and
(-not $_.DemoFinished)
</ScriptBlock>
</ItemSelectionCondition>
<ScriptBlock>
$promptOutput = prompt
$null = New-Event -SourceIdentifier Demo.WritePrompt -Sender $demo -MessageData $promptOutput
if ($_.Interactive) {
$promptOutput | Out-Host
} # and we're running interactively
else {
$promptOutput | Out-String
}
</ScriptBlock>
</ExpressionBinding>
<ExpressionBinding>
<ItemSelectionCondition>
<ScriptBlock>
# If we still have a current step
$_.CurrentStep
</ScriptBlock>
</ItemSelectionCondition>
<ScriptBlock>
$demo = $_
$stepToRun = $demo.CurrentChapter.Steps[$demo.CurrentStep - 1]
# Update the object with it.
$demo | Add-Member NoteProperty StepToRun $stepToRun -Force
# If we are rendering markdown
if ($demo.Markdown) {
# and the step is a comment
if ($stepToRun.IsComment) {
# replace the comment start and end
("$stepToRun" -replace '^\<{0,1}\#{1}' -replace '\#\>\s{0,}$').Trim()
}
# If the step was not a comment
else
{
# Make it a PowerShell code block.
[Environment]::NewLine +
(& ${ShowDemo_Format-Markdown} -InputObject $stepToRun.Trim() -CodeLanguage PowerShell) +
[Environment]::NewLine
}
# If we are outputting markdown, we're done with this formatting step.
return
}
# If we are not outputting markdown, then let's figure out our real sleep
$realSleep =
# If it's greater than a millisecond
if ($demo.TypeSpeed.TotalMilliseconds -ge 1) {
$demo.TypeSpeed # trust their input
} elseif ($demo.TypeSpeed.Ticks)
{
# Otherwise, try to convert from
$letterPerMillisecond =
($demo.TypeSpeed.Ticks * 6) # words per minute
/ (60 * 1000) # to milliseconds.
[TimeSpan]::FromMilliseconds($letterPerMillisecond)
} else {
# otherwise, have no delay
[timespan]0
}
# Now run over each segment of colorized output for the step
$strOut = @(foreach ($output in $demo.ShowStep($stepToRun)) {
$outputCopy = @{} + $output
if ($output.InputObject) {
# Start off by setting the rich text formatting used for this sequence of tokens
$null = New-Event -SourceIdentifier Demo.WriteStep -Sender $demo -MessageData ([Ordered]@{} + $output)
$outputCopy.NoClear = $true
$outputCopy.InputObject = ''
# If we're running interactively, write that to the console now
if ($demo.Interactive) {
[Console]::Write((& ${ShowDemo_Format-RichText} @outputCopy) -join '')
} else {
# otherwise, add it to $strOut.
& ${ShowDemo_Format-RichText} @outputCopy
}
# Next, determine our chunks of output
$chunks =
# If we're going letter-by-letter
if ($demo.TypeStyle -eq 'Letters') {
# it's a character array.
"$($output.InputObject)".ToCharArray()
}
# If we're going word by word,
elseif ($demo.TypeStyle -eq 'Words') {
# it's split next to each space.
"$($output.InputObject)" -split '(?=\s)'
}
# otherwise, just output the block
else{
"$($output.InputObject)"
}
# Walk over each chunk of output
foreach ($chunk in $chunks) {
if (-not $chunk) { continue }
# If running interactively,
if ($demo.Interactive) {
# write it to the console
[Console]::Write("$chunk")
} else {
# otherwise, add it to $strOut
$chunk
}
# If we are running interactively, sleep.
if ($realSleep.Ticks -and $demo.Interactive) {
# (this gives us our typing effect)
$null = Start-Sleep -Milliseconds $realSleep.TotalMilliseconds
}
}
# Now we need to do one more write to close the formatting
$null = $outputCopy.Remove('NoClear')
$outputCopy.InputObject = ' '
$output.InputObject = ''
# If we're running interactively
if ($demo.Interactive) {
# that goes to the console now.
[Console]::Write((& ${ShowDemo_Format-RichText} @output) -join '')
} else {
(& ${ShowDemo_Format-RichText} @output) -join ''
}
}
})
# If we are running interactively
if ($demo.Interactive) {
'' # emit nothing from the formatter (since we've already written to the console)
} else {
# otherwise, emit the string.
$strOut -join ''
}
</ScriptBlock>
</ExpressionBinding>
<ExpressionBinding>
<ItemSelectionCondition>
<ScriptBlock>
# If the demo is not done and it is interactive
-not $_.DemoFinished -and $_.Interactive -and -not $_.AutoPlay
</ScriptBlock>
</ItemSelectionCondition>
<ScriptBlock>
$demo = $_
# Read input
$hostInput = Read-Host
# and the process it
foreach ($output in $demo.ProcessInput($hostInput)) {
# any output we want to display as a warning
if ($output -is [string]) {
& ${ShowDemo_Format-RichText} -ForegroundColor Warning -InputObject $output | Out-Host
}
# unless it was a series of splats for Format-RichText
elseif ($output -is [Collections.IDictionary]) {
& ${ShowDemo_Format-RichText} @output | Out-Host # ( which we will run and output )
}
# or a scriptblock.
elseif ($output -is [scriptblock]) {
. output | Out-Host # (which we will run).
}
}
</ScriptBlock>
</ExpressionBinding>
<ExpressionBinding>
<ItemSelectionCondition>
<ScriptBlock>
$_.StepToRun # If we have a StepToRun
</ScriptBlock>
</ItemSelectionCondition>
<ScriptBlock>
$demo = $_
# Run it.
$DemoStepOutput = $null
if ($PSStyle) {
$PSStyle.OutputRendering = 'ANSI'
}
if ($demo.Interactive) {
[Console]::WriteLine()
if ($demo.PauseBetweenLine) {
# If we're running interactively, pipe it out.
$DemoStepOutput = @(Invoke-Expression -Command $demo.StepToRun *>&1 |
Out-String) -split '(?>\r\n|\n)'
foreach ($demoOutputLine in $DemoStepOutput) {
Start-Sleep -Milliseconds $demo.PauseBetweenLine.TotalMilliseconds
Write-Host $demoOutputLine
}
} else {
# If we're running interactively, pipe it out.
Invoke-Expression -Command $demo.StepToRun *>&1 |
Out-String -OutVariable DemoStepOutput |
Out-Host
}
}
else{
# Otherwise, pipe it to Out-String
$stepOutput =
Invoke-Expression -Command $demo.StepToRun *>&1 |
Out-String -Width 1kb -OutVariable DemoStepOutput
# If we're outputting markdown
if ($demo.Markdown) {
# add a newline above and below
[Environment]::NewLine + $(
@(
# If it looks like a tag
if ($stepOutput -match '^\<') {
$stepOutput # include without indentation
} else {
# Otherwise, indent 4 chars so it is seen as preformatted text.
foreach ($line in @($stepOutput -split '(?>\r\n|\n)')) {
(' ' * 4) + $line
}
}
) -join [Environment]::NewLine
) +
[Environment]::NewLine
} else {
[Environment]::NewLine + $stepOutput
}
}
if ($DemoStepOutput) {
$null = New-Event -SourceIdentifier Demo.WriteOutput -Sender $demo -EventArguments $demo.StepToRun -MessageData $DemoStepOutput
}
</ScriptBlock>
</ExpressionBinding>
<ExpressionBinding>
<ItemSelectionCondition>
<ScriptBlock>
# If we had a step to run
$_.StepToRun -and
(-not $_.DemoFinished) -and # and the demo's not done
(-not $_.StepToRun.IsComment) -and # and the step is not a comment
(-not $_.Autoplay) -and # and we're not autoplaying
$_.Interactive # and we're running interactively
</ScriptBlock>
</ItemSelectionCondition>
<ScriptBlock>
$demo = $_
# Prompt and process again
$hostInput = Read-Host
foreach ($output in $demo.ProcessInput($hostInput)) {
if ($output -is [string]) {
& ${ShowDemo_Format-RichText} -ForegroundColor Warning -InputObject $output | Out-Host
}
elseif ($output -is [Collections.IDictionary]) {
& ${ShowDemo_Format-RichText} @output | Out-Host
}
elseif ($output -is [scriptblock]) {
. output | Out-Host
}
}
</ScriptBlock>
</ExpressionBinding>
<ExpressionBinding>
<ItemSelectionCondition>
<ScriptBlock>
$_.Autoplay
</ScriptBlock>
</ItemSelectionCondition>
<ScriptBlock>
Start-Sleep -Milliseconds $_.PauseBetweenStep.TotalMilliseconds
</ScriptBlock>
</ExpressionBinding>
<ExpressionBinding>
<ItemSelectionCondition>
<ScriptBlock>
# If we had a current step
$_.CurrentStep
</ScriptBlock>
</ItemSelectionCondition>
<ScriptBlock>
# Advanced to the next step
$_.NextStep()
</ScriptBlock>
</ExpressionBinding>
<ExpressionBinding>
<ItemSelectionCondition>
<ScriptBlock>
-not $_.DemoFinished # If the demo was not finished
</ScriptBlock>
</ItemSelectionCondition>
<ScriptBlock>
# recursively call this formatter
$_
</ScriptBlock>
<CustomControlName>DemoViewer</CustomControlName>
</ExpressionBinding>
<ExpressionBinding>
<ItemSelectionCondition>
<ScriptBlock>
# If the demo is finished
$_.DemoFinished
</ScriptBlock>
</ItemSelectionCondition>
<ScriptBlock>
$demo = $_
# figure out how long it took
$duration = $_.DemoFinished - $_.DemoStarted
# change the status
$demo.SetStatus('Finished')
if ($demo.RecordDemo) {
$stopRecording = $ExecutionContext.SessionState.InvokeCommand.GetCommand('Stop-Recording', 'Alias,Function')
if ($stopRecording) {
$recordingOutputFile = Stop-Recording
$newRecordingName = "$($demo.Name).$($demo.DemoStarted.ToString('s') -replace ':', '-')$($recordingOutputFile.Extension)"
if ($recordingOutputFile) {
try {
Copy-Item $recordingOutputFile.FullName -Destination ($recordingOutputFile.FullName | Split-Path | Join-Path -ChildPath $newRecordingName )
} catch {
Write-Warning "Could not copy $($recordingOutputFile) to $($demo.Name): $($_ | Out-String)"
}
}
}
}
# and prepare a message.
if ($demo.EndMessage) {
$finishedMessage =
& ${ShowDemo_Format-RichText} -InputObject (
$demo.EndMessage -f [int]$duration.TotalMinutes, [int]$duration.Seconds
) -ForegroundColor Warning -Italic
# If the demo was interactive
if ($demo.Interactive) {
# writ the message
$finishedMessage | Out-Host
# and if we had a nested prompt, exit it
if ($NestedPromptLevel) {
$host.ExitNestedPrompt()
}
} elseif (-not $demo.Markdown) {
$finishedMessage -join ''
}
}
# Last but not least, reset the demo.
$demo.Reset()
</ScriptBlock>
</ExpressionBinding>
</CustomItem>
</CustomEntry>
</CustomEntries>
</CustomControl>
</Control>
<Control>
<Name>${ShowDemo_Format-RichText}</Name>
<CustomControl>
<CustomEntries>
<CustomEntry>
<CustomItem>
<ExpressionBinding>
<ScriptBlock>
<#
.Synopsis
Formats the text color of output
.Description
Formats the text color of output
* ForegroundColor
* BackgroundColor
* Bold
* Underline
.Notes
Stylized Output works in two contexts at present:
* Rich consoles (Windows Terminal, PowerShell.exe, Pwsh.exe) (when $host.UI.SupportsVirtualTerminal)
* Web pages (Based off the presence of a $Request variable, or when $host.UI.SupportsHTML (you must add this property to $host.UI))
#>
[Management.Automation.Cmdlet("Format","Object")]
[ValidateScript({
$canUseANSI = $host.UI.SupportsVirtualTerminal
$canUseHTML = $Request -or $host.UI.SupportsHTML -or $OutputMode -eq 'HTML'
if (-not ($canUseANSI -or $canUseHTML)) { return $false}
return $true
})]
[OutputType([string])]
param(
# The input object
[Parameter(ValueFromPipeline)]
[PSObject]
$InputObject,
# The foreground color
[string]$ForegroundColor,
# The background color
[string]$BackgroundColor,
# If set, will render as bold
[switch]$Bold,
# If set, will render as italic.
[Alias('Italics')]
[switch]$Italic,
# If set, will render as faint
[switch]$Faint,
# If set, will render as hidden text.
[switch]$Hide,
# If set, will render as blinking (not supported in all terminals or HTML)
[switch]$Blink,
# If set, will render as strikethru
[Alias('Strikethrough', 'Crossout')]
[switch]$Strikethru,
# If set, will underline text
[switch]$Underline,
# If set, will double underline text.
[switch]$DoubleUnderline,
# If set, will invert text
[switch]$Invert,
# If provided, will create a hyperlink to a given uri
[Alias('Hyperlink', 'Href')]
[uri]
$Link,
# If set, will not clear formatting
[switch]$NoClear,
# The alignment. Defaulting to Left.
# Setting an alignment will pad the remaining space on each line.
[ValidateSet('Left','Right','Center')]
[string]
$Alignment,
# The length of a line. By default, the buffer width
[int]$LineLength = $($host.UI.RawUI.BufferSize.Width)
)
begin {
$canUseANSI = $host.UI.SupportsVirtualTerminal
$canUseHTML = $Request -or $host.UI.SupportsHTML -or $OutputMode -eq 'HTML'
$knownStreams = @{
Output='';Error='BrightRed';Warning='BrightYellow';
Verbose='BrightCyan';Debug='Yellow';Progress='Cyan';
Success='BrightGreen';Failure='Red';Default=''}
$ansiCode = [Regex]::new(@'
(?<ANSI_Code>
(?-i)\e # An Escape
\[ # Followed by a bracket
(?<ParameterBytes>[\d\:\;\<\=\>\?]{0,}) # Followed by zero or more parameter
bytes
(?<IntermediateBytes>[\s\!\"\#\$\%\&\'\(\)\*\+\,\-\.\/]{0,}) # Followed by zero or more
intermediate bytes
(?<FinalByte>[\@ABCDEFGHIJKLMNOPQRSTUVWXYZ\[\\\]\^_\`abcdefghijklmnopqrstuvwxyz\{\|\}\~]) # Followed by a final byte
)
'@)
$esc = [char]0x1b
$standardColors = 'Black', 'Red', 'Green', 'Yellow', 'Blue','Magenta', 'Cyan', 'White'
$brightColors = 'BrightBlack', 'BrightRed', 'BrightGreen', 'BrightYellow', 'BrightBlue','BrightMagenta', 'BrightCyan', 'BrightWhite'
$allOutput = @()
$n =0
$cssClasses = @()
$colorAttributes =
@(:nextColor foreach ($hc in $ForegroundColor,$BackgroundColor) {
$n++
if (-not $hc) { continue }
if ($hc[0] -eq $esc) {
if ($canUseANSI) {
$hc; continue
}
}
$ansiStartPoint = if ($n -eq 1) { 30 } else { 40 }
if ($knownStreams.ContainsKey($hc)) {
$i = $brightColors.IndexOf($knownStreams[$hc])
if ($canUseHTML) {
$cssClasses += $hc
} else {
if ($i -ge 0 -and $canUseANSI) {
'' + $esc + "[1;$($ansiStartPoint + $i)m"
} else {
$i = $standardColors.IndexOf($knownStreams[$hc])
if ($i -ge 0 -and $canUseANSI) {
'' + $esc + "[1;$($ansiStartPoint + $i)m"
} elseif ($i -le 0 -and $canUseANSI) {
'' + $esc + "[$($ansistartpoint + 8):5m"
}
}
}
continue nextColor
}
elseif ($standardColors -contains $hc) {
for ($i = 0; $i -lt $standardColors.Count;$i++) {
if ($standardColors[$i] -eq $hc) {
if ($canUseANSI -and -not $canUseHTML) {
'' + $esc + "[$($ansiStartPoint + $i)m"
} else {
$cssClasses += $standardColors[$i]
}
continue nextColor
}
}
} elseif ($brightColors -contains $hc) {
for ($i = 0; $i -lt $brightColors.Count;$i++) {
if ($brightColors[$i] -eq $hc) {
if ($canUseANSI -and -not $canUseHTML) {
'' + $esc + "[1;$($ansiStartPoint + $i)m"
} else {
$cssClasses += $standardColors[$i]
}
continue nextColor
}
}
}
elseif ($psStyle -and $psStyle.Formatting.$hc -and
$psStyle.Formatting.$hc -match '^\e') {
if ($canUseANSI -and -not $canUseHTML) {
$psStyle.Formatting.$hc
} else {
$cssClasses += "formatting-$hc"
}
}
elseif (-not $n -and $psStyle -and $psStyle.Foreground.$hc -and
$psStyle.Foreground.$hc -match '^\e' ) {
if ($canUseANSI -and -not $canUseHTML) {
$psStyle.Foreground.$hc
} else {
$cssClasses += "foreground-$hc"
}
}
elseif ($n -and $psStyle -and $psStyle.Background.$hc -and
$psStyle.Background.$hc -match '^\e') {
if ($canUseANSI -and -not $canUseHTML) {
$psStyle.Background.$hc
} else {
$cssClasses += "background-$hc"
}
}
if ($hc -and $hc -notmatch '^[\#\e]') {
$placesToLook=
@(if ($hc.Contains('.')) {
$module, $setting = $hc -split '\.', 2
$theModule = Get-Module $module
$theModule.PrivateData.Color,
$theModule.PrivateData.Colors,
$theModule.PrivateData.Colour,
$theModule.PrivateData.Colours,
$theModule.PrivateData.EZOut,
$global:PSColors,
$global:PSColours
} else {
$setting = $hc
$moduleColorSetting = $theModule.PrivateData.PSColors.$setting
})
foreach ($place in $placesToLook) {
if (-not $place) { continue }
foreach ($propName in $setting -split '\.') {
$place = $place.$propName
if (-not $place) { break }
}
if ($place -and "$place".StartsWith('#') -and 4,7 -contains "$place".Length) {
$hc = $place
continue
}
}
if (-not $hc.StartsWith -or -not $hc.StartsWith('#')) {
continue
}
}
$r,$g,$b = if ($hc.Length -eq 7) {
[int]::Parse($hc[1..2]-join'', 'HexNumber')
[int]::Parse($hc[3..4]-join '', 'HexNumber')
[int]::Parse($hc[5..6] -join'', 'HexNumber')
}elseif ($hc.Length -eq 4) {
[int]::Parse($hc[1], 'HexNumber') * 16
[int]::Parse($hc[2], 'HexNumber') * 16
[int]::Parse($hc[3], 'HexNumber') * 16
}
if ($canUseHTML) {
if ($n -eq 1) { "color:$hc" }
elseif ($n -eq 2) { "background-color:$hc"}
}
elseif ($canUseANSI) {
if ($n -eq 1) { $esc+"[38;2;$r;$g;${b}m" }
elseif ($n -eq 2) { $esc+"[48;2;$r;$g;${b}m" }
}
})
$styleAttributes = @() + $colorAttributes
$styleAttributes += @(
if ($Bold) {
if ($canUseHTML) {"font-weight:bold"}
elseif ($canUseANSI) { '' + $esc + "[1m" }
}
if ($Faint) {
if ($canUseHTML) { "opacity:.5" }
elseif ($canUseANSI) { '' + $esc + "[2m" }
}
if ($Italic) {
if ($canUseHTML) { "font-weight:bold" }
elseif ($canUseANSI) {'' + $esc + "[3m" }
}
if ($Underline -and -not $doubleUnderline) {
if ($canUseHTML) { "text-decoration:underline"}
elseif ($canUseANSI) {'' +$esc + "[4m" }
}
if ($Blink) {
if ($canUseANSI) { '' +$esc + "[5m" }
}
if ($invert) {
if ($canUseHTML) {"filter:invert(100%)"}
elseif ($canUseANSI) { '' + $esc + "[7m"}
}
if ($hide) {
if ($canUseHTML) {"opacity:0"}
elseif ($canUseANSI) { '' + $esc + "[8m"}
}
if ($Strikethru) {
if ($canUseHTML) {"text-decoration: line-through"}
elseif ($canUseANSI) { '' +$esc + "[9m" }
}
if ($DoubleUnderline) {
if ($canUseHTML) { "border-bottom: 3px double;"}
elseif ($canUseANSI) {'' +$esc + "[21m" }
}
if ($Alignment -and $canUseHTML) {
"display:block;text-align:$($Alignment.ToLower())"
}
if ($Link) {
if ($canUseHTML) {
# Hyperlinks need to be a nested element
# so we will not add it to style attributes for HTML
}
elseif ($canUseANSI) {
# For ANSI,
'' + $esc + ']8;;' + $Link + $esc + '\'
}
}
)
$header =
if ($canUseHTML) {
"<span$(
if ($styleAttributes) { " style='$($styleAttributes -join ';')'"}
)$(
if ($cssClasses) { " class='$($cssClasses -join ' ')'"}
)>" + $(
if ($Link) {
"<a href='$link'>"
}
)
} elseif ($canUseANSI) {
$styleAttributes -join ''
}
}
process {
$inputObjectAsString =
"$(if ($inputObject) { $inputObject | Out-String})".Trim()
$inputObjectAsString =
if ($Alignment -and -not $canUseHTML) {
(@(foreach ($inputObjectLine in ($inputObjectAsString -split '(?>\r\n|\n)')) {
$inputObjectLength = $ansiCode.Replace($inputObjectLine, '').Length
if ($inputObjectLength -lt $LineLength) {
if ($Alignment -eq 'Left') {
$inputObjectLine
} elseif ($Alignment -eq 'Right') {
(' ' * ($LineLength - $inputObjectLength)) + $inputObjectLine
} else {
$half = ($LineLength - $inputObjectLength)/2
(' ' * [Math]::Floor($half)) + $inputObjectLine +
(' ' * [Math]::Ceiling($half))
}
}
else {
$inputObjectLine
}
}) -join [Environment]::NewLine) + [Environment]::newline
} else {
$inputObjectAsString
}
$allOutput +=
if ($header) {
"$header" + $inputObjectAsString
}
elseif ($inputObject) {
$inputObjectAsString
}
}
end {
if (-not $NoClear) {
$allOutput +=
if ($canUseHTML) {
if ($Link) {
"</a>"
}
"</span>"
}
elseif ($canUseANSI) {
if ($Bold -or $Faint -or $colorAttributes -match '\[1;') {
"$esc[22m"
}
if ($Italic) {
"$esc[23m"
}
if ($Underline -or $doubleUnderline) {
"$esc[24m"
}
if ($Blink) {
"$esc[25m"
}
if ($Invert) {
"$esc[27m"
}
if ($hide) {
"$esc[28m"
}
if ($Strikethru) {
"$esc[29m"
}
if ($ForegroundColor) {
"$esc[39m"
}
if ($BackgroundColor) {
"$esc[49m"
}
if ($Link) {
"$esc]8;;$esc\"
}
if (-not ($Underline -or $Bold -or $Invert -or $ForegroundColor -or $BackgroundColor)) {
'' + $esc + '[0m'
}
}
}
$allOutput -join ''
}
</ScriptBlock>
</ExpressionBinding>
</CustomItem>
</CustomEntry>
</CustomEntries>
</CustomControl>
</Control>
<Control>
<Name>${ShowDemo_Format-Markdown}</Name>
<CustomControl>
<CustomEntries>
<CustomEntry>
<CustomItem>
<ExpressionBinding>
<ScriptBlock>
<#
.SYNOPSIS
Formats an object as Markdown
.DESCRIPTION
Formats an object as Markdown, with many options to work with
.EXAMPLE
Format-Markdown -ScriptBlock {
Get-Process
}
.EXAMPLE
1..6 | Format-Markdown -HeadingSize { $_ }
#>
[Management.Automation.Cmdlet("Format","Object")]
[ValidateScript({return $true})]
param(
[Parameter(ValueFromPipeline,ValueFromPipelineByPropertyName)]
[PSObject]
$InputObject,
# If set, will treat the -InputObject as a paragraph.
# This is the default for strings, booleans, numbers, and other primitive types.
[Parameter(ValueFromPipelineByPropertyName)]
[switch]
$MarkdownParagraph,
# If set, will generate a markdown table.