Monday, June 30, 2008

Programmatically opening an editor

Eclipse uses file associations for opening appropriate editor on a file. You can see this in action when you click on a Java file or a ant build file. The correct editor is opened for you. If you want to do the same thing in your own plugins - it could not be easier in 3.4.

The class org.eclipse.ui.IDE has a set of static functions that opens an editor and returns a handle to that editor. This function needs a IWorkbenchPage. We can typically get it by PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(). The second parameter is a handle to the file. It can be a reference to IFile, URI, IMarker, IEditorInput, IFileStore or a URI. The last two cases typically open editors for the files that are outside the file system.

I came across this gem when I need to open an editor on a OS file path. The file is in the workspace, but the path is OS specific. In this case I used ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(Path.fromOSString(file)) to convert the OS path into an IFile. The getFileForLocation() returns null in case the path does not belong to the workspace. That is OK - that is what I exactly wanted.

So here is the entire code:


String filePath = "..." ;
final IFile inputFile = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(Path.fromOSString(filePath));
if (inputFile != null) {
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
IEditorPart openEditor = IDE.openEditor(page, inputFile);
}


If you want to position the cursor to a specific line in the editor - do the following.


int Line = ...
if (openEditor instanceof ITextEditor) {
ITextEditor textEditor = (ITextEditor) openEditor ;
IDocument document= textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput());
textEditor.selectAndReveal(document.getLineOffset(line - 1), document.getLineLength(line-1);
}

2 comments:

Anonymous said...

Hi, this is very useful. I have a question: how can I open an editor in the same way but if I dont have the full path of the file. Im basically creating a file programmatically and I want to display it with the correct editor. Because of some other limitations, Im still need to use IFile, so if I could use this exact code and just give the relative path and not the full path it'd be perfect.

Thanks!

KD said...

Long time since I wrote this and worked on eclipse plugins. I suspect you can just use IDE.openEditor directly as you already have an IFile object.