简体   繁体   English

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

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

I'm making an Eclipse plug-in that requires access to code written in the Eclipse editor. 我正在创建一个Eclipse插件,需要访问Eclipse编辑器中编写的代码。 I've followed the process mentioned in the link. 我已经按照链接中提到的过程进行了操作。 Accessing Eclipse editor code But it's showing filepath instead of code in the message box. 访问Eclipse编辑器代码但它在消息框中显示文件路径而不是代码。 The getEditorInput() of IEditorEditor class isn't doing what it should do according to the link. IEditorEditor类的getEditorInput()根据链接没有做它应该做的事情。 Here's my code. 这是我的代码。 Please help me find what i'm doing wrong. 请帮我找一下我做错了什么。

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

And here's snap of the output. 这是输出的快照。 在此输入图像描述

You can do this two different ways. 你可以用两种不同的方式做到这一点 This way works regardless of whether the contents are backed by a file on disk or not. 无论内容是否由磁盘上的文件支持,这种方式都有效。

This method gets the text IDocument from the editor, which is how the contents are stored and accessed for most uses. 此方法从编辑器获取文本IDocument ,这是大多数用途存储和访问内容的方式。 StyledText is a widget, and unless you are doing something with Widgets and Controls, it's not the right way in. For that you're going to go from the editor part, through the ITextEditor interface, and then use the IDocumentProvider with the current editor input. StyledText是一个小部件,除非你正在使用小部件和控件,否则它不是正确的方式。为此你将从编辑器部分,通过ITextEditor接口,然后使用IDocumentProvider与当前编辑器输入。 This is skipping the instanceof check you'd want to do beforehand, as well as anything you might have to do if this is a page in a MultiPageEditorPart (there's no standard way for handling those). 这是跳过你想要事先做的检查的instanceof ,以及如果这是MultiPageEditorPart的页面(没有标准的方法来处理那些)你可能需要做的任何事情。

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

You can get, and modify, the contents through the IDocument . 您可以通过IDocument获取和修改内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM