RichTextBoxでシンタックスハイライト

Richtextboxコントロールを使うと装飾されたテキストを表示することができる.ということでhtmlシンタックスハイライトもどきを実装.

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.Text.RegularExpressions;

namespace htmlHighLighter
{
    public partial class Form1 : Form
    {
       public Form1()
        {
            string file = @"test.html";
            System.IO.StreamReader sr = new System.IO.StreamReader(file);
            string innerhtml = sr.ReadToEnd();
            richTextBox_html.Text = innerhtml;
            syntaxHighlight();
        }

        private void syntaxHighlight()
        {
            Font f = new Font("Courier new",10,FontStyle.Regular);
            Regex r = new Regex("</*(.+?)[ >]");
            regexHighLight(r,f,Color.Purple,1);
        }

        private void regexHighLight(Regex r,Font font, Color color,int target)
        {
            Regex s = new Regex("\n");
            string[] lines = s.Split(richTextBox_html.Text);
            int i = 0;
            foreach (string line in lines)
            {
                MatchCollection col = r.Matches(line);
                foreach (Match m in col)
                {
                    richTextBox_html.Select(richTextBox_html.GetFirstCharIndexFromLine(i) + m.Groups[target].Index, m.Groups[target].Length);
                    richTextBox_html.SelectionColor = color;
                    richTextBox_html.SelectionFont = font;
                }
                i++;
            }
        }

RichTextBoxのインデックスとRegexのインデックスを一致させるために,RichTextBoxのWordWrapをFalseにして余計な改行を防いでおく必要がある.コメント,パラメータ等の装飾はsyntaxHighLight()内にRegexを順次追加すればよい.改行でスプリットしているので行をまたがったコメントは正しく判別できないけど,とりあえずお手軽な実装として.

こんな風に表示される.