Reputation: 1810
I've created a simple vb.net text editor using a RichTextBox for a Logic Program. I've got the coloring(highlighting) to to work except for comments. However it runs really really slow after a 100 lines or so. Does anyone know of a more efficient way to do this? Note: I call the SyntaxHandler on the RichTextBox TextChanged event.
Friend vbKeys As String = "And|As|Case|Catch|CDbl|Ceiling|CInt|Class|Const|Continue|CStr|Decimal|" & _
"Default|Delegate|Dim|Do|Double|Each|End|Else|Enum|Event|" & _
"Explicit|Extern|False|Finally|Floor|For|Format|GoTo|If|IIf|In|Int|Is|Long|Module|" & _
"Namespace|New|Next|Not|Null|Object|Option|Or|Override|Params|PI|Private|Protected|" & _
"Public|Readonly|Ref|Replace|Return|Round|Sbyte|Sealed|Select|Short|Sqrt|" & _
"Static|String|Structure|Sub|Then|Throw|True|Try|TypeOf|Uint|Ulong|" & _
"Unchecked|Using|With|While"
Friend Sub SyntaxHandler(ByVal txtScript As RichTextBox)
Dim selPos As Integer = txtScript.SelectionStart
'set everything to black to start with
txtScript.SelectAll()
txtScript.SelectionColor = Color.Black
'Regex Variables for user
FormatWithRegEx("\b(?:" & regexVaribles & ")\b", txtScript, Color.DarkViolet)
'double quoted strings are all red
FormatWithRegEx("""", txtScript, Color.Red)
FormatWithRegEx("""[^""]*""", txtScript, Color.Red)
'reserved words are all blue
FormatWithRegEx("\b(?:" & vbKeys & ")\b", txtScript, Color.Blue)
'single line comments are all green
FormatWithRegEx("'[\w*\t*\S*\[ ]*]*", txtScript, Color.Green)
txtScript.Select(selPos, 0)
txtScript.SelectionColor = Color.Black
End Sub
Private Sub FormatWithRegEx(ByVal strRegEx As String, ByRef txtRTB As RichTextBox, ByVal colour As System.Drawing.Color)
Dim regex As New Regex(strRegEx, _
RegexOptions.IgnoreCase _
Or RegexOptions.Multiline _
Or RegexOptions.Singleline _
Or RegexOptions.IgnorePatternWhitespace)
Dim myMatches As MatchCollection = regex.Matches(txtRTB.Text)
For Each GoodMatch As Match In myMatches
txtRTB.Select(GoodMatch.Index, GoodMatch.Length)
txtRTB.SelectionColor = colour
Next
End Sub
Upvotes: 1
Views: 825
Reputation: 415735
One option is to use an existing library (for example, prettify, which is used by Stack Overflow).
Upvotes: 1