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

Time:06-18

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.

CodePudding user response:

I have found the solution to this problem in Selecting a File in Project Tree.

The code section is posted below:

// file absulute path
String path="D:\Projects\Demo-Plugin\out\production\Demo-Plugin\TestAction.class"
// Files found by path, or obtain the `virtualfile` file in other ways
VirtualFile classFile = LocalFileSystem.getInstance().findFileByPath(path);
// SelectInContext 
SelectInContext context = new SelectInContext() {

    @Override
    public @NotNull
    Project getProject() {
        // Project project = event.getData(PlatformDataKeys.PROJECT);
        return project;
    }

    @Override
    public @NotNull
    VirtualFile getVirtualFile() {
        // VirtualFile
        return classFile;
    }

    @Override
    public @Nullable
    Object getSelectorInFile() {
        return null;
    }

    @Override
    public @Nullable
    FileEditorProvider getFileEditorProvider() {
        return null;
    }
};
for (SelectInTarget target : SelectInManager.getInstance(project).getTargets()) {
    if (target.canSelect(context)) {
        target.selectIn(context, true);
        return;
    }
}

CodePudding user response:

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 */);
    }
  }
  • Related