在AvalonEdit中选择像双击一样的单词

时间:2014-11-18 20:51:53

标签: avalonedit

AvalonEdit中是否有辅助方法可以选择与双击鼠标的方式类似的单词?我需要它来编写SelectWordFromCurrentCaretPosition函数。

2 个答案:

答案 0 :(得分:1)

不,这不会在API中公开。您可以通过执行EditingCommands MoveLeftByWord(Ctrl +左)和SelectRightByWord(Ctrl + Shift +右)相互接近来接近,但如果相同,则无法获得所需的效果插入符号位于单词的开头。

EditingCommands.MoveLeftByWord.Execute(null, textEditor.TextArea);
EditingCommands.SelectRightByWord.Execute(null, textEditor.TextArea);

或者,您可以自己实现。检测字边界的逻辑可以VisualLine.GetNextCaretPosition(..., CaretPositioningMode.WordBorder)

您可以查看AvalonEdit源代码,了解双击逻辑的实现方式:SelectionMouseHandler.GetWordAtMousePosition()

另外,您可能需要查看CaretNavigationCommandHandler的源代码,它实现了Ctrl + Left和Ctrl + Right快捷方式。

答案 1 :(得分:1)

以下是基于@ Daniel的回答

的实现
    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);
    }

将委托添加到MouseMove事件处理程序

TextArea.MouseMove += OnMouseMove;