Colorized RichEdit

Some words are colored while typing in RichEdit

A RichEdit-ben gépelés közben kiszínesedik néhány szó
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
  System.Classes, Vcl.Graphics,strutils,richedit,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Panna, Vcl.ComCtrls,RegularExpressions,
  Vcl.ExtCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    RichEdit1: TRichEdit;
    procedure atszinez(sor:Integer);
    procedure RichEdit1Change(Sender: TObject);
    procedure Button1Click(Sender: TObject);
  private

  public
    { Public declarations }
  end;

var
  Form1: TForm1;  zarol: Boolean=false;

implementation

{$R *.dfm}

procedure TForm1.atszinez(sor:Integer);
var
  yIndex: Integer;
  sorText: string;
  Buffer: array[0..255] of Char;
  oriStartPos,ziXX, stPos: Integer;
  OriginalColor: TColor;
  procedure nana(szo:String; co:TColor);
  var RegEx: TRegEx; Match: TMatch; len:Integer;
  begin
  len:=Length(szo);
  RegEx := TRegEx.Create('\b'+szo+'\b');
  Match := RegEx.Match(sorText);
    while Match.Success do
    begin
    stPos:= Match.Index;
    ziXX := RichEdit1.Perform(EM_LINEINDEX, sor, 0) + (stPos - 1);
    OriginalColor := RichEdit1.SelAttributes.Color;
    oriStartPos:=RichEdit1.SelStart;
    RichEdit1.SelStart := ziXX;
    RichEdit1.SelLength := len;
    RichEdit1.SelAttributes.Color := co;
    RichEdit1.SelStart:=oriStartPos;
    RichEdit1.SelAttributes.Color := OriginalColor;
    Match := RegEx.Match(sorText, Match.Index + len);
    end;
  end;
begin
RichEdit1.Lines.BeginUpdate;
if sor=-1 then sor := RichEdit1.Perform(EM_LINEFROMCHAR, RichEdit1.SelStart, 0);
oriStartPos:=RichEdit1.SelStart;
yIndex:=RichEdit1.Perform(EM_LINEINDEX, sor, 0);
RichEdit1.SelStart:= yIndex;
RichEdit1.SelLength:= RichEdit1.Perform(EM_LINELENGTH, yIndex, 0);
RichEdit1.SelAttributes.Color := clBlack;
RichEdit1.SelStart:=oriStartPos;
Buffer[0] := Chr(Length(Buffer));
RichEdit1.Perform(EM_GETLINE, sor, LongInt(@Buffer));
sorText := StrPas(Buffer);
nana('begin',clBlue);
nana('asztal',clGreen);
nana('end',clred);
RichEdit1.Lines.EndUpdate;
zarol:=false;
end;

procedure TForm1.RichEdit1Change(Sender: TObject);
begin
if zarol=true then exit;
zarol:=true;
atszinez(-1);  //-1 ha az adott sor, 0-.. ha konkrét sort kell színezni
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
zarol:=true;
atszinez(2);
end;

end.