Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/eclipse/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Eclipse从光标/插入符号下选择文本并返回它_Java_Eclipse_Eclipse Plugin_Editor - Fatal编程技术网

Java Eclipse从光标/插入符号下选择文本并返回它

Java Eclipse从光标/插入符号下选择文本并返回它,java,eclipse,eclipse-plugin,editor,Java,Eclipse,Eclipse Plugin,Editor,使用eclipse插件,并为我的编辑器提供一些功能,我有一个方法,可以从编辑器中选择突出显示的文本并将其作为字符串返回: public String getCurrentSelection() { IEditorPart part = PlatformUI.getWorkbench().getActiveWorkbenchWindow() .getActivePage().getActiveEditor(); if (part instanceof ITe

使用eclipse插件,并为我的编辑器提供一些功能,我有一个方法,可以从编辑器中选择突出显示的文本并将其作为字符串返回:

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;
}
但现在我想,如果我把光标放在一个单词里,它会选择整个单词,并将其作为字符串返回


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

我设法找到了一些有用的方法。对于面临相同问题的任何人,以下代码都有效(至少对我而言):


如果您有Eclipse的源代码,请查找通过Ctrl+Alt+Left调用的命令的实现。
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;
}