6
votes

Can anybody give me some simple code that would give me the ability to search a simple string in a memo and have it highlighted in the memo after being found?

2

2 Answers

11
votes

This search allows for document wrap, case (in)sensitive search and searching from cursor position.

type
  TSearchOption = (soIgnoreCase, soFromStart, soWrap);
  TSearchOptions = set of TSearchOption;


function SearchText(
    Control: TCustomEdit; 
    Search: string; 
    SearchOptions: TSearchOptions): Boolean;
var
  Text: string;
  Index: Integer;
begin
  if soIgnoreCase in SearchOptions then
  begin
    Search := UpperCase(Search);
    Text := UpperCase(Control.Text);
  end
  else
    Text := Control.Text;

  Index := 0;
  if not (soFromStart in SearchOptions) then
    Index := PosEx(Search, Text, 
         Control.SelStart + Control.SelLength + 1);

  if (Index = 0) and 
      ((soFromStart in SearchOptions) or 
       (soWrap in SearchOptions)) then
    Index := PosEx(Search, Text, 1);

  Result := Index > 0;
  if Result then
  begin
    Control.SelStart := Index - 1;
    Control.SelLength := Length(Search);
  end;
end;

You can set HideSelection = False on the memo to show the selection even if the memo isn't focussed.

Use like this:

  SearchText(Memo1, Edit1.Text, []);

Allows searching edits as well.

3
votes
  function TForm1.FindText( const aPatternToFind: String):Boolean;
  var
    p: Integer;
  begin
    p := pos(aPatternToFind, Memo1.Text);
    Result :=  (p > 0);
    if Result then
      begin
        Memo1.SelStart := p;
        Memo1.SelLength := Length(aPatternToFind);
        Memo1.SetFocus; // necessary so highlight is visible
      end;
  end;

This does NOT search across lines if WordWrap is true.