从 Eclipse Java 编辑器中抓取选定的文本

2022-01-16 00:00:00 editor eclipse-plugin eclipse

我正在开发一个 Eclipse 插件,在按下按钮时,该插件会在 Java 编辑器中获取选定的文本并将其放入出现的文本框中.

I'm developing an Eclipse plug-in where upon pressing a button, the plug-in takes the selected text in the Java editor and puts in a text box which appears.

我的代码如下所示:我从这里得到它:http://dev.eclipse.org/newslists/news.eclipse.newcomer/msg02200.html

My code looks like this: I got it from here: http://dev.eclipse.org/newslists/news.eclipse.newcomer/msg02200.html

private ITextSelection getSelection(ITextEditor editor) {
     ISelection selection = editor.getSelectionProvider()
            .getSelection();
     return (ITextSelection) selection;
}

private String getSelectedText(ITextEditor editor) {
     return getSelection(editor).getText();
}

问题是如何让Java 编辑器的ITextEditor 显示出来.巧合的是,这是我发布的链接中的下一个问题,但没有答案:(

The problem is how will I get the ITextEditor of the Java editor being displayed. Coincidentally it's the next question in the thread in the link I posted but it's unanswered :(

推荐答案

你可以要求 ActiveEditor,如 这个帖子:

IEditorPart part;

part =
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().get
ActiveEditor();

if(part instanceof ITextEditor){
    ITextEditor editor = (ITextEditor)part;
    IDocumentProvider provider = editor.getDocumentProvider();
    IDocument document = provider.getDocument(editor.getEditorInput());

<小时>

OP Krt_Malta 提到了这个 博客条目以编程方式查询当前文本选择",类似于这个其他 SO 答案(写成 之前博客条目)替换选定的代码eclipse 编辑器通过插件命令".


The OP Krt_Malta mentions this blog entry "Programmatically query current text selection", which is similar to this other SO answer (written before the blog entry) "Replace selected code from eclipse editor through plugin command".

相关文章