简体   繁体   English

.net richtextbox中的语法突出显示,如何处理换行符?

[英]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). 我试图突出显示RichText控件中的某些语法(引用文本,XML标记,XML注释)。 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.) (我删除了注释,因为具有讽刺意味的是,VB注释破坏了SO的语法突出显示。)

I also tried other RegexOptions but the problem remains that while, for example 我也尝试了其他RegexOptions,但问题仍然存在,例如

"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? 或者,如何在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. 编辑:到目前为止,我发现RichTextBox方法Find()找不到包含换行符的字符串。 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? 如何在包含换行符的RichTextBox中找到字符串?

You might want to look here: http://blogs.microsoft.co.il/blogs/tamir/archive/2006/12/14/RichTextBox-syntax-highlighting.aspx 您可能需要在这里查看: 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. 它提供了一个很好的示例,说明如何使用RichTextBox在C#中对高光进行语法处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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