Page 1 of 1

[Example] How to replace text in selection

Posted: Mon Oct 05, 2020 3:48 pm
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;