Author: Jonas Bilinkevicius
How to do syntax highlighting in a TRichEdit
Answer:
1 {Content of the TRichEdit for example:
2
3 This is a test to show how to find the @ character in a rich text.
4 The @ character occurs twice in the text.
5 }
6
7 procedure MarkFirstWord(RE: TRichEdit; TheWord: string; Color: TColor; Style:
8 TFontStyles);
9 var
10 i, CharPos, noChars: Integer;
11 begin
12 CharPos := 0;
13 noChars := 0;
14 for i := 0 to Pred(RE.Lines.Count) do
15 noChars := noChars + Length(RE.Lines[i]);
16 CharPos := RE.FindText(TheWord, CharPos, noChars, [stWholeWord]);
17 RE.SelStart := CharPos;
18 RE.SelLength := Length(TheWord);
19 RE.SelAttributes.Color := Color;
20 RE.SelAttributes.Style := Style;
21 RE.SelLength := 0;
22 end;
23
24 procedure MarkAllWords(RE: TRichEdit; TheWord: string; Color: TColor; Style:
25 TFontStyles);
26 var
27 i, CharPos, CharPos2, noChars: Integer;
28 begin
29 CharPos := 0;
30 noChars := 0;
31 for i := 0 to Pred(RE.Lines.Count) do
32 noChars := noChars + Length(RE.Lines[i]);
33 repeat
34 CharPos2 := RE.FindText(TheWord, CharPos, noChars, [stWholeWord]);
35 CharPos := CharPos2 + 1;
36 RE.SelStart := CharPos2;
37 RE.SelLength := Length(TheWord);
38 RE.SelAttributes.Color := Color;
39 RE.SelAttributes.Style := Style;
40 until
41 charpos = 0;
42 RE.SelLength := 0;
43 end;
44
45 procedure TForm1.Button2Click(Sender: TObject);
46 begin
47 {Will mark only the first occurance of '@' in Red}
48 MarkFirstWord(RichEdit1, '@', clRed, [fsBold]);
49 {Will mark all occurances of @ in Teal and italic}
50 MarkAllWords(RichEdit1, '@', clTeal, [fsItalic, fsBold]);
51 end;
|