Search code examples
javaintellij-ideaintellij-plugin

Get a list of all PsiFiles/VirtualFiles in opened project in IntelliJ


I am developing a plugin in IntelliJ in which I am trying to find all the comments throughout the whole project source code.

I am currently able to get only the comments in an opened or selected file, not in all the project files. This is done by the following code:

public void actionPerformed(AnActionEvent e) {

    Editor editor = e.getData(PlatformDataKeys.EDITOR);
    PsiFile psiFile = e.getData(LangDataKeys.PSI_FILE);
    PsiElement element = psiFile.getFirstChild(); WORKS

    for(PsiElement el : element.getParent().getChildren()){
        for(PsiElement el2 : el.getChildren()){
            if(el2 instanceof PsiComment){

This obviously only gives me the PsiFile corresponding to the opened file in the editor.

I found out that I could find a list of VirtualFiles from which I would be able to extract PsiElements, however, using:

VirtualFile[] vFiles = e.getData(PlatformDataKeys.VIRTUAL_FILE_ARRAY);

also gives me only the selected files and not all the project files.

I am new to PsiElements and VirtualFiles and therefore might even be misunderstanding their usage. If however, my previously listed code is close, is there a way I could get all the PsiFiles/VirtualFiles of the project?

Thanks to Peter's comment I have tried the following block of code:

ProjectFileIndex.SERVICE.getInstance(e.getProject()).iterateContent(new        ContentIterator() {
        @Override
        public boolean processFile(VirtualFile fileInProject) {
            System.out.println(fileInProject.getFileType());
            PsiFile psiFile1 = PsiManager.getInstance(e.getProject()).findFile(fileInProject);
            if (psiFile1 == null)
                    System.out.println("IT'S NULL!");
            System.out.println(psiFile1.getText());
            return true;
        }
    });

Which as an output gives me: com.intellij.openapi.fileTypes.UnknownFileType@18cf8e97 IT'S NULL!

Meaning it's finding only one VirtualFile with unknown type.


Solution

  • You can use ProjectFileIndex.SERVICE.getInstance(project).iterateContent to iterate over all VirtualFiles. Then you can use PsiManager#findFile to get a PsiFile.