Select Word like Double Click in AvalonEdit

954 views Asked by At

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.

2

There are 2 answers

0
Daniel On BEST ANSWER

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.

0
NearHuscarl 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;