Character before caret

General TRichView support forum. Please post your questions here
Post Reply
Extorian
Posts: 24
Joined: Wed Dec 28, 2011 3:52 pm

Character before caret

Post by Extorian »

Hi,

How do I character that is before and after the caret?

For example. In the sentence:

The quick bro^wn fox.

The caret is placed between o and w. I would like to extract o and w.

Thank you.
Sergey Tkachenko
Site Admin
Posts: 17566
Joined: Sat Aug 27, 2005 10:28 am
Contact:

Post by Sergey Tkachenko »

Let you have RichViewEdit1.

Define a variable rve: TCustomRichViewEdit, and assign
rve := RichViewEdit1.TopLevelEditor.

Use the properties rve.CurItemNo and rve.OffsetInCurItem.
If rve.GetItemStyle(rve.CurItemNo)>=0, this is a text item, you can get it text using rve.GetItemText(rve.CurItemNo). In this case, rve.OffsetInCurItem is the index of character (starting from 1) after the caret. The last possible offset = Length+1, meaning the caret is after the item.

So , the problem is solved if the caret is inside a text item. However, it may be between items. In this case, the following methods and properties may be useful:
- rve.ItemCount (items are numbered from 0 to rve.ItemCount)
- rve.IsFromNewLine(ItemNo) (True if the item starts the paragraph, or a line break (added using Shift+Enter) inside a paragraph)
- rve.GetOffsBeforeItem(ItemNo), rve.GetOffsAfterItem(ItemNo) - compare with rve.OffsetInCurItem to determine if the caret between items.

PS: You can look at function GetCurrentChar from RVGetText.pas (or RVGetTextW.pas).
It returns character to the left of caret. If caret is at the beginning of line, - to the right. If no character, returns empty string.
Extorian
Posts: 24
Joined: Wed Dec 28, 2011 3:52 pm

Post by Extorian »

Excellent. Thanks :)
Sergey Tkachenko
Site Admin
Posts: 17566
Joined: Sat Aug 27, 2005 10:28 am
Contact:

Post by Sergey Tkachenko »

There is an inefficient but simple alternative method, using RVLinear.pas

s := RVGetTextRange(RichViewEdit1, 0, RVGetTextLength(RichViewEdit1)) returns the whole text. All non-text items (except for tabs and tables) are saved as a character specified in RVNonTextCharacter variable (space character by default).

Now, the caret position is returned as
pos := RVGetLinearCaretPos(RichViewEdit1).
This position corresponds to character indices in s (0 - before the first character)
Post Reply