How can I optimize this or is there a better way to do it?(HTML Syntax Highlighter)

Posted by Tanner on Stack Overflow See other posts from Stack Overflow or by Tanner
Published on 2010-05-12T01:53:37Z Indexed on 2010/05/12 1:54 UTC
Read the original article Hit count: 315

Hello every one, I have made a HTML syntax highlighter in C# and it works great, but there's one problem. First off It runs pretty fast because it syntax highlights line by line, but when I paste more than one line of code or open a file I have to highlight the whole file which can take up to a minute for a file with only 150 lines of code. I tried just highlighting visible lines in the richtextbox but then when I try to scroll I can't it to highlight the new visible text. Here is my code:(note: I need to use regex so I can get the stuff in between < & > characters)

Highlight Whole File:

  public void AllMarkup()
    {
        int selectionstart = richTextBox1.SelectionStart;



        Regex rex = new Regex("<html>|</html>|<head.*?>|</head>|<body.*?>|</body>|<div.*?>|</div>|<span.*?>|</span>|<title.*?>|</title>|<style.*?>|</style>|<script.*?>|</script>|<link.*?/>|<meta.*?/>|<base.*?/>|<center.*?>|</center>|<a.*?>|</a>");
        foreach (Match m in rex.Matches(richTextBox1.Text))
        {
            richTextBox1.Select(m.Index, m.Value.Length);
            richTextBox1.SelectionColor = Color.Blue;
            richTextBox1.Select(selectionstart, -1);
            richTextBox1.SelectionColor = Color.Black;
        }

        richTextBox1.SelectionStart = selectionstart;
    }


    private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
    {
        try
        {
            LockWindowUpdate(richTextBox1.Handle);//Stops text from flashing flashing
            richTextBox1.Paste();
            AllMarkup();

        }finally { LockWindowUpdate(IntPtr.Zero); }
    }

I want to know if there's a better way to highlight this and make it faster or if someone can help me make it highlight only the visible text.

Please help. :) Thanks, Tanner.

© Stack Overflow or respective owner

Related posts about c#

Related posts about regex