Eclipse select下的文字来自cursor/caret和return而已

Eclipse select text from under the cursor/caret and return it

使用 eclipse 插件,并为我的编辑器做一些功能,我有这个方法,selects 突出显示编辑器中的文本,returns 它作为字符串:

public String getCurrentSelection() {
    IEditorPart part = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
            .getActivePage().getActiveEditor();
    if (part instanceof ITextEditor) {
        final ITextEditor editor = (ITextEditor) part;
        ISelection sel = editor.getSelectionProvider().getSelection();
        if (sel instanceof TextSelection) {
            ITextSelection textSel = (ITextSelection) sel;
            return textSel.getText();
        }
    }
    return null;
}

但现在我希望,如果我将光标放在一个单词中,它将 select 整个单词和 return 它作为一个字符串。

除了我解析整个编辑器、获取光标位置、左右搜索空格等等的复杂算法之外,还有什么更简单的方法可以将光标所在位置的文本作为字符串获取吗?

我设法让一些东西工作了。对于遇到相同问题的任何人,以下代码都有效(至少对我而言):

private String getTextFromCursor() {
    IEditorPart part = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
            .getActivePage().getActiveEditor();
    TextEditor editor = null;

    if (part instanceof TextEditor) {
        editor = (TextEditor) part;
    }

    if (editor == null) {
        return "";
    }

    StyledText text = (StyledText) editor.getAdapter(Control.class);

    int caretOffset = text.getCaretOffset();

    IDocumentProvider dp = editor.getDocumentProvider();
    IDocument doc = dp.getDocument(editor.getEditorInput());

    IRegion findWord = CWordFinder.findWord(doc, caretOffset);
    String text2 = "";
    if (findWord.getLength() != 0)
        text2 = text.getText(findWord.getOffset(), findWord.getOffset()
                + findWord.getLength() - 1);
    return text2;
}