Click here to Skip to main content
15,880,543 members
Articles / Programming Languages / C#
Article

Enabling syntax highlighting in a RichTextBox

Rate me:
Please Sign up or sign in to vote.
4.76/5 (74 votes)
14 Jun 20053 min read 648.5K   19.4K   242   137
An article on how to enable syntax highlighting in a RichTextBox.

Sample Image - SyntaxRichTextBox.gif

Introduction

I am currently involved in writing a game called Hydria that uses Lua as a scripting language. To handle the scripts for different npc:s, I got the assignment of writing a simple editor that would be implemented in the npc-editor. Everything worked fine but editing scripts can be a real pain if there is no syntax highlighting. So I decided to write a control that could do that.

I started my research on the subject and found several good articles. One of the most useful articles I found was one by Michael Gold and my work is in some parts based on his.

This control is meant to be used for simple syntax highlighting, so it is far from perfect. For instance, you can not (yet) define C-style comments like /* comment */ but I'm going to implement it in the next version.

Since I'm using generics, this code only works with version >= 2.0 of the .NET Framework.

The control

The SyntaxRichTextBox is (as the name reveals) derived from RichTextBox but has some slight differences.

Properties

  • List<string> Settings.KeyWords

    The keywords that will be used in the SyntaxRichTextBox.

  • Color Settings.KeywordColor

    The color that will be used to colorize the keywords (default blue).

  • string Settings.Comment

    The identifier for comments. As I mentioned in the introduction, C-style comments like /* comment */ is not yet implemented.

  • Color Settings.CommentColor

    The color that will be used to colorize comments (default green).

  • Color Settings.StringColor

    The color that will be used to colorize strings (default grey).

  • Color Settings.IntegerColor

    The color that will be used to colorize integers (default red).

  • bool Settings.EnableComments

    If this property is set to false, comments will not be processed.

  • bool Settings.EnableStrings

    If this property is set to false, strings will not be processed.

  • bool Settings.EnableIntegers
  • If this property is set to false, integers will not be processed.

Functions

  • public void CompileKeywords()

    Compiles the keywords into a regular expression. This function should be called when you've added all keywords.

  • public void ProcessAllLines()

    Updates the syntax highlighting of all text in the SyntaxRichTextBox control.

Using the SyntaxRichTextBox control

Step 1:

You can either add the whole SyntaxHighlighter project to your solution by right-clicking the root in the solution explorer and choose "Add -> Existing Project" or you can add the assembly to the toolbox by right-clicking on the toolbox view and select "Choose Items...".

Step 2:

Create the control from the toolbox by dragging SyntaxRichTextBox to the form. If you chose to add the SyntaxHighlighter project to your solution, SyntaxRichTextBox is located in a new tab in the toolbox-view that's called "SyntaxHighlighter components". If you chose to add the assembly to the toolbox directly, SyntaxRichTextBox will be located in the tab "Common Controls".

Step 3:

Now right click on the newly created SyntaxRichTextBox and select "Properties...". Give the control a suitable name. In this example, I give the control the name m_syntaxRichTextBox.

Step 4:

Now we have added the control to our form and now we should prepare it with some keywords. Let's make a simple highlighter for the script language Lua as an example.

C#
private void MainForm_Load(object sender, EventArgs e)
{
    // Add the keywords to the list.
    m_syntaxRichTextBox.Settings.Keywords.Add("function");
    m_syntaxRichTextBox.Settings.Keywords.Add("if");
    m_syntaxRichTextBox.Settings.Keywords.Add("then");
    m_syntaxRichTextBox.Settings.Keywords.Add("else");
    m_syntaxRichTextBox.Settings.Keywords.Add("elseif");
    m_syntaxRichTextBox.Settings.Keywords.Add("end");

    // Set the comment identifier. 
    // For Lua this is two minus-signs after each other (--).
    // For C++ code we would set this property to "//".
    m_syntaxRichTextBox.Settings.Comment = "--";

    // Set the colors that will be used.
    m_syntaxRichTextBox.Settings.KeywordColor = Color.Blue;
    m_syntaxRichTextBox.Settings.CommentColor = Color.Green;
    m_syntaxRichTextBox.Settings.StringColor = Color.Gray;
    m_syntaxRichTextBox.Settings.IntegerColor = Color.Red;

    // Let's not process strings and integers.
    m_syntaxRichTextBox.Settings.EnableStrings = false;
    m_syntaxRichTextBox.Settings.EnableIntegers = false;

    // Let's make the settings we just set valid by compiling
    // the keywords to a regular expression.
    m_syntaxRichTextBox.CompileKeywords();

    // Load a file and update the syntax highlighting.
    m_syntaxRichTextBox.LoadFile("script.txt", RichTextBoxStreamType.PlainText);
    m_syntaxRichTextBox.ProcessAllLines();
}

Known issues

  • Colorizing fails to work when pasting something larger than one line.
  • C-style comments not yet implemented.
  • Can be slow sometimes. Optimization needed.

Points of Interest

This is my first C# article here on CodeProject. I have only worked with C# for about three months so it is probably very much that I'm not aware of. If you see something in the code that makes you laugh :) or something that is just plain wrong, tell me so and I will correct it.

The control is not in any way perfect but my plan is to continue working on it until I'm totally satisfied.

References

History

  • 2005-06-14

    First revision of this article posted.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Software Developer
Sweden Sweden
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralRe: More optimized version Pin
Daniel Liedke30-Sep-06 15:35
professionalDaniel Liedke30-Sep-06 15:35 
GeneralRe: More optimized version Pin
Rocker Irwin19-Jan-07 3:10
Rocker Irwin19-Jan-07 3:10 
GeneralTransactSQL type highlighting Pin
Moonark14-Jun-05 17:38
Moonark14-Jun-05 17:38 
GeneralRe: TransactSQL type highlighting Pin
Patrik Svensson15-Jun-05 5:20
Patrik Svensson15-Jun-05 5:20 
GeneralRe: TransactSQL type highlighting Pin
Rohant Kunnat10-Aug-09 18:47
Rohant Kunnat10-Aug-09 18:47 
GeneralGood job. Pin
Jodde14-Jun-05 14:29
Jodde14-Jun-05 14:29 
QuestionIs it fast enough? Pin
iliyang14-Jun-05 12:03
iliyang14-Jun-05 12:03 
AnswerRe: Is it fast enough? Pin
Patrik Svensson14-Jun-05 12:26
Patrik Svensson14-Jun-05 12:26 
In editing-mode the speed works fine for me but I haven't tried it with large scripts. Since the control only updates the current line, the only problem that I can see might be when using ProcessAllLines(), but that's a function you only use when loading new text into the SyntaxRichTextBox.


"If knowledge can create problems, it is not through ignorance that we can solve them."
Isaac Asimov
GeneralRe: Is it fast enough? Pin
mav.northwind15-Jun-05 4:33
mav.northwind15-Jun-05 4:33 
GeneralRe: Is it fast enough? Pin
Patrik Svensson15-Jun-05 5:10
Patrik Svensson15-Jun-05 5:10 
GeneralRe: Is it fast enough? Pin
Dejan Petrovic15-Jun-05 18:25
Dejan Petrovic15-Jun-05 18:25 
GeneralRe: Is it fast enough? Pin
mav.northwind15-Jun-05 20:20
mav.northwind15-Jun-05 20:20 
GeneralRe: Is it fast enough? Pin
iliyang16-Jun-05 0:56
iliyang16-Jun-05 0:56 
GeneralRe: Is it fast enough? Pin
Patrik Svensson16-Jun-05 3:35
Patrik Svensson16-Jun-05 3:35 
GeneralRe: Is it fast enough? Pin
C_Simpkins21-Jun-05 20:51
C_Simpkins21-Jun-05 20:51 
GeneralRe: Is it fast enough? Pin
Rei Miyasaka11-Oct-05 23:17
Rei Miyasaka11-Oct-05 23:17 
GeneralRe: Is it fast enough? Pin
Kevin I21-Jun-05 21:04
Kevin I21-Jun-05 21:04 
GeneralRe: Is it fast enough? Pin
NormDroid20-Jul-05 22:29
professionalNormDroid20-Jul-05 22:29 
AnswerRe: Is it fast enough? Pin
Anonymous25-Jun-05 13:13
Anonymous25-Jun-05 13:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.