[Example] How to replace text in selection

Demos, code samples. Only questions related to the existing topics are allowed here.
Post Reply
Sergey Tkachenko
Site Admin
Posts: 17554
Joined: Sat Aug 27, 2005 10:28 am
Contact:

[Example] How to replace text in selection

Post by Sergey Tkachenko »

This example shows how to replace all occurrences of SFrom to STo only in the selected fragment.
This operation is undoable.

Code: Select all

uses RVLinear;
procedure ReplaceInSelection(rve: TCustomRichViewEdit; const SFrom, STo: String);
var
  SelStart, SelLength, EndPos, LenDif: Integer;
begin
  rve := rve.TopLevelEditor;
  RVGetSelection(rve, SelStart, SelLength);
  if SelLength < Length(SFrom) then
    exit;
  EndPos := SelStart + SelLength;
  LenDif := Length(STo) - Length(SFrom);
  rve.BeginUpdate;
  rve.BeginUndoGroup(rvutModifyItem);
  rve.SetUndoGroupMode(True);
  try
    RVSetSelection(rve, SelStart, 0);
    while rve.SearchText(SFrom, [rvseoDown, rvseoMultiItem]) and
      (RVGetLinearCaretPos(rve) <= EndPos) do
    begin
      rve.InsertText(STo);
      inc(EndPos, LenDif);
    end;
  finally
    rve.SetUndoGroupMode(False);
    rve.EndUpdate;
  end;
  RVSetSelection(rve, SelStart, EndPos - SelStart);
end;
Post Reply