简体   繁体   English

获取Eclipse编辑器的当前源代码?

[英]Get the current source code of an Eclipse editor?

I am working with Eclipse IDE. 我正在使用Eclipse IDE。 I want to develop a plug-in first of all, this plug-in allows me to get the whole source code as a simple string. 首先,我想开发一个插件,这个插件使我可以将整个源代码作为一个简单的字符串来获取。

I made a simple "hello the world" plug-in using the template "hello world command". 我使用模板“ hello world命令”制作了一个简单的“ hello the world”插件。 Now I am searching to get the source code from the editor of Eclipse and display it with System.out.println(); 现在,我正在寻找从Eclipse编辑器中获取源代码,并使用System.out.println();显示它。 statement instead of showing HELLO THE WORLD. 而不是显示HELLO THE WORLD。

I tried this but it shows me only the hierarchical sequence of my project, packageName/src/nameOfClass. 我试过了,但它只显示了我项目的层次结构顺序,即packageName / src / nameOfClass。

System.out.println(
    Workbench.getInstance().getActiveWorkbenchWindow().getActivePage().getActiveEditor().getEditorInput() 
);

My goal is to get the source code of the class itself (public class nameOfClass{ *** }). 我的目标是获取类本身的源代码(公共类nameOfClass {***})。

First do not use Workbench this is an internal class and must not be used. 首先不要使用Workbench这是一个内部类,一定不能使用。 Use PlatformUI to get the workbench. 使用PlatformUI获取工作台。

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

if (editor instanceof ITextEditor)
 {
   ITextEditor textEditor = (ITextEditor)editor;

   IDocumentProvider provider = textEditor.getDocumentProvider();

   IEditorInput input = editor.getEditorInput();

   IDocument document = provider.getDocument(input);

   String text = document.get();

   ...
 }

Note: Not all editors are text editors so this needs to be checked (the ITextEditor instance check above). 注意:并非所有编辑器都是文本编辑器,因此需要进行检查(上面的ITextEditor实例检查)。

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

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