com.intellij.psi.PsiFile

Here are the examples of the java api class com.intellij.psi.PsiFile taken from open source projects.

1. ReformatFilesWithFiltersTest#testIDEA126830()

View license
public void testIDEA126830() throws IOException {
    TestFileStructure fileTree = new TestFileStructure(getModule(), myWorkingDirectory);
    fileTree.createDirectoryAndMakeItCurrent("src");
    PsiFile java2 = fileTree.addTestFile("Test2.tj", "empty content");
    PsiFile php2 = fileTree.addTestFile("Pair2.php", "empty content");
    PsiFile js2 = fileTree.addTestFile("Pair2.js", "empty content");
    PsiDirectory test = fileTree.createDirectoryAndMakeItCurrent("test");
    PsiFile testJava1 = fileTree.addTestFile("testJava1.tj", "empty content");
    PsiFile testPhp1 = fileTree.addTestFile("testPhp1.php", "empty content");
    PsiFile testJs1 = fileTree.addTestFile("testJs1.js", "empty content");
    GlobalSearchScope testScope = directoryScope(test, true);
    reformatAndOptimize(myWorkingDirectory, testScope);
    assertWasFormatted(testJava1, testPhp1, testJs1);
    assertWasNotFormatted(java2, php2, js2);
}

2. ReformatOnlyVcsChangedTextTest#testReformatInAllSubtree()

View license
public void testReformatInAllSubtree() throws IOException {
    ChangedFilesStructure fs = new ChangedFilesStructure(myWorkingDirectory);
    PsiFile modified11 = fs.createFile("Test4.java", COMMITTED, MODIFIED);
    PsiFile modified12 = fs.createFile("Test5.java", COMMITTED, MODIFIED);
    fs.createDirectoryAndMakeItCurrent();
    PsiDirectory dirToReformat = fs.getCurrentDirectory();
    PsiFile modified21 = fs.createFile("Test6.java", COMMITTED, MODIFIED);
    PsiFile modified22 = fs.createFile("Test7.java", COMMITTED, MODIFIED);
    fs.createDirectoryAndMakeItCurrent();
    PsiFile modified31 = fs.createFile("Test8.java", COMMITTED, MODIFIED);
    PsiFile modified32 = fs.createFile("Test9.java", COMMITTED, MODIFIED);
    reformatDirectory(dirToReformat);
    assertFormattedLines(CHANGED_LINES, modified21, modified22, modified31, modified32);
    assertFormattedLines(NO_CHANGED_LINES, modified11, modified12);
}

3. ReformatFilesWithFiltersTest#testReformatWithoutMask()

View license
public void testReformatWithoutMask() throws IOException {
    TestFileStructure fileTree = new TestFileStructure(getModule(), myWorkingDirectory);
    PsiFile java1 = fileTree.addTestFile("Test.java", "empty content");
    PsiFile java2 = fileTree.addTestFile("Pair.java", "empty content");
    PsiFile java3 = fileTree.addTestFile("Pair2.java", "empty content");
    PsiFile php = fileTree.addTestFile("Test.php", "empty content");
    PsiFile js = fileTree.addTestFile("Test.js", "empty content");
    reformatDirectoryWithFileMask(myWorkingDirectory, null);
    assertWasFormatted(java1, java2, java3, php, js);
}

4. ReformatFilesWithFiltersTest#testFormatByOnlyOneMask()

View license
public void testFormatByOnlyOneMask() throws IOException {
    TestFileStructure fileTree = new TestFileStructure(getModule(), myWorkingDirectory);
    PsiFile java1 = fileTree.addTestFile("Test.java", "empty content");
    PsiFile java2 = fileTree.addTestFile("Pair.java", "empty content");
    PsiFile java3 = fileTree.addTestFile("Pair2.java", "empty content");
    PsiFile php = fileTree.addTestFile("Test.php", "empty content");
    PsiFile js = fileTree.addTestFile("Test.js", "empty content");
    reformatDirectoryWithFileMask(myWorkingDirectory, "*.java");
    assertWasFormatted(java1, java2, java3);
    assertWasNotFormatted(php, js);
    reformatDirectoryWithFileMask(myWorkingDirectory, "*.js");
    assertWasFormatted(js);
    assertWasNotFormatted(java1, java2, java3, php);
}

5. ReformatOnlyVcsChangedTextTest#testReformatOnlyChanged()

View license
public void testReformatOnlyChanged() throws IOException {
    ChangedFilesStructure fs = new ChangedFilesStructure(myWorkingDirectory);
    PsiFile untouched1 = fs.createFile("Test1.java", COMMITTED, COMMITTED);
    PsiFile untouched2 = fs.createFile("Test2.java", COMMITTED, COMMITTED);
    PsiFile modified1 = fs.createFile("Test4.java", COMMITTED, MODIFIED);
    PsiFile modified2 = fs.createFile("Test5.java", COMMITTED, MODIFIED);
    PsiFile modified3 = fs.createFile("Test6.java", COMMITTED, MODIFIED);
    reformatDirectory(fs.getCurrentDirectory());
    assertFormattedLines(CHANGED_LINES, modified1, modified2, modified3);
    assertFormattedLines(NO_CHANGED_LINES, untouched1, untouched2);
}

6. ReformatOnlyVcsChangedTextTest#testReformatFiles()

View license
public void testReformatFiles() throws IOException {
    ChangedFilesStructure fs = new ChangedFilesStructure(myWorkingDirectory);
    PsiFile m1 = fs.createFile("Test1.java", COMMITTED, MODIFIED);
    PsiFile u1 = fs.createFile("Test2.java", COMMITTED, COMMITTED);
    fs.createDirectoryAndMakeItCurrent();
    PsiFile m2 = fs.createFile("Test3.java", COMMITTED, MODIFIED);
    PsiFile u2 = fs.createFile("Test4.java", COMMITTED, COMMITTED);
    new ReformatCodeProcessor(getProject(), new PsiFile[] { m1, m2, u1, u2 }, null, true).run();
    assertFormattedLines(CHANGED_LINES, m1, m2);
    assertFormattedLines(NO_CHANGED_LINES, u1, u2);
}

7. HaskellGoToSymbolTest#testGoToSymbolFunction_QualifiedImport()

View license
public void testGoToSymbolFunction_QualifiedImport() {
    PsiFile[] psiFiles = myFixture.configureByFiles("QualifiedImport/Usage.hs", "QualifiedImport/Definition.hs");
    PsiFile usage = psiFiles[0];
    PsiFile definition = psiFiles[1];
    String textOfFile = definition.getText();
    int expectedStartOffset = textOfFile.indexOf("seven ::");
    PsiElement psiElement = usage.findElementAt(myFixture.getCaretOffset()).getParent();
    HaskellVarid varId = (HaskellVarid) psiElement;
    PsiReference reference = varId.getReference();
    HaskellVarid referencedElement = (HaskellVarid) reference.resolve();
    assertNotSame(psiElement, referencedElement);
    assertEquals(expectedStartOffset, referencedElement.getTextRange().getStartOffset());
}

8. HaskellGoToSymbolTest#testGoToSymbolFunction_QualifiedImportNoAs()

View license
public void testGoToSymbolFunction_QualifiedImportNoAs() {
    PsiFile[] psiFiles = myFixture.configureByFiles("QualifiedImportNoAs/Usage.hs", "QualifiedImportNoAs/Definition.hs");
    PsiFile usage = psiFiles[0];
    PsiFile definition = psiFiles[1];
    String textOfFile = definition.getText();
    int expectedStartOffset = textOfFile.indexOf("seven ::");
    PsiElement psiElement = usage.findElementAt(myFixture.getCaretOffset()).getParent();
    HaskellVarid varId = (HaskellVarid) psiElement;
    PsiReference reference = varId.getReference();
    HaskellVarid referencedElement = (HaskellVarid) reference.resolve();
    assertNotSame(psiElement, referencedElement);
    assertEquals(expectedStartOffset, referencedElement.getTextRange().getStartOffset());
}

9. HaskellGoToSymbolTest#testGoToSymbolFunction_QualifiedImportMultipleLevels()

View license
public void testGoToSymbolFunction_QualifiedImportMultipleLevels() {
    PsiFile[] psiFiles = myFixture.configureByFiles("QualifiedImportMultipleLevels/Usage/Usage.hs", "QualifiedImportMultipleLevels/Definition/Definition.hs");
    PsiFile usage = psiFiles[0];
    PsiFile definition = psiFiles[1];
    String textOfFile = definition.getText();
    int expectedStartOffset = textOfFile.indexOf("seven ::");
    PsiElement psiElement = usage.findElementAt(myFixture.getCaretOffset()).getParent();
    HaskellVarid varId = (HaskellVarid) psiElement;
    PsiReference reference = varId.getReference();
    HaskellVarid referencedElement = (HaskellVarid) reference.resolve();
    assertNotSame(psiElement, referencedElement);
    assertEquals(expectedStartOffset, referencedElement.getTextRange().getStartOffset());
}

10. HaskellGoToSymbolTest#testGoToSymbolFunction_QualifiedImportMultipleLevels_LocalFunctionWithSameName()

View license
public void testGoToSymbolFunction_QualifiedImportMultipleLevels_LocalFunctionWithSameName() {
    PsiFile[] psiFiles = myFixture.configureByFiles("QualifiedImportMultipleLevels_LocalFunctionWithSameName/Usage/Usage.hs", "QualifiedImportMultipleLevels_LocalFunctionWithSameName/Definition/Definition.hs");
    PsiFile usage = psiFiles[0];
    PsiFile definition = psiFiles[1];
    String textOfFile = definition.getText();
    int expectedStartOffset = textOfFile.indexOf("seven ::");
    PsiElement psiElement = usage.findElementAt(myFixture.getCaretOffset()).getParent();
    HaskellVarid varId = (HaskellVarid) psiElement;
    PsiReference reference = varId.getReference();
    HaskellVarid referencedElement = (HaskellVarid) reference.resolve();
    assertNotSame(psiElement, referencedElement);
    assertEquals(expectedStartOffset, referencedElement.getTextRange().getStartOffset());
}

11. HaskellGoToSymbolTest#testGoToSymbolFunction_QualifiedImportMultipleLevels_AsPartConsistsOfMultipleCons()

View license
public void testGoToSymbolFunction_QualifiedImportMultipleLevels_AsPartConsistsOfMultipleCons() {
    PsiFile[] psiFiles = myFixture.configureByFiles("QualifiedImportMultipleLevels_AsPartConsistsOfMultipleCons/Usage/Usage.hs", "QualifiedImportMultipleLevels_AsPartConsistsOfMultipleCons/Definition/Definition.hs");
    PsiFile usage = psiFiles[0];
    PsiFile definition = psiFiles[1];
    String textOfFile = definition.getText();
    int expectedStartOffset = textOfFile.indexOf("seven ::");
    PsiElement psiElement = usage.findElementAt(myFixture.getCaretOffset()).getParent();
    HaskellVarid varId = (HaskellVarid) psiElement;
    PsiReference reference = varId.getReference();
    HaskellVarid referencedElement = (HaskellVarid) reference.resolve();
    assertNotSame(psiElement, referencedElement);
    assertEquals(expectedStartOffset, referencedElement.getTextRange().getStartOffset());
}

12. HaskellGoToSymbolTest#testGoToSymbolFunction_ImportResolvesToModule()

View license
public void testGoToSymbolFunction_ImportResolvesToModule() {
    PsiFile[] psiFiles = myFixture.configureByFiles("ImportResolvesToModule/Usage.hs", "ImportResolvesToModule/Definition.hs");
    PsiFile usage = psiFiles[0];
    PsiFile definition = psiFiles[1];
    String textOfFile = definition.getText();
    int expectedStartOffset = textOfFile.indexOf("module Definition") + 7;
    PsiElement psiElement = usage.findElementAt(myFixture.getCaretOffset()).getParent();
    HaskellConid conId = (HaskellConid) psiElement;
    PsiReference reference = conId.getReference();
    HaskellConid referencedElement = (HaskellConid) reference.resolve();
    assertNotSame(psiElement, referencedElement);
    assertEquals(expectedStartOffset, referencedElement.getTextRange().getStartOffset());
}

13. HaskellGoToSymbolTest#testGoToSymbolFunction_ImportResolvesToModule_MultipleCons_OnModule()

View license
public void testGoToSymbolFunction_ImportResolvesToModule_MultipleCons_OnModule() {
    PsiFile[] psiFiles = myFixture.configureByFiles("ImportResolvesToModule_MultipleCons_OnModule/Usage.hs", "ImportResolvesToModule_MultipleCons_OnModule/Definition.hs");
    PsiFile usage = psiFiles[0];
    PsiFile definition = psiFiles[1];
    String textOfFile = definition.getText();
    int expectedStartOffset = textOfFile.indexOf("module Definition.Definition") + 18;
    PsiElement psiElement = usage.findElementAt(myFixture.getCaretOffset()).getParent();
    HaskellConid conId = (HaskellConid) psiElement;
    PsiReference reference = conId.getReference();
    HaskellConid referencedElement = (HaskellConid) reference.resolve();
    assertNotSame(psiElement, referencedElement);
    assertEquals(expectedStartOffset, referencedElement.getTextRange().getStartOffset());
}

14. HaskellGoToSymbolTest#testGoToSymbolFunction_ImportResolvesToModule_MultipleCons_OnPrefix()

View license
public void testGoToSymbolFunction_ImportResolvesToModule_MultipleCons_OnPrefix() {
    PsiFile[] psiFiles = myFixture.configureByFiles("ImportResolvesToModule_MultipleCons_OnPrefix/Usage.hs", "ImportResolvesToModule_MultipleCons_OnPrefix/Definition.hs");
    PsiFile usage = psiFiles[0];
    PsiFile definition = psiFiles[1];
    String textOfFile = definition.getText();
    int expectedStartOffset = textOfFile.indexOf("module Definition.Definition") + 7;
    PsiElement psiElement = usage.findElementAt(myFixture.getCaretOffset()).getParent();
    HaskellConid conId = (HaskellConid) psiElement;
    PsiReference reference = conId.getReference();
    HaskellConid referencedElement = (HaskellConid) reference.resolve();
    assertNotSame(psiElement, referencedElement);
    assertEquals(expectedStartOffset, referencedElement.getTextRange().getStartOffset());
}

15. AnnotationHolderImpl#assertMyFile()

Project: consulo
Source File: AnnotationHolderImpl.java
View license
private void assertMyFile(PsiElement node) {
    if (node == null)
        return;
    PsiFile myFile = myAnnotationSession.getFile();
    PsiFile containingFile = node.getContainingFile();
    LOG.assertTrue(containingFile != null, node);
    VirtualFile containingVFile = containingFile.getVirtualFile();
    VirtualFile myVFile = myFile.getVirtualFile();
    if (!Comparing.equal(containingVFile, myVFile)) {
        LOG.error("Annotation must be registered for an element inside '" + myFile + "' which is in '" + myVFile + "'.\n" + "Element passed: '" + node + "' is inside the '" + containingFile + "' which is in '" + containingVFile + "'");
    }
}

16. LanguageVersionUtil#findLanguageVersion()

Project: consulo
Source File: LanguageVersionUtil.java
View license
public static LanguageVersion<?> findLanguageVersion(@NotNull Language language, @NotNull PsiFile psiFile) {
    if (psiFile.getLanguage() == language) {
        return psiFile.getLanguageVersion();
    }
    FileViewProvider viewProvider = psiFile.getViewProvider();
    PsiFile psi = viewProvider.getPsi(language);
    if (psi == null) {
        return LanguageVersionResolvers.INSTANCE.forLanguage(language).getLanguageVersion(language, psiFile);
    }
    return psi.getLanguageVersion();
}

17. PrintManager#addToPsiFileList()

Project: consulo
Source File: PrintManager.java
View license
private static void addToPsiFileList(PsiDirectory psiDirectory, List<Pair<PsiFile, Editor>> filesList, boolean isRecursive) {
    PsiFile[] files = psiDirectory.getFiles();
    for (PsiFile file : files) {
        filesList.add(Pair.create(file, PsiUtilBase.findEditor(file)));
    }
    if (isRecursive) {
        for (PsiDirectory directory : psiDirectory.getSubdirectories()) {
            if (!Project.DIRECTORY_STORE_FOLDER.equals(directory.getName())) {
                addToPsiFileList(directory, filesList, isRecursive);
            }
        }
    }
}

18. ShowIntentionActionsHandler#chooseBetweenHostAndInjected()

View license
@Nullable
public static Pair<PsiFile, Editor> chooseBetweenHostAndInjected(@NotNull PsiFile hostFile, @NotNull Editor hostEditor, @NotNull PairProcessor<PsiFile, Editor> predicate) {
    Editor editorToApply = null;
    PsiFile fileToApply = null;
    int offset = hostEditor.getCaretModel().getOffset();
    PsiFile injectedFile = InjectedLanguageUtil.findInjectedPsiNoCommit(hostFile, offset);
    if (injectedFile != null) {
        Editor injectedEditor = InjectedLanguageUtil.getInjectedEditorForInjectedFile(hostEditor, injectedFile);
        if (predicate.process(injectedFile, injectedEditor)) {
            editorToApply = injectedEditor;
            fileToApply = injectedFile;
        }
    }
    if (editorToApply == null && predicate.process(hostFile, hostEditor)) {
        editorToApply = hostEditor;
        fileToApply = hostFile;
    }
    if (editorToApply == null)
        return null;
    return Pair.create(fileToApply, editorToApply);
}

19. LookupImpl#getPsiElement()

Project: consulo
Source File: LookupImpl.java
View license
@Override
public PsiElement getPsiElement() {
    PsiFile file = getPsiFile();
    if (file == null)
        return null;
    int offset = getLookupStart();
    Editor editor = getEditor();
    if (editor instanceof EditorWindow) {
        offset = editor.logicalPositionToOffset(((EditorWindow) editor).hostToInjected(myEditor.offsetToLogicalPosition(offset)));
    }
    if (offset > 0)
        return file.findElementAt(offset - 1);
    return file.findElementAt(0);
}

20. BackwardDependenciesBuilder#subtractScope()

View license
private static void subtractScope(final DependenciesBuilder builders, final AnalysisScope scope) {
    final Map<PsiFile, Set<PsiFile>> dependencies = builders.getDependencies();
    Set<PsiFile> excluded = new HashSet<PsiFile>();
    for (final PsiFile psiFile : dependencies.keySet()) {
        if (scope.contains(psiFile)) {
            excluded.add(psiFile);
        }
    }
    for (final PsiFile psiFile : excluded) {
        dependencies.remove(psiFile);
    }
}

21. TextFieldCompletionProvider#createDocument()

View license
private Document createDocument(final Project project, @NotNull String text) {
    final FileType fileType = PlainTextLanguage.INSTANCE.getAssociatedFileType();
    assert fileType != null;
    final long stamp = LocalTimeCounter.currentTime();
    final PsiFile psiFile = PsiFileFactory.getInstance(project).createFileFromText("Dummy." + fileType.getDefaultExtension(), fileType, text, stamp, true, false);
    psiFile.putUserData(COMPLETING_TEXT_FIELD_KEY, this);
    final Document document = PsiDocumentManager.getInstance(project).getDocument(psiFile);
    assert document != null;
    return document;
}

22. AbstractFileProcessor#findFiles()

Project: consulo
Source File: AbstractFileProcessor.java
View license
private static void findFiles(List<PsiFile> files, PsiDirectory directory, boolean subdirs) {
    final Project project = directory.getProject();
    PsiFile[] locals = directory.getFiles();
    for (PsiFile local : locals) {
        CopyrightProfile opts = CopyrightManager.getInstance(project).getCopyrightOptions(local);
        if (opts != null && CopyrightUpdaters.hasExtension(local)) {
            files.add(local);
        }
    }
    if (subdirs) {
        PsiDirectory[] dirs = directory.getSubdirectories();
        for (PsiDirectory dir : dirs) {
            findFiles(files, dir, subdirs);
        }
    }
}

23. BackgroundTaskPsiFileTreeNode#getChildrenImpl()

View license
@Override
public Collection<AbstractTreeNode> getChildrenImpl() {
    VirtualFile ourVirtualFile = getVirtualFile();
    if (ourVirtualFile == null) {
        return super.getChildrenImpl();
    }
    BackgroundTaskByVfsChangeManager vfsChangeManager = BackgroundTaskByVfsChangeManager.getInstance(getProject());
    List<BackgroundTaskByVfsChangeTask> tasks = vfsChangeManager.findTasks(ourVirtualFile);
    if (tasks.isEmpty()) {
        return super.getChildrenImpl();
    }
    List<VirtualFile> generatedFiles = new ArrayList<VirtualFile>();
    for (BackgroundTaskByVfsChangeTask task : tasks) {
        Collections.addAll(generatedFiles, task.getGeneratedFiles());
    }
    if (generatedFiles.isEmpty()) {
        return super.getChildrenImpl();
    }
    PsiFile[] psiFiles = PsiUtilBase.virtualToPsiFiles(generatedFiles, myProject);
    List<AbstractTreeNode> newChildren = new ArrayList<AbstractTreeNode>(psiFiles.length);
    for (PsiFile psiFile : psiFiles) {
        newChildren.add(new PsiFileNode(getProject(), psiFile, getSettings()));
    }
    return newChildren;
}

24. IgnoreTemplatesFactory#createFromTemplate()

View license
/**
     * Creates new Gitignore file or uses an existing one.
     *
     * @param directory working directory
     * @return file
     * @throws IncorrectOperationException
     */
@Nullable
public PsiFile createFromTemplate(final PsiDirectory directory) throws IncorrectOperationException {
    final String filename = fileType.getIgnoreLanguage().getFilename();
    final PsiFile currentFile = directory.findFile(filename);
    if (currentFile != null) {
        return currentFile;
    }
    final PsiFileFactory factory = PsiFileFactory.getInstance(directory.getProject());
    final IgnoreLanguage language = fileType.getIgnoreLanguage();
    String content = StringUtil.join(TEMPLATE_NOTE, Constants.NEWLINE);
    if (language.isSyntaxSupported() && !IgnoreBundle.Syntax.GLOB.equals(language.getDefaultSyntax())) {
        content = StringUtil.join(content, IgnoreBundle.Syntax.GLOB.getPresentation(), Constants.NEWLINE, Constants.NEWLINE);
    }
    final PsiFile file = factory.createFileFromText(filename, fileType, content);
    return (PsiFile) directory.add(file);
}

25. PhpRouteInspection#buildVisitor()

View license
@NotNull
@Override
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
    PsiFile psiFile = holder.getFile();
    if (!Symfony2ProjectComponent.isEnabled(psiFile.getProject()) || !Settings.getInstance(psiFile.getProject()).phpAnnotateRoute) {
        return super.buildVisitor(holder, isOnTheFly);
    }
    psiFile.acceptChildren(new PsiRecursiveElementWalkingVisitor() {

        @Override
        public void visitElement(PsiElement element) {
            if (element instanceof StringLiteralExpression) {
                annotate((StringLiteralExpression) element, holder);
            }
            super.visitElement(element);
        }
    });
    return super.buildVisitor(holder, isOnTheFly);
}

26. YamlPsiElementFactory#createYamlPsiFromText()

View license
@NotNull
public static PsiElement createYamlPsiFromText(Project p, final IElementType type, @NotNull String text) {
    final Ref<PsiElement> ret = new Ref<PsiElement>();
    PsiFile dummyFile = createDummyFile(p, text);
    dummyFile.accept(new PsiRecursiveElementWalkingVisitor() {

        @Override
        public void visitElement(PsiElement element) {
            if (element.getNode() == type) {
                ret.set(element);
            }
            super.visitElement(element);
        }
    });
    assert !ret.isNull() : "cannot create element from text:\n" + dummyFile.getText();
    return ret.get();
}

27. AnnotationHolderImpl#assertMyFile()

View license
private void assertMyFile(PsiElement node) {
    if (node == null)
        return;
    PsiFile myFile = myAnnotationSession.getFile();
    PsiFile containingFile = node.getContainingFile();
    LOG.assertTrue(containingFile != null, node);
    VirtualFile containingVFile = containingFile.getVirtualFile();
    VirtualFile myVFile = myFile.getVirtualFile();
    if (!Comparing.equal(containingVFile, myVFile)) {
        LOG.error("Annotation must be registered for an element inside '" + myFile + "' which is in '" + myVFile + "'.\n" + "Element passed: '" + node + "' is inside the '" + containingFile + "' which is in '" + containingVFile + "'");
    }
}

28. BackwardDependenciesBuilder#subtractScope()

View license
private static void subtractScope(final DependenciesBuilder builders, final AnalysisScope scope) {
    final Map<PsiFile, Set<PsiFile>> dependencies = builders.getDependencies();
    Set<PsiFile> excluded = new HashSet<PsiFile>();
    for (final PsiFile psiFile : dependencies.keySet()) {
        if (scope.contains(psiFile)) {
            excluded.add(psiFile);
        }
    }
    for (final PsiFile psiFile : excluded) {
        dependencies.remove(psiFile);
    }
}

29. PrintManager#addToPsiFileList()

View license
private static void addToPsiFileList(PsiDirectory psiDirectory, List<Pair<PsiFile, Editor>> filesList, boolean isRecursive) {
    PsiFile[] files = psiDirectory.getFiles();
    for (PsiFile file : files) {
        filesList.add(Pair.create(file, PsiUtilBase.findEditor(file)));
    }
    if (isRecursive) {
        for (PsiDirectory directory : psiDirectory.getSubdirectories()) {
            if (!Project.DIRECTORY_STORE_FOLDER.equals(directory.getName())) {
                addToPsiFileList(directory, filesList, true);
            }
        }
    }
}

30. ShowIntentionActionsHandler#chooseBetweenHostAndInjected()

View license
@Nullable
public static Pair<PsiFile, Editor> chooseBetweenHostAndInjected(@NotNull PsiFile hostFile, @NotNull Editor hostEditor, @NotNull PairProcessor<PsiFile, Editor> predicate) {
    Editor editorToApply = null;
    PsiFile fileToApply = null;
    int offset = hostEditor.getCaretModel().getOffset();
    PsiFile injectedFile = InjectedLanguageUtil.findInjectedPsiNoCommit(hostFile, offset);
    if (injectedFile != null) {
        Editor injectedEditor = InjectedLanguageUtil.getInjectedEditorForInjectedFile(hostEditor, injectedFile);
        if (predicate.process(injectedFile, injectedEditor)) {
            editorToApply = injectedEditor;
            fileToApply = injectedFile;
        }
    }
    if (editorToApply == null && predicate.process(hostFile, hostEditor)) {
        editorToApply = hostEditor;
        fileToApply = hostFile;
    }
    if (editorToApply == null)
        return null;
    return Pair.create(fileToApply, editorToApply);
}

31. LookupImpl#getPsiElement()

Project: intellij-community
Source File: LookupImpl.java
View license
@Override
public PsiElement getPsiElement() {
    PsiFile file = getPsiFile();
    if (file == null)
        return null;
    int offset = getLookupStart();
    Editor editor = getEditor();
    if (editor instanceof EditorWindow) {
        offset = editor.logicalPositionToOffset(((EditorWindow) editor).hostToInjected(myEditor.offsetToLogicalPosition(offset)));
    }
    if (offset > 0)
        return file.findElementAt(offset - 1);
    return file.findElementAt(0);
}

32. FileTypesTest#testAutoDetectEmptyFile()

View license
public void testAutoDetectEmptyFile() throws IOException {
    File dir = createTempDirectory();
    File file = FileUtil.createTempFile(dir, "x", "xxx_xx_xx", true);
    VirtualFile virtualFile = getVirtualFile(file);
    assertNotNull(virtualFile);
    assertEquals(FileTypes.UNKNOWN, virtualFile.getFileType());
    PsiFile psi = getPsiManager().findFile(virtualFile);
    assertTrue(psi instanceof PsiBinaryFile);
    assertEquals(FileTypes.UNKNOWN, virtualFile.getFileType());
    setBinaryContent(virtualFile, "xxxxxxx".getBytes(CharsetToolkit.UTF8_CHARSET));
    assertEquals(FileTypes.PLAIN_TEXT, virtualFile.getFileType());
    PsiFile after = getPsiManager().findFile(virtualFile);
    assertNotSame(psi, after);
    assertFalse(psi.isValid());
    assertTrue(after.isValid());
    assertTrue(after instanceof PsiPlainTextFile);
}

33. AntResolveTest#testAntFilePropertyWithContexts()

View license
public void testAntFilePropertyWithContexts() throws Exception {
    final PsiReference refImporting = configureByFile("PropertyAntFileImporting.ant");
    final PsiFile importing = refImporting.getElement().getContainingFile();
    assertTrue(importing instanceof XmlFile);
    final VirtualFile vFile = importing.getVirtualFile();
    assertTrue(vFile != null);
    final PsiReference refImported = configureByFile("PropertyAntFileImported.ant", vFile.getParent());
    final PsiFile imported = refImported.getElement().getContainingFile();
    assertTrue(imported instanceof XmlFile);
    final VirtualFile importedVFile = imported.getVirtualFile();
    assertTrue(importedVFile != null);
    AntConfigurationBase.getInstance(getProject()).setContextFile((XmlFile) imported, (XmlFile) importing);
    assertTrue(refImported.resolve() != null);
    assertTrue(refImporting.resolve() != null);
}

34. AbstractFileProcessor#findFiles()

View license
private static void findFiles(List<PsiFile> files, PsiDirectory directory, boolean subdirs) {
    final Project project = directory.getProject();
    PsiFile[] locals = directory.getFiles();
    for (PsiFile local : locals) {
        CopyrightProfile opts = CopyrightManager.getInstance(project).getCopyrightOptions(local);
        if (opts != null && FileTypeUtil.isSupportedFile(local)) {
            files.add(local);
        }
    }
    if (subdirs) {
        PsiDirectory[] dirs = directory.getSubdirectories();
        for (PsiDirectory dir : dirs) {
            findFiles(files, dir, subdirs);
        }
    }
}

35. GroovyUnresolvedReferenceFilterByFile#isReject()

View license
@Override
public boolean isReject(@NotNull GrReferenceExpression expression) {
    PsiFile file = expression.getContainingFile();
    Boolean cachedValue = file.getUserData(KEY);
    if (cachedValue != null)
        return cachedValue;
    boolean res = false;
    for (GroovyUnresolvedHighlightFileFilter filter : GroovyUnresolvedHighlightFileFilter.EP_NAME.getExtensions()) {
        if (filter.isReject(file)) {
            res = true;
            break;
        }
    }
    file.putUserData(KEY, res);
    return res;
}

36. CustomResourceBundleTest#testPropertiesFilesDefaultCombiningToResourceBundle()

View license
public void testPropertiesFilesDefaultCombiningToResourceBundle() {
    final PsiFile file = myFixture.addFileToProject("prop_core_en.properties", "");
    final PsiFile file2 = myFixture.addFileToProject("prop_core_fi.properties", "");
    final PropertiesFile propertiesFile = PropertiesImplUtil.getPropertiesFile(file);
    final PropertiesFile propertiesFile2 = PropertiesImplUtil.getPropertiesFile(file2);
    assertNotNull(propertiesFile);
    assertNotNull(propertiesFile2);
    final ResourceBundle bundle = propertiesFile.getResourceBundle();
    final ResourceBundle bundle2 = propertiesFile2.getResourceBundle();
    assertTrue(bundle.equals(bundle2));
    assertSize(2, bundle.getPropertiesFiles());
    assertTrue(bundle.getDefaultPropertiesFile().equals(bundle2.getDefaultPropertiesFile()));
    assertEquals("prop_core", bundle.getBaseName());
    assertNotSame(propertiesFile.getLocale().getLanguage(), propertiesFile.getLocale().getDisplayLanguage());
    assertNotSame(propertiesFile2.getLocale().getLanguage(), propertiesFile2.getLocale().getDisplayLanguage());
}

37. CustomResourceBundleTest#testPropertiesFileNotAssociatedWhileLanguageCodeNotRecognized()

View license
public void testPropertiesFileNotAssociatedWhileLanguageCodeNotRecognized() {
    final PsiFile file = myFixture.addFileToProject("some_property_file.properties", "");
    final PsiFile file2 = myFixture.addFileToProject("some_property_fil.properties", "");
    final PropertiesFile propertiesFile = PropertiesImplUtil.getPropertiesFile(file);
    assertNotNull(propertiesFile);
    final ResourceBundle resourceBundle = propertiesFile.getResourceBundle();
    assertSize(1, resourceBundle.getPropertiesFiles());
    final PropertiesFile propertiesFile2 = PropertiesImplUtil.getPropertiesFile(file2);
    assertNotNull(propertiesFile2);
    final ResourceBundle resourceBundle2 = propertiesFile.getResourceBundle();
    assertSize(1, resourceBundle2.getPropertiesFiles());
    assertEquals(PropertiesUtil.DEFAULT_LOCALE, propertiesFile.getLocale());
}

38. CustomResourceBundleTest#testLanguageCodeNotRecognized()

View license
public void testLanguageCodeNotRecognized() {
    final PsiFile file = myFixture.addFileToProject("p.properties", "");
    final PsiFile file2 = myFixture.addFileToProject("p_asd.properties", "");
    final PropertiesFile propertiesFile = PropertiesImplUtil.getPropertiesFile(file);
    final PropertiesFile propertiesFile2 = PropertiesImplUtil.getPropertiesFile(file2);
    assertNotNull(propertiesFile);
    assertNotNull(propertiesFile2);
    final ResourceBundle bundle = propertiesFile.getResourceBundle();
    final ResourceBundle bundle2 = propertiesFile2.getResourceBundle();
    assertSize(1, bundle.getPropertiesFiles());
    assertSize(1, bundle2.getPropertiesFiles());
    assertEquals("p", bundle.getBaseName());
    assertEquals("p_asd", bundle2.getBaseName());
    final ResourceBundleManager manager = ResourceBundleManager.getInstance(getProject());
    final ArrayList<PropertiesFile> rawBundle = ContainerUtil.newArrayList(propertiesFile, propertiesFile2);
    final String suggestedBaseName = PropertiesUtil.getDefaultBaseName(rawBundle);
    assertEquals("p", suggestedBaseName);
    manager.combineToResourceBundle(rawBundle, suggestedBaseName);
    assertEquals("asd", propertiesFile2.getLocale().getLanguage());
}

39. ResourceBundleEditorInsertManagerTest#doTest()

View license
private void doTest(final TestAction testAction) {
    final PsiFile baseFile = myFixture.configureByFile(getTestName(true) + "/p.properties");
    final PsiFile translationFile = myFixture.configureByFile(getTestName(true) + "/p_en.properties");
    final PropertiesFile basePropertiesFile = PropertiesImplUtil.getPropertiesFile(baseFile);
    assertNotNull(basePropertiesFile);
    final ResourceBundle bundle = basePropertiesFile.getResourceBundle();
    final ResourceBundlePropertiesUpdateManager manager = new ResourceBundlePropertiesUpdateManager(bundle);
    assertInstanceOf(manager, ResourceBundlePropertiesUpdateManager.class);
    WriteCommandAction.runWriteCommandAction(getProject(), () -> testAction.doTestAction(basePropertiesFile, PropertiesImplUtil.getPropertiesFile(translationFile), manager));
    myFixture.checkResultByFile(getTestName(true) + "/p.properties", getTestName(true) + "/p-after.properties", true);
    myFixture.checkResultByFile(getTestName(true) + "/p_en.properties", getTestName(true) + "/p-after_en.properties", true);
}

40. ResourceBundleTest#doTestRenameResourceBundleEntryFile()

View license
private void doTestRenameResourceBundleEntryFile(String fileNameToRenameBefore, String fileNameToCheckBefore, String fileNameToRenameAfter, String fileNameToCheckAfter) {
    final PsiFile toRenameFile = myFixture.addFileToProject(fileNameToRenameBefore, "");
    final PsiFile toCheck = myFixture.addFileToProject(fileNameToCheckBefore, "");
    final RenameProcessor processor = new RenameProcessor(getProject(), toRenameFile, fileNameToRenameAfter, true, true);
    for (AutomaticRenamerFactory factory : Extensions.getExtensions(AutomaticRenamerFactory.EP_NAME)) {
        if (factory instanceof ResourceBundleRenamerFactory) {
            processor.addRenamerFactory(factory);
        }
    }
    processor.run();
    assertEquals(fileNameToCheckAfter, toCheck.getName());
}

41. Form2SourceCompiler#findSourceFile()

View license
private static VirtualFile findSourceFile(final CompileContext context, final VirtualFile formFile, final String className) {
    final Module module = context.getModuleByFile(formFile);
    if (module == null) {
        return null;
    }
    final PsiClass aClass = FormEditingUtil.findClassToBind(module, className);
    if (aClass == null) {
        return null;
    }
    final PsiFile containingFile = aClass.getContainingFile();
    if (containingFile == null) {
        return null;
    }
    return containingFile.getVirtualFile();
}

42. Form#containsFile()

Project: intellij-community
Source File: Form.java
View license
public boolean containsFile(final VirtualFile vFile) {
    final PsiFile classFile = myClassToBind.getContainingFile();
    final VirtualFile classVFile = classFile == null ? null : classFile.getVirtualFile();
    if (classVFile != null && classVFile.equals(vFile)) {
        return true;
    }
    for (PsiFile psiFile : myFormFiles) {
        final VirtualFile virtualFile = psiFile.getVirtualFile();
        if (virtualFile != null && virtualFile.equals(vFile)) {
            return true;
        }
    }
    return false;
}

43. XsltIncludeIndex#_process()

View license
private static boolean _process(VirtualFile[] files, Project project, Processor<XmlFile> processor) {
    final PsiManager psiManager = PsiManager.getInstance(project);
    final PsiFile[] psiFiles = ContainerUtil.map2Array(files, PsiFile.class, (NullableFunction<VirtualFile, PsiFile>)  file -> psiManager.findFile(file));
    for (final PsiFile psiFile : psiFiles) {
        if (XsltSupport.isXsltFile(psiFile)) {
            if (!processor.process((XmlFile) psiFile)) {
                return false;
            }
        }
    }
    return true;
}

44. PyStudyImportResolver#resolveImportReference()

View license
@Nullable
public PsiElement resolveImportReference(QualifiedName name, QualifiedNameResolveContext context, boolean withRoots) {
    if (StudyTaskManager.getInstance(context.getProject()).getCourse() == null) {
        return null;
    }
    final String nameString = name.toString();
    PsiFile containingFile = context.getFootholdFile();
    if (containingFile == null)
        return null;
    final PsiDirectory directory = containingFile.getContainingDirectory();
    if (directory == null)
        return null;
    final PsiFile file = directory.findFile(nameString + ".py");
    if (file != null) {
        return file;
    }
    return null;
}

45. PyToxTestLocator#getLocation()

View license
@NotNull
@Override
public List<Location> getLocation(@NotNull final String protocol, @NotNull final String path, @NotNull final Project project, @NotNull final GlobalSearchScope scope) {
    final PsiFile file = PyElementGenerator.getInstance(project).createDummyFile(LanguageLevel.PYTHON24, DUMMY_FILE_PADDING);
    file.putUserData(ENV_NAME_KEY, path);
    @SuppressWarnings("unchecked") final List<Location> locations = Collections.<Location>singletonList(new PsiLocation(file));
    return locations;
}

46. RelaxIncludeIndex#processRelatedFiles()

View license
private static boolean processRelatedFiles(PsiFile file, VirtualFile[] files, PsiElementProcessor<XmlFile> processor) {
    Project project = file.getProject();
    final PsiManager psiManager = PsiManager.getInstance(project);
    final PsiFile[] psiFiles = ContainerUtil.map2Array(files, PsiFile.class, (NullableFunction<VirtualFile, PsiFile>)  file1 -> psiManager.findFile(file1));
    for (final PsiFile psiFile : psiFiles) {
        if (!processFile(psiFile, processor)) {
            return false;
        }
    }
    return true;
}

47. HaskellGoToSymbolTest#testGoToSymbolFunction_QualifiedImportMultipleLevels_LocalFunctionWithSameName_CaretOnLocal()

View license
public void testGoToSymbolFunction_QualifiedImportMultipleLevels_LocalFunctionWithSameName_CaretOnLocal() {
    PsiFile[] psiFiles = myFixture.configureByFiles("QualifiedImportMultipleLevels_LocalFunctionWithSameName_CaretOnLocal/Usage/Usage.hs", "QualifiedImportMultipleLevels_LocalFunctionWithSameName_CaretOnLocal/Definition/Definition.hs");
    PsiFile usage = psiFiles[0];
    String textOfFile = usage.getText();
    int expectedStartOffset = textOfFile.indexOf("seven ::");
    PsiElement psiElement = usage.findElementAt(myFixture.getCaretOffset()).getParent();
    HaskellVarid varId = (HaskellVarid) psiElement;
    PsiReference reference = varId.getReference();
    HaskellVarid referencedElement = (HaskellVarid) reference.resolve();
    assertNotSame(psiElement, referencedElement);
    assertEquals(expectedStartOffset, referencedElement.getTextRange().getStartOffset());
}

48. HaskellGoToSymbolTest#testGoToSymbolFunction_QualifiedImportQualifierresolves()

View license
public void testGoToSymbolFunction_QualifiedImportQualifierresolves() {
    PsiFile[] psiFiles = myFixture.configureByFiles("QualifiedImport_QualifierResolves/Usage.hs", "QualifiedImport_QualifierResolves/Definition.hs");
    PsiFile usage = psiFiles[0];
    String textOfFile = usage.getText();
    int expectedStartOffset = textOfFile.indexOf("as Def") + 3;
    PsiElement psiElement = usage.findElementAt(myFixture.getCaretOffset()).getParent();
    HaskellConid conId = (HaskellConid) psiElement;
    PsiReference reference = conId.getReference();
    HaskellConid referencedElement = (HaskellConid) reference.resolve();
    assertNotSame(psiElement, referencedElement);
    assertEquals(expectedStartOffset, referencedElement.getTextRange().getStartOffset());
}

49. HaskellGoToSymbolTest#testGoToSymbolFunction_QualifiedImportQualifierresolvesMultipleCons_Cons1()

View license
public void testGoToSymbolFunction_QualifiedImportQualifierresolvesMultipleCons_Cons1() {
    PsiFile[] psiFiles = myFixture.configureByFiles("QualifiedImport_QualifierResolvesMultipleCons_Cons1/Usage.hs", "QualifiedImport_QualifierResolvesMultipleCons_Cons1/Definition.hs");
    PsiFile usage = psiFiles[0];
    String textOfFile = usage.getText();
    int expectedStartOffset = textOfFile.indexOf("as Def.Lef") + 3;
    PsiElement psiElement = usage.findElementAt(myFixture.getCaretOffset()).getParent();
    HaskellConid conId = (HaskellConid) psiElement;
    PsiReference reference = conId.getReference();
    HaskellConid referencedElement = (HaskellConid) reference.resolve();
    assertNotSame(psiElement, referencedElement);
    assertEquals(expectedStartOffset, referencedElement.getTextRange().getStartOffset());
}

50. HaskellGoToSymbolTest#testGoToSymbolFunction_QualifiedImportQualifierresolvesMultipleCons_Cons2()

View license
public void testGoToSymbolFunction_QualifiedImportQualifierresolvesMultipleCons_Cons2() {
    PsiFile[] psiFiles = myFixture.configureByFiles("QualifiedImport_QualifierResolvesMultipleCons_Cons2/Usage.hs", "QualifiedImport_QualifierResolvesMultipleCons_Cons2/Definition.hs");
    PsiFile usage = psiFiles[0];
    String textOfFile = usage.getText();
    int expectedStartOffset = textOfFile.indexOf("as Def.Lef") + 7;
    PsiElement psiElement = usage.findElementAt(myFixture.getCaretOffset()).getParent();
    HaskellConid conId = (HaskellConid) psiElement;
    PsiReference reference = conId.getReference();
    HaskellConid referencedElement = (HaskellConid) reference.resolve();
    assertNotSame(psiElement, referencedElement);
    assertEquals(expectedStartOffset, referencedElement.getTextRange().getStartOffset());
}

51. HaskellGoToSymbolTest#testGoToSymbolFunction_QualifiedImportQualifierresolvesMultipleCons_Cons1_NoAs()

View license
public void testGoToSymbolFunction_QualifiedImportQualifierresolvesMultipleCons_Cons1_NoAs() {
    PsiFile[] psiFiles = myFixture.configureByFiles("QualifiedImport_QualifierResolvesMultipleCons_Cons1_NoAs/Usage.hs", "QualifiedImport_QualifierResolvesMultipleCons_Cons1_NoAs/Definition.hs");
    PsiFile usage = psiFiles[0];
    String textOfFile = usage.getText();
    int expectedStartOffset = textOfFile.indexOf("qualified Definition.Definition") + 10;
    PsiElement psiElement = usage.findElementAt(myFixture.getCaretOffset()).getParent();
    HaskellConid conId = (HaskellConid) psiElement;
    PsiReference reference = conId.getReference();
    HaskellConid referencedElement = (HaskellConid) reference.resolve();
    assertNotSame(psiElement, referencedElement);
    assertEquals(expectedStartOffset, referencedElement.getTextRange().getStartOffset());
}

52. HaskellGoToSymbolTest#testGoToSymbolFunction_QualifiedImportQualifierresolvesMultipleCons_Cons2_NoAs()

View license
public void testGoToSymbolFunction_QualifiedImportQualifierresolvesMultipleCons_Cons2_NoAs() {
    PsiFile[] psiFiles = myFixture.configureByFiles("QualifiedImport_QualifierResolvesMultipleCons_Cons2_NoAs/Usage.hs", "QualifiedImport_QualifierResolvesMultipleCons_Cons2_NoAs/Definition.hs");
    PsiFile usage = psiFiles[0];
    String textOfFile = usage.getText();
    int expectedStartOffset = textOfFile.indexOf("qualified Definition.Definition") + 21;
    PsiElement psiElement = usage.findElementAt(myFixture.getCaretOffset()).getParent();
    HaskellConid conId = (HaskellConid) psiElement;
    PsiReference reference = conId.getReference();
    HaskellConid referencedElement = (HaskellConid) reference.resolve();
    assertNotSame(psiElement, referencedElement);
    assertEquals(expectedStartOffset, referencedElement.getTextRange().getStartOffset());
}

53. HaskellGoToSymbolTest#testGoToSymbolFunction_QualifiedImport_MultipleImportSameQualifiedName1()

View license
public void testGoToSymbolFunction_QualifiedImport_MultipleImportSameQualifiedName1() {
    PsiFile[] psiFiles = myFixture.configureByFiles("QualifiedImport_MultipleImportSameQualifiedName1/Usage/Usage.hs", "QualifiedImport_MultipleImportSameQualifiedName1/Definition/Definition.hs", "QualifiedImport_MultipleImportSameQualifiedName1/Other/Definition.hs");
    PsiFile usage = psiFiles[0];
    String textOfFile = usage.getText();
    int expectedStartOffset = textOfFile.indexOf("qualified Definition.Definition as Definition") + 35;
    PsiElement psiElement = usage.findElementAt(myFixture.getCaretOffset()).getParent();
    HaskellConid conId = (HaskellConid) psiElement;
    PsiReference reference = conId.getReference();
    HaskellConid referencedElement = (HaskellConid) reference.resolve();
    assertNotSame(psiElement, referencedElement);
    assertEquals(expectedStartOffset, referencedElement.getTextRange().getStartOffset());
}

54. HaskellGoToSymbolTest#testGoToSymbolFunction_QualifiedImport_MultipleImportSameQualifiedName2()

View license
public void testGoToSymbolFunction_QualifiedImport_MultipleImportSameQualifiedName2() {
    PsiFile[] psiFiles = myFixture.configureByFiles("QualifiedImport_MultipleImportSameQualifiedName2/Usage/Usage.hs", "QualifiedImport_MultipleImportSameQualifiedName2/Definition/Definition.hs", "QualifiedImport_MultipleImportSameQualifiedName2/Other/Definition.hs");
    PsiFile usage = psiFiles[0];
    String textOfFile = usage.getText();
    int expectedStartOffset = textOfFile.indexOf("qualified Other.Definition as Definition") + 30;
    PsiElement psiElement = usage.findElementAt(myFixture.getCaretOffset()).getParent();
    HaskellConid conId = (HaskellConid) psiElement;
    PsiReference reference = conId.getReference();
    HaskellConid referencedElement = (HaskellConid) reference.resolve();
    assertNotSame(psiElement, referencedElement);
    assertEquals(expectedStartOffset, referencedElement.getTextRange().getStartOffset());
}

55. AbstractLombokParsingTestCase#doTest()

View license
protected void doTest(final String beforeFileName, final String afterFileName) throws IOException {
    final PsiFile psiDelombokFile = loadToPsiFile(afterFileName);
    final PsiFile psiLombokFile = loadToPsiFile(beforeFileName);
    if (!(psiLombokFile instanceof PsiJavaFile) || !(psiDelombokFile instanceof PsiJavaFile)) {
        fail("The test file type is not supported");
    }
    final PsiJavaFile beforeFile = (PsiJavaFile) psiLombokFile;
    final PsiJavaFile afterFile = (PsiJavaFile) psiDelombokFile;
    PsiClass[] beforeClasses = beforeFile.getClasses();
    PsiClass[] afterClasses = afterFile.getClasses();
    compareClasses(beforeClasses, afterClasses);
}

56. ModulesUtil#isModule()

Project: svgtoandroid
Source File: ModulesUtil.java
View license
private boolean isModule(PsiDirectory directory) {
    boolean hasGradle = false;
    boolean hasSrc = false;
    PsiFile[] files = directory.getFiles();
    PsiDirectory[] dirs = directory.getSubdirectories();
    for (PsiFile file : files) {
        if (file.getName().equals("build.gradle")) {
            hasGradle = true;
            break;
        }
    }
    for (PsiDirectory dir : dirs) {
        if (dir.getName().equals("src")) {
            hasSrc = true;
            break;
        }
    }
    return hasGradle && hasSrc;
}

57. ParcelableAction#getPsiClassFromContext()

View license
private PsiClass getPsiClassFromContext(AnActionEvent e) {
    PsiFile psiFile = e.getData(LangDataKeys.PSI_FILE);
    Editor editor = e.getData(PlatformDataKeys.EDITOR);
    if (psiFile == null || editor == null) {
        return null;
    }
    int offset = editor.getCaretModel().getOffset();
    PsiElement element = psiFile.findElementAt(offset);
    return PsiTreeUtil.getParentOfType(element, PsiClass.class);
}

58. ScanFiles#mapsModulesToFiles()

Project: checkstyle-idea
Source File: ScanFiles.java
View license
private Map<Module, Set<PsiFile>> mapsModulesToFiles() {
    final Map<Module, Set<PsiFile>> modulesToFiles = new HashMap<>();
    for (final PsiFile file : files) {
        final Module module = ModuleUtil.findModuleForPsiElement(file);
        Set<PsiFile> filesForModule = modulesToFiles.get(module);
        if (filesForModule == null) {
            filesForModule = new HashSet<>();
            modulesToFiles.put(module, filesForModule);
        }
        filesForModule.add(file);
    }
    return modulesToFiles;
}

59. ScanFiles#filesWithProblems()

Project: checkstyle-idea
Source File: ScanFiles.java
View license
@NotNull
private Map<PsiFile, List<Problem>> filesWithProblems(final Set<PsiFile> filesForModule, final Map<PsiFile, List<Problem>> moduleFileResults) {
    final Map<PsiFile, List<Problem>> moduleResults = new HashMap<>();
    for (final PsiFile psiFile : filesForModule) {
        final List<Problem> resultsForFile = moduleFileResults.get(psiFile);
        if (resultsForFile != null && !resultsForFile.isEmpty()) {
            moduleResults.put(psiFile, new ArrayList<>(resultsForFile));
        }
    }
    return moduleResults;
}

60. LocalQuickFixOnPsiElement#isAvailable()

View license
protected boolean isAvailable() {
    if (myStartElement == null)
        return false;
    final PsiElement startElement = myStartElement.getElement();
    final PsiElement endElement = myEndElement == null ? startElement : myEndElement.getElement();
    PsiFile file = myStartElement.getContainingFile();
    Project project = myStartElement.getProject();
    return startElement != null && endElement != null && startElement.isValid() && (endElement == startElement || endElement.isValid()) && file != null && isAvailable(project, file, startElement, endElement);
}

61. UpdateHighlightersUtil#setHighlightersToEditor()

Project: consulo
Source File: UpdateHighlightersUtil.java
View license
public static void setHighlightersToEditor(@NotNull Project project, @NotNull Document document, int startOffset, int endOffset, @NotNull Collection<HighlightInfo> highlights, // if null global scheme will be used
@Nullable final EditorColorsScheme colorsScheme, int group) {
    TextRange range = new TextRange(startOffset, endOffset);
    ApplicationManager.getApplication().assertIsDispatchThread();
    PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document);
    final DaemonCodeAnalyzerEx codeAnalyzer = DaemonCodeAnalyzerEx.getInstanceEx(project);
    codeAnalyzer.cleanFileLevelHighlights(project, group, psiFile);
    MarkupModel markup = DocumentMarkupModel.forDocument(document, project, true);
    assertMarkupConsistent(markup, project);
    setHighlightersInRange(project, document, range, colorsScheme, new ArrayList<HighlightInfo>(highlights), (MarkupModelEx) markup, group);
}

62. QuickFixWrapper#invoke()

Project: consulo
Source File: QuickFixWrapper.java
View license
@Override
public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
    //if (!CodeInsightUtil.prepareFileForWrite(file)) return;
    // consider all local quick fixes do it themselves
    final PsiElement element = myDescriptor.getPsiElement();
    final PsiFile fileForUndo = element == null ? null : element.getContainingFile();
    LocalQuickFix fix = getFix();
    fix.applyFix(project, myDescriptor);
    DaemonCodeAnalyzer.getInstance(project).restart();
    if (fileForUndo != null && !fileForUndo.equals(file)) {
        UndoUtil.markPsiFileForUndo(fileForUndo);
    }
}

63. CompileActionBase#actionPerformed()

Project: consulo
Source File: CompileActionBase.java
View license
@RequiredDispatchThread
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
    final DataContext dataContext = e.getDataContext();
    final Project project = e.getData(CommonDataKeys.PROJECT);
    if (project == null) {
        return;
    }
    Editor editor = e.getData(PlatformDataKeys.EDITOR);
    PsiFile file = e.getData(LangDataKeys.PSI_FILE);
    if (file != null && editor != null && !DumbService.getInstance(project).isDumb()) {
        //let autoimport complete
        DaemonCodeAnalyzer.getInstance(project).autoImportReferenceAtCursor(editor, file);
    }
    doAction(dataContext, project);
}

64. IconDescriptorUpdaters#computeBaseIcon()

Project: consulo
Source File: IconDescriptorUpdaters.java
View license
@NotNull
private static Icon computeBaseIcon(@NotNull PsiElement element) {
    PsiFile containingFile = element.getContainingFile();
    if (containingFile != null) {
        VirtualFile virtualFile = containingFile.getVirtualFile();
        if (virtualFile != null) {
            Icon icon = virtualFile.getFileType().getIcon();
            if (icon != null) {
                return icon;
            }
        }
    }
    return AllIcons.Nodes.NodePlaceholder;
}

65. CodeInsightUtilCore#forcePsiPostprocessAndRestoreElement()

Project: consulo
Source File: CodeInsightUtilCore.java
View license
public static <T extends PsiElement> T forcePsiPostprocessAndRestoreElement(@NotNull T element) {
    final PsiFile psiFile = element.getContainingFile();
    final Document document = psiFile.getViewProvider().getDocument();
    //if (document == null) return element;
    final Language language = psiFile.getLanguage();
    final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(psiFile.getProject());
    final RangeMarker rangeMarker = document.createRangeMarker(element.getTextRange());
    documentManager.doPostponedOperationsAndUnblockDocument(document);
    documentManager.commitDocument(document);
    T elementInRange = findElementInRange(psiFile, rangeMarker.getStartOffset(), rangeMarker.getEndOffset(), (Class<? extends T>) element.getClass(), language);
    rangeMarker.dispose();
    return elementInRange;
}

66. PsiBuilderImpl#checkTreeDepth()

Project: consulo
Source File: PsiBuilderImpl.java
View license
private void checkTreeDepth(final int maxDepth, final boolean isFileRoot) {
    if (myFile == null)
        return;
    final PsiFile file = myFile.getOriginalFile();
    final Boolean flag = file.getUserData(BlockSupport.TREE_DEPTH_LIMIT_EXCEEDED);
    if (maxDepth > BlockSupport.INCREMENTAL_REPARSE_DEPTH_LIMIT) {
        if (!Boolean.TRUE.equals(flag)) {
            file.putUserData(BlockSupport.TREE_DEPTH_LIMIT_EXCEEDED, Boolean.TRUE);
        }
    } else if (isFileRoot && flag != null) {
        file.putUserData(BlockSupport.TREE_DEPTH_LIMIT_EXCEEDED, null);
    }
}

67. DocumentCommitThread#commitAsynchronously()

Project: consulo
Source File: DocumentCommitThread.java
View license
@Override
public void commitAsynchronously(@NotNull final Project project, @NotNull final Document document, @NonNls @NotNull Object reason, @NotNull ModalityState currentModalityState) {
    assert !isDisposed : "already disposed";
    if (!project.isInitialized())
        return;
    PsiFile psiFile = PsiDocumentManager.getInstance(project).getCachedPsiFile(document);
    if (psiFile == null)
        return;
    doQueue(project, document, getAllFileNodes(psiFile), reason, currentModalityState);
}

68. FileContextUtil#getContextFile()

Project: consulo
Source File: FileContextUtil.java
View license
@Nullable
public static PsiFile getContextFile(@NotNull PsiElement element) {
    if (!element.isValid())
        return null;
    PsiFile file = element.getContainingFile();
    if (file == null)
        return null;
    PsiElement context = file.getContext();
    if (context == null) {
        return file;
    } else {
        return getContextFile(context);
    }
}

69. CompositeElement#getThreadingDiagnostics()

Project: consulo
Source File: CompositeElement.java
View license
private String getThreadingDiagnostics() {
    FileElement fileElement;
    PsiFile psiFile;
    return " Under write: " + ApplicationManager.getApplication().isWriteAccessAllowed() + "; Thread.holdsLock(PsiLock.LOCK): " + Thread.holdsLock(PsiLock.LOCK) + "; wrapper: " + myWrapper + "; wrapper.isPhysical(): " + (myWrapper != null && myWrapper.isPhysical()) + "; fileElement: " + (fileElement = TreeUtil.getFileElement(this)) + "; psiFile: " + (psiFile = fileElement == null ? null : (PsiFile) fileElement.getPsi()) + "; psiFile.getViewProvider(): " + (psiFile == null ? null : psiFile.getViewProvider()) + "; psiFile.isPhysical(): " + (psiFile != null && psiFile.isPhysical()) + "; nonPhysicalOrInjected: " + isNonPhysicalOrInjected();
}

70. CompositeElement#isNonPhysicalOrInjected()

Project: consulo
Source File: CompositeElement.java
View license
private boolean isNonPhysicalOrInjected() {
    FileElement fileElement = TreeUtil.getFileElement(this);
    if (fileElement == null || fileElement instanceof DummyHolderElement)
        return true;
    // dummy holder
    if (fileElement.getTreeParent() != null)
        return true;
    PsiElement wrapper = this instanceof PsiElement ? (PsiElement) this : myWrapper;
    if (wrapper == null)
        return true;
    PsiFile psiFile = wrapper.getContainingFile();
    return psiFile == null || psiFile instanceof DummyHolder || psiFile.getViewProvider() instanceof FreeThreadedFileViewProvider || !psiFile.isPhysical();
}

71. FileContentImpl#getPsiFile()

Project: consulo
Source File: FileContentImpl.java
View license
/**
   * @return psiFile associated with the content. If the file was not set on FileContentCreation, it will be created on the spot
   */
@NotNull
@Override
public PsiFile getPsiFile() {
    PsiFile psi = getUserData(IndexingDataKeys.PSI_FILE);
    if (psi == null) {
        psi = getUserData(CACHED_PSI);
    }
    if (psi == null) {
        psi = createFileFromText(getContentAsText());
        psi.putUserData(IndexingDataKeys.VIRTUAL_FILE, getFile());
        putUserData(CACHED_PSI, psi);
    }
    return psi;
}

72. FileContentImpl#getPsiFileForPsiDependentIndex()

Project: consulo
Source File: FileContentImpl.java
View license
@RequiredReadAction
public PsiFile getPsiFileForPsiDependentIndex() {
    Document document = FileDocumentManager.getInstance().getCachedDocument(getFile());
    PsiFile psi = null;
    if (document != null) {
        PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(getProject());
        if (psiDocumentManager.isUncommited(document)) {
            PsiFile existingPsi = psiDocumentManager.getPsiFile(document);
            if (existingPsi != null) {
                psi = existingPsi;
            }
        }
    }
    if (psi == null) {
        psi = getPsiFile();
    }
    return psi;
}

73. CoverageLineMarkerRenderer#getReport()

View license
private String getReport(final Editor editor, final int lineNumber) {
    final LineData lineData = getLineData(lineNumber);
    final Document document = editor.getDocument();
    final Project project = editor.getProject();
    assert project != null;
    final PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document);
    assert psiFile != null;
    final int lineStartOffset = document.getLineStartOffset(lineNumber);
    final int lineEndOffset = document.getLineEndOffset(lineNumber);
    return myCoverageSuite.getCoverageEngine().generateBriefReport(editor, psiFile, lineNumber, lineStartOffset, lineEndOffset, lineData);
}

74. ExternalSystemTasksPanel#buildLocation()

View license
@Nullable
private Location buildLocation() {
    if (mySelectedTaskProvider == null) {
        return null;
    }
    ExternalTaskExecutionInfo task = mySelectedTaskProvider.produce();
    if (task == null) {
        return null;
    }
    String projectPath = task.getSettings().getExternalProjectPath();
    String name = myExternalSystemId.getReadableName() + projectPath + StringUtil.join(task.getSettings().getTaskNames(), " ");
    // We create a dummy text file instead of re-using external system file in order to avoid clashing with other configuration producers.
    // For example gradle files are enhanced groovy scripts but we don't want to run them via regular IJ groovy script runners.
    // Gradle tooling api should be used for running gradle tasks instead. IJ execution sub-system operates on Location objects
    // which encapsulate PsiElement and groovy runners are automatically applied if that PsiElement IS-A GroovyFile.
    PsiFile file = PsiFileFactory.getInstance(myProject).createFileFromText(name, PlainTextFileType.INSTANCE, "nichts");
    return new ExternalSystemTaskLocation(myProject, file, task);
}

75. ParenthesesInsertHandler#findNextToken()

View license
@Nullable
protected PsiElement findNextToken(final InsertionContext context) {
    final PsiFile file = context.getFile();
    PsiElement element = file.findElementAt(context.getTailOffset());
    if (element instanceof PsiWhiteSpace) {
        if (!myAllowParametersOnNextLine && element.getText().contains("\n")) {
            return null;
        }
        element = file.findElementAt(element.getTextRange().getEndOffset());
    }
    return element;
}

76. LanguageImportStatements#forFile()

View license
public Set<ImportOptimizer> forFile(PsiFile file) {
    Set<ImportOptimizer> optimizers = new HashSet<ImportOptimizer>();
    for (PsiFile psiFile : file.getViewProvider().getAllFiles()) {
        List<ImportOptimizer> langOptimizers = allForLanguage(psiFile.getLanguage());
        for (ImportOptimizer optimizer : langOptimizers) {
            if (optimizer != null && optimizer.supports(psiFile)) {
                optimizers.add(optimizer);
                break;
            }
        }
    }
    return optimizers;
}

77. CodeStyleAbstractPanel#collectChangesBeforeCurrentSettingsAppliance()

Project: consulo
Source File: CodeStyleAbstractPanel.java
View license
/**
   * Reformats {@link #myTextToReformat target text} with the {@link #mySettings current code style settings} and returns
   * list of changes applied to the target text during that.
   *
   * @param project   project to use
   * @return          list of changes applied to the {@link #myTextToReformat target text} during reformatting. It is sorted
   *                  by change start offset in ascending order
   */
@Nullable
private Document collectChangesBeforeCurrentSettingsAppliance(Project project) {
    PsiFile psiFile = createFileFromText(project, myTextToReformat);
    prepareForReformat(psiFile);
    PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
    if (documentManager != null) {
        Document document = documentManager.getDocument(psiFile);
        if (document != null) {
            CodeStyleSettings clone = mySettings.clone();
            clone.setRightMargin(getDefaultLanguage(), getAdjustedRightMargin());
            CodeStyleSettingsManager.getInstance(project).setTemporarySettings(clone);
            try {
                CodeStyleManager.getInstance(project).reformat(psiFile);
            } finally {
                CodeStyleSettingsManager.getInstance(project).dropTemporarySettings();
            }
            return document;
        }
    }
    return null;
}

78. ExportToHTMLAction#update()

Project: consulo
Source File: ExportToHTMLAction.java
View license
@RequiredDispatchThread
@Override
public void update(@NotNull AnActionEvent event) {
    Presentation presentation = event.getPresentation();
    DataContext dataContext = event.getDataContext();
    PsiElement psiElement = LangDataKeys.PSI_ELEMENT.getData(dataContext);
    if (psiElement instanceof PsiDirectory) {
        presentation.setEnabled(true);
        return;
    }
    PsiFile psiFile = LangDataKeys.PSI_FILE.getData(dataContext);
    presentation.setEnabled(psiFile != null && psiFile.getContainingDirectory() != null);
}

79. PrintAction#update()

Project: consulo
Source File: PrintAction.java
View license
@Override
public void update(AnActionEvent event) {
    Presentation presentation = event.getPresentation();
    DataContext dataContext = event.getDataContext();
    VirtualFile file = PlatformDataKeys.VIRTUAL_FILE.getData(dataContext);
    if (file != null && file.isDirectory()) {
        presentation.setEnabled(true);
        return;
    }
    Editor editor = PlatformDataKeys.EDITOR.getData(dataContext);
    PsiFile psiFile = LangDataKeys.PSI_FILE.getData(dataContext);
    presentation.setEnabled(psiFile != null || editor != null);
}

80. ShowReformatFileDialog#update()

Project: consulo
Source File: ShowReformatFileDialog.java
View license
@Override
public void update(AnActionEvent event) {
    Presentation presentation = event.getPresentation();
    DataContext dataContext = event.getDataContext();
    Project project = CommonDataKeys.PROJECT.getData(dataContext);
    Editor editor = CommonDataKeys.EDITOR.getData(dataContext);
    if (project == null || editor == null) {
        presentation.setEnabled(false);
        return;
    }
    PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
    if (file == null || file.getVirtualFile() == null) {
        presentation.setEnabled(false);
        return;
    }
    if (LanguageFormatting.INSTANCE.forContext(file) != null) {
        presentation.setEnabled(true);
    }
}

81. ShowReformatFileDialog#actionPerformed()

Project: consulo
Source File: ShowReformatFileDialog.java
View license
@Override
public void actionPerformed(AnActionEvent event) {
    Presentation presentation = event.getPresentation();
    DataContext dataContext = event.getDataContext();
    Project project = CommonDataKeys.PROJECT.getData(dataContext);
    Editor editor = CommonDataKeys.EDITOR.getData(dataContext);
    if (project == null || editor == null) {
        presentation.setEnabled(false);
        return;
    }
    PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
    if (file == null || file.getVirtualFile() == null) {
        presentation.setEnabled(false);
        return;
    }
    boolean hasSelection = editor.getSelectionModel().hasSelection();
    LayoutCodeDialog dialog = new LayoutCodeDialog(project, file, hasSelection, HELP_ID);
    dialog.show();
    if (dialog.isOK()) {
        new FileInEditorProcessor(file, editor, dialog.getRunOptions()).processCode();
    }
}

82. BaseCodeCompletionAction#update()

View license
@Override
public void update(AnActionEvent e) {
    DataContext dataContext = e.getDataContext();
    e.getPresentation().setEnabled(false);
    Project project = CommonDataKeys.PROJECT.getData(dataContext);
    if (project == null)
        return;
    Editor editor = PlatformDataKeys.EDITOR.getData(dataContext);
    if (editor == null)
        return;
    final PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(editor, project);
    if (psiFile == null)
        return;
    if (!ApplicationManager.getApplication().isUnitTestMode() && !editor.getContentComponent().isShowing())
        return;
    e.getPresentation().setEnabled(true);
}

83. CodeCompletionGroup#update()

Project: consulo
Source File: CodeCompletionGroup.java
View license
@Override
public void update(AnActionEvent event) {
    Presentation presentation = event.getPresentation();
    DataContext dataContext = event.getDataContext();
    Project project = CommonDataKeys.PROJECT.getData(dataContext);
    if (project == null) {
        presentation.setEnabled(false);
        return;
    }
    Editor editor = PlatformDataKeys.EDITOR.getData(dataContext);
    if (editor == null) {
        presentation.setEnabled(false);
        return;
    }
    PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
    if (file == null) {
        presentation.setEnabled(false);
        return;
    }
    presentation.setEnabled(true);
}

84. CodeCompletionHandlerBase#createCompletionContext()

View license
private static CompletionContext createCompletionContext(PsiFile hostCopy, int hostStartOffset, OffsetMap hostMap, PsiFile originalFile) {
    CompletionAssertions.assertHostInfo(hostCopy, hostMap);
    InjectedLanguageManager injectedLanguageManager = InjectedLanguageManager.getInstance(hostCopy.getProject());
    CompletionContext context;
    PsiFile injected = InjectedLanguageUtil.findInjectedPsiNoCommit(hostCopy, hostStartOffset);
    if (injected != null) {
        if (injected instanceof PsiFileImpl) {
            ((PsiFileImpl) injected).setOriginalFile(originalFile);
        }
        DocumentWindow documentWindow = InjectedLanguageUtil.getDocumentWindow(injected);
        CompletionAssertions.assertInjectedOffsets(hostStartOffset, injectedLanguageManager, injected, documentWindow);
        context = new CompletionContext(injected, translateOffsetMapToInjected(hostMap, documentWindow));
    } else {
        context = new CompletionContext(hostCopy, hostMap);
    }
    CompletionAssertions.assertFinalOffsets(originalFile, context, injected);
    return context;
}

85. LegacyCompletionContributor#fillCompletionVariants()

View license
@RequiredReadAction
@Override
public void fillCompletionVariants(CompletionParameters parameters, CompletionResultSet _result) {
    if (parameters.getCompletionType() != CompletionType.BASIC) {
        return;
    }
    CompletionData completionData = getCompletionData(parameters);
    if (completionData == null)
        return;
    final PsiElement insertedElement = parameters.getPosition();
    final CompletionResultSet result = _result.withPrefixMatcher(completionData.findPrefix(insertedElement, parameters.getOffset()));
    completeReference(parameters, result);
    final Set<LookupElement> lookupSet = new LinkedHashSet<LookupElement>();
    final Set<CompletionVariant> keywordVariants = new HashSet<CompletionVariant>();
    PsiFile file = parameters.getOriginalFile();
    completionData.addKeywordVariants(keywordVariants, insertedElement, file);
    completionData.completeKeywordsBySet(lookupSet, keywordVariants, insertedElement, result.getPrefixMatcher(), file);
    result.addAllElements(lookupSet);
}

86. HighlightingSettingsPerFile#getHighlightingSettingForRoot()

View license
@NotNull
public FileHighlightingSetting getHighlightingSettingForRoot(@NotNull PsiElement root) {
    final PsiFile containingFile = root.getContainingFile();
    final VirtualFile virtualFile = containingFile.getVirtualFile();
    FileHighlightingSetting[] fileHighlightingSettings = myHighlightSettings.get(virtualFile);
    final int index = PsiUtilBase.getRootIndex(root);
    if (fileHighlightingSettings == null || fileHighlightingSettings.length <= index) {
        return getDefaultHighlightingSetting(root.getProject(), virtualFile);
    }
    return fileHighlightingSettings[index];
}

87. HighlightingSettingsPerFile#setHighlightingSettingForRoot()

View license
public void setHighlightingSettingForRoot(@NotNull PsiElement root, @NotNull FileHighlightingSetting setting) {
    final PsiFile containingFile = root.getContainingFile();
    final VirtualFile virtualFile = containingFile.getVirtualFile();
    if (virtualFile == null)
        return;
    FileHighlightingSetting[] defaults = myHighlightSettings.get(virtualFile);
    int rootIndex = PsiUtilBase.getRootIndex(root);
    if (defaults != null && rootIndex >= defaults.length)
        defaults = null;
    if (defaults == null)
        defaults = getDefaults(containingFile);
    defaults[rootIndex] = setting;
    boolean toRemove = true;
    for (FileHighlightingSetting aDefault : defaults) {
        if (aDefault != FileHighlightingSetting.NONE)
            toRemove = false;
    }
    if (toRemove) {
        myHighlightSettings.remove(virtualFile);
    } else {
        myHighlightSettings.put(virtualFile, defaults);
    }
}

88. RenameFileFix#applyFix()

Project: consulo
Source File: RenameFileFix.java
View license
@Override
public void applyFix(@NotNull final Project project, @NotNull ProblemDescriptor descriptor) {
    final PsiFile file = descriptor.getPsiElement().getContainingFile();
    if (isAvailable(project, null, file)) {
        new WriteCommandAction(project) {

            @Override
            protected void run(Result result) throws Throwable {
                invoke(project, FileEditorManager.getInstance(project).getSelectedTextEditor(), file);
            }
        }.execute();
    }
}

89. MoveElementLeftRightActionHandler#isEnabledForCaret()

View license
@Override
@RequiredDispatchThread
protected boolean isEnabledForCaret(@NotNull Editor editor, @NotNull Caret caret, DataContext dataContext) {
    Project project = editor.getProject();
    if (project == null)
        return false;
    Document document = editor.getDocument();
    if (!(document instanceof DocumentEx))
        return false;
    PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(project);
    psiDocumentManager.commitDocument(document);
    PsiFile file = psiDocumentManager.getPsiFile(document);
    if (file == null || !file.isValid())
        return false;
    PsiElement[] elementList = getElementList(file, caret.getSelectionStart(), caret.getSelectionEnd());
    return elementList != null;
}

90. BaseMoveHandler#executeWriteAction()

Project: consulo
Source File: BaseMoveHandler.java
View license
@RequiredWriteAction
@Override
public void executeWriteAction(Editor editor, Caret caret, DataContext dataContext) {
    final Project project = editor.getProject();
    assert project != null;
    final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
    final Document document = editor.getDocument();
    PsiFile file = getRoot(documentManager.getPsiFile(document), editor);
    if (file != null) {
        final MoverWrapper mover = getSuitableMover(editor, file);
        if (mover != null && mover.getInfo().toMove2 != null) {
            LineRange range = mover.getInfo().toMove;
            if ((range.startLine > 0 || isDown) && (range.endLine < document.getLineCount() || !isDown)) {
                mover.move(editor, file);
            }
        }
    }
}

91. MoverWrapper#indentLinesIn()

Project: consulo
Source File: MoverWrapper.java
View license
private static void indentLinesIn(final Editor editor, final PsiFile file, final Document document, final Project project, RangeMarker range) {
    final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
    int line1 = editor.offsetToLogicalPosition(range.getStartOffset()).line;
    int line2 = editor.offsetToLogicalPosition(range.getEndOffset()).line;
    while (!lineContainsNonSpaces(document, line1) && line1 < line2) line1++;
    while (!lineContainsNonSpaces(document, line2) && line1 < line2) line2--;
    final FileViewProvider provider = file.getViewProvider();
    PsiFile rootToAdjustIndentIn = provider.getPsi(provider.getBaseLanguage());
    codeStyleManager.adjustLineIndent(rootToAdjustIndentIn, new TextRange(document.getLineStartOffset(line1), document.getLineStartOffset(line2)));
}

92. PasteHandler#indentBlock()

Project: consulo
Source File: PasteHandler.java
View license
static void indentBlock(Project project, Editor editor, final int startOffset, final int endOffset, int originalCaretCol) {
    final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
    documentManager.commitAllDocuments();
    final Document document = editor.getDocument();
    PsiFile file = documentManager.getPsiFile(document);
    if (file == null) {
        return;
    }
    if (LanguageFormatting.INSTANCE.forContext(file) != null) {
        indentBlockWithFormatter(project, document, startOffset, endOffset, file);
    } else {
        indentPlainTextBlock(document, startOffset, endOffset, originalCaretCol);
    }
}

93. CodeFoldingManagerImpl#releaseFoldings()

Project: consulo
Source File: CodeFoldingManagerImpl.java
View license
@Override
public void releaseFoldings(@NotNull Editor editor) {
    ApplicationManagerEx.getApplicationEx().assertIsDispatchThread();
    final Project project = editor.getProject();
    if (project != null && (!project.equals(myProject) || !project.isOpen()))
        return;
    Document document = editor.getDocument();
    PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(document);
    if (file == null || !file.getViewProvider().isPhysical() || !file.isValid())
        return;
    PsiDocumentManager.getInstance(myProject).commitDocument(document);
    Editor[] otherEditors = EditorFactory.getInstance().getEditors(document, myProject);
    if (otherEditors.length == 0 && !editor.isDisposed()) {
        getDocumentFoldingInfo(document).loadFromEditor(editor);
    }
    EditorFoldingInfo.get(editor).dispose();
}

94. EditorFoldingInfo#getPsiElementRange()

Project: consulo
Source File: EditorFoldingInfo.java
View license
@Nullable
public TextRange getPsiElementRange(@NotNull FoldRegion region) {
    PsiElement element = getPsiElement(region);
    if (element == null)
        return null;
    PsiFile containingFile = element.getContainingFile();
    InjectedLanguageManager injectedManager = InjectedLanguageManager.getInstance(containingFile.getProject());
    boolean isInjected = injectedManager.isInjectedFragment(containingFile);
    TextRange range = element.getTextRange();
    if (isInjected) {
        range = injectedManager.injectedToHost(element, range);
    }
    return range;
}

95. SurroundWithAction#isValidForFile()

Project: consulo
Source File: SurroundWithAction.java
View license
@Override
protected boolean isValidForFile(@NotNull Project project, @NotNull Editor editor, @NotNull final PsiFile file) {
    final Language language = file.getLanguage();
    if (!LanguageSurrounders.INSTANCE.allForLanguage(language).isEmpty()) {
        return true;
    }
    final PsiFile baseFile = PsiUtilCore.getTemplateLanguageFile(file);
    if (baseFile != null && baseFile != file && !LanguageSurrounders.INSTANCE.allForLanguage(baseFile.getLanguage()).isEmpty()) {
        return true;
    }
    if (!SurroundWithTemplateHandler.getApplicableTemplates(editor, file, true).isEmpty()) {
        return true;
    }
    return false;
}

96. InspectionDescriptionLinkHandler#getDescription()

View license
@Override
public String getDescription(@NotNull final String refSuffix, @NotNull final Editor editor) {
    final Project project = editor.getProject();
    if (project == null) {
        LOG.error(editor);
        return null;
    }
    final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
    if (file == null) {
        return null;
    }
    final InspectionProfile profile = (InspectionProfile) InspectionProfileManager.getInstance().getRootProfile();
    final InspectionToolWrapper toolWrapper = profile.getInspectionTool(refSuffix, file);
    if (toolWrapper == null)
        return null;
    String description = toolWrapper.loadDescription();
    if (description == null) {
        LOG.warn("No description for inspection '" + refSuffix + "'");
        description = InspectionsBundle.message("inspection.tool.description.under.construction.text");
    }
    return description;
}

97. ParameterInfoController#getPrevOrNextParameterOffset()

View license
private int getPrevOrNextParameterOffset(boolean isNext) {
    if (!(myHandler instanceof ParameterInfoHandlerWithTabActionSupport))
        return -1;
    int offset = CharArrayUtil.shiftBackward(myEditor.getDocument().getCharsSequence(), myEditor.getCaretModel().getOffset() - 1, " \t") + 1;
    int lbraceOffset = myLbraceMarker.getStartOffset();
    PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(myEditor.getDocument());
    PsiElement argList = lbraceOffset < offset ? findArgumentList(file, offset, lbraceOffset) : null;
    if (argList == null)
        return -1;
    ParameterInfoHandlerWithTabActionSupport handler = (ParameterInfoHandlerWithTabActionSupport) myHandler;
    int currentParameterIndex = ParameterInfoUtils.getCurrentParameterIndex(argList.getNode(), offset, handler.getActualParameterDelimiterType());
    if (currentParameterIndex == -1)
        return -1;
    @SuppressWarnings("unchecked") PsiElement[] parameters = handler.getActualParameters(argList);
    int prevOrNextParameterIndex = isNext && currentParameterIndex < parameters.length - 1 ? currentParameterIndex + 1 : !isNext && currentParameterIndex > 0 ? currentParameterIndex - 1 : -1;
    return prevOrNextParameterIndex != -1 ? parameters[prevOrNextParameterIndex].getTextRange().getStartOffset() : -1;
}

98. QuickEditAction#invokeImpl()

Project: consulo
Source File: QuickEditAction.java
View license
public QuickEditHandler invokeImpl(@NotNull final Project project, final Editor editor, PsiFile file) throws IncorrectOperationException {
    int offset = editor.getCaretModel().getOffset();
    Pair<PsiElement, TextRange> pair = ObjectUtils.assertNotNull(getRangePair(file, editor));
    PsiFile injectedFile = (PsiFile) pair.first;
    QuickEditHandler handler = getHandler(project, injectedFile, editor, file);
    if (!ApplicationManager.getApplication().isUnitTestMode()) {
        DocumentWindow documentWindow = InjectedLanguageUtil.getDocumentWindow(injectedFile);
        if (documentWindow != null) {
            handler.navigate(((DocumentWindowImpl) documentWindow).hostToInjectedUnescaped(offset));
        }
    }
    return handler;
}

99. LookupImpl#getEditor()

Project: consulo
Source File: LookupImpl.java
View license
@Override
@NotNull
public Editor getEditor() {
    PsiFile hostFile = PsiDocumentManager.getInstance(myProject).getPsiFile(myEditor.getDocument());
    if (hostFile != null) {
        int offset = myEditor.getCaretModel().getOffset();
        // inspired by com.intellij.codeInsight.editorActions.TypedHandler.injectedEditorIfCharTypedIsSignificant()
        for (DocumentWindow documentWindow : InjectedLanguageUtil.getCachedInjectedDocuments(hostFile)) {
            if (documentWindow.isValid() && documentWindow.containsRange(offset, offset)) {
                PsiFile injectedFile = PsiDocumentManager.getInstance(myProject).getPsiFile(documentWindow);
                return InjectedLanguageUtil.getInjectedEditorForInjectedFile(myEditor, injectedFile);
            }
        }
    }
    return myEditor;
}

100. TemplateManagerImpl#filterApplicableCandidates()

Project: consulo
Source File: TemplateManagerImpl.java
View license
private static List<TemplateImpl> filterApplicableCandidates(PsiFile file, int caretOffset, List<TemplateImpl> candidates) {
    if (candidates.isEmpty()) {
        return candidates;
    }
    PsiFile copy = insertDummyIdentifier(file, caretOffset, caretOffset);
    List<TemplateImpl> result = new ArrayList<TemplateImpl>();
    for (TemplateImpl candidate : candidates) {
        if (isApplicable(copy, caretOffset - candidate.getKey().length(), candidate)) {
            result.add(candidate);
        }
    }
    return result;
}