In one of my eclipse plugin based application I wanted to open Java files in read only mode. One option was to use
org.eclipse.jface.text.source.SourceViewer , where I could have used
JavaSourceViewerConfiguration
for providing Java highlighting and all. But there were two problems:
- Source viewer won't inherit the Java editor settings (and if you have modified eclipse Java editor theme), which means your background and foreground in the SourceViewer gets completely messed up.
- Secondly you would lose all the markup and bookmarking facilities available with editors
So, I decided to extend the existing Java editor. The steps are extremely simple,
- Create an editor extension
- Extend the extension class with org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor
- Override some of the methods
- Open your file with this editor
Code
Editor Code
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor;
@SuppressWarnings("restriction")
public class ReadonlyEd extends CompilationUnitEditor
{
public static final String ID = "read.only";
public ReadonlyEd() {
}
@Override
public boolean isEditable() {
return false;
}
@Override
public boolean isEditorInputModifiable() {
return false;
}
@Override
public boolean isEditorInputReadOnly() {
return true;
}
@Override
public boolean isDirty() {
return false;
}
}
Code for Invoking the Editor
IFile file = ...; // Get the Java file instance
IWorkbenchPage page = ...; // Get the workbench page
FileEditorInput input = new FileEditorInput(file);
try {
IDE.openEditor(window.getActivePage(), input, ReadonlyEd.ID);
} catch (PartInitException e) {
e.printStackTrace();
}