Showing posts with label File. Show all posts
Showing posts with label File. Show all posts

Wednesday, 29 June 2011

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);
}