Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- [CmdletBinding()]
- param($Code)
- # Load required assemblies
- [void] [System.Reflection.Assembly]::Load("System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
- # Generate an HTML span and append it to HTML string builder
- Function Append-HtmlSpan ($block, $TokenClass)
- {
- If ( ( $TokenClass -eq 'NewLine' ) -or ( $TokenClass -eq 'LineContinuation' ) )
- {
- If ( $TokenClass -eq 'LineContinuation' )
- {
- $null = $CodeBuilder.Append("`")
- }
- $null = $CodeBuilder.Append("`n")
- }
- Else
- {
- $Block = [System.Web.HttpUtility]::HtmlEncode($Block)
- If ( -not $Block.Trim() )
- {
- $Block = $Block.Replace(' ', ' ')
- }
- If ( $TokenColor -eq 'String' )
- {
- $Lines = $block -split "`n"
- $Block = ""
- $MultipleLines = $False
- ForEach ( $Line in $Lines )
- {
- If ( $MultipleLines )
- {
- $Block += "`n"
- }
- $NewText = $line.TrimStart()
- $NewText = " " * ($Line.Length - $NewText.Length) + $NewText
- $Block += $NewText
- $MultipleLines = $True
- }
- }
- $null = $CodeBuilder.Append("<span class='ps-$TokenClass'>$block</span>")
- }
- }
- Function Main
- {
- # Do syntax parsing.
- $Errors = $null
- $Tokens = [System.Management.Automation.PsParser]::Tokenize( $Code, [ref]$Errors )
- # Initialize HTML builder.
- $CodeBuilder = New-Object System.Text.StringBuilder
- # Iterate over the tokens and set the colors appropriately.
- $position = 0
- ForEach ( $Token in $Tokens)
- {
- If ( $Position -lt $Token.Start )
- {
- $Block = $Code.Substring( $Position, ($Token.Start-$Position) )
- $TokenColor = 'Unknown'
- Append-HtmlSpan $block $TokenColor
- }
- $Block = $Code.Substring( $Token.Start, $Token.Length )
- $TokenColor = $Token.Type.ToString()
- Append-HtmlSpan $Block $TokenColor
- $Position = $Token.Start + $Token.Length
- }
- # Build the entire syntax-highlighted script
- $Code = $CodeBuilder.ToString()
- # Replace some problematic characters
- $Code = $Code -replace '\t', '	' -replace '\$', "$" -replace '\{', '{' -replace '\}', '}'
- # Output HTML
- $Code
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement