我想编写一个 eclipse 插件,它从编辑器窗口读取内容并将其显示给我。在我在这篇文章中找到如何执行此操作后,这应该是一项非常简单的任务 Adding item to Eclipse text viewer context menu
在我陈述我的问题之前,让我陈述一下我到目前为止所做的事情:
我在 eclipse 3.7 上开发,我创建了一个简单的 hello world 插件,它的代码是由 eclipse 为我自动生成的。
这是运行函数:
public void run(IAction action) {
MessageDialog.openInformation(
window.getShell(),
"AnirudhPlugin",
"Hello, Eclipse world");
try {
IEditorPart part = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
if(part instanceof IReusableEditor){
System.out.println("is of type reusable editor");
final IReusableEditor editor = (IReusableEditor)part;
if(editor instanceof AbstractTextEditor){
System.out.println("abstract");
}
if(editor instanceof StatusTextEditor){
System.out.println("status");
}
if(editor instanceof TextEditor){
System.out.println("text");
}
if(editor instanceof AbstractDecoratedTextEditor){
System.out.println("abs dec");
}
if(editor instanceof CommonSourceNotFoundEditor){
System.out.println("comm");
}
}
if ( part instanceof ITextEditor ) {
final ITextEditor editor = (ITextEditor)part;
IDocumentProvider prov = editor.getDocumentProvider();
IDocument doc = prov.getDocument( editor.getEditorInput() );
ISelection sel = editor.getSelectionProvider().getSelection();
if ( sel instanceof TextSelection ) {
final TextSelection textSel = (TextSelection)sel;
String newText = "/*" + textSel.getText() + "*/";
MessageDialog.openInformation(
window.getShell(),
"AnirudhPlugin",
newText);
doc.replace( textSel.getOffset(), textSel.getLength(), newText );
}
}else{
MessageDialog.openInformation(
window.getShell(),
"AnirudhPlugin",
"Not ITextEditor");
}
} catch ( Exception ex ) {
ex.printStackTrace();
}
}
现在,当我运行这段代码时,我得到的输出是“可重用编辑器”类型,而不是它应该是“ITextEditor”的类型(请纠正我,因为我是 eclipse 插件的新手,所以我在做一些愚蠢的陈述开发)。我尝试检查 IReusableEditor 实例类型(如您在上面的代码中所见,我尝试使用“instance of”进行检查)但令我惊讶的是它没有指向任何实现 IReusableEditor 接口(interface)的类。
我尝试阅读的编辑器是一个简单的编辑器窗口,我在其中编写了一些 Java 代码。
我还得到以下的 doc2 变量值为 null
final IDocument doc2 = (IDocument) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor().getAdapter(IDocument.class);
请让我知道我哪里做错了,在此先感谢。
最佳答案
好的,我知道如何从编辑器窗口读取
if (editor instanceof CompilationUnitEditor) {
CompilationUnitEditor compEditor = (CompilationUnitEditor)editor;
IEditorInput input = compEditor.getEditorInput();
IDocumentProvider provider = compEditor.getDocumentProvider();
IDocument document = provider.getDocument(input);
if (document != null) {
System.out.println("document contents:" + document.get());
}
}
关于java - 用于读取编辑器内容的 Eclipse 插件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8284391/