Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling organize imports programmatically

I'm trying to execute 'OrganizeImports' programmatically on files that I'm editing programmatically. My code looks like this:

    final ICommandService cmdService = (ICommandService)PlatformUI.getWorkbench().getService    (ICommandService.class);
    if (cmdService != null) {
        final Command cmd = cmdService.getCommand(IJavaEditorActionDefinitionIds.ORGANIZE_IMPORTS);
        final ExecutionEvent execEvt = new ExecutionEvent(cmd, Collections.EMPTY_MAP, compileationUnit, null);

        PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
        ResourcesPlugin.getWorkspace().

        Display.getDefault().syncExec(new Runnable() {
            @Override
            public void run() {
                try {
                    //cmd.executeWithChecks(execEvt);
                    cmd.execute(execEvt);
                } catch (Exception e) {
                    getLogger().severe("organize imports failed: " + e.getMessage());
                }
            }

My problem is that OrganizeImportsAction executes on the current selection which is not the same as the compilation unit I'm editing. I would like to set the selection programmatically on the compilation unit but I don't know how to do that. Or maybe there is another way to trigger OrganizeImports.

thanks, stefan

like image 348
Stefan Roka Avatar asked May 04 '10 10:05

Stefan Roka


1 Answers

May be this test ui.org.eclipse.jdt.ui.tests.quickfix.CleanUpTest class could offer some clue.
It is based on the enable method in ui.org.eclipse.jdt.ui.tests.quickfix.CleanUpTestCase and on the org.eclipse.ltk.core.refactoring.PerformChangeOperation class.

You can see PerformChangeOperation invoked ink the class org.eclipse.ltk.ui.refactoring.RefactoringWizard.

like image 82
VonC Avatar answered Nov 02 '22 01:11

VonC