How to get text from active editor in Eclipse PDE
我有一个处理程序,我想在该处理程序中从工作台中的活动编辑器获取文本。 从下面的屏幕截图中,我想将所有内容都保存在Test.java("公共类Test ...")中。
我已经在"源"菜单下成功添加了新命令。 只是不确定现在从何处从活动编辑器获取文本。 这是到目前为止我尝试获取文本的内容(它只是在弹出窗口中显示文件名):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | package generatebuilderproject.handlers; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.handlers.HandlerUtil; import org.eclipse.jface.dialogs.MessageDialog; public class GenerateBuilderHandler extends AbstractHandler { public GenerateBuilderHandler() { } public Object execute(ExecutionEvent event) throws ExecutionException { IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event); IEditorPart editorPart = HandlerUtil.getActiveEditor(event); MessageDialog.openInformation( window.getShell(), "GenerateBuilderProject", editorPart.getEditorInput().getName()); return null; } } |
拥有
1 2 3 4 5 6 | IEditorInput input = editorPart.getEditorInput(); if (input instanceof FileEditorInput) { IFile file = ((FileEditorInput) input).getFile(); InputStream is = file.getContents(); // TODO get contents from InputStream } |
或者从这里
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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(); ... } |