unit demoUnit2;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  StdCtrls, ComCtrls, ExtCtrls;

type
  TfrmDemo = class(TForm)
    memo: TRichEdit;
    Panel1: TPanel;
    Button1: TButton;
    Button2: TButton;
    procedure memoChange(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
    procedure UpdateSyntax;
  end;

var
  frmDemo: TfrmDemo;

implementation

uses psvPas;


{$R *.DFM}

procedure TfrmDemo.UpdateSyntax;
var
  TempMS: TMemoryStream;
  FSyntax: TpsvPasRTF;
  pos, top: Integer;
  OnChange: TNotifyEvent;
begin
  if (Length(memo.Text) <= 0) then
    exit;
  pos := memo.selstart;
  top := SendMessage(memo.Handle, EM_GETFIRSTVISIBLELINE, 0, 0);
  OnChange := memo.OnChange;
  TempMS := TMemoryStream.Create;
  memo.OnChange := nil;
  try
    FSyntax := TpsvpasRTF.Create;
    try
      try
        FSyntax.SetText(Memo.Text);
        FSyntax.ConvertToRTFStream(TempMS);
        TempMS.Position := 0;
        memo.PlainText := False;
        memo.Lines.BeginUpdate;
        memo.Lines.LoadFromStream(TempMS);
        SendMessage(memo.Handle, EM_LINESCROLL, 0, top);
        memo.Lines.EndUpdate;
      finally
        FSyntax.Free;
      end;
    except
      memo.SelAttributes := memo.DefAttributes;
    end;
  finally
    memo.PlainText := True;
    memo.SelStart := Pos;
    TempMS.Free;
    memo.OnChange := OnChange;
  end;
end;

procedure TfrmDemo.memoChange(Sender: TObject);
begin
  UpdateSyntax;
end;

procedure TfrmDemo.FormCreate(Sender: TObject);
begin
  UpdateSyntax;
end;

procedure TfrmDemo.Button1Click(Sender: TObject);
begin
  memo.OnChange := memoChange;
  UpdateSyntax;
end;

procedure TfrmDemo.Button2Click(Sender: TObject);
var
 MS : TMemoryStream;
begin
  memo.OnChange := nil;
  memo.PlainText := true;
  MS := TMemoryStream.Create;
  memo.Lines.SaveToStream(MS);
  MS.Position := 0;
  memo.Clear;
  memo.Lines.LoadFromStream(MS);
  MS.Free;
end;

end.
