首页 > 解决方案 > Eclipse 插件开发:如何访问在 Eclipse 编辑器中编写的代码

问题描述

我正在制作一个需要访问在 Eclipse 编辑器中编写的代码的 Eclipse 插件。我已经按照链接中提到的过程进行了操作。 访问 Eclipse 编辑器代码 但它在消息框中显示文件路径而不是代码。IEditorEditor类的getEditorInput()没有按照链接做它应该做的事情。这是我的代码。请帮我找出我做错了什么。

public Object execute(ExecutionEvent event) throws ExecutionException {
    IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);

    IEditorPart editor = ((IWorkbenchPage) PlatformUI.getWorkbench()
            .getActiveWorkbenchWindow().getActivePage()).getActiveEditor();

    IEditorInput input = (IEditorInput) editor.getEditorInput();     // accessing code from eclipse editor

    String code = input.toString();

    MessageDialog.openInformation(
            window.getShell(),
            "Project",
            code);

    return null;
}

这是输出的快照。 在此处输入图像描述

标签: javaeclipse-plugincode-editor

解决方案


你可以用两种不同的方式来做到这一点。无论内容是否由磁盘上的文件支持,这种方式都有效。

此方法从编辑器获取文本IDocument,这是大多数用途存储和访问内容的方式。StyledText是一个小部件,除非您使用 Widgets 和 Controls 做某事,否则它不是正确的方法。为此,您将从编辑器部分开始,通过ITextEditor界面,然后将IDocumentProvider与当前编辑器输入一起使用。这会跳过instanceof您事先想要做的检查,以及如果这是 a 中的一个页面,您可能需要做的任何事情MultiPageEditorPart(没有处理这些的标准方法)。

org.eclipse.jface.text.IDocument document = 
    ((org.eclipse.ui.texteditor.ITextEditor)editor).
    getDocumentProvider().
    getDocument(input);

您可以通过IDocument.


推荐阅读