[Lazarus] Find exact cursor position in TMemo

Timothy Groves the.tail.kinker at gmail.com
Tue Nov 19 12:56:51 CET 2024


I'm using a TMemo as the base of a text editor, and the editor has to do 
some text replacement.  How do I get the exact insert position of the 
insertion point?  I used SelStart, but when the insertion point is too 
close to the end of the document, this becomes unreliable.  Here's my code.

procedure TfrmEditor.txtEditorKeyPress(Sender: TObject; var Key: char);
var
   CursorPos: Integer;
   TextLen : integer;
   TextBeforeCursor: string;
begin
   TextLen := length (txtEditor.Text);
   if Key = '-' then
   begin
     // Get the current cursor position
     CursorPos := txtEditor.SelStart;

     // Ensure there is enough text to analyze
     if CursorPos >= 2 then
     begin
       // Get the last two characters before the dash
       TextBeforeCursor := Copy(txtEditor.Text, CursorPos - 2, 2);

       // Check if the last two characters are also dashes
       if TextBeforeCursor = '--' then
       begin
         // Remove the three dashes
         txtEditor.SelStart := CursorPos - 2;
         txtEditor.SelLength := 2;
         txtEditor.SelText := '\[em]';

         // Cancel the current dash keypress
         Key := #0;
       end;
     end;
   end;
end;

TextLen is there only for debugging purposes.



More information about the lazarus mailing list