PsiFile in FileDocumentManagerAdapter#beforeDocumentSaving always null

I'm trying to implement a "On save" plugin (to reorganize imports automatically before the file is saved for example), but I don't understand why I can't get hold of any non-null PsiFile references :

public class OnFileSaveComponentTest implements ApplicationComponent {


    @NotNull

    public String getComponentName() {

        return "My On-Save Component";

    }


    public OnFileSaveComponentTest() {

        Log.print("OnFileSaveComponent");

    }


    public void initComponent() {

        MessageBus bus = ApplicationManager.getApplication().getMessageBus();

        MessageBusConnection connection = bus.connect();

        connection.subscribe(AppTopics.FILE_DOCUMENT_SYNC, new FileDocumentManagerAdapter() {

            @Override

            public void beforeDocumentSaving(@NotNull Document document) {

                Project myProject = ProjectManager.getInstance().getDefaultProject();

                PsiFile psiFile = PsiDocumentManager.getInstance(myProject).getPsiFile(document); // THIS IS ALWAYS NULL

                if (null != psiFile) {

                    ...

                }

            }

        });

    }


    public void disposeComponent() {

    }


}

Thank you for your time.

2 comments
Comment actions Permalink

It's null because you're trying to access the PSI in a default project. The default project is not supposed to be used for this purpose; it has dummy implementations for many of the components.

0
Comment actions Permalink

Thank you Dmitry that worked. I should have read the javadoc more thoughtfully as it says the default project is a template.

0

Please sign in to leave a comment.