Monday, October 1, 2012

How to open a Java file in read-only mode?

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:
  1. 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.
  2. 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,
  1. Create an editor extension
  2. Extend the extension class with org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor
  3. Override some of the methods
  4. 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();
}