1

I'm having difficulty creating a code that able to pick up specific words and color them. I'm currently using this code:

private void Colorize(string word, Color color, int startIndex)
{
    if (this.richTextBox1.Text.Contains(word))
    {
        int index = -1;
        int selectStart = this.richTextBox1.SelectionStart;

        while ((index = this.richTextBox1.Text.IndexOf(word, (index + 1))) != -1)
        {
            this.richTextBox1.Select((index + startIndex), word.Length);
            this.richTextBox1.SelectionColor = color;
            this.richTextBox1.Select(selectStart, 0);
            this.richTextBox1.SelectionFont = new Font(richTextBox1.Font, FontStyle.Regular);
            this.richTextBox1.SelectionColor = Color.Black;
        }
        this.richTextBox1.SelectionColor = Color.Black;
    }
}

The problem is that when the text of the RichTextBox is too large it hangs and runs from top to bottom, is there any way to instantly color keywords? I'm doing a basic IDE, but I need some color java-based keywords.

Any error sorry I used the google translator.

Mohit S
  • 13,723
  • 6
  • 34
  • 69
jpdante
  • 28
  • 4
  • Does 'hangs' mean it really hangs or only that it takes too long? You may want to use `richTextBox1.SupendLayout`and `richTextBox1.ResumeLayout` to prevent screen updates until it is done. Other than that you could try to modify the `richTextBox1.Rtf `property directly with the correct font & color table codes, but that's rather icky.. – TaW Nov 13 '15 at 07:28
  • It sounds like you want to implement syntax highlighting? If so, you should use an existing library/solution. See this question for some options: http://stackoverflow.com/questions/2809545/how-to-create-syntax-highlighting-text-box. The question is old, though, so there might be better options since then. –  Nov 13 '15 at 07:57
  • http://stackoverflow.com/a/3282911/17034 – Hans Passant Nov 13 '15 at 08:49

2 Answers2

0

Once Iv'e needed to implement C#, Python and Matlab syntax highlighting so I've spent some time researching about it.

The problem with this Select method in RichTextBox is that the selection itself takes time since it also grafically select the text and when you want to dinamically color the syntax when the code is written there are many selections which makes it slow.

Trying to parse the modify the rtf is possible but is a real headache and requires you and the ones that will maintain the code after you to understand this format.

A good solution I've found is that there are many open sources implement a Control of their own for syntax highlighting which you acn use.

In FastColoredTextBox, the one I used, you can choose the language to highlight and the format in which you want it to be shown, you can also add your own language to that list and configure it to indent the hightlighted code automatically using Regex.

Sorry if this is not the answer you expected but this is exacly the type of thing to search for and not implement by yourself.

Tamir Vered
  • 10,187
  • 5
  • 45
  • 57
0

You are aware that String.Contains does not check for words, aren't you?

If you use String.Contains("able"), then indeed you will find the word "able", but you'll also find words like "disabled", "sable" and "IEquatable".

To check for words you'll need a regular expression.

Whenever you need to process sequences of something, LINQ is your friend. Consider to familiarize yourself with the possibilities of LINQ.

Introduction of LINQ

Using Regular expressions and LINQ I could colorize the complete works of shakespeare (over five million characters) in about 5 seconds

// on load form: fill the rich text box with
// the complete works of William Shakespeare
private async void Form1_Load(object sender, EventArgs e)
{
    const string completeShakespeare = "http://www.gutenberg.org/cache/epub/100/pg100.txt";
    using (var downloader = new HttpClient())
    {
        this.richTextBox1.Text = await downloader.GetStringAsync (completeShakespeare);
    }
}

// on button click: mark all "thee" red
private void button1_Click(object sender, EventArgs e)
{
    var stopwatch = Stopwatch.StartNew();
    this.Colorize2("thee", Color.Red);
    var elapsed = stopwatch.Elapsed;
    Debug.WriteLine ("Coloring a text with {0} characters took {1:F3} sec",
        this.richTextBox1.Text.Length,
        elapsed.TotalSeconds);
}

private void Colorize2(string word, Color color)
{
    string regString = String.Format(@"\b{0}\b", word);
    // regex: match substring that match word,
    // with boundaries to non alphanumeric characters like space and \n \r \t

    var regex = new Regex(regString, RegexOptions.IgnoreCase);
    var matches = regex.Matches(richTextBox1.Text);
    foreach (Match match in matches.Cast<Match>())
    {
        this.richTextBox1.Select(match.Index, match.Length);
        this.richTextBox1.SelectionColor = color;
    }
}
Harald Coppoolse
  • 28,834
  • 7
  • 67
  • 116