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

Enabling syntax highlighting in a RichTextBox

By , 14 Jun 2005
 

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

About the Author

Patrik Svensson
Software Developer
Sweden Sweden
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
BugIt looks like the undo (ctrl+z) is broken for this controlmemberIlan Firsov13 Jan '13 - 22:47 
When pressing ctrl+z to undo the changes done to the text, the cursor just jumps to the beginning of the line.
GeneralThanksmemberkevininstructor31 Dec '12 - 15:38 
Just included this with a VS2010 solution, works perfectly for syntax highlighting SQL.
Kevin S. Gallagher
Programming is an art form that fights back

Questionpasting multiple lines and only the last line is processedmemberwxhubo26 Sep '12 - 16:30 
Did anyone notice the problem that when a block of code is pasted into the Syntaxrickbox, only that last line is processed
 
                        
			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();      //  <<---- it only processes the last line????

			m_bPaint = true;
 


SuggestionSpend a lot of timememberjasonangela7 Aug '12 - 14:44 
I am a beginner c # and I'm a chinese.Sorry,My English is so poor.
I think you can write this way:first
write a class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
 
namespace WindowsFormsApplication2
{
    public class ChangeColor
    {
        public void ChangeColorToBlue(string text, Color color, RichTextBox r)
        {
            int s = 0;
            while ((-1 + text.Length - 1) != (s = text.Length - 1 + r.Find(text, s, -1, RichTextBoxFinds.MatchCase | RichTextBoxFinds.WholeWord)))
            {
                r.SelectionColor = color;
            }
        }
        public void SelectKeyWords(RichTextBox r)
        {
 
            int sIndex = r.SelectionStart;
            r.SelectAll();
            r.SelectionColor = Color.Black;
            r.Select(sIndex, 0);
            ChangeColorToBlue("static", Color.Blue, r);//调用改变文字颜色的方法
            ChangeColorToBlue("void", Color.Blue, r);
            ChangeColorToBlue("using", Color.Blue, r);
            ChangeColorToBlue("if", Color.Blue, r);
            ChangeColorToBlue("else", Color.Blue, r);
            ChangeColorToBlue("public", Color.Blue, r);
            ChangeColorToBlue("private", Color.Blue, r);
            ChangeColorToBlue("class", Color.Blue, r);
            ChangeColorToBlue("new", Color.Blue, r);
            ChangeColorToBlue("int", Color.Blue, r);
            ChangeColorToBlue("true", Color.Blue, r);
            ChangeColorToBlue("double", Color.Blue, r);
            ChangeColorToBlue("is", Color.Blue, r);
            ChangeColorToBlue("byte", Color.Blue, r);
            ChangeColorToBlue("foreach", Color.Blue, r);
            ChangeColorToBlue("struct", Color.Blue, r);
            ChangeColorToBlue("while", Color.Blue, r);
            ChangeColorToBlue("typeof", Color.Blue, r);
            ChangeColorToBlue("float", Color.Blue, r);
            ChangeColorToBlue("decimal", Color.Blue, r);
            r.Select(sIndex, 0);
            r.SelectionColor = Color.Black;
 
        }
    }
}
 
And in Form:
you just use it;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.InteropServices;
 
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
[DllImport("user32")]
private static extern int SendMessage(IntPtr hwnd, int wMsg, int wParam, IntPtr lParam);
private void button1_Click(object sender, EventArgs e)
{
string fname = GetFileName();
textBox1.Text = fname;
richTextBox1.Text = show(fname);
 
}
public string GetFileName()
{
string fname = string.Empty;
OpenFileDialog dlg = new OpenFileDialog();
 
dlg.InitialDirectory = "c:\\";
dlg.Filter = "All files (*.*)|*.*";
dlg.FilterIndex = 1;
dlg.RestoreDirectory = true;
 
if (dlg.ShowDialog() == DialogResult.OK)
{
fname = dlg.FileName;
}
return fname;
}
public string show(string fileurl)
{
if (fileurl.Equals(""))
{
return "";
}
else
{
string source = string.Empty;
StreamReader sr = new StreamReader(fileurl, System.Text.Encoding.Default);
string strLine = sr.ReadLine();
while (strLine != null)
{
source += strLine + "\n";
strLine = sr.ReadLine();
}
return source;
}
 
}

private void richTextBox1_TextChanged(object sender, EventArgs e)
{
base.OnTextChanged(e);
SendMessage(base.Handle, 0xB, 0, IntPtr.Zero);
ChangeColor change = new ChangeColor();
change.SelectKeyWords(richTextBox1);
SendMessage(base.Handle, 0xB, 1, IntPtr.Zero);
this.Refresh();
}
 
}
}
GeneralMy vote of 4memberBurak Tunçbilek25 Jul '12 - 4:52 
thank you
GeneralMy vote of 5memberRafalChmiel11 Apr '12 - 8:41 
Just perfect!
Bugout of range display [modified]memberdvir12320 Mar '12 - 4:33 
Hi,
There is a small problem with the paint size of the richtextbox , when i open a diffrent text files (i copy only the text from the file) to the richtextbox the size of the richtextbox is exceed from the original size of the scrolls and paint the exceed part in white(i have a sceen capture if you want i can send you).
every time that i open a diffrent text file i debuging the event of size_changed of the richtextbox and i see in the call stack that when the size changed it happen from the function "WndProc" that you created.
can you sugget some soultion for the problem ?

modified 21 Mar '12 - 10:20.

QuestionGood codememberjlkdaslkfjd6 Aug '11 - 16:07 
when I comment out GetscrollPos in C# or vb.net it does not affect multi-line coloring.
 
Is there a reason why it is coloring only ToEOL when it is converted to Vb.net?
(Trying to color for Chr(34) and C# didn't have that symbol)
GeneralMy vote of 1memberanoop_dp25 Jul '11 - 0:38 
not working properly
GeneralRe: My vote of 1memberjb060820 Sep '11 - 0:52 
idiot - at the very least explain then problems you encounter
GeneralRe: My vote of 1memberRafalChmiel12 Apr '12 - 1:30 
Agree with you.
GeneralThank youmemberC#Wolf26 Feb '11 - 6:25 
Many thanks for this - it has saved me lots of work. (I'm writing an SQL client, so highlighting key words)Thumbs Up | :thumbsup:
QuestionHow about putting the settings in the class itself?memberjsoldi2 Oct '10 - 16:32 
Instead of in a separated class. I just erased the SyntaxSettings class and put all the settings in SyntaxRichTextBox, so now I can edit them in the Properties panel. A lot handier Smile | :) . Great job by the way.
GeneralProperties Settings....membertim_mcgwyn17 Apr '10 - 10:53 
Hello (again),
 
another question: how can I edit the properties in the (form) editing mode (not like actually in the code section?) Is there a way to realize this?
 
Best regards
Tim
GeneralRe: Properties Settings....memberjsoldi2 Oct '10 - 16:36 
Just move all the settings from SyntaxSettings to SyntaxRichTextBox and then erease all occurrences of "Settings." for "". Voila! (Well, almost actually there is some stuff to be done still).
GeneralMy vote of 2memberAlexanderBorup19 Feb '10 - 0:29 
Can't enabled the script to work within an "if" statement..
Generalperformance problemsmemberf.developpement16 Nov '09 - 3:25 
You say that performance problems solved but only during Load file Ok.
But do you have a solution when you change the text after loading ?
 
I try the same way with the property selectedRtf but it's to slow because I must use the select method. Frown | :( :(
GeneralRe: performance problemsmemberwuhi18 Nov '09 - 4:28 
do you mean to clear the textbox and paste new text from clipboard?
for this problem i dont have an solution ... (at the moment) sorry
Generalperformance problemes solvedmemberwuhi12 Nov '09 - 20:22 
hi ...
 
i was searching a lot for the reasing why the syntaxhighlight is that slow.
the problem is not the regex, but the richTextBox.Select. it takes a lomg time to select each keyword an change its color.
so i wrote a helper-class to color very large documents.
 
it uses the same Settings and should ONLY be used to perform the 'init-coloring'.
example: SyntaxTester -> MainForm -> MainFormLoad()
[...]

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

//m_syntaxRichTextBox.ProcessAllLines();
SyntaxHighlighter.RtfColoring.ProcessRtfColoring(m_syntaxRichTextBox);

 
all other methods are ok. so for the first init i use the rtf-coloring and for live-editing i usw the existing richTextBox.Select(...

using System;
using System.Text.RegularExpressions;
 
namespace SyntaxHighlighter
{
/// <summary>
/// enabes syntaxhighlighting for a richtextbox by using rtf
/// </summary>
public static class RtfColoring
{
public static void ProcessRtfColoring(SyntaxRichTextBox richTextBox)
{
SyntaxSettings Settings = richTextBox.Settings;
if (Settings.Keywords.Count < 1)
return;
 
// reset the text to get a clear rtf
string strTextToAdd = richTextBox.Text;
richTextBox.Clear();
richTextBox.AppendText(strTextToAdd);
string strRTF = richTextBox.Rtf;

// find index of start of header
int iRTFLoc = strRTF.IndexOf("\\rtf");

// get index of where we'll insert the colour table
// try finding opening bracket of first property of header first
int iInsertLoc = strRTF.IndexOf('{', iRTFLoc);
 
// if there is no property, we'll insert colour table
// just before the end bracket of the header
if (iInsertLoc == -1) iInsertLoc = strRTF.IndexOf('}', iRTFLoc) - 1;
 
string strCommentColor = "\\red" + Settings.CommentColor.R.ToString() +
"\\green" + Settings.CommentColor.G.ToString() +
"\\blue" + Settings.CommentColor.B.ToString();

string strStringColor = "\\red" + Settings.StringColor.R.ToString() +
"\\green" + Settings.StringColor.G.ToString() +
"\\blue" + Settings.StringColor.B.ToString();

string strKeywordColor = "\\red" + Settings.KeywordColor.R.ToString() +
"\\green" + Settings.KeywordColor.G.ToString() +
"\\blue" + Settings.KeywordColor.B.ToString();

string strIntegerColor = "\\red" + Settings.IntegerColor.R.ToString() +
"\\green" + Settings.IntegerColor.G.ToString() +
"\\blue" + Settings.IntegerColor.B.ToString();
 
// insert the colour table at our chosen location
strRTF = strRTF.Insert(iInsertLoc, "{\\colortbl ;" + strCommentColor + ";" + strStringColor + ";" + strKeywordColor + ";" + strIntegerColor + ";}");

// build the keywords regex
string strKeywords = String.Empty;
foreach (string keyword in Settings.Keywords)
{
strKeywords += keyword + ",";
}
strKeywords = strKeywords.Substring(0, strKeywords.Length - 1);
 
Regex r = new Regex(@", ?");
strKeywords = @"\b(" + r.Replace(strKeywords, @"|") + @")\b";

// start coloring
// Keywords
r = new Regex(strKeywords, RegexOptions.Singleline | RegexOptions.IgnoreCase);
strRTF = r.Replace(strRTF, new MatchEvaluator(MatchKeyword));
 
// Integers
r = new Regex("(\\b(?:[0-9]*\\.)?[0-9]+\\b)", RegexOptions.IgnoreCase);
strRTF = r.Replace(strRTF, new MatchEvaluator(MatchInteger));
 
// Comments
r = new Regex("("+Settings.Comment+".*$)", RegexOptions.Multiline | RegexOptions.IgnoreCase);
strRTF = r.Replace(strRTF, new MatchEvaluator(MatchComment));
 
// Strings
r = new Regex("(\"[^\"\\\\\\r\\n]*(?:\\\\.[^\"\\\\\\r\\n]*)*\"|\'[^\'\\\\\\r\\n]*(?:\\\\.[^\'\\\\\\r\\n]*)*\')", RegexOptions.Singleline | RegexOptions.IgnoreCase);
strRTF = r.Replace(strRTF, new MatchEvaluator(MatchString));
 
richTextBox.Rtf = strRTF;
}
 
private static string MatchKeyword(Match match)
{
if (match.Groups[1].Success)
{
return @"\cf3 " + RemoveRtfColors(match.Value) + @"\cf0 ";
}
 
return String.Empty;
}
 
private static string MatchString(Match match)
{
if (match.Groups[1].Success)
{
return @"\cf2 " + RemoveRtfColors(match.Value) + @"\cf0 ";
}
 
return String.Empty;
}
 
private static string MatchComment(Match match)
{
if (match.Groups[1].Success)
{
return @"\cf1 " + RemoveRtfColors(match.Value) + @"\cf0 ";
}
 
return String.Empty;
}
 
private static string MatchInteger(Match match)
{
if (match.Groups[1].Success)
{
return @"\cf4 " + RemoveRtfColors(match.Value) + @"\cf0 ";
}
 
return String.Empty;
}
 
/// <summary>
/// remove all rtf-colors from a string
/// </summary>
/// <param name="strText"></param>
/// <returns>String</returns>
private static string RemoveRtfColors(string strText)
{
Regex r = new Regex(@"\\cf[0-9] ");
strText = r.Replace(strText, "");
 
return strText;
}
}
 
}
 

 
have fun Smile | :)
GeneralRe: performance problemes solvedmemberleosco17 Dec '09 - 2:31 
Where do I put that code? I made a new class and put the code you pasted in there. The speed is still slow though, what do I need to do afterwards?
 
Sorry, I am new to C# so it's difficult for me Confused | :confused:
GeneralRe: performance problemes solvedmemberJoao Tito Livio27 Dec '09 - 13:00 
Good Work man, super fast now, congrats to the original control author Wink | ;)
GeneralRe: performance problemes solvedmemberb4326854@uggsrock.com22 Feb '10 - 18:27 
Could you show me / upload how this is supposed to be?
Thanks
 
Email:
ZoMbiESsSZ@Gmail.com
GeneralRe: performance problemes solvedmemberiRoN_RoCK22 Jul '10 - 4:54 
your code doesn't color first line in rtb?
GeneralRe: performance problemes solvedmemberJonathan Nappee10 Dec '10 - 7:13 
Hi,
 
I tried this too but it makes it quite complex.
 
I have a simple solution which is to use a temporary richTextBox which is not shown and do the changes to it.
Finally copy rtTemp RTF back to original richTextBox.
 
The speed is not incredibly better but no flicker.
 
Here is how I did it:
 
        private static bool isAutoChange = false;
        private void richTextBox_TextChanged(object sender, EventArgs e)
        {
            if (!isAutoChange)
                Highlight();
        }
 
        private void Highlight()
        {
            RichTextBox rtTemp = new RichTextBox();
            rtTemp.Font = richTextBox.Font;
            rtTemp.Rtf = richTextBox.Rtf;
            rtTemp.Visible = false;
            rtTemp.HideSelection = true;
 
            // Do the changes

            // set isAutoChange so that Highlight is called only once
            // richTextBox.Rtf = rtTemp.Rtf; triggers textChange..

            isAutoChange = true;
            richTextBox.Rtf = rtTemp.Rtf;
            isAutoChange = false;
        }
--
Cui Bono?

QuestionHow to apply syntax coloring for SAS language?memberJulienV10 Nov '09 - 2:04 
Hello,
 
Thanks for your article and sources, it works great!
 
I have a problem when I try to use it to color code in SAS language. The following keywords are not colored, perhaps because of the special character percent: "%let", "%nrbquote("?
Comment lines starting with the star character are not colored either. Would you have any idea to fix this problem?
 
            // Add the keywords to the list.
            txt.Settings.Keywords.Add("%let");
            txt.Settings.Keywords.Add("%nrbquote(");
            txt.Settings.Keywords.Add(");");
 
            // Set the comment identifier. For Lua this is two minus-signs after each other (--). 
            // For C++ we would set this property to "//".
            txt.Settings.Comment = "/*";
            txt.Settings.Comment = "*";
 
Thank you in advance
Julien
GeneralThanksmemberGlimmerMan14 Oct '09 - 10:16 
I am using it for a SQL editor and works great
 
Kevin S. Gallagher
Programming is an art form that fights back

GeneralRegex to slow :( [modified]memberno_morser21 Jul '09 - 23:16 
I added some new keywords and then the program slows down very dramaticaly.
I seached the reason and found it^^
private void ProcessRegex(string strRegex, Color color)
If "strRegex" is too long the highlighing takes a lot of time. Cry | :((
 
So I changed "list Keywords" to "SortedList Keywords". I filled the two strings with the same word (e.g. Keywords.Add("int", "int")).
After that i changed the "ProcessRegex(..., ...)" to:
private void ProcessRegex(string strRegex, Color color)
		{
			Regex regKeywords = new Regex(@"\w+", RegexOptions.IgnoreCase | RegexOptions.Compiled);
			Match regMatch;
 
			for (regMatch = regKeywords.Match(m_strLine); regMatch.Success; regMatch = regMatch.NextMatch())
			{
				string keyword;
				if (Settings.Keywords.TryGetValue(regMatch.Value, out keyword))
				{
					int nStart = m_nLineStart + regMatch.Index;
					int nLenght = regMatch.Length;
					SelectionStart = nStart;
					SelectionLength = nLenght;
					SelectionColor = color;
				}
			}
		}
 
Now the program detects very fast the keywords Roll eyes | :rolleyes:
 
But there is one thing which isn't nice Sigh | :sigh:
After these changes the comments arn't working fine so I wrote a extra methode, but it was very easy so u can fix that on your own^^
 
Hope this post is/was helpful
mfg no_morser
 
ps: Sorry for my bad english (I'm from Austria)Cool | :cool:
 
modified on Friday, July 24, 2009 7:44 AM

GeneralRe: Regex to slow :(membermichele_cv22 Jul '09 - 1:57 
Hi,
 
can you please post also the extra function for the comments.
 
Thanks Smile | :)
GeneralRe: Regex to slow :(memberno_morser24 Jul '09 - 1:37 
well, I changed the code again and now its very simple:
 
now i use the old methode for integers, strings and comments
private void ProcessRegex(string strRegex, Color color)
		{
			Regex regKeywords = new Regex(strRegex, RegexOptions.IgnoreCase | RegexOptions.Compiled);
			Match regMatch;
 
			for (regMatch = regKeywords.Match(m_strLine); regMatch.Success; regMatch = regMatch.NextMatch())
			{
				int nStart = m_nLineStart + regMatch.Index;
				int nLenght = regMatch.Length;
				SelectionStart = nStart;
				SelectionLength = nLenght;
				SelectionColor = color;
			}
		}
and just the new one for highlighting
private void HighLightRegex(string strRegex, Color color)
		{
			Regex regKeywords = new Regex(@"\w+", RegexOptions.IgnoreCase | RegexOptions.Compiled);
			Match regMatch;
 
			for (regMatch = regKeywords.Match(m_strLine); regMatch.Success; regMatch = regMatch.NextMatch())
			{
				string keyword;
				if (Settings.Keywords.TryGetValue(regMatch.Value, out keyword))
				{
					// Process the words
					int nStart = m_nLineStart + regMatch.Index;
					int nLenght = regMatch.Length;
					SelectionStart = nStart;
					SelectionLength = nLenght;
					SelectionColor = color;
				}
			}
		}
it's still faster then the original code, because the comments, integers and strings aren't using the keywords.
 
Also I changed the strRegex for strings. Now it also highlights chars (e.g. 'a'):
"(\"[^\"\\\\\\r\\n]*(?:\\\\.[^\"\\\\\\r\\n]*)*\"|\'[^\'\\\\\\r\\n]*(?:\\\\.[^\'\\\\\\r\\n]*)*\')"
 
if there is an easier way: post reply, please Wink | ;)
no_morser
GeneralRe: Regex to slow :(membertim_mcgwyn17 Apr '10 - 10:44 
Hello,
 
I'm trying to add your new code. But now I've got the problem, that the line with "TryGetValue" occurs an error:
 
Error1 "System.Collections.Generic.List" has now definition for "TryGetValue",and there is no expanded method with "TryGetValue" found in the code, there is no argument "System.Collections.Generic.List" accepted. (Maybe there are some missing Using-Directive or Assembly?)
 
the using-directive "using System.Collections.Generic;" is set, so maybe you know whats wrong? Or you update you Download-Code to see whats wrong (Maybe I placed it wrong?!? (I place your new routine right after the old one)
 
Best regards
Tim
Generalabout regex stringmemberGumbon20 May '09 - 3:35 
Can you explain more about this string: "\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\""
 
Thanks Blush | :O
 
Tran Ho Le NGuyen

Generalit is much better to add one more term for functionsmemberSeraph_summer7 May '09 - 9:55 
just like visual studio highlight, the functions are highlighted in different colors as keywords.
it is easy to add this term.
QuestionTextChanged event not "reaching" a parent controlmemberefisir10 Dec '08 - 6:50 
Hi.
I'm using your excellent control inside my editor.
I've just dragged it to my MainForm and I've registered a method (MainForm_TextChanged)to the TextChanged event.
Then I've implemented MainForm_TextChanged.
But it seems that the application doesn't reach this method when I changes the text of the SyntaxRichTextBox. Do you have any idea what privents MainForm of listening to the TextChanged event?
AnswerRe: TextChanged event not "reaching" a parent controlmemberMember 19325392 Feb '09 - 6:29 
at the end of the OnTextChanged event put base.OnTextChanged(e);
QuestionPerformance problemsmemberAmrykid9 Dec '08 - 12:10 
hi, i love this control and i use it in my app.
but my apps users have reported that the textbox highlights a little too slow.
are u planning on a new release better performane?
 
_____________________________
Don't download it, make it.
Visual Basic /C#

GeneralMany many thanks to you.memberashu fouzdar1 Sep '08 - 19:54 
I really need this one. fortunately I found in my first search from google.
 
Again, Thanks a lot for sharing.
 
dnpro
"Very bad programmer"

QuestionWhat License?memberMember 40469032 Jul '08 - 18:33 
What license is the code released under?
Thanks.
AnswerRe: What License?memberPatrik Svensson2 Jul '08 - 23:22 
The do-whatever-you-want-licence. Wink | ;)
 

"If knowledge can create problems, it is not through ignorance that we can solve them."
Isaac Asimov

GeneralRe: What License?memberMember 40469033 Jul '08 - 13:57 
Patrik, thanks.
GeneralHighlight only if line starts with "fox"memberUltraWhack16 Jun '08 - 4:36 
Is there any way to background highlight a line if it STARTS WITH "fox", then highlight the entire line AS THE USER IS TYPING ?
GeneralThank you.memberDonald Snowdy27 May '08 - 10:30 
Thank you for the control; it's great. I gave you a 5.
 
BTW, I used your control in my application and I gave you credit at the bottom of the article. You can check out the article here: http://www.codeproject.com/KB/recipes/EvaluationEngine.aspx
 
Donald.
GeneralUndo and redomemberBetaNium12 Nov '07 - 23:38 
How can I undo and redo in SyntaxRichTextBox?
 
Please help me...Big Grin | :-D
 
This is my signature.

GeneralRe: Undo and redomemberAmir_Saniyan16 Feb '08 - 2:09 
Hi,
 
To solve Redo/Undo problem:
 
Use TextEditorControl_KeyUp event instead of TextEditorControl_TextChanged or TextEditorControl_KeyPress events.
 
Now, Redo/Undo works.
 
To bypass Redo/Undo selection steps, REWRITE a NEW Undo/Redo and DO base.Undo/base.Redo until Text property changes.
GeneralRe: Undo and redomemberxiwang16 Oct '08 - 23:50 
I do not really think that you need to rewrite the REDO or UNDO.
 
// <summary>
/// OnTextChanged
/// </summary>
/// <param name="e"></param>
protected override void OnKeyUp(KeyEventArgs e)
{
if (!e.Control)
{
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;
}
else if (e.KeyCode == Keys.Z)
{
base.OnKeyUp(e);
}
}
 
should be solving the problem, this is just a quick answer, you might find better idea to solve the problem
Questionwhat about HTML [modified]memberhackrogenius9 Sep '07 - 21:53 
What if you are using html as syntax...
i tried "<html>" & "<html" both... i think "<" is not working..
 
I was using this RTF Box in a small html editor and taking preview on a WebBrowser, i tried to used TextChanged Event, the Event is not working the Break point on this point doesnt get a hit on text changed.
 
is it right?
 


 
--
ASif Ashraf
MCAD.Net,MCP
Asif.Log@gmail | hotmail.com
92-306-4526526
Sr. dotNet & Flash Developer
Blu Media Works LHR PK

AnswerRe: what about HTMLmemberPatrik Svensson9 Sep '07 - 21:58 
Probably not. Smile | :)
 

"If knowledge can create problems, it is not through ignorance that we can solve them."
Isaac Asimov

GeneralRe: what about HTMLmemberhackrogenius9 Sep '07 - 23:47 
hmmm..
thats fine.. no problem ....
 
anyhow i checked and it dint work fine with me.. maybe my own fault... i just added keywords and did nothing else....
 

 
bye
 
--
ASif Ashraf
MCAD.Net,MCP
Asif.Log@gmail | hotmail.com
92-306-4526526
Sr. dotNet & Flash Developer
Blu Media Works LHR PK

GeneralPossible optimizationsmemberbiopsy17 Jun '07 - 9:43 
I am using this code as the base of my syntax highlighter and there are several things that i've done to reduce loading time. Here is something you can do:
1. Process line when user hits space bar, rather than having it processed as a new char gets added.
2. Preload regular expressions. I have a DLL with all of my regular expressions in it. The dll is loaded once on start-up and then used throughout the code so that you don't create a new regex instance while abandoning the previous one.
3. Use standard RichTextBox operations to perform line calculations instead of doing everything in loops.
4. When processing a line, split it by empty space and use a for each loop to traverse through a line looking for keywords. This is more efficient than using for loops. I also used a balanced binary tree to store keywords which have already been highlighted and the position of their last character. This way, if i have a duplication keyword on one line i can keep track of them.
All of this reduced loading time significantly. You could also put some operations in threads if you wanted an even better performance.

GeneralRe: Possible optimizationsmemberHaydeng28 Jun '07 - 4:41 
How does one go about using adding these optimizations... Im kinda new at this.
GeneralRe: Possible optimizationsmemberBetaNium13 Nov '07 - 1:41 
How I Process line when user hits space bar?
 

 
This is my signature.

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

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