SIGN UP MEMBER LOGIN:    
ARTICLE

Syntax Highlighting in RichTextBox Control - Part 2

Posted by Duncan Harris Articles | Windows Controls C# June 12, 2003
This article shows how to perform interactive syntax highlighting within the RichTextBox control.
Reader Level:
Download Files:
 

Introduction

This article shows how to perform interactive syntax highlighting within the RichTextBox control. The source code is written in C#.

This text builds upon the previous article Syntax Highlighting within the RichTextBox Control - Part 1 that described how to highlight text as it is loaded into the RichTextBox.

Description

To perform interactive syntax highlighting within the RichTextBox, the events generated by the control need to be monitored. In this example I monitor the event TextChanged which is triggered each time text is modified within the control. Further to make life easy apply formatting to the entire line that the user is editing. Note, this implmentation has some drawbacks in terms of screen flicker. More about that later.

We begin by attaching an event handler to the RichTextBox property TextChanged like so.

RichTextBox m_rtb = null;
m_rtb =
new RichTextBox();
...
m_rtb.TextChanged +=
new EventHandler(this.TextChangedEvent)

Next I define the TextChanged() method to handle the event and perform interactive text highlighting to the entire line being edited by the user. The method begins by locating the start and end offset for the current line being edited. Next I extract this line of text from the RichTextBox so it can be processed. Before processing the line of text, I must save the RichTextBox properties SelectionStart and SelectionLength since it is these properties that are used to set the individual text highlighting positions. Next I split the line of text into tokens and analyze each token to see whether it is a keyword that requires special highlighting or not and then apply the font and color. Finally, I return the original values of the RichTextBox properties SelectionStart and SelectionLength.

Note, I have removed the highlighting code for comments to make the example more readable. See the attached file for a more complete example.

private void TextChangedEvent(object sender, EventArgs e) {
// Calculate the starting position of the current line.
int start = 0, end = 0;
for (start = m_rtb.SelectionStart - 1; start > 0; start--) {
if (m_rtb.Text[start] == '\n') { start++; break; }
}
// Calculate the end position of the current line.
for (end = m_rtb.SelectionStart; end < m_rtb.Text.Length; end++) {
if (m_rtb.Text[end] == '\n') break;
}
// Extract the current line that is being edited.
String line = m_rtb.Text.Substring(start, end - start);
// Backup the users current selection point.
int selectionStart = m_rtb.SelectionStart;
int selectionLength = m_rtb.SelectionLength;
// Split the line into tokens.
Regex r = new Regex("([ \\t{}();])");
string [] tokens = r.Split(line);
int index = start;
foreach (string token in tokens) {
// Set the token's default color and font.
m_rtb.SelectionStart = index;
m_rtb.SelectionLength = token.Length;
m_rtb.SelectionColor = Color.Black;
m_rtb.SelectionFont =
new Font("Courier New", 10,
FontStyle.Regular);
// Check whether the token is a keyword.
String [] keywords = { "public", "void", "using", "static","class" };
for (int i = 0; i < keywords.Length; i++) {
if (keywords[i] == token) {
// Apply alternative color and font to highlight keyword.
m_rtb.SelectionColor = Color.Blue;
m_rtb.SelectionFont =
new Font("Courier New", 10,
FontStyle.Bold);
break;
}

index += token.Length;
}
// Restore the users current selection point.
m_rtb.SelectionStart = selectionStart;
m_rtb.SelectionLength = selectionLength;
}
}

Note, updating a whole line of text produces some noticeable flicker on the line of text being entered by the user. A more thorough implementation of highlighting might use a data structure to store the formatting properties of all text characters within the control so that only necessary updates are performed in the control. Moreover, the KeyPressed event could be utilized to handle the insertion of individual characters into the control.

Conclusion:

This article described a rudimentary example of how to perform syntax highlighting interactively within the RichTextBox control. A more thorough implementation is left to the reader.

Login to add your contents and source code to this article
share this article :
post comment
 

very thanks it's good, waiting for next articles. The world is a rose smell it and pass it to your friends. good work.

Posted by Nader A Mar 30, 2011

Thanks for your tutorial. It was very helpful.
I have a question though  , the csysntax highlighting doesn't work when i do a cut copy paste into my richtextbox . What needs to be changed to implement this ?

Many Thnaks

Posted by chithra r Aug 25, 2010

You can just add an if statement after calculating start position to check whether start is negative, set it to 0.
Like this:
    if (start < 0) { start = 0; }

And you will get no exception

Posted by Timur Ustyan Jun 07, 2010

Sorry for my English, I'm French...

But I found an error :
when I write something, it works, but if I delete the line, when there is'nt any character 
"String line = rtbTexte.Text.Substring(start, end - start);" startIndex is < 0 and there ise an error. We have to manage ArgumentOutOfRangeException, and I don't know how to do it :/

Posted by pierre charrier Jun 02, 2010

Wow. Worked like a charm. Thankyou! The flickering get very annoying.

Posted by Yasahiro Di Apr 11, 2010
Team Foundation Server Hosting
Become a Sponsor
PREMIUM SPONSORS
  • The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Become a Sponsor