Posts Tagged ‘delphi’

TRichEdit: change the substring but don’t change color/font attributes

Thursday, August 28th, 2008

For example, if you have some TRichEdit instance and you want to change some substring there but do not change the formatting (color/font etc) for this text, you may use this code:

var
  i: Integer;
begin
  if SameText(strNewValue, strOldValue) then exit;
  repeat
    i := Pos(strOldValue, yourRichEdit.Lines.Text);
    if (i > 0) then
    begin
      yourRichEdit.SelStart := i-1;
      yourRichEdit.SelLength := Length(strOldValue);
      yourRichEdit.SelText := strNewValue;
    end;
  until (i = 0)
end;

PS: if use the next code, then formatting will be lost:
yourRichEdit.Lines.Text := StringReplace(yourRichEdit.Lines.Text, strOldValue, strNewValue, [rfIgnoreCase, rfReplaceAll])