Feb 20, 2007

Opening an Editor programmatically

When you click on a file in the Package Explorer or Navigator, the file will open the associated editor. If you are looking for a way to do the same action through code, this tip is for you.

There are three things you need to open an editor:
(*) The IEditorInput for the resource you want to open
(*) A IWorkbenchPage, in which you want to open the editor
(*) The id of the editor, which you want to open.

For this tip, we assume that you want to open a file. So we can use FileEditorInput.
IEditorInput editorInput = new FileEditorInput(fileToBeOpened);

We will open the editor in the active page of the active window.
IWorkbenchWindow window=PlatformUI.getWorkbench().getActiveWorkbenchWindow();
IWorkbenchPage page = window.getActivePage();

Open the TextEditor in that page.
page.openEditor(editorInput, "org.eclipse.ui.DefaultTextEdtior");

So here goes the entire snippet:

IFile fileToBeOpened = ...;
IEditorInput editorInput = new FileEditorInput(fileToBeOpened);
IWorkbenchWindow window=PlatformUI.getWorkbench().getActiveWorkbenchWindow();
IWorkbenchPage page = window.getActivePage();
page.openEditor(editorInput, "org.eclipse.ui.DefaultTextEdtior");

2 comments:

Anonymous said...

Where can I get the classes
IFile
FileEditorInput
?

Prakash G.R. said...

IFile is in org.eclipse.core.resources plugin
IFileEditorInput is in org.eclipse.ui.ide plugin.