Search code examples
javaintellij-plugin

IntellijIdea plugin dev: Navigate to the source file of a given class in the text editor


suppose I have a class name like:

org.myPackage.MyClass

I want to navigate to the source file of that class in the text editor. So far, I know how to open a file in the editor:

FileEditorManager fileEditorManager = FileEditorManager.getInstance(project);
VirtualFile vf = LocalFileSystem.getInstance().findFileByPath(myPath);
fileEditorManager.openFile(vf, true, true);

I also know how to obtain the source root of a module, so what I'm doing so far is to set myPath to something like:

myPath = mainModuleSourceRoot + substituteDotsForSlash("org.myPackage.MyClass")

However I want to know if there is a more "IntellijIdea-Plugin oriented" (easier, perhaps more robust) way of opening the source file of a given class.


Solution

  • I was able to do it like this:

        GlobalSearchScope scope = GlobalSearchScope.allScope(project);
        PsiClass psiClass = JavaPsiFacade.getInstance(project).findClass("org.myPackage.MyClass", scope);
    
        if ( psiClass != null ) {
            FileEditorManager fileEditorManager = FileEditorManager.getInstance(project);
            fileEditorManager.openFile(psiClass.getContainingFile().getVirtualFile(), true, true);
        } else {
            //handle the class not found
        }
    

    Found the answer in here: https://code.google.com/p/ide-examples/wiki/IntelliJIdeaPsiCookbook#Find_a_Class


    Edited answer

    I finally did something like:

        GlobalSearchScope scope = GlobalSearchScope.allScope(project);
        PsiClass psiClass = JavaPsiFacade.getInstance(project).findClass(className, scope);
    
        if (psiClass != null) {
            FileEditorManager fileEditorManager = FileEditorManager.getInstance(project);
            //Open the file containing the class
            VirtualFile vf = psiClass.getContainingFile().getVirtualFile();
            //Jump there
            new OpenFileDescriptor(project, vf, 1, 0).navigateInEditor(project, false);
        } else {
            //Handle file not found here....
            return;
        }