unit replaceWin;

interface

uses
  Windows, Messages, SysUtils, Variants, Types, Classes, Graphics, Controls,
  Forms, Dialogs, StdCtrls, ExtCtrls, TextEditor;

type
  TreplaceFrm = class(TForm)
    cbMatchCase: TCheckBox;
    cbWWO: TCheckBox;
    btnReplaceAll: TButton;
    btnClose: TButton;
    cbLF: TCheckBox;
    rbSelection: TRadioButton;
    rbEntireFile: TRadioButton;
    stSearchFor: TStaticText;
    eSearch: TEdit;
    stReplaceWith: TStaticText;
    eReplace: TEdit;
    stScope: TStaticText;
    procedure CheckValidSettings(Sender: TObject);
    procedure btnReplaceAllClick(Sender: TObject);
    procedure btnCloseClick(Sender: TObject);
    procedure FormActivate(Sender: TObject);
  private
    FEditor: TTextEditor;
  public
    property Editor: TTextEditor read FEditor write FEditor;
  end;

implementation

uses
  UxPanel, TDMB;

{$R *.dfm}

procedure TreplaceFrm.btnCloseClick(Sender: TObject);
begin
  Close;
end;

procedure TreplaceFrm.btnReplaceAllClick(Sender: TObject);
var
  num: integer;
begin
  BeginBusyWork;
  try
    num :=
      FEditor.ReplaceAll(
        MakeFindQuery(
          eSearch.Text,
          cbMatchCase.Checked,
          cbWWO.Checked,
          cbLF.Checked
        ),
        eReplace.Text,
        rbSelection.Checked
      );
  finally
    EndBusyWork;
  end;
  if num = 0 then
    TD('The search text was not found; the file has not been changed.').Info.Execute
  else
    TD.TextFmt('%d match(es) replaced.', [num]).Info.Execute;
  FormActivate(Sender);
end;

procedure TreplaceFrm.CheckValidSettings(Sender: TObject);
begin
  btnReplaceAll.Enabled := not (rbSelection.Checked and (FEditor.SelectionType = stBlock) and cbLF.Checked);
end;

procedure TreplaceFrm.FormActivate(Sender: TObject);
begin
  rbSelection.Enabled := FEditor.TextFile.HasSelection;
  if not rbSelection.Enabled then
    rbEntireFile.Checked := True;
end;

end.
