{*******************************************************}
{                                                       }
{       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,
  SclRView;

type
  TfrmMain = class(TForm)
    PopupMenu1: TPopupMenu;
    srv: TSRichViewEdit;
    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

uses
  {$IFDEF RVUNICODESTR}
  RVGetTextW; // Delphi 2009+, using Unicode strings
  {$ELSE}
  RVGetText;  // older versions, using ANSI strings
  {$ENDIF}

{$R *.dfm}

procedure TfrmMain.FormCreate(Sender: TObject);
begin
  {$IFDEF RICHVIEWDEF6}
  PopupMenu1.AutoHotkeys := maManual;
  {$ENDIF}
  srv.RichViewEdit.Clear;
  srv.RichViewEdit.AddNL('Type a word and press Ctrl+Space for suggestions',0,0);
  srv.RichViewEdit.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
  srv.RichViewEdit.SelectCurrentWord;
  srv.RichViewEdit.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(srv.RichViewEdit);
    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);
      pt := srv.ClientToScreen(srv.CaretPos);
      PopupMenu1.Popup(pt.X, pt.Y+10);
    end;
    Key := 0;
  end;
end;

end.
