简体   繁体   中英

Syntax highlighting in .net richtextbox, how do I deal with newlines?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM