Search code examples
delphisearchrichedit

mark all the instances of a word (Delphi, RichText)


OK, this is a problem that's been nagging and I can't see to find a definitive answer. How do you find and mark all instances of a word?

What I mean is, I search for a word (say: Person). If the word exists the I mark (using red or whatever color) all instances of that word in the richedit. If I press Esc then it gets deselected.

Any ideas?

code is appreciated.


Solution

  • wonderer, I wrote this code, I hope it will be useful :

    Procedure MarkString(RichEdit:TRichEdit;strtomark : string);
    Var
    FoundAt : integer;
    begin
        FoundAt:=RichEdit.FindText(strtomark,0,maxInt,[stWholeWord]);
        while FoundAt <> -1 do
        begin
                 RichEdit.SelStart := FoundAt;
                 RichEdit.SelLength := Length(strtomark);
                 RichEdit.SelAttributes.Style := [fsBold];
                 RichEdit.SelAttributes.Color := clRed;
                 RichEdit.SelText :=strtomark;
                 FoundAt:=RichEdit.FindText(strtomark,FoundAt + length(strtomark),maxInt,[stWholeWord]);
        end;
    end;
    
    
    Procedure UnMarkString(RichEdit:TRichEdit;strtomark : string);
    Var
    FoundAt : integer;
    begin
        FoundAt:=RichEdit.FindText(strtomark,0,maxInt,[stWholeWord]);
        while FoundAt <> -1 do
        begin
                 RichEdit.SelStart := FoundAt;
                 RichEdit.SelLength := Length(strtomark);
                 RichEdit.SelAttributes.Style := [];
                 RichEdit.SelAttributes.Color := clBlack;
                 RichEdit.SelText :=strtomark;
                 FoundAt:=RichEdit.FindText(strtomark,FoundAt + length(strtomark),maxInt,[stWholeWord]);
        end;
    end;
    
    
    MarkString(RichEdit1,'delphi'); //To Mark a string
    
    UnMarkString(RichEdit1,'delphi'); //To UnMark a string
    

    Bye.