Syntax Highlighter – in 20 minutes…

Ok I cheated slightly, I had the basic sub routine at the bottom of this code already working. The dictionary and lists idea came just now and I’ve implemented it in 20 minutes. This is quick, dirty and Winforms.

Why? I want it for my custom code generator – to be blogged soon.


Module SyntaxHighLighter
ReadOnly DarkBlue As List(Of String) = New List(Of String)(New String() {"public", "private", "sub", "byval", "byref", "integer", "Friend", "friend",
"Shared", "shared",
"long", "string", "object", "handles", "for", "to", "as",
"if", "in", "then", "end", "next", "loop", "dim",
"redim", "new", "of", "and", "function", "class", "me", "#Region", "RaiseEvent", "Return",
"While", "With", "Get", "Set", "Property", "#End Region"})

ReadOnly Grey As List(Of String) = New List(Of String)(New String() {"<#@", "#>"})
ReadOnly Maroon As List(Of String) = New List(Of String)(New String() {"import", "assembly", "output"})
ReadOnly Red As List(Of String) = New List(Of String)(New String() {" extension", "namespace"})

Dim LightBlue As List(Of String) = New List(Of String)(New String() {"implements", "List(Of"})

Public Sub SyntaxHighLight(richText As RichTextBox)
richText.Font = New Font("Arial", 10, FontStyle.Regular)
Dim colourDict As New Dictionary(Of List(Of String), Color) From {{Grey, Color.Gray},
{Red, Color.Red},
{Maroon, Color.Maroon},
{DarkBlue, Color.DarkBlue},
{LightBlue, Color.LightBlue}}

richText.SelectAll()
richText.SelectionColor = Color.Black

For Each item In colourDict
SyntaxHighLight(richText, item.Key, item.Value, FontStyle.Regular)
Next

End Sub

Public Sub SyntaxHighlight(richText As RichTextBox, Words As List(Of String), color As Color, style As FontStyle)

Dim FoundPos As Integer = 0
For Each w As String In Words
While FoundPos <> -1 And FoundPos < richText.TextLength FoundPos = richText.Find(w, FoundPos, RichTextBoxFinds.WholeWord) If FoundPos > -1 Then
richText.Select(FoundPos, w.Length)
richText.SelectionColor = color

richText.SelectionFont = New Font("Arial", 10, style)
richText.SelectionLength = 0
FoundPos += w.Length
End If
End While
FoundPos = 0
Next
End Sub
End Module