2008. október 2., csütörtök

How to do syntax highlighting in a TRichEdit


Problem/Question/Abstract:

How to do syntax highlighting in a TRichEdit

Answer:

{Content of the TRichEdit for example:

This is a test to show how to find the @ character in a rich text.
The @ character occurs twice in the text.
}

procedure MarkFirstWord(RE: TRichEdit; TheWord: string; Color: TColor; Style:
  TFontStyles);
var
  i, CharPos, noChars: Integer;
begin
  CharPos := 0;
  noChars := 0;
  for i := 0 to Pred(RE.Lines.Count) do
    noChars := noChars + Length(RE.Lines[i]);
  CharPos := RE.FindText(TheWord, CharPos, noChars, [stWholeWord]);
  RE.SelStart := CharPos;
  RE.SelLength := Length(TheWord);
  RE.SelAttributes.Color := Color;
  RE.SelAttributes.Style := Style;
  RE.SelLength := 0;
end;

procedure MarkAllWords(RE: TRichEdit; TheWord: string; Color: TColor; Style:
  TFontStyles);
var
  i, CharPos, CharPos2, noChars: Integer;
begin
  CharPos := 0;
  noChars := 0;
  for i := 0 to Pred(RE.Lines.Count) do
    noChars := noChars + Length(RE.Lines[i]);
  repeat
    CharPos2 := RE.FindText(TheWord, CharPos, noChars, [stWholeWord]);
    CharPos := CharPos2 + 1;
    RE.SelStart := CharPos2;
    RE.SelLength := Length(TheWord);
    RE.SelAttributes.Color := Color;
    RE.SelAttributes.Style := Style;
  until
    charpos = 0;
  RE.SelLength := 0;
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  {Will mark only the first occurance of '@' in Red}
  MarkFirstWord(RichEdit1, '@', clRed, [fsBold]);
  {Will mark all occurances of @ in Teal and italic}
  MarkAllWords(RichEdit1, '@', clTeal, [fsItalic, fsBold]);
end;

Nincsenek megjegyzések:

Megjegyzés küldése