PsiPackage (final PsiElement element) { if (element == null || !element.isValid()) return null; final Project project = element.getProject(); final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex(); if (element instanceof PsiPackage aPackage) { final PsiDirectory[] directories = aPackage.getDirectories(GlobalSearchScope.projectScope(project)); for (final PsiDirectory directory : directories) { if (isSource(directory, fileIndex)) return aPackage; } return null; } else if (element instanceof PsiDirectory) { final PsiDirectory directory = (PsiDirectory)element; if (isSource(directory, fileIndex)) { return JavaDirectoryService.getInstance().getPackage(directory); } else { final VirtualFile virtualFile = directory.getVirtualFile(); //choose default package when selection on content root if (virtualFile.equals(fileIndex.getContentRootForFile(virtualFile))) { final Module module = ModuleUtilCore.findModuleForFile(virtualFile, project); if (module != null) { for (ContentEntry entry : ModuleRootManager.getInstance(module).getContentEntries()) { if (virtualFile.equals(entry.getFile())) { final SourceFolder[] folders = entry.getSourceFolders(); Set<String> packagePrefixes = new HashSet<>(); for (SourceFolder folder : folders) { packagePrefixes.add(folder.getPackagePrefix()); } if (packagePrefixes.size() > 1) return null; return JavaPsiFacade.getInstance(project).findPackage(packagePrefixes.isEmpty() ? "" : packagePrefixes.iterator().next()); } } } } return null; } } else { return null; } }