TrichRichViewEdit.GetWordUnderCursorWithDelimiters ?

General TRichView support forum. Please post your questions here
Post Reply
Fab85
Posts: 17
Joined: Tue Apr 09, 2024 6:02 am

TrichRichViewEdit.GetWordUnderCursorWithDelimiters ?

Post by Fab85 »

Hello,


I need to extract a selected word delimited by text (start delimiter '[' end delimiter ']'), for example:
"Sample data speed: [CustomerTable.MyField] km/h".
I want to display a "friendly" caption of the selected delimited field.

If a letter of MyField is selected, TrichRichViewEdit.GetCurrentWord will return 'MyField', but I need to get 'CustomerTable.MyField'.

I was thinking of removing '[', ']', '.' from TCustomRichView.delimiters before calling TrichRichViewEdit.GetCurrentWord, but this approach seems to be above all since I am using TrichRichViewEdit.OnSelect event.
I haven't found a solution in the Trichview documentation, so I have come up with the following code.
Unfortunately, it does not work in some cases. Do you have a better solution?

Code: Select all

function GetWordUnderCursorWithDelimiters(  ARichView: TRichViewEdit;   APrefix, ASuffix: string  ): string;
var
  LItemIndex, LOffset, LStartPos, LEndPos: Integer;
  LText: string;
begin
  Result := '';

  // Get index of item focused 
  LItemIndex := ARichView.CurItemNo;
  LOffset := ARichView.OffsetInCurItem;

  // Check active item 
  if (LItemIndex >= 0) and (ARichView.GetItemStyle(LItemIndex) >= 0) then
  begin
    // get texy
    LText := ARichView.GetItemText(LItemIndex);

    // find start delimiter
    LStartPos := LOffset;
    while (LStartPos > 1) and (Copy(LText, LStartPos - Length(APrefix), Length(APrefix)) <> APrefix) do
      Dec(LStartPos);

    // find end delimiter
    LEndPos := LOffset;
    while (LEndPos <= Length(LText)) and (Copy(LText, LEndPos, Length(ASuffix)) <> ASuffix) do
      Inc(LEndPos);

    // Adjust position to exclude delimiters
    if (Copy(LText, LStartPos - Length(APrefix), Length(APrefix)) = APrefix) and
       (Copy(LText, LEndPos, Length(ASuffix)) = ASuffix) then
    begin
      // Exclure le préfixe et le suffixe de l'extraction
      Result := Copy(LText, LStartPos, LEndPos - LStartPos);
    end;
  end;
end;
Sergey Tkachenko
Site Admin
Posts: 17651
Joined: Sat Aug 27, 2005 10:28 am
Contact:

Re: TrichRichViewEdit.GetWordUnderCursorWithDelimiters ?

Post by Sergey Tkachenko »

I think your code is correct.

I'd add the following line at the beginning, to allow working with text in table cells:

Code: Select all

  ARichView := ARichView.TopLevelEditor as TRichViewEdit;
This code will not work if you need text belonging to multiple items ('[' in one text item, ']' in another text item). Otherwise, it must be ok.
Post Reply