Click here to Skip to main content
Click here to Skip to main content

Enabling syntax highlighting in a RichTextBox

, 14 Jun 2005
Rate this:
Please Sign up or sign in to vote.
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.

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 Smile | :) 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

Share

About the Author

Patrik Svensson
Software Developer
Sweden Sweden
No Biography provided

Comments and Discussions

 
QuestionI need to start one of my keywords using "!" character Pinmemberalmendietamor9-Apr-14 18:56 
QuestionGreat! Save me a lot of time, thank you Pinmemberalmendietamor9-Apr-14 16:41 
QuestionMulti-line comment PinmemberWrangly6-Nov-13 5:17 
GeneralNew Editor Features :) PinmemberAIbanezW19-Sep-13 13:34 
BugIt looks like the undo (ctrl+z) is broken for this control PinmemberIlan Firsov13-Jan-13 22:47 
GeneralThanks Pinmemberkevininstructor31-Dec-12 15:38 
Questionpasting multiple lines and only the last line is processed Pinmemberwxhubo26-Sep-12 16:30 
SuggestionSpend a lot of time Pinmemberjasonangela7-Aug-12 14:44 
GeneralMy vote of 4 PinmemberBurak Tunçbilek25-Jul-12 4:52 
GeneralMy vote of 5 PinmemberRafalChmiel11-Apr-12 8:41 
Bugout of range display [modified] Pinmemberdvir12320-Mar-12 4:33 
QuestionGood code Pinmemberjlkdaslkfjd6-Aug-11 16:07 
GeneralMy vote of 1 Pinmemberanoop_dp25-Jul-11 0:38 
GeneralRe: My vote of 1 Pinmemberjb060820-Sep-11 0:52 
GeneralRe: My vote of 1 PinmemberRafalChmiel12-Apr-12 1:30 
GeneralRe: My vote of 1 PinmemberDelphiCoder29-Apr-14 12:59 
GeneralThank you PinmemberC#Wolf26-Feb-11 6:25 
QuestionHow about putting the settings in the class itself? Pinmemberjsoldi2-Oct-10 16:32 
GeneralProperties Settings.... Pinmembertim_mcgwyn17-Apr-10 10:53 
GeneralRe: Properties Settings.... Pinmemberjsoldi2-Oct-10 16:36 
GeneralMy vote of 2 PinmemberAlexanderBorup19-Feb-10 0:29 
Generalperformance problems Pinmemberf.developpement16-Nov-09 3:25 
GeneralRe: performance problems Pinmemberwuhi18-Nov-09 4:28 
Generalperformance problemes solved Pinmemberwuhi12-Nov-09 20:22 
GeneralRe: performance problemes solved Pinmemberleosco17-Dec-09 2:31 
GeneralRe: performance problemes solved PinmemberJoao Tito Livio27-Dec-09 13:00 
GeneralRe: performance problemes solved Pinmemberb4326854@uggsrock.com22-Feb-10 18:27 
GeneralRe: performance problemes solved PinmemberiRoN_RoCK22-Jul-10 4:54 
GeneralRe: performance problemes solved PinmemberJonathan Nappee10-Dec-10 7:13 
QuestionHow to apply syntax coloring for SAS language? PinmemberJulienV10-Nov-09 2:04 
GeneralThanks PinmemberGlimmerMan14-Oct-09 10:16 
GeneralRegex to slow :( [modified] Pinmemberno_morser21-Jul-09 23:16 
GeneralRe: Regex to slow :( Pinmembermichele_cv22-Jul-09 1:57 
GeneralRe: Regex to slow :( Pinmemberno_morser24-Jul-09 1:37 
GeneralRe: Regex to slow :( Pinmembertim_mcgwyn17-Apr-10 10:44 
Generalabout regex string PinmemberGumbon20-May-09 3:35 
Generalit is much better to add one more term for functions PinmemberSeraph_summer7-May-09 9:55 
QuestionTextChanged event not "reaching" a parent control Pinmemberefisir10-Dec-08 6:50 
AnswerRe: TextChanged event not "reaching" a parent control PinmemberMember 19325392-Feb-09 6:29 
QuestionPerformance problems PinmemberAmrykid9-Dec-08 12:10 
GeneralMany many thanks to you. Pinmemberashu fouzdar1-Sep-08 19:54 
QuestionWhat License? PinmemberMember 40469032-Jul-08 18:33 
AnswerRe: What License? PinmemberPatrik Svensson2-Jul-08 23:22 
GeneralRe: What License? PinmemberMember 40469033-Jul-08 13:57 
GeneralHighlight only if line starts with "fox" PinmemberUltraWhack16-Jun-08 4:36 
GeneralThank you. PinmemberDonald Snowdy27-May-08 10:30 
GeneralUndo and redo PinmemberBetaNium12-Nov-07 23:38 
GeneralRe: Undo and redo PinmemberAmir_Saniyan16-Feb-08 2:09 
GeneralRe: Undo and redo Pinmemberxiwang16-Oct-08 23:50 
Questionwhat about HTML [modified] Pinmemberhackrogenius9-Sep-07 21:53 

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

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

| Advertise | Privacy | Mobile
Web02 | 2.8.140827.1 | Last Updated 14 Jun 2005
Article Copyright 2005 by Patrik Svensson
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid