【问题标题】:Eclipse select text from under the cursor/caret and return itEclipse 从光标/插入符号下选择文本并返回
【发布时间】:2015-08-17 05:45:55
【问题描述】:

在 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 调用的命令的实现。

标签: java eclipse eclipse-plugin editor


【解决方案1】:

我设法让一些工作正常进行。对于面临同样问题的任何人,以下代码都有效(至少对我而言):

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;
}

【讨论】:

    猜你喜欢
    • 2019-09-17
    • 1970-01-01
    • 2018-10-28
    • 2019-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-23
    • 2010-10-20
    相关资源
    最近更新 更多