Search code examples
javaintellij-ideaintellij-plugin

I want to write an IDEA plugin that performs the same functions as `Always Select Opened File`


Creating my IDEA plugin. If give a path, I can open the corresponding file through the following code:

VirtualFile classFile = LocalFileSystem.getInstance().findFileByPath(f.getAbsolutePath());
OpenFileDescriptor openFileDescriptor = new OpenFileDescriptor(project, classFile);
FileEditorManager.getInstance(project).openTextEditor(openFileDescriptor, true);

But I want the Navigation view on the left to also focus on the file represented by the path I give.

enter image description here

This is similar to the setting of 'always select opened file'.

enter image description here

I didn't find what I needed in the official API.

I sincerely hope for help.


Solution

  • A possibly more reliable solution that requires less code:

      private static void selectInProjectView(VirtualFile file, Project project) {
        FileSelectInContext selectInContext = new FileSelectInContext(project, file);
        SelectInTarget selectInTarget = SelectInManager.findSelectInTarget(ToolWindowId.PROJECT_VIEW, project);
        if (selectInTarget != null) {
          selectInTarget.selectIn(selectInContext, true /* request focus */);
        }
      }