{*******************************************************}
{                                                       }
{       RichView                                        }
{       AutoComplete demo                               }
{                                                       }
{       Copyright (c) Sergey Tkachenko                  }
{       svt@trichview.com                               }
{       http://www.trichview.com                        }
{                                                       }
{*******************************************************}

unit MainFrm;

interface

{$I RV_Defs.inc}

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
  Dialogs, Menus, RVStyle, RVScroll, RichView, RVEdit, RVGetText;

type
  TfrmMain = class(TForm)
    RichViewEdit1: TRichViewEdit;
    RVStyle1: TRVStyle;
    PopupMenu1: TPopupMenu;
    procedure RichViewEdit1KeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure FormCreate(Sender: TObject);
  private
    procedure AddPopupMenuItem(s: String);
    procedure AutoCompletePopupMenuClick(Sender: TObject);
    { Private declarations }
  public
    { Public declarations }
  end;

var
  frmMain: TfrmMain;

implementation

{$R *.dfm}

procedure TfrmMain.FormCreate(Sender: TObject);
begin
  {$IFDEF RICHVIEWDEF6}
  PopupMenu1.AutoHotkeys := maManual;
  {$ENDIF}
  RichViewEdit1.Clear;
  RichViewEdit1.AddNL(
    'Type a word and press Ctrl+Space for suggestions', 0,0);
  RichViewEdit1.Format;
end;

procedure TfrmMain.AddPopupMenuItem(s: String);
var mi: TMenuItem;
begin
   mi := TMenuItem.Create(PopupMenu1);
   mi.Caption := s;
   mi.OnClick := AutoCompletePopupMenuClick;
   PopupMenu1.Items.Add(mi);
end;

procedure TfrmMain.AutoCompletePopupMenuClick(Sender: TObject);
begin
  RichViewEdit1.SelectCurrentWord;
  RichViewEdit1.InsertText((Sender as TMenuItem).Caption, False);
end;

procedure TfrmMain.RichViewEdit1KeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
var s: String;
    pt: TPoint;
begin
  if (Key=VK_SPACE) and (ssCtrl in Shift) then begin
    s := GetCurrentWord(RichViewEdit1);
    if s<>'' then begin
      while PopupMenu1.Items.Count>0 do
        PopupMenu1.Items[0].Free;
      AddPopupMenuItem('super'+s);
      AddPopupMenuItem('mega'+s);
      AddPopupMenuItem('ultra'+s);
      AddPopupMenuItem('grand'+s);
      GetCaretPos(pt);
      pt := RichViewEdit1.TopLevelEditor.ClientToScreen(pt);
      PopupMenu1.Popup(pt.X, pt.Y+10);
    end;
    Key := 0;
  end;
end;

end.
