I am trying to highlight some syntax in a richtextcontrol (quoted text, XML tags, XML comments). Apart from the obvious problem created by my own stupidity (for example, a run through the text to highlight the syntax takes over a second and I certainly cannot check the syntax whenever a character was typed) I also ran into an issue caused by newlines in the text.
This is my feeble attempt to syntaxhighlight:
While i < l
ssRelevantText = t.Text.Substring(i)
ssSelectedText = Regex.Match(ssRelevantText, pattern, RegexOptions.Singleline).Value
idxSelectionStart = t.Find(ssSelectedText, i, RichTextBoxFinds.None)
idxSelectionLength = ssSelectedText.Length
t.SelectionStart = idxSelectionStart
t.SelectionLength = idxSelectionLength
t.SelectionColor = color
i = idxSelectionStart + idxSelectionLength
t.SelectionStart = idxCursorBeforeSelection
t.SelectionLength = 0
t.SelectionColor = color.Black
End While
(I removed comments because, ironically, VB comments break SO's syntax-highlighting.)
I also tried other RegexOptions but the problem remains that while, for example
"hello"
is found and accurately coloured,
"
hello
"
is not found. (The colouring also fails below such an incident, but not always.)
If I replace all newlines with some other symbol, the above works and everything is highlighted correctly. Why are newlines interfering?
Alternatively, how does one do syntax-highlighting in a richtextbox? All the examples I can find refer to syntax-highlighting of reserved words and not terms based on patterns.
Edit: I so far figured out that the RichTextBox method Find() does not find strings containing newlines. Since that triggers an exception (easily avoided) no further highlighting is done after that. How can I find a string in a RichTextBox that contains newlines?