AnotherUser AnotherUser - 25 days ago 6
C# Question

RichTextBox syntax highlighting

I am working with this code. It is for syntax highlighting in a

RichTextBox
. I am specifically looking at the function
ProcessLine()
and
OnTextChanged()
, which I have modified as such:

protected override void OnTextChanged(EventArgs e)
{
// Calculate stuff here.
m_nContentLength = this.TextLength;

int nCurrentSelectionStart = SelectionStart;
int nCurrentSelectionLength = SelectionLength;

m_bPaint = false;

// Find the start of the current line.
m_nLineStart = nCurrentSelectionStart;
while ((m_nLineStart > 0) && (Text[m_nLineStart - 1] != '\n'))
m_nLineStart--;
// Find the end of the current line.
m_nLineEnd = nCurrentSelectionStart;
while ((m_nLineEnd < Text.Length) && (Text[m_nLineEnd] != '\n'))
m_nLineEnd++;
// Calculate the length of the line.
m_nLineLength = m_nLineEnd - m_nLineStart;
// Get the current line.
m_strLine = Text.Substring(m_nLineStart, m_nLineLength);

// Process this line.
ProcessLine();

m_bPaint = true;
}

// Process a line.
private void ProcessLine()
{
// Save the position and make the whole line black
int nPosition = SelectionStart;
SelectionStart = m_nLineStart;
SelectionLength = m_nLineLength;
SelectionColor = Color.Black;

/*// Process the keywords
ProcessRegex(m_strKeywords, Settings.KeywordColor);
// Process numbers
if(Settings.EnableIntegers)
ProcessRegex("\\b(?:[0-9]*\\.)?[0-9]+\\b", Settings.IntegerColor);
// Process strings
if(Settings.EnableStrings)
ProcessRegex("\"[^\"\\\\\\r\\n]*(?:\\\\.[^\"\\\\\\r\\n]*)*\"", Settings.StringColor);
// Process comments
if(Settings.EnableComments && !string.IsNullOrEmpty(Settings.Comment))
ProcessRegex(Settings.Comment + ".*$", Settings.CommentColor);*/

SelectionStart = nPosition;
SelectionLength = 0;
SelectionColor = Color.Red;

m_nCurSelection = nPosition;
}



  • My first question is, when I enter into the
    ProcessLine()
    in
    OnTextChanged()
    , will I always have a newline character at the end of
    m_strLine
    ? Will the smallest value or
    m_strLine
    be "\n" and the largest "any#ofchars+\n"?

  • And just so I have this right,
    SelectionStart
    is my caret position if
    SelectionLength
    is zero, and if
    SelectionLength
    is greater than zero my caret is at
    SelectStart+SelectionLength
    ?

  • I am trying to modify this code to color a whole lot of different syntax expressions, and I plan to go through it one character at a time, for each line. How might this fair when pasting or loading a file of 20k+ lines?


Answer

All I can suggest you right now is to use something stable, more powerful and less error prone such as Scintilla for .NET and Color Code. These controls are free and open source. Try them out:

ScintillaNET
ColorCode - Syntax Highlighting/Colorization for .NET

RichTextBox is extremely inefficient for working with large text. Even if you get some decent highlighting, the performance issues will start to pop up pretty soon.