Eclipse 插件开发:如何访问在 Eclipse 编辑器中编写的代码

Eclipse Plugin Development: How to access code written in the eclipse editor

我正在制作一个 Eclipse 插件,它需要访问在 Eclipse 编辑器中编写的代码。我遵循了 link 中提到的过程。 Accessing Eclipse editor code 但它在消息框中显示文件路径而不是代码。 IEditorEditor class 的 getEditorInput() 没有根据 link 执行它应该执行的操作。这是我的代码。请帮我找出我做错了什么。

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

这是输出的快照。

您可以通过两种不同的方式执行此操作。无论内容是否由磁盘上的文件支持,这种方式都有效。

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

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

您可以通过IDocument获取和修改内容。