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.

- 66,950
- 18
- 261
- 230

- 3,211
- 1
- 29
- 42
2 Answers
No, this is not exposed in the API. You can get close by executing the EditingCommands
MoveLeftByWord
(Ctrl+Left) and SelectRightByWord
(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.
EditingCommands.MoveLeftByWord.Execute(null, textEditor.TextArea);
EditingCommands.SelectRightByWord.Execute(null, textEditor.TextArea);
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.

- 15,944
- 2
- 54
- 60
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;

- 66,950
- 18
- 261
- 230