Is there a helper method in AvalonEdit to select a word similar to how double-clicking the mouse does? I need it to write a SelectWordFromCurrentCaretPosition
function.
Select Word like Double Click in AvalonEdit
954 views Asked by Mike Ward At
2
There are 2 answers
0
On
Here is my implementation based on @Daniel's answer:
private string GetWordAtMousePosition(MouseEventArgs e)
{
var mousePosition = this.GetPositionFromPoint(e.GetPosition(this));
if (mousePosition == null)
return string.Empty;
var line = mousePosition.Value.Line;
var column = mousePosition.Value.Column;
var offset = Document.GetOffset(line, column);
if (offset >= Document.TextLength)
offset--;
int offsetStart = TextUtilities.GetNextCaretPosition(Document, offset, LogicalDirection.Backward, CaretPositioningMode.WordBorder);
int offsetEnd = TextUtilities.GetNextCaretPosition(Document, offset, LogicalDirection.Forward, CaretPositioningMode.WordBorder);
if (offsetEnd == -1 || offsetStart == -1)
return string.Empty;
var currentChar = Document.GetText(offset, 1);
if (string.IsNullOrWhiteSpace(currentChar))
return string.Empty;
return Document.GetText(offsetStart, offsetEnd - offsetStart);
}
private void OnMouseMove(object sender, MouseEventArgs e)
{
string wordUnderCaret = GetWordAtMousePosition(e);
Debug.Print(wordUnderCaret);
}
And add the delegate to the MouseMove event handler
TextArea.MouseMove += OnMouseMove;
No, this is not exposed in the API. You can get close by executing the
EditingCommands
MoveLeftByWord
(Ctrl+Left) andSelectRightByWord
(Ctrl+Shift+Right) after each other, but this doesn't have the desired effect if the caret is placed at the beginning of the word.Alternatively, you can implement this yourself. The logic for detecting word boundaries is available as
VisualLine.GetNextCaretPosition(..., CaretPositioningMode.WordBorder)
.You can look in the AvalonEdit source code to see how the double-clicking logic is implemented:
SelectionMouseHandler.GetWordAtMousePosition()
Also, you might want to look at the source code of the
CaretNavigationCommandHandler
, which implements the Ctrl+Left and Ctrl+Right shortcuts.