PsiElement () { if (myTargetContainer instanceof PsiDirectory psiDirectory) { PsiPackage oldPackage = getTargetPackage(); String name = oldPackage == null ? "" : oldPackage.getQualifiedName(); final String targetName = getPackageName(); if (!Objects.equals(name, targetName)) { final ProjectRootManager projectRootManager = ProjectRootManager.getInstance(myProject); final List<VirtualFile> contentSourceRoots = JavaProjectRootsUtil.getSuitableDestinationSourceRoots(myProject); final PackageWrapper newPackage = new PackageWrapper(PsiManager.getInstance(myProject), targetName); final VirtualFile targetSourceRoot; if (contentSourceRoots.size() > 1) { PsiPackage targetPackage = JavaPsiFacade.getInstance(myProject).findPackage(targetName); PsiDirectory initialDir = null; if (targetPackage != null) { final PsiDirectory[] directories = targetPackage.getDirectories(); final VirtualFile root = projectRootManager.getFileIndex().getSourceRootForFile(psiDirectory.getVirtualFile()); for(PsiDirectory dir: directories) { if (Comparing.equal(projectRootManager.getFileIndex().getSourceRootForFile(dir.getVirtualFile()), root)) { initialDir = dir; break; } } } final VirtualFile sourceRoot = CommonMoveClassesOrPackagesUtil.chooseSourceRoot(newPackage, contentSourceRoots, initialDir); if (sourceRoot == null) return null; targetSourceRoot = sourceRoot; } else { targetSourceRoot = contentSourceRoots.get(0); } PsiDirectory dir = CommonJavaRefactoringUtil.findPackageDirectoryInSourceRoot(newPackage, targetSourceRoot); if (dir == null) { dir = ApplicationManager.getApplication().runWriteAction((NullableComputable<PsiDirectory>)() -> { try { return CommonJavaRefactoringUtil.createPackageDirectoryInSourceRoot(newPackage, targetSourceRoot); } catch (IncorrectOperationException e) { return null; } }); } return dir; } } return myTargetContainer; }