void (@NotNull Project project, @NotNull VirtualFile directory, @NotNull Collection<? super VirtualFile> outSourceRoots) { ProjectFileIndex index = ProjectFileIndex.getInstance(project); // if we already are in the sources, search just in this directory only if (!index.isInLibraryClasses(directory)) return; VirtualFile classRoot = index.getClassRootForFile(directory); if (classRoot == null) return; String relativePath = VfsUtilCore.getRelativePath(directory, classRoot); if (relativePath == null) return; Collection<VirtualFile> otherSourceRoots = new HashSet<>(); // if we are in the library sources, return (to search in this directory only) // otherwise, if we outside sources or in a jar directory, add directories from other source roots searchForOtherSourceDirs: for (OrderEntry entry : index.getOrderEntriesForFile(directory)) { if (entry instanceof LibraryOrderEntry) { Library library = ((LibraryOrderEntry)entry).getLibrary(); if (library == null) continue; // note: getUrls() returns jar directories too String[] sourceUrls = library.getUrls(OrderRootType.SOURCES); for (String sourceUrl : sourceUrls) { if (VfsUtilCore.isEqualOrAncestor(sourceUrl, directory.getUrl())) { // already in this library sources, no need to look for another source root otherSourceRoots.clear(); break searchForOtherSourceDirs; } // otherwise we may be inside the jar file in a library which is configured as a jar directory // in which case we have no way to know whether this is a source jar or classes jar - so try to locate the source jar } } for (VirtualFile sourceRoot : entry.getFiles(OrderRootType.SOURCES)) { VirtualFile sourceFile = sourceRoot.findFileByRelativePath(relativePath); if (sourceFile != null) { otherSourceRoots.add(sourceFile); } } } outSourceRoots.addAll(otherSourceRoots); }