Search code examples
eclipseeclipse-plugineclipse-rcpeclipse-cdt

How to close an editor programatically in eclipse


We want to close all opened files of a project (IProject) in eclipse when we delete it. I can reach IFiles via members method of a project. I want to close deleted project's all files.


Solution

  • You can get references to the open editors on a page with:

    IWorkbenchWindow workbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
    IWorkbenchPage page = workbenchWindow.getActivePage();
    
    IEditorReference[] editorRefs = page.getEditorReferences();
    

    Get the actual editor part from the references with:

    IEditorPart editor = editorRefs[index].getEditor(true);
    

    Get the editor input:

    IEditorInput input = editor.getEditorInput();
    

    Get the file the editor is editing:

    IFile file = (IFile)input.getAdapter(IFile.class);
    

    Close an editor:

    page.closeEditor(editor, true);