views:

36

answers:

1

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?

A: 

You might want to look here: http://blogs.microsoft.co.il/blogs/tamir/archive/2006/12/14/RichTextBox-syntax-highlighting.aspx

It provides a nice example of how to Syntax higlight in C# using a RichTextBox.

kyndigs
That's one of those examples I was talking about. It only explains highlighting specific words, which is not the issue here. I need to highlight syntax elements as well, i.e. "hello" and "world" should both be highlighted as quoted text, even if they contain newlines.
Andrew J. Brehm
Are you capturing everything between quotes as 1 string? Even on a new line so when you pass the string to the regular expression it will read as. " hello "If this is the case then before you pass the string to the regex you can do a String.TrimEnd('\n');
kyndigs
Not the problem. Spaces are not an issue. The problem is that the text I have to, say, paint red can contain newlines, like "hello\nworld". Any line-based approach would not see the end of the quoted text (and the second "). My code works for input without newlines.
Andrew J. Brehm