Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search thru a memo in Delphi?

Tags:

delphi

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?

like image 584
micheal Avatar asked Nov 20 '10 12:11

micheal


1 Answers

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.

like image 52
GolezTrol Avatar answered Oct 13 '22 02:10

GolezTrol