从Eclipse Java编辑器中获取所选文本

Krt*_*lta 6 eclipse eclipse-plugin editor

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

我的代码看起来像这样:我从这里得到它: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();
}
Run Code Online (Sandbox Code Playgroud)

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

Von*_*onC 7

你可以要求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());
Run Code Online (Sandbox Code Playgroud)

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