1: class MySyntaxHighlightServiceWrapper : ISyntaxHighlightService
2: {
3: RichEdit control;
4: static string[] str;
5: List<int> paragraphHashes;
6: static MySyntaxHighlightServiceWrapper() {
7: str = new string[] { "INSERT", "SELECT", "CREATE", "TABLE", "USE", "IDENTITY", "ON", "OFF", "NOT", "NULL", "WITH", "SET" };
8: Array.Sort(str);
9: }
10:
11: public MySyntaxHighlightServiceWrapper(RichEdit control) {
12: this.control = control;
13: paragraphHashes = new List<int>();
14:
15: }
16:
17: public void ResetCache() {
18: paragraphHashes.Clear();
19: }
20:
21: public void Execute() {
22: Document doc = this.control.RichControl.Document;
23: int paragraphCount = doc.Paragraphs.Count;
24: for (int i = 0; i < paragraphCount; i++) {
25: HighlightParagraph(i);
26: }
27: }
28:
29: void HighlightParagraph(int paragraphIndex) {
30: Document doc = this.control.RichControl.Document;
31: Paragraph paragraph = doc.Paragraphs[paragraphIndex];
32: DocumentRange paragraphRange = paragraph.Range;
33: int paragraphStart = paragraphRange.Start.ToInt();
34: string text = doc.GetText(paragraphRange);
35: int hash = text.GetHashCode();
36: if (paragraphIndex < paragraphHashes.Count && paragraphHashes[paragraphIndex] == hash)
37: return;
38: int length = text.Length;
39: int prevWhiteSpaceIndex = -1;
40: for (int i = 0; i < length; i++) {
41: char ch = text[i];
42: if (Char.IsWhiteSpace(ch) || Char.IsPunctuation(ch)) {
43: int wordLength = i - prevWhiteSpaceIndex - 1;
44: if (wordLength > 0) {
45: int wordStart = prevWhiteSpaceIndex + 1;
46: string word = text.Substring(wordStart, wordLength);
47: int index = Array.BinarySearch(str, word);
48: DocumentRange range = doc.CreateRange(paragraphStart + wordStart, wordLength);
49: CharacterProperties cp = doc.BeginUpdateCharacters(range);
50: if (index >= 0)
51: cp.ForeColor = Colors.Blue;
52: else
53: cp.ForeColor = Colors.Black;
54: doc.EndUpdateCharacters(cp);
55: }
56: prevWhiteSpaceIndex = i;
57: }
58: }
59: for (int i = paragraphHashes.Count; i <= paragraphIndex; i++)
60: paragraphHashes.Add(String.Empty.GetHashCode());
61: paragraphHashes[paragraphIndex] = hash;
62: }
63: }