com.intellij.psi.PsiElement

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

1. PyParameterInfoTest#testKwdFunction()

Project: intellij-community
File: PyParameterInfoTest.java
public void testKwdFunction() {
    Map<String, PsiElement> marks = loadTest(5);
    PsiElement arg1 = marks.get("<arg1>");
    feignCtrlP(arg1.getTextOffset()).check("a, b, **c", new String[] { "a, " });
    feignCtrlP(arg1.getTextOffset() + 1).check("a, b, **c", new String[] { "a, " });
    PsiElement arg2 = marks.get("<arg2>");
    feignCtrlP(arg2.getTextOffset()).check("a, b, **c", new String[] { "b, " });
    feignCtrlP(arg2.getTextOffset() + 1).check("a, b, **c", new String[] { "b, " });
    PsiElement arg3 = marks.get("<arg3>");
    feignCtrlP(arg3.getTextOffset()).check("a, b, **c", new String[] { "**c" });
    feignCtrlP(arg3.getTextOffset() + 1).check("a, b, **c", new String[] { "**c" });
    PsiElement arg4 = marks.get("<arg4>");
    feignCtrlP(arg4.getTextOffset()).check("a, b, **c", new String[] { "**c" });
    feignCtrlP(arg4.getTextOffset() + 1).check("a, b, **c", new String[] { "**c" });
    PsiElement arg5 = marks.get("<arg5>");
    feignCtrlP(arg5.getTextOffset()).check("a, b, **c", new String[] { "**c" });
}

2. CollectHighlightsUtil#findCommonParent()

Project: consulo
File: CollectHighlightsUtil.java
@Nullable
public static PsiElement findCommonParent(final PsiElement root, final int startOffset, final int endOffset) {
    if (startOffset == endOffset)
        return null;
    final PsiElement left = findElementAtInRoot(root, startOffset);
    PsiElement right = findElementAtInRoot(root, endOffset - 1);
    if (left == null || right == null)
        return null;
    PsiElement commonParent = PsiTreeUtil.findCommonParent(left, right);
    if (commonParent == null) {
        LOG.error("No common parent for " + left + " and " + right + "; root: " + root + "; startOffset: " + startOffset + "; endOffset: " + endOffset);
    }
    LOG.assertTrue(commonParent.getTextRange() != null, commonParent);
    PsiElement parent = commonParent.getParent();
    while (parent != null && commonParent.getTextRange().equals(parent.getTextRange())) {
        commonParent = parent;
        parent = parent.getParent();
    }
    return commonParent;
}

3. CollectHighlightsUtil#findCommonParent()

Project: intellij-community
File: CollectHighlightsUtil.java
@Nullable
public static PsiElement findCommonParent(final PsiElement root, final int startOffset, final int endOffset) {
    if (startOffset == endOffset)
        return null;
    final PsiElement left = findElementAtInRoot(root, startOffset);
    PsiElement right = findElementAtInRoot(root, endOffset - 1);
    if (left == null || right == null)
        return null;
    PsiElement commonParent = PsiTreeUtil.findCommonParent(left, right);
    if (commonParent == null) {
        LOG.error("No common parent for " + left + " and " + right + "; root: " + root + "; startOffset: " + startOffset + "; endOffset: " + endOffset);
    }
    LOG.assertTrue(commonParent.getTextRange() != null, commonParent);
    PsiElement parent = commonParent.getParent();
    while (parent != null && commonParent.getTextRange().equals(parent.getTextRange())) {
        commonParent = parent;
        parent = parent.getParent();
    }
    return commonParent;
}

4. GenerationInfoBase#findInsertionAnchor()

Project: intellij-community
File: GenerationInfoBase.java
/**
   * @param aClass
   * @param leaf leaf element. Is guaranteed to be a tree descendant of aClass.
   * @return the value that will be passed to the {@link #insert(com.intellij.psi.PsiClass, com.intellij.psi.PsiElement, boolean)} method later.
   */
@Override
@Nullable
public PsiElement findInsertionAnchor(@NotNull PsiClass aClass, @NotNull PsiElement leaf) {
    PsiElement element = leaf;
    while (element.getParent() != aClass) {
        element = element.getParent();
    }
    PsiElement lBrace = aClass.getLBrace();
    if (lBrace == null) {
        return null;
    }
    PsiElement rBrace = aClass.getRBrace();
    if (!GenerateMembersUtil.isChildInRange(element, lBrace.getNextSibling(), rBrace)) {
        return null;
    }
    PsiElement prev = leaf.getPrevSibling();
    if (prev != null && prev.getNode() != null && prev.getNode().getElementType() == JavaTokenType.END_OF_LINE_COMMENT) {
        element = leaf.getNextSibling();
    }
    return element;
}

5. ConvertToGeeseBracesIntention#findRange()

Project: intellij-community
File: ConvertToGeeseBracesIntention.java
private static TextRange findRange(PsiElement element) {
    PsiElement first = null;
    PsiElement last = null;
    for (PsiElement cur = element; GeeseUtil.isClosureRBrace(cur) && GeeseUtil.isClosureContainLF(cur); cur = getNext(cur)) {
        last = cur;
    }
    for (PsiElement cur = element; GeeseUtil.isClosureRBrace(cur) && GeeseUtil.isClosureContainLF(cur); cur = getPrev(cur)) {
        first = cur;
    }
    LOG.assertTrue(first != null);
    LOG.assertTrue(last != null);
    return new TextRange(first.getTextRange().getStartOffset(), last.getTextRange().getEndOffset());
}

6. InvertIfIntention#generateElseBranchTextAndRemoveTailStatements()

Project: intellij-community
File: InvertIfIntention.java
private static void generateElseBranchTextAndRemoveTailStatements(@NotNull GrIfStatement ifStatement, @NotNull GrIfStatement newIf) {
    final GrStatement thenBranch = newIf.getThenBranch();
    assert thenBranch != null;
    GrStatement elseBranch = ifStatement.getElseBranch();
    if (elseBranch != null) {
        thenBranch.replaceWithStatement(elseBranch);
        return;
    }
    PsiElement parent = ifStatement.getParent();
    if (!(parent instanceof GrStatementOwner))
        return;
    if (!isTailAfterIf(ifStatement, ((GrStatementOwner) parent)))
        return;
    final PsiElement start = ifStatement.getNextSibling();
    PsiElement end = parent instanceof GrCodeBlock ? ((GrCodeBlock) parent).getRBrace().getPrevSibling() : parent.getLastChild();
    final GrOpenBlock block = ((GrBlockStatement) thenBranch).getBlock();
    block.addRangeAfter(start, end, block.getLBrace());
    parent.deleteChildRange(start, end);
}

7. GrJoinBlockStatementHandler#tryJoinLines()

Project: intellij-community
File: GrJoinBlockStatementHandler.java
@Override
public int tryJoinLines(Document document, PsiFile file, int start, int end) {
    if (!(file instanceof GroovyFileBase))
        return CANNOT_JOIN;
    final PsiElement startElement = file.findElementAt(start);
    if (startElement == null || startElement.getNode().getElementType() != GroovyTokenTypes.mLCURLY)
        return CANNOT_JOIN;
    final PsiElement parent = startElement.getParent();
    if (!(parent instanceof GrOpenBlock))
        return CANNOT_JOIN;
    final GrStatement[] statements = ((GrOpenBlock) parent).getStatements();
    if (statements.length != 1)
        return CANNOT_JOIN;
    final PsiElement parent1 = parent.getParent();
    if (!(parent1 instanceof GrBlockStatement))
        return CANNOT_JOIN;
    final PsiElement parent2 = parent1.getParent();
    if (!(parent2 instanceof GrIfStatement) && !(parent2 instanceof GrWhileStatement) && !(parent2 instanceof GrForStatement)) {
        return CANNOT_JOIN;
    }
    final GrStatement statement = ((GrBlockStatement) parent1).replaceWithStatement(statements[0]);
    return statement.getTextRange().getStartOffset();
}

8. PyParameterInfoTest#testStarredFunction()

Project: intellij-community
File: PyParameterInfoTest.java
public void testStarredFunction() {
    Map<String, PsiElement> marks = loadTest(4);
    PsiElement arg1 = marks.get("<arg1>");
    feignCtrlP(arg1.getTextOffset()).check("a, b, *c", new String[] { "a, " });
    feignCtrlP(arg1.getTextOffset() + 1).check("a, b, *c", new String[] { "a, " });
    PsiElement arg2 = marks.get("<arg2>");
    feignCtrlP(arg2.getTextOffset()).check("a, b, *c", new String[] { "b, " });
    feignCtrlP(arg2.getTextOffset() + 1).check("a, b, *c", new String[] { "b, " });
    PsiElement arg3 = marks.get("<arg3>");
    feignCtrlP(arg3.getTextOffset()).check("a, b, *c", new String[] { "*c" });
    feignCtrlP(arg3.getTextOffset() + 1).check("a, b, *c", new String[] { "*c" });
    PsiElement arg4 = marks.get("<arg4>");
    feignCtrlP(arg4.getTextOffset()).check("a, b, *c", new String[] { "*c" });
    feignCtrlP(arg4.getTextOffset() + 1).check("a, b, *c", new String[] { "*c" });
    // sticks to *arg
    feignCtrlP(arg4.getTextOffset() + 2).check("a, b, *c", new String[] { "*c" });
}

9. PsiAwareLineWrapPositionStrategy#getPrevious()

Project: intellij-community
File: PsiAwareLineWrapPositionStrategy.java
@Nullable
private static PsiElement getPrevious(@NotNull PsiElement element) {
    PsiElement result = element.getPrevSibling();
    if (result != null) {
        return result;
    }
    PsiElement parent = element.getParent();
    if (parent == null) {
        return null;
    }
    PsiElement parentSibling = null;
    for (; parent != null && parentSibling == null; parent = parent.getParent()) {
        parentSibling = parent.getPrevSibling();
    }
    if (parentSibling == null) {
        return null;
    }
    result = parentSibling.getLastChild();
    return result == null ? parentSibling : result;
}

10. LocalSearchScope#intersection()

Project: intellij-community
File: LocalSearchScope.java
@NotNull
private static LocalSearchScope intersection(@NotNull LocalSearchScope scope1, @NotNull LocalSearchScope scope2) {
    List<PsiElement> result = new ArrayList<PsiElement>();
    final PsiElement[] elements1 = scope1.myScope;
    final PsiElement[] elements2 = scope2.myScope;
    for (final PsiElement element1 : elements1) {
        for (final PsiElement element2 : elements2) {
            final PsiElement element = intersectScopeElements(element1, element2);
            if (element != null) {
                result.add(element);
            }
        }
    }
    return new LocalSearchScope(PsiUtilCore.toPsiElementArray(result), null, scope1.myIgnoreInjectedPsi || scope2.myIgnoreInjectedPsi);
}

11. PsiDocTagValueManipulator#getRangeInElement()

Project: intellij-community
File: PsiDocTagValueManipulator.java
@NotNull
@Override
public TextRange getRangeInElement(@NotNull final PsiDocTag tag) {
    final PsiElement[] elements = tag.getDataElements();
    if (elements.length == 0) {
        final PsiElement name = tag.getNameElement();
        final int offset = name.getStartOffsetInParent() + name.getTextLength();
        return new TextRange(offset, offset);
    }
    final PsiElement first = elements[0];
    final PsiElement last = elements[elements.length - 1];
    return new TextRange(first.getStartOffsetInParent(), last.getStartOffsetInParent() + last.getTextLength());
}

12. SurroundPostfixTemplateBase#expand()

Project: consulo
File: SurroundPostfixTemplateBase.java
@Override
public void expand(@NotNull PsiElement context, @NotNull final Editor editor) {
    PsiElement topmostExpression = myPsiInfo.getTopmostExpression(context);
    PsiElement expression = getWrappedExpression(topmostExpression);
    assert topmostExpression != null;
    PsiElement replace = topmostExpression.replace(expression);
    TextRange range = PostfixTemplatesUtils.surround(getSurrounder(), editor, replace);
    if (range != null) {
        editor.getCaretModel().moveToOffset(range.getStartOffset());
    }
}

13. PsiAwareLineWrapPositionStrategy#getPrevious()

Project: consulo
File: PsiAwareLineWrapPositionStrategy.java
@Nullable
private static PsiElement getPrevious(@NotNull PsiElement element) {
    PsiElement result = element.getPrevSibling();
    if (result != null) {
        return result;
    }
    PsiElement parent = element.getParent();
    if (parent == null) {
        return null;
    }
    PsiElement parentSibling = null;
    for (; parent != null && parentSibling == null; parent = parent.getParent()) {
        parentSibling = parent.getPrevSibling();
    }
    if (parentSibling == null) {
        return null;
    }
    result = parentSibling.getLastChild();
    return result == null ? parentSibling : result;
}

14. TwigUtilIntegrationTest#createPsiElementAndFindString()

Project: idea-php-symfony2-plugin
File: TwigUtilIntegrationTest.java
private PsiElement createPsiElementAndFindString(@NotNull String content, @NotNull IElementType type) {
    PsiElement psiElement = TwigElementFactory.createPsiElement(getProject(), content, type);
    if (psiElement == null) {
        fail();
    }
    final PsiElement[] string = { null };
    psiElement.acceptChildren(new PsiRecursiveElementVisitor() {

        @Override
        public void visitElement(PsiElement element) {
            if (string[0] == null && element.getNode().getElementType() == TwigTokenTypes.STRING_TEXT) {
                string[0] = element;
            }
            super.visitElement(element);
        }
    });
    return string[0];
}

15. TwigTemplateGoToLocalDeclarationHandler#getParentGoto()

Project: idea-php-symfony2-plugin
File: TwigTemplateGoToLocalDeclarationHandler.java
private PsiElement[] getParentGoto(PsiElement psiElement) {
    // find printblock
    PsiElement printBlock = psiElement.getParent();
    if (printBlock == null || !PlatformPatterns.psiElement(TwigElementTypes.PRINT_BLOCK).accepts(printBlock)) {
        return new PsiElement[0];
    }
    // printblock need to be child block statement
    PsiElement blockStatement = printBlock.getParent();
    if (blockStatement == null || !PlatformPatterns.psiElement(TwigElementTypes.BLOCK_STATEMENT).accepts(blockStatement)) {
        return new PsiElement[0];
    }
    // BlockTag is first child of block statement
    PsiElement blockTag = blockStatement.getFirstChild();
    if (!(blockTag instanceof TwigBlockTag)) {
        return new PsiElement[0];
    }
    String blockName = ((TwigBlockTag) blockTag).getName();
    return TwigTemplateGoToDeclarationHandler.getBlockNameGoTo(psiElement.getContainingFile(), blockName);
}

16. CodeInsightUtilCore#findElementInRange()

Project: consulo
File: CodeInsightUtilCore.java
public static <T extends PsiElement> T findElementInRange(@NotNull PsiFile file, int startOffset, int endOffset, @NotNull Class<T> klass, @NotNull Language language) {
    PsiElement element1 = file.getViewProvider().findElementAt(startOffset, language);
    PsiElement element2 = file.getViewProvider().findElementAt(endOffset - 1, language);
    if (element1 instanceof PsiWhiteSpace) {
        startOffset = element1.getTextRange().getEndOffset();
        element1 = file.getViewProvider().findElementAt(startOffset, language);
    }
    if (element2 instanceof PsiWhiteSpace) {
        endOffset = element2.getTextRange().getStartOffset();
        element2 = file.getViewProvider().findElementAt(endOffset - 1, language);
    }
    if (element2 == null || element1 == null)
        return null;
    final PsiElement commonParent = PsiTreeUtil.findCommonParent(element1, element2);
    final T element = ReflectionUtil.isAssignable(klass, commonParent.getClass()) ? (T) commonParent : PsiTreeUtil.getParentOfType(commonParent, klass);
    if (element == null || element.getTextRange().getStartOffset() != startOffset || element.getTextRange().getEndOffset() != endOffset) {
        return null;
    }
    return element;
}

17. LocalSearchScope#intersection()

Project: consulo
File: LocalSearchScope.java
private static LocalSearchScope intersection(LocalSearchScope scope1, LocalSearchScope scope2) {
    List<PsiElement> result = new ArrayList<PsiElement>();
    final PsiElement[] elements1 = scope1.myScope;
    final PsiElement[] elements2 = scope2.myScope;
    for (final PsiElement element1 : elements1) {
        for (final PsiElement element2 : elements2) {
            final PsiElement element = intersectScopeElements(element1, element2);
            if (element != null) {
                result.add(element);
            }
        }
    }
    return new LocalSearchScope(PsiUtilCore.toPsiElementArray(result), null, scope1.myIgnoreInjectedPsi || scope2.myIgnoreInjectedPsi);
}

18. HaxeRefactoringUtil#findOccurrenceUnderCaret()

Project: intellij-haxe
File: HaxeRefactoringUtil.java
@Nullable
public static PsiElement findOccurrenceUnderCaret(List<PsiElement> occurrences, Editor editor) {
    if (occurrences.isEmpty()) {
        return null;
    }
    int offset = editor.getCaretModel().getOffset();
    for (PsiElement occurrence : occurrences) {
        if (occurrence.getTextRange().contains(offset)) {
            return occurrence;
        }
    }
    int line = editor.getDocument().getLineNumber(offset);
    for (PsiElement occurrence : occurrences) {
        if (occurrence.isValid() && editor.getDocument().getLineNumber(occurrence.getTextRange().getStartOffset()) == line) {
            return occurrence;
        }
    }
    for (PsiElement occurrence : occurrences) {
        if (occurrence.isValid()) {
            return occurrence;
        }
    }
    return null;
}

19. PyDemorganIntention#replaceExpression()

Project: intellij-community
File: PyDemorganIntention.java
private static void replaceExpression(String newExpression, PyBinaryExpression expression) {
    PsiElement expressionToReplace = expression;
    String expString = "not(" + newExpression + ')';
    final PsiElement parent = expression.getParent().getParent();
    if (isNegation(parent)) {
        expressionToReplace = parent;
        expString = newExpression;
    }
    final PyElementGenerator generator = PyElementGenerator.getInstance(expression.getProject());
    final PyExpression newCall = generator.createExpressionFromText(LanguageLevel.forElement(expression), expString);
    expressionToReplace.replace(newCall);
// codeStyleManager = expression.getManager().getCodeStyleManager()
// TODO codeStyleManager.reformat(insertedElement)
}

20. PyBaseConvertCollectionLiteralIntention#invoke()

Project: intellij-community
File: PyBaseConvertCollectionLiteralIntention.java
@Override
public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
    final PySequenceExpression literal = findCollectionLiteralUnderCaret(editor, file);
    assert literal != null;
    final PsiElement replacedElement = wrapCollection(literal);
    final PsiElement copy = prepareOriginalElementCopy(replacedElement.copy());
    final TextRange contentRange = getRangeOfContentWithoutBraces(copy);
    final String contentToWrap = contentRange.substring(copy.getText());
    final PyElementGenerator elementGenerator = PyElementGenerator.getInstance(project);
    final PyExpression newLiteral = elementGenerator.createExpressionFromText(LanguageLevel.forElement(file), myLeftBrace + contentToWrap + myRightBrace);
    replacedElement.replace(newLiteral);
}

21. YAMLHashImpl#addNewKey()

Project: intellij-community
File: YAMLHashImpl.java
@Override
protected void addNewKey(@NotNull YAMLKeyValue key) {
    PsiElement anchor = null;
    for (PsiElement child = getLastChild(); child != null; child = child.getPrevSibling()) {
        final IElementType type = child.getNode().getElementType();
        if (type == YAMLTokenTypes.COMMA || type == YAMLTokenTypes.LBRACE) {
            anchor = child;
        }
    }
    addAfter(key, anchor);
    final YAMLFile dummyFile = YAMLElementGenerator.getInstance(getProject()).createDummyYamlWithText("{,}");
    final PsiElement comma = dummyFile.findElementAt(1);
    assert comma != null && comma.getNode().getElementType() == YAMLTokenTypes.COMMA;
    addAfter(comma, key);
}

22. MavenDomTestCase#assertDocumentation()

Project: intellij-community
File: MavenDomTestCase.java
protected void assertDocumentation(String expectedText) throws IOException {
    PsiElement originalElement = getElementAtCaret(myProjectPom);
    PsiElement targetElement = DocumentationManager.getInstance(myProject).findTargetElement(getEditor(), getTestPsiFile(), originalElement);
    DocumentationProvider provider = DocumentationManager.getProviderFromElement(targetElement);
    assertEquals(expectedText, provider.generateDoc(targetElement, originalElement));
    // should work for lookup as well as for tags
    PsiElement lookupElement = provider.getDocumentationElementForLookupItem(PsiManager.getInstance(myProject), originalElement.getText(), originalElement);
    assertSame(targetElement, lookupElement);
}

23. MavenPluginConfigurationDomExtender#isInPluginManagement()

Project: intellij-community
File: MavenPluginConfigurationDomExtender.java
private static boolean isInPluginManagement(MavenDomConfiguration pluginNode) {
    XmlElement xmlElement = pluginNode.getXmlElement();
    if (xmlElement == null)
        return false;
    PsiElement pluginTag = xmlElement.getParent();
    if (pluginTag == null)
        return false;
    PsiElement pluginsTag = pluginTag.getParent();
    if (pluginsTag == null)
        return false;
    PsiElement pluginManagementTag = pluginsTag.getParent();
    return pluginManagementTag instanceof XmlTag && "pluginManagement".equals(((XmlTag) pluginManagementTag).getName());
}

24. PyAssignmentMappingTest#testTuplePack()

Project: intellij-community
File: PyAssignmentMappingTest.java
public void testTuplePack() throws Exception {
    Map<String, PsiElement> marks = loadTest();
    final int SRC_NUM = 2;
    Assert.assertEquals(SRC_NUM + 1, marks.size());
    PsiElement[] srcs = new PsiElement[SRC_NUM];
    for (int i = 0; i < SRC_NUM; i += 1) {
        // ident -> target expr
        PsiElement src = marks.get("<src" + String.valueOf(i + 1) + ">").getParent();
        Assert.assertTrue(src instanceof PyExpression);
        srcs[i] = src;
    }
    // ident -> target expr
    PsiElement dst = marks.get("<dst>").getParent();
    PyAssignmentStatement stmt = (PyAssignmentStatement) dst.getParent();
    List<Pair<PyExpression, PyExpression>> mapping = stmt.getTargetsToValuesMapping();
    Assert.assertEquals(1, mapping.size());
    Pair<PyExpression, PyExpression> pair = mapping.get(0);
    Assert.assertEquals(dst, pair.getFirst());
    for (PsiElement src : srcs) {
        // numeric expr -> tuple
        Assert.assertEquals(src.getParent(), pair.getSecond());
    }
}

25. PyExtractMethodHandler#getStatementsRange()

Project: intellij-community
File: PyExtractMethodHandler.java
@Nullable
private static Couple<PsiElement> getStatementsRange(final PsiElement element1, final PsiElement element2) {
    final PsiElement parent = PsiTreeUtil.findCommonParent(element1, element2);
    if (parent == null) {
        return null;
    }
    final PyElement statementList = PyPsiUtils.getStatementList(parent);
    if (statementList == null) {
        return null;
    }
    final PsiElement statement1 = PyPsiUtils.getParentRightBefore(element1, statementList);
    final PsiElement statement2 = PyPsiUtils.getParentRightBefore(element2, statementList);
    if (statement1 == null || statement2 == null) {
        return null;
    }
    // return elements if they are really first and last elements of statements
    if (element1 == PsiTreeUtil.getDeepestFirst(statement1) && element2 == PyPsiUtils.getPrevSignificantLeaf(PsiTreeUtil.getDeepestLast(statement2), !(element2 instanceof PsiComment))) {
        return Couple.of(statement1, statement2);
    }
    return null;
}

26. PyRemoveDictKeyQuickFix#applyFix()

Project: intellij-community
File: PyRemoveDictKeyQuickFix.java
public void applyFix(@NotNull final Project project, @NotNull final ProblemDescriptor descriptor) {
    final PsiElement element = descriptor.getPsiElement();
    final PyKeyValueExpression expression = PsiTreeUtil.getParentOfType(element, PyKeyValueExpression.class);
    if (expression == null)
        return;
    final PsiElement nextSibling = PsiTreeUtil.skipSiblingsForward(expression, PsiWhiteSpace.class);
    final PsiElement prevSibling = PsiTreeUtil.skipSiblingsBackward(expression, PsiWhiteSpace.class);
    expression.delete();
    if (nextSibling != null && nextSibling.getNode().getElementType().equals(PyTokenTypes.COMMA)) {
        nextSibling.delete();
        return;
    }
    if (prevSibling != null && prevSibling.getNode().getElementType().equals(PyTokenTypes.COMMA)) {
        prevSibling.delete();
    }
}

27. PyRemoveArgumentQuickFix#applyFix()

Project: intellij-community
File: PyRemoveArgumentQuickFix.java
public void applyFix(@NotNull final Project project, @NotNull final ProblemDescriptor descriptor) {
    final PsiElement element = descriptor.getPsiElement();
    if (!(element instanceof PyExpression))
        return;
    final PyExpression expression = (PyExpression) element;
    final PsiElement nextSibling = PsiTreeUtil.skipSiblingsForward(expression, PsiWhiteSpace.class);
    final PsiElement prevSibling = PsiTreeUtil.skipSiblingsBackward(expression, PsiWhiteSpace.class);
    expression.delete();
    if (nextSibling != null && nextSibling.getNode().getElementType().equals(PyTokenTypes.COMMA)) {
        nextSibling.delete();
        return;
    }
    if (prevSibling != null && prevSibling.getNode().getElementType().equals(PyTokenTypes.COMMA)) {
        prevSibling.delete();
    }
}

28. GroovyGenerationInfo#findInsertionAnchor()

Project: intellij-community
File: GroovyGenerationInfo.java
@Override
public PsiElement findInsertionAnchor(@NotNull PsiClass aClass, @NotNull PsiElement leaf) {
    PsiElement parent = aClass instanceof GroovyScriptClass ? aClass.getContainingFile() : ((GrTypeDefinition) aClass).getBody();
    if (parent == null)
        return null;
    if (!PsiTreeUtil.isAncestor(parent, leaf, true)) {
        // we are not in class body
        return null;
    }
    PsiElement element = PsiTreeUtil.findPrevParent(parent, leaf);
    PsiElement lBrace = aClass.getLBrace();
    if (lBrace == null) {
        return null;
    } else {
        PsiElement rBrace = aClass.getRBrace();
        if (!GenerateMembersUtil.isChildInRange(element, lBrace.getNextSibling(), rBrace)) {
            return null;
        }
    }
    return element;
}

29. StringPartInfo#findStringPart()

Project: intellij-community
File: StringPartInfo.java
@Nullable
public static StringPartInfo findStringPart(@NotNull PsiFile file, int startOffset, int endOffset) {
    final PsiElement start = file.findElementAt(startOffset);
    final PsiElement fin = file.findElementAt(endOffset - 1);
    if (start == null || fin == null)
        return null;
    final PsiElement psi = PsiTreeUtil.findCommonParent(start, fin);
    if (psi == null)
        return null;
    GrLiteral literal = findLiteral(psi);
    if (literal != null && checkSelectedRange(startOffset, endOffset, literal)) {
        return new StringPartInfo(literal, new TextRange(startOffset, endOffset));
    }
    return null;
}

30. GrTypeParameterListImpl#appendParenthesesIfNeeded()

Project: intellij-community
File: GrTypeParameterListImpl.java
private void appendParenthesesIfNeeded() {
    PsiElement first = getFirstChild();
    if (first == null) {
        getNode().addLeaf(GroovyTokenTypes.mLT, "<", null);
    }
    PsiElement last = getLastChild();
    if (last.getNode().getElementType() != GroovyTokenTypes.mGT) {
        getNode().addLeaf(GroovyTokenTypes.mGT, ">", null);
    }
    PsiElement parent = getParent();
    if (parent instanceof GrMethod) {
        GrModifierList list = ((GrMethod) parent).getModifierList();
        PsiElement[] modifiers = list.getModifiers();
        if (modifiers.length == 0) {
            list.setModifierProperty(GrModifier.DEF, true);
        }
    }
}

31. ConvertToJBColorQuickFix#applyFix()

Project: intellij-community
File: ConvertToJBColorQuickFix.java
@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
    final PsiElement element = descriptor.getPsiElement();
    final PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory();
    final String newJBColor = String.format("new %s(%s, new java.awt.Color())", JBColor.class.getName(), element.getText());
    final PsiExpression expression = factory.createExpressionFromText(newJBColor, element.getContext());
    final PsiElement newElement = element.replace(expression);
    final PsiElement el = JavaCodeStyleManager.getInstance(project).shortenClassReferences(newElement);
    final int offset = el.getTextOffset() + el.getText().length() - 2;
    final Editor editor = PsiUtilBase.findEditor(el);
    if (editor != null) {
        editor.getCaretModel().moveToOffset(offset);
    }
}

32. UpdatePropertiesFileCopyright#scanFile()

Project: intellij-community
File: UpdatePropertiesFileCopyright.java
protected void scanFile() {
    // PropertiesList
    PsiElement first = getFile().getFirstChild();
    PsiElement last = first;
    PsiElement next = first;
    while (next != null) {
        if (next instanceof PsiComment || next instanceof PsiWhiteSpace) {
            next = getNextSibling(next);
        } else {
            break;
        }
        last = next;
    }
    if (first != null) {
        checkComments(first, last, true);
    }
}

33. XmlEntityDeclImpl#parse()

Project: intellij-community
File: XmlEntityDeclImpl.java
@Override
public PsiElement parse(PsiFile baseFile, EntityContextType contextType, final XmlEntityRef originalElement) {
    PsiElement dep = XmlElement.DEPENDING_ELEMENT.get(getParent());
    PsiElement dependsOnElement = getValueElement(dep instanceof PsiFile ? (PsiFile) dep : baseFile);
    String value = null;
    if (dependsOnElement instanceof XmlAttributeValue) {
        XmlAttributeValue attributeValue = (XmlAttributeValue) dependsOnElement;
        value = attributeValue.getValue();
    } else if (dependsOnElement instanceof PsiFile) {
        PsiFile file = (PsiFile) dependsOnElement;
        value = file.getText();
    }
    if (value == null)
        return null;
    DtdParsing dtdParsing = new DtdParsing(value, XML_ELEMENT_DECL, contextType, baseFile);
    PsiElement generated = dtdParsing.parse().getPsi().getFirstChild();
    if (contextType == EntityContextType.ELEMENT_CONTENT_SPEC && generated instanceof XmlElementContentSpec) {
        generated = generated.getFirstChild();
    }
    setDependsOnElement(generated, dependsOnElement);
    return setOriginalElement(generated, originalElement);
}

34. XmlTagSelectioner#addTagContentSelection()

Project: intellij-community
File: XmlTagSelectioner.java
private static void addTagContentSelection(final PsiElement[] children, final List<TextRange> result, final CharSequence editorText) {
    PsiElement first = null;
    PsiElement last = null;
    for (PsiElement child : children) {
        if (child instanceof XmlToken) {
            XmlToken token = (XmlToken) child;
            if (token.getTokenType() == XmlTokenType.XML_TAG_END) {
                first = token.getNextSibling();
            }
            if (token.getTokenType() == XmlTokenType.XML_END_TAG_START) {
                last = token.getPrevSibling();
                break;
            }
        }
    }
    if (first != null && last != null) {
        result.addAll(expandToWholeLine(editorText, new TextRange(first.getTextRange().getStartOffset(), last.getTextRange().getEndOffset()), false));
    }
}

35. PyQuickDocTest#checkRefDocPair()

Project: intellij-community
File: PyQuickDocTest.java
private void checkRefDocPair() {
    Map<String, PsiElement> marks = loadTest();
    assertEquals(2, marks.size());
    final PsiElement originalElement = marks.get("<the_doc>");
    // ident -> expr
    PsiElement docElement = originalElement.getParent();
    assertTrue(docElement instanceof PyStringLiteralExpression);
    String stringValue = ((PyStringLiteralExpression) docElement).getStringValue();
    assertNotNull(stringValue);
    // ident -> expr
    PsiElement referenceElement = marks.get("<the_ref>").getParent();
    final PyDocStringOwner docOwner = (PyDocStringOwner) ((PyReferenceExpression) referenceElement).getReference().resolve();
    assertNotNull(docOwner);
    assertEquals(docElement, docOwner.getDocStringExpression());
    checkByHTML(myProvider.generateDoc(docOwner, originalElement));
}

36. PyParameterInfoTest#testSimpleFunction()

Project: intellij-community
File: PyParameterInfoTest.java
public void testSimpleFunction() {
    Map<String, PsiElement> marks = loadTest(3);
    PsiElement arg1 = marks.get("<arg1>");
    feignCtrlP(arg1.getTextOffset()).check("a, b, c", new String[] { "a, " });
    feignCtrlP(arg1.getTextOffset() + 1).check("a, b, c", new String[] { "a, " });
    // ^P before arglist gives nothing
    feignCtrlP(arg1.getTextOffset() - 3).assertNotFound();
    PsiElement arg2 = marks.get("<arg2>");
    feignCtrlP(arg2.getTextOffset()).check("a, b, c", new String[] { "b, " });
    feignCtrlP(arg2.getTextOffset() + 1).check("a, b, c", new String[] { "b, " });
    // one too far after arg2, and we came to arg3
    feignCtrlP(arg2.getTextOffset() + 2).check("a, b, c", new String[] { "c" });
    PsiElement arg3 = marks.get("<arg3>");
    feignCtrlP(arg3.getTextOffset()).check("a, b, c", new String[] { "c" });
    feignCtrlP(arg3.getTextOffset() + 1).check("a, b, c", new String[] { "c" });
    // space before arg goes to that arg
    feignCtrlP(arg3.getTextOffset() - 1).check("a, b, c", new String[] { "c" });
    // ^P on a ")" gives nothing
    feignCtrlP(arg3.getTextOffset() + 2).check("a, b, c", new String[] {});
}

37. AbstractMatchingVisitor#matchSonsInAnyOrder()

Project: intellij-community
File: AbstractMatchingVisitor.java
public final boolean matchSonsInAnyOrder(PsiElement element1, PsiElement element2) {
    if (element1 == null && isLeftLooseMatching()) {
        return true;
    }
    if (element2 == null && isRightLooseMatching()) {
        return true;
    }
    if (element1 == null || element2 == null) {
        return element1 == element2;
    }
    PsiElement e = element1.getFirstChild();
    PsiElement e2 = element2.getFirstChild();
    return (e == null && isLeftLooseMatching()) || (e2 == null && isRightLooseMatching()) || matchInAnyOrder(new FilteringNodeIterator(new SiblingNodeIterator(e), getNodeFilter()), new FilteringNodeIterator(new SiblingNodeIterator(e2), getNodeFilter()));
}

38. CollectHighlightsUtil#getElementsInRange()

Project: intellij-community
File: CollectHighlightsUtil.java
@NotNull
public static List<PsiElement> getElementsInRange(@NotNull PsiElement root, final int startOffset, final int endOffset, boolean includeAllParents) {
    PsiElement commonParent = findCommonParent(root, startOffset, endOffset);
    if (commonParent == null)
        return new ArrayList<PsiElement>();
    final List<PsiElement> list = getElementsToHighlight(commonParent, startOffset, endOffset);
    PsiElement parent = commonParent;
    while (parent != null && parent != root) {
        list.add(parent);
        parent = includeAllParents ? parent.getParent() : null;
    }
    list.add(root);
    return list;
}

39. LocalQuickFixOnPsiElement#isAvailable()

Project: intellij-community
File: LocalQuickFixOnPsiElement.java
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);
}

40. LocalQuickFixAndIntentionActionOnPsiElement#isAvailable()

Project: intellij-community
File: LocalQuickFixAndIntentionActionOnPsiElement.java
@Override
public final boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
    if (myStartElement == null)
        return false;
    final PsiElement startElement = myStartElement.getElement();
    final PsiElement endElement = myEndElement == null ? startElement : myEndElement.getElement();
    return startElement != null && endElement != null && startElement.isValid() && (endElement == startElement || endElement.isValid()) && file != null && isAvailable(project, file, startElement, endElement);
}

41. JsonPsiUtil#addProperty()

Project: intellij-community
File: JsonPsiUtil.java
@NotNull
public static PsiElement addProperty(@NotNull JsonObject object, @NotNull JsonProperty property, boolean first) {
    final List<JsonProperty> propertyList = object.getPropertyList();
    if (!first) {
        final JsonProperty lastProperty = ContainerUtil.getLastItem(propertyList);
        if (lastProperty != null) {
            final PsiElement addedProperty = object.addAfter(property, lastProperty);
            object.addBefore(new JsonElementGenerator(object.getProject()).createComma(), addedProperty);
            return addedProperty;
        }
    }
    final PsiElement leftBrace = object.getFirstChild();
    assert hasElementType(leftBrace, JsonElementTypes.L_CURLY);
    final PsiElement addedProperty = object.addAfter(property, leftBrace);
    if (!propertyList.isEmpty()) {
        object.addAfter(new JsonElementGenerator(object.getProject()).createComma(), addedProperty);
    }
    return addedProperty;
}

42. JsonStandardComplianceInspection#findTrailingComma()

Project: intellij-community
File: JsonStandardComplianceInspection.java
@Nullable
private static PsiElement findTrailingComma(@NotNull JsonContainer container, @NotNull IElementType ending) {
    final PsiElement lastChild = container.getLastChild();
    if (lastChild.getNode().getElementType() != ending) {
        return null;
    }
    final PsiElement beforeEnding = PsiTreeUtil.skipSiblingsBackward(lastChild, PsiComment.class, PsiWhiteSpace.class);
    if (beforeEnding != null && beforeEnding.getNode().getElementType() == JsonElementTypes.COMMA) {
        return beforeEnding;
    }
    return null;
}

43. HeaderValuePartImpl#getHighlightingRange()

Project: intellij-community
File: HeaderValuePartImpl.java
@NotNull
@Override
public TextRange getHighlightingRange() {
    int endOffset = getTextRange().getEndOffset();
    PsiElement last = getLastChild();
    while (isSpace(last)) {
        endOffset -= last.getTextLength();
        last = last.getPrevSibling();
    }
    int startOffset = getTextOffset();
    PsiElement first = getFirstChild();
    while (startOffset < endOffset && isSpace(first)) {
        startOffset += first.getTextLength();
        first = first.getNextSibling();
    }
    return new TextRange(startOffset, endOffset);
}

44. GotoImplementationHandlerTest#testMethodReferences()

Project: intellij-community
File: GotoImplementationHandlerTest.java
public void testMethodReferences() {
    PsiFile file = myFixture.addFileToProject("Foo.java", "interface I {void f();}\n" + "class A implements I { public void f(){}}\n" + "class B implements I { public void f(){}}\n" + "class C {\n" + "  void foo(java.util.List<I> l) {l.stream().forEach(I::<caret>f);}" + "}");
    myFixture.configureFromExistingVirtualFile(file.getVirtualFile());
    final PsiElement[] impls = getTargets(file);
    assertEquals(2, impls.length);
    // target are non-deterministic now
    Arrays.sort(impls, ( o1,  o2) -> {
        String name1 = ((PsiMethod) o1).getContainingClass().getName();
        String name2 = ((PsiMethod) o2).getContainingClass().getName();
        return StringUtil.compare(name1, name2, false);
    });
    final PsiElement method = impls[0];
    assertTrue(method instanceof PsiMethod);
    final PsiClass aClass = ((PsiMethod) method).getContainingClass();
    assertNotNull(aClass);
    assertEquals("A", aClass.getName());
}

45. JavaStubPsiElement#getChildren()

Project: intellij-community
File: JavaStubPsiElement.java
@Override
@NotNull
public PsiElement[] getChildren() {
    PsiElement psiChild = getFirstChild();
    if (psiChild == null)
        return EMPTY_ARRAY;
    int count = 0;
    while (psiChild != null) {
        count++;
        psiChild = psiChild.getNextSibling();
    }
    PsiElement[] answer = new PsiElement[count];
    count = 0;
    psiChild = getFirstChild();
    while (psiChild != null) {
        answer[count++] = psiChild;
        psiChild = psiChild.getNextSibling();
    }
    return answer;
}

46. AfterElementFilter#isAcceptable()

Project: intellij-community
File: AfterElementFilter.java
@Override
public boolean isAcceptable(Object element, PsiElement scope) {
    if (!(element instanceof PsiElement))
        return false;
    PsiElement currentChild = getOwnerChild(scope, (PsiElement) element);
    PsiElement currentElement = scope.getFirstChild();
    while (currentElement != null) {
        if (currentElement == currentChild)
            break;
        if (getFilter().isAcceptable(currentElement, scope)) {
            return true;
        }
        currentElement = currentElement.getNextSibling();
    }
    return false;
}

47. ThrowsUsageTargetProvider#getTargets()

Project: intellij-community
File: ThrowsUsageTargetProvider.java
@Override
@Nullable
public UsageTarget[] getTargets(Editor editor, final PsiFile file) {
    if (editor == null || file == null)
        return null;
    PsiElement element = file.findElementAt(TargetElementUtil.adjustOffset(file, editor.getDocument(), editor.getCaretModel().getOffset()));
    if (element == null)
        return null;
    if (element instanceof PsiKeyword && PsiKeyword.THROWS.equals(element.getText())) {
        return new UsageTarget[] { new PsiElement2UsageTargetAdapter(element) };
    }
    final PsiElement parent = element.getParent();
    if (parent instanceof PsiThrowStatement) {
        return new UsageTarget[] { new PsiElement2UsageTargetAdapter(parent) };
    }
    return null;
}

48. SuggestFirstVariableNameMacro#getVariables()

Project: intellij-community
File: SuggestFirstVariableNameMacro.java
@Override
protected PsiElement[] getVariables(Expression[] params, ExpressionContext context) {
    final PsiElement[] variables = super.getVariables(params, context);
    if (variables == null)
        return null;
    final List<PsiElement> result = new ArrayList<PsiElement>();
    final List<String> skip = Arrays.asList("true", "false", "this", "super");
    for (PsiElement variable : variables) {
        if (!skip.contains(variable.getText())) {
            result.add(variable);
        }
    }
    return PsiUtilCore.toPsiElementArray(result);
}

49. PsiMatcherImpl#descendant()

Project: intellij-community
File: PsiMatcherImpl.java
@Override
public PsiMatcher descendant(PsiMatcherExpression e) {
    final PsiElement[] children = myElement.getChildren();
    for (PsiElement child : children) {
        myElement = child;
        final Boolean res = e == null ? Boolean.TRUE : e.match(myElement);
        if (res == Boolean.TRUE) {
            return this;
        } else if (res == Boolean.FALSE) {
            final PsiMatcher grandChild = descendant(e);
            if (grandChild != NullPsiMatcherImpl.INSTANCE)
                return grandChild;
        }
    }
    return NullPsiMatcherImpl.INSTANCE;
}

50. UnnecessaryModuleDependencyAnnotator#onMarkReferenced()

Project: intellij-community
File: UnnecessaryModuleDependencyAnnotator.java
@Override
public void onMarkReferenced(RefElement refWhat, RefElement refFrom, boolean referencedFromClassInitializer) {
    final PsiElement onElement = refWhat.getElement();
    final PsiElement fromElement = refFrom.getElement();
    if (onElement != null && fromElement != null) {
        final Module onModule = ModuleUtilCore.findModuleForPsiElement(onElement);
        final Module fromModule = ModuleUtilCore.findModuleForPsiElement(fromElement);
        if (onModule != null && fromModule != null && onModule != fromModule) {
            final RefModule refModule = myManager.getRefModule(fromModule);
            if (refModule != null) {
                Set<Module> modules = refModule.getUserData(DEPENDENCIES);
                if (modules == null) {
                    modules = new HashSet<Module>();
                    refModule.putUserData(DEPENDENCIES, modules);
                }
                modules.add(onModule);
            }
        }
    }
}

51. FormatterUtil#findPreviousWhiteSpace()

Project: consulo
File: FormatterUtil.java
@Nullable
private static ASTNode findPreviousWhiteSpace(final ASTNode leafElement, final IElementType whiteSpaceTokenType) {
    final int offset = leafElement.getTextRange().getStartOffset() - 1;
    if (offset < 0)
        return null;
    final PsiElement psiElement = SourceTreeToPsiMap.treeElementToPsi(leafElement);
    if (psiElement == null) {
        return null;
    }
    final PsiElement found = psiElement.getContainingFile().findElementAt(offset);
    if (found == null)
        return null;
    final ASTNode treeElement = found.getNode();
    if (treeElement != null && treeElement.getElementType() == whiteSpaceTokenType)
        return treeElement;
    return null;
}

52. GenericDynamicContextProvider#getOffset()

Project: consulo
File: GenericDynamicContextProvider.java
@Override
public int getOffset(PsiElement element, int offset, String elementText) {
    final PsiElement[] children = element.getChildren();
    for (PsiElement child : children) {
        if (isDynamic(child)) {
            final int i = child.getStartOffsetInParent();
            if (i == offset) {
                // dynamic context?
                final PsiElement next = child.getNextSibling();
                if (next == null || !next.getText().startsWith("/")) {
                    return -1;
                }
                offset = next.getStartOffsetInParent();
            } else {
                final int pos = PathReferenceProviderBase.getLastPosOfURL(offset, elementText);
                if (pos == -1 || pos > i) {
                    return -1;
                }
                return offset;
            }
        }
    }
    return offset;
}

53. NamedElementDuplicateHandler#findNameIdentifier()

Project: consulo
File: NamedElementDuplicateHandler.java
@Nullable
private static PsiElement findNameIdentifier(Editor editor, PsiFile file, TextRange toDuplicate) {
    int nonWs = CharArrayUtil.shiftForward(editor.getDocument().getCharsSequence(), toDuplicate.getStartOffset(), "\n\t ");
    PsiElement psi = file.findElementAt(nonWs);
    PsiElement named = null;
    while (psi != null) {
        TextRange range = psi.getTextRange();
        if (range == null || psi instanceof PsiFile || !toDuplicate.contains(psi.getTextRange())) {
            break;
        }
        if (psi instanceof PsiNameIdentifierOwner) {
            named = ((PsiNameIdentifierOwner) psi).getNameIdentifier();
        }
        psi = psi.getParent();
    }
    return named;
}

54. PsiViewerDialog#resolve()

Project: consulo
File: PsiViewerDialog.java
@Nullable
private PsiElement resolve(int index) {
    final PsiElement element = getPsiElement();
    if (element == null)
        return null;
    @SuppressWarnings("unchecked") Map<PsiElement, PsiElement[]> map = (Map<PsiElement, PsiElement[]>) myRefs.getClientProperty(REFS_CACHE);
    if (map == null) {
        myRefs.putClientProperty(REFS_CACHE, map = new HashMap<PsiElement, PsiElement[]>());
    }
    PsiElement[] cache = map.get(element);
    if (cache == null) {
        final PsiReference[] references = element.getReferences();
        cache = new PsiElement[references.length];
        for (int i = 0; i < references.length; i++) {
            cache[i] = references[i].resolve();
        }
        map.put(element, cache);
    }
    return index >= cache.length ? null : cache[index];
}

55. StructureViewElementWrapper#getNavigatableInTemplateLanguageFile()

Project: consulo
File: StructureViewElementWrapper.java
@Nullable
private Navigatable getNavigatableInTemplateLanguageFile() {
    PsiElement element = (PsiElement) myTreeElement.getValue();
    if (element == null)
        return null;
    int offset = element.getTextRange().getStartOffset();
    final Language dataLanguage = ((TemplateLanguageFileViewProvider) myMainFile.getViewProvider()).getTemplateDataLanguage();
    final PsiFile dataFile = myMainFile.getViewProvider().getPsi(dataLanguage);
    if (dataFile == null)
        return null;
    PsiElement tlElement = dataFile.findElementAt(offset);
    while (true) {
        if (tlElement == null || tlElement.getTextRange().getStartOffset() != offset)
            break;
        if (tlElement instanceof Navigatable) {
            return (Navigatable) tlElement;
        }
        tlElement = tlElement.getParent();
    }
    return null;
}

56. AbstractDocumentationTooltipAction#getDocInfo()

Project: consulo
File: AbstractDocumentationTooltipAction.java
@Nullable
private Pair<PsiElement, /* doc anchor */
PsiElement> getDocInfo() {
    WeakReference<PsiElement> docAnchorRef = myDocAnchor;
    if (docAnchorRef == null) {
        return null;
    }
    PsiElement docAnchor = docAnchorRef.get();
    if (docAnchor == null) {
        return null;
    }
    WeakReference<PsiElement> originalElementRef = myOriginalElement;
    if (originalElementRef == null) {
        return null;
    }
    PsiElement originalElement = originalElementRef.get();
    if (originalElement == null) {
        return null;
    }
    return Pair.create(docAnchor, originalElement);
}

57. ParameterInfoController#getPrevOrNextParameterOffset()

Project: consulo
File: ParameterInfoController.java
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;
}

58. AbstractElementSignatureProvider#restoreElementInternal()

Project: consulo
File: AbstractElementSignatureProvider.java
@Nullable
protected static <T extends PsiNamedElement> T restoreElementInternal(@NotNull PsiElement parent, String name, int index, @NotNull Class<T> hisClass) {
    PsiElement[] children = parent.getChildren();
    for (PsiElement child : children) {
        if (ReflectionUtil.isAssignable(hisClass, child.getClass())) {
            T namedChild = hisClass.cast(child);
            final String childName = namedChild.getName();
            if (Comparing.equal(name, childName)) {
                if (index == 0) {
                    return namedChild;
                }
                index--;
            }
        }
    }
    return null;
}

59. AbstractElementSignatureProvider#getChildIndex()

Project: consulo
File: AbstractElementSignatureProvider.java
protected static <T extends PsiNamedElement> int getChildIndex(T element, PsiElement parent, String name, Class<T> hisClass) {
    PsiElement[] children = parent.getChildren();
    int index = 0;
    for (PsiElement child : children) {
        if (ReflectionUtil.isAssignable(hisClass, child.getClass())) {
            T namedChild = hisClass.cast(child);
            final String childName = namedChild.getName();
            if (Comparing.equal(name, childName)) {
                if (namedChild.equals(element)) {
                    return index;
                }
                index++;
            }
        }
    }
    return index;
}

60. EnterAfterUnmatchedBraceHandler#calculateOffsetToInsertClosingBrace()

Project: consulo
File: EnterAfterUnmatchedBraceHandler.java
/**
   * Current handler inserts closing curly brace (right brace) if necessary. There is a possible case that it should be located
   * more than one line forward.
   * <p/>
   * <b>Example</b> 
   * <pre>
   *     if (test1()) {
   *     } else {<caret> if (test2()) {
   *         foo();
   *     }
   * </pre>
   * <p/>
   * We want to get this after the processing:
   * <pre>
   *     if (test1()) {
   *     } else {
   *         if (test2()) {
   *             foo();
   *         }
   *     }
   * </pre>
   * I.e. closing brace should be inserted two lines below current caret line. Hence, we need to calculate correct offset
   * to use for brace inserting. This method is responsible for that.
   * <p/>
   * In essence it inspects PSI structure and finds PSE elements with the max length that starts at caret offset. End offset
   * of that element is used as an insertion point.
   * 
   * @param file    target PSI file
   * @param text    text from the given file
   * @param offset  target offset where line feed will be inserted
   * @return        offset to use for inserting closing brace
   */
private static int calculateOffsetToInsertClosingBrace(PsiFile file, CharSequence text, final int offset) {
    PsiElement element = PsiUtilCore.getElementAtOffset(file, offset);
    ASTNode node = element.getNode();
    if (node != null && node.getElementType() == TokenType.WHITE_SPACE) {
        return CharArrayUtil.shiftForwardUntil(text, offset, "\n");
    }
    for (PsiElement parent = element.getParent(); parent != null; parent = parent.getParent()) {
        ASTNode parentNode = parent.getNode();
        if (parentNode == null || parentNode.getStartOffset() != offset) {
            break;
        }
        element = parent;
    }
    if (element.getTextOffset() != offset) {
        return CharArrayUtil.shiftForwardUntil(text, offset, "\n");
    } else {
        return element.getTextRange().getEndOffset();
    }
}

61. PsiMatcherImpl#descendant()

Project: consulo
File: PsiMatcherImpl.java
@Override
public PsiMatcher descendant(PsiMatcherExpression e) {
    final PsiElement[] children = myElement.getChildren();
    for (PsiElement child : children) {
        myElement = child;
        final Boolean res = e == null ? Boolean.TRUE : e.match(myElement);
        if (res == Boolean.TRUE) {
            return this;
        } else if (res == Boolean.FALSE) {
            final PsiMatcher grandChild = descendant(e);
            if (grandChild != NullPsiMatcherImpl.INSTANCE)
                return grandChild;
        }
    }
    return NullPsiMatcherImpl.INSTANCE;
}

62. CreateElementActionBase#actionPerformed()

Project: consulo
File: CreateElementActionBase.java
@RequiredDispatchThread
@Override
public final void actionPerformed(@NotNull final AnActionEvent e) {
    final IdeView view = e.getData(LangDataKeys.IDE_VIEW);
    if (view == null) {
        return;
    }
    final Project project = e.getProject();
    final PsiDirectory dir = view.getOrChooseDirectory();
    if (dir == null)
        return;
    final PsiElement[] createdElements = invokeDialog(project, dir);
    for (PsiElement createdElement : createdElements) {
        view.selectElement(createdElement);
    }
}

63. BaseElementAtCaretIntentionAction#isAvailable()

Project: consulo
File: BaseElementAtCaretIntentionAction.java
@Override
public final boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
    if (!file.getManager().isInProject(file))
        return false;
    useElementToTheLeft = false;
    final PsiElement elementToTheRight = getElementToTheRight(editor, file);
    if (elementToTheRight == null) {
        return false;
    }
    if (isAvailable(project, editor, elementToTheRight)) {
        return true;
    }
    final PsiElement elementToTheLeft = getElementToTheLeft(editor, file);
    if (elementToTheLeft != null && isAvailable(project, editor, elementToTheLeft)) {
        useElementToTheLeft = true;
        return true;
    }
    return false;
}

64. StatementUpDownMover#getElementRange()

Project: consulo
File: StatementUpDownMover.java
@Nullable
protected static Pair<PsiElement, PsiElement> getElementRange(@NotNull Editor editor, @NotNull PsiFile file, @NotNull LineRange range) {
    final int startOffset = editor.logicalPositionToOffset(new LogicalPosition(range.startLine, 0));
    PsiElement startingElement = firstNonWhiteElement(startOffset, file, true);
    if (startingElement == null)
        return null;
    final int endOffset = editor.logicalPositionToOffset(new LogicalPosition(range.endLine, 0)) - 1;
    PsiElement endingElement = firstNonWhiteElement(endOffset, file, false);
    if (endingElement == null)
        return null;
    if (PsiTreeUtil.isAncestor(startingElement, endingElement, false) || startingElement.getTextRange().getEndOffset() <= endingElement.getTextRange().getStartOffset()) {
        return Pair.create(startingElement, endingElement);
    }
    if (PsiTreeUtil.isAncestor(endingElement, startingElement, false)) {
        return Pair.create(startingElement, endingElement);
    }
    return null;
}

65. UnfocusedNameIdentifier#shouldFocusLookup()

Project: consulo
File: UnfocusedNameIdentifier.java
@NotNull
@Override
public ThreeState shouldFocusLookup(@NotNull CompletionParameters parameters) {
    final PsiElement position = parameters.getPosition();
    final PsiElement parent = position.getParent();
    if (parent instanceof PsiNameIdentifierOwner) {
        final PsiElement nameIdentifier = ((PsiNameIdentifierOwner) parent).getNameIdentifier();
        if (nameIdentifier == position) {
            return ThreeState.NO;
        }
        if (nameIdentifier != null && position.getTextRange().equals(nameIdentifier.getTextRange())) {
            //sometimes name identifiers are non-physical (e.g. Groovy)
            return ThreeState.NO;
        }
    }
    return ThreeState.UNSURE;
}

66. YamlHelper#getPreviousSequenceItemAsText()

Project: idea-php-symfony2-plugin
File: YamlHelper.java
/**
     * Returns "@foo" value of ["@foo", "fo<caret>o"]
     */
@Nullable
public static String getPreviousSequenceItemAsText(@NotNull PsiElement psiElement) {
    PsiElement yamlScalar = psiElement.getParent();
    if (!(yamlScalar instanceof YAMLScalar)) {
        return null;
    }
    PsiElement yamlSequence = yamlScalar.getParent();
    if (!(yamlSequence instanceof YAMLSequenceItem)) {
        return null;
    }
    // @TODO: catch new lexer error on empty item [<caret>,@foo] "PsiErrorElement:Sequence item expected"
    YAMLSequenceItem prevSequenceItem = PsiTreeUtil.getPrevSiblingOfType(yamlSequence, YAMLSequenceItem.class);
    if (prevSequenceItem == null) {
        return null;
    }
    YAMLValue value = prevSequenceItem.getValue();
    if (!(value instanceof YAMLScalar)) {
        return null;
    }
    return ((YAMLScalar) value).getTextValue();
}

67. YamlHelper#getChildrenFix()

Project: idea-php-symfony2-plugin
File: YamlHelper.java
/**
     * getChildren eg on YamlArray is empty, provide workaround
     */
public static PsiElement[] getChildrenFix(PsiElement psiElement) {
    List<PsiElement> psiElements = new ArrayList<PsiElement>();
    PsiElement startElement = psiElement.getFirstChild();
    if (startElement == null) {
        return psiElements.toArray(new PsiElement[psiElements.size()]);
    }
    psiElements.add(startElement);
    for (PsiElement child = psiElement.getFirstChild().getNextSibling(); child != null; child = child.getNextSibling()) {
        psiElements.add(child);
    }
    return psiElements.toArray(new PsiElement[psiElements.size()]);
}

68. TranslationInsertUtil#findEol()

Project: idea-php-symfony2-plugin
File: TranslationInsertUtil.java
/**
     * Remove TODO; moved to core
     */
@Deprecated
@NotNull
public static String findEol(@NotNull PsiElement psiElement) {
    for (PsiElement child : YamlHelper.getChildrenFix(psiElement)) {
        if (PlatformPatterns.psiElement(YAMLTokenTypes.EOL).accepts(child)) {
            return child.getText();
        }
    }
    PsiElement[] indentPsiElements = PsiTreeUtil.collectElements(psiElement.getContainingFile(), new PsiElementFilter() {

        @Override
        public boolean isAccepted(PsiElement element) {
            return PlatformPatterns.psiElement(YAMLTokenTypes.EOL).accepts(element);
        }
    });
    if (indentPsiElements.length > 0) {
        return indentPsiElements[0].getText();
    }
    return "\n";
}

69. TranslationReference#multiResolve()

Project: idea-php-symfony2-plugin
File: TranslationReference.java
@NotNull
@Override
public ResolveResult[] multiResolve(boolean incompleteCode) {
    List<ResolveResult> results = new ArrayList<ResolveResult>();
    PsiElement[] psiElements = TranslationUtil.getTranslationPsiElements(this.element.getProject(), this.element.getContents(), this.domainName);
    for (PsiElement psiElement : psiElements) {
        results.add(new PsiElementResolveResult(psiElement));
    }
    return results.toArray(new ResolveResult[results.size()]);
}

70. TwigControllerLineMarkerProvider#attachBlockOverwrites()

Project: idea-php-symfony2-plugin
File: TwigControllerLineMarkerProvider.java
@Nullable
private LineMarkerInfo attachBlockOverwrites(PsiElement psiElement) {
    PsiElement[] blocks = TwigTemplateGoToDeclarationHandler.getBlockGoTo(psiElement);
    if (blocks.length == 0) {
        return null;
    }
    List<GotoRelatedItem> gotoRelatedItems = new ArrayList<GotoRelatedItem>();
    for (PsiElement blockTag : blocks) {
        gotoRelatedItems.add(new RelatedPopupGotoLineMarker.PopupGotoRelatedItem(blockTag, TwigUtil.getPresentableTemplateName(getTemplateFilesByName(psiElement.getProject()).getTemplates(), blockTag, true)).withIcon(TwigIcons.TwigFileIcon, Symfony2Icons.TWIG_LINE_MARKER));
    }
    // single item has no popup
    String title = "Overwrites";
    if (gotoRelatedItems.size() == 1) {
        String customName = gotoRelatedItems.get(0).getCustomName();
        if (customName != null) {
            title = title.concat(": ").concat(customName);
        }
    }
    return new LineMarkerInfo<PsiElement>(psiElement, psiElement.getTextOffset(), PhpIcons.OVERRIDES, 6, new ConstantFunction<PsiElement, String>(title), new RelatedPopupGotoLineMarker.NavigationHandler(gotoRelatedItems));
}

71. FormOptionsUtil#getFormExtensionsKeysTargets()

Project: idea-php-symfony2-plugin
File: FormOptionsUtil.java
@NotNull
public static Collection<PsiElement> getFormExtensionsKeysTargets(StringLiteralExpression psiElement, String... formTypes) {
    Map<String, FormOption> test = FormOptionsUtil.getFormExtensionKeys(psiElement.getProject(), formTypes);
    String value = psiElement.getContents();
    if (!test.containsKey(value)) {
        return Collections.emptyList();
    }
    // @TODO: use core method find method
    String className = test.get(value).getFormClass().getPhpClass().getPresentableFQN();
    PsiElement[] psiElements = PhpElementsUtil.getPsiElementsBySignature(psiElement.getProject(), "#M#C\\" + className + ".setDefaultOptions");
    if (psiElements.length == 0) {
        return Collections.emptyList();
    }
    PsiElement keyValue = PhpElementsUtil.findArrayKeyValueInsideReference(psiElements[0], "setDefaults", value);
    if (keyValue != null) {
        return Arrays.asList(keyValue);
    }
    return Collections.emptyList();
}

72. PsiElementUtils#isFunctionReference()

Project: idea-php-laravel-plugin
File: PsiElementUtils.java
public static boolean isFunctionReference(@NotNull PsiElement psiElement, @NotNull String functionName, int parameterIndex) {
    PsiElement parameterList = psiElement.getParent();
    if (!(parameterList instanceof ParameterList)) {
        return false;
    }
    ParameterBag index = PhpElementsUtil.getCurrentParameterIndex(psiElement);
    if (index == null || index.getIndex() != parameterIndex) {
        return false;
    }
    PsiElement functionCall = parameterList.getParent();
    if (!(functionCall instanceof FunctionReference)) {
        return false;
    }
    return functionName.equals(((FunctionReference) functionCall).getName());
}

73. PsiElementUtils#getChildrenFix()

Project: idea-php-laravel-plugin
File: PsiElementUtils.java
/**
     * getChildren fixed helper
     */
public static PsiElement[] getChildrenFix(PsiElement psiElement) {
    List<PsiElement> psiElements = new ArrayList<PsiElement>();
    PsiElement startElement = psiElement.getFirstChild();
    if (startElement == null) {
        return new PsiElement[0];
    }
    psiElements.add(startElement);
    for (PsiElement child = psiElement.getFirstChild().getNextSibling(); child != null; child = child.getNextSibling()) {
        psiElements.add(child);
    }
    return psiElements.toArray(new PsiElement[psiElements.size()]);
}

74. MoveDirectoryWithClassesProcessor#collectFiles2Move()

Project: consulo
File: MoveDirectoryWithClassesProcessor.java
private static void collectFiles2Move(Map<PsiFile, TargetDirectoryWrapper> files2Move, PsiDirectory directory, PsiDirectory rootDirectory, @NotNull TargetDirectoryWrapper targetDirectory) {
    final PsiElement[] children = directory.getChildren();
    final String relativePath = VfsUtilCore.getRelativePath(directory.getVirtualFile(), rootDirectory.getVirtualFile(), '/');
    final TargetDirectoryWrapper newTargetDirectory = relativePath.length() == 0 ? targetDirectory : targetDirectory.findOrCreateChild(relativePath);
    for (PsiElement child : children) {
        if (child instanceof PsiFile) {
            files2Move.put((PsiFile) child, newTargetDirectory);
        } else if (child instanceof PsiDirectory) {
            collectFiles2Move(files2Move, (PsiDirectory) child, directory, newTargetDirectory);
        }
    }
}

75. SimpleDuplicatesFinder#isDuplicateFragment()

Project: consulo
File: SimpleDuplicatesFinder.java
@Nullable
protected SimpleMatch isDuplicateFragment(@NotNull final PsiElement candidate) {
    for (PsiElement pattern : myPattern) {
        if (PsiTreeUtil.isAncestor(pattern, candidate, false))
            return null;
    }
    PsiElement sibling = candidate;
    final ArrayList<PsiElement> candidates = new ArrayList<PsiElement>();
    for (int i = 0; i != myPattern.size(); ++i) {
        if (sibling == null)
            return null;
        candidates.add(sibling);
        sibling = PsiTreeUtil.skipSiblingsForward(sibling, PsiWhiteSpace.class, PsiComment.class);
    }
    if (myPattern.size() != candidates.size())
        return null;
    if (candidates.size() <= 0)
        return null;
    final SimpleMatch match = new SimpleMatch(candidates.get(0), candidates.get(candidates.size() - 1));
    for (int i = 0; i < myPattern.size(); i++) {
        if (!matchPattern(myPattern.get(i), candidates.get(i), match))
            return null;
    }
    return match;
}

76. SimpleDuplicatesFinder#findPatternOccurrences()

Project: consulo
File: SimpleDuplicatesFinder.java
private void findPatternOccurrences(@NotNull final List<SimpleMatch> array, @NotNull final PsiElement scope, @NotNull final PsiElement generatedMethod) {
    if (scope == generatedMethod)
        return;
    final PsiElement[] children = scope.getChildren();
    for (PsiElement child : children) {
        final SimpleMatch match = isDuplicateFragment(child);
        if (match != null) {
            array.add(match);
            continue;
        }
        findPatternOccurrences(array, child, generatedMethod);
    }
}

77. ClassRefactoringHandlerBase#invoke()

Project: consulo
File: ClassRefactoringHandlerBase.java
@Override
public void invoke(@NotNull Project project, Editor editor, PsiFile file, DataContext dataContext) {
    int offset = editor.getCaretModel().getOffset();
    editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);
    final PsiElement position = file.findElementAt(offset);
    PsiElement element = position;
    while (true) {
        if (element == null || element instanceof PsiFile) {
            String message = RefactoringBundle.getCannotRefactorMessage(getInvalidPositionMessage());
            CommonRefactoringUtil.showErrorHint(project, editor, message, getTitle(), getHelpId());
            return;
        }
        if (!CommonRefactoringUtil.checkReadOnlyStatus(project, element))
            return;
        if (acceptsElement(element)) {
            invoke(project, new PsiElement[] { position }, dataContext);
            return;
        }
        element = element.getParent();
    }
}

78. CollectHighlightsUtil#getElementsInRange()

Project: consulo
File: CollectHighlightsUtil.java
@NotNull
public static List<PsiElement> getElementsInRange(@NotNull PsiElement root, final int startOffset, final int endOffset, boolean includeAllParents) {
    PsiElement commonParent = findCommonParent(root, startOffset, endOffset);
    if (commonParent == null)
        return new ArrayList<PsiElement>();
    final List<PsiElement> list = getElementsToHighlight(commonParent, startOffset, endOffset);
    PsiElement parent = commonParent;
    while (parent != null && parent != root) {
        list.add(parent);
        parent = includeAllParents ? parent.getParent() : null;
    }
    list.add(root);
    return list;
}

79. LocalQuickFixOnPsiElement#isAvailable()

Project: consulo
File: LocalQuickFixOnPsiElement.java
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);
}

80. LocalQuickFixAndIntentionActionOnPsiElement#isAvailable()

Project: consulo
File: LocalQuickFixAndIntentionActionOnPsiElement.java
@Override
public final boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
    if (myStartElement == null)
        return false;
    final PsiElement startElement = myStartElement.getElement();
    final PsiElement endElement = myEndElement == null ? startElement : myEndElement.getElement();
    return startElement != null && endElement != null && startElement.isValid() && (endElement == startElement || endElement.isValid()) && file != null && isAvailable(project, file, startElement, endElement);
}

81. DependenciesOptimizer#sortArray()

Project: buck
File: DependenciesOptimizer.java
private static void sortArray(BuckValueArray array) {
    BuckArrayElements arrayElements = array.getArrayElements();
    PsiElement[] arrayValues = arrayElements.getChildren();
    Arrays.sort(arrayValues, new Comparator<PsiElement>() {

        @Override
        public int compare(PsiElement e1, PsiElement e2) {
            return compareDependencyStrings(e1.getText(), e2.getText());
        }
    });
    PsiElement[] oldValues = new PsiElement[arrayValues.length];
    for (int i = 0; i < arrayValues.length; ++i) {
        oldValues[i] = arrayValues[i].copy();
    }
    for (int i = 0; i < arrayValues.length; ++i) {
        arrayElements.getChildren()[i].replace(oldValues[i]);
    }
}

82. BuckBuildUtil#getPropertyValue()

Project: buck
File: BuckBuildUtil.java
/**
   * Get the value of a property in a specific buck rule body.
   * TODO(#7908675): We should use Buck's own classes for it.
   */
public static String getPropertyValue(BuckRuleBody body, String name) {
    if (body == null) {
        return null;
    }
    PsiElement[] children = body.getChildren();
    for (PsiElement child : children) {
        if (BuckPsiUtils.testType(child, BuckTypes.PROPERTY)) {
            PsiElement lvalue = child.getFirstChild();
            PsiElement propertyName = lvalue.getFirstChild();
            if (propertyName != null && propertyName.getText().equals(name)) {
                BuckExpression expression = (BuckExpression) BuckPsiUtils.findChildWithType(child, BuckTypes.EXPRESSION);
                return expression != null ? BuckPsiUtils.getStringValueFromExpression(expression) : null;
            }
        }
    }
    return null;
}

83. BuckBuildUtil#extractBuckTarget()

Project: buck
File: BuckBuildUtil.java
/**
   * Get the buck target from a buck file.
   * TODO(#7908675): We should use Buck's own classes for it.
   */
public static String extractBuckTarget(Project project, VirtualFile file) {
    BuckFile buckFile = (BuckFile) PsiManager.getInstance(project).findFile(file);
    if (buckFile == null) {
        return null;
    }
    PsiElement[] children = buckFile.getChildren();
    for (PsiElement child : children) {
        if (child.getNode().getElementType() == BuckTypes.RULE_BLOCK) {
            PsiElement ruleName = child.getFirstChild();
            // Find rule "project_config"
            if (ruleName != null && BuckPsiUtils.testType(ruleName, BuckTypes.RULE_NAME) && ruleName.getText().equals(PROJECT_CONFIG_RULE_NAME)) {
                // Find property "src_target"
                PsiElement bodyElement = BuckPsiUtils.findChildWithType(child, BuckTypes.RULE_BODY);
                return getPropertyValue((BuckRuleBody) bodyElement, SRC_TARGET_PROPERTY_NAME);
            }
        }
    }
    return null;
}

84. FormatterUtil#findPreviousWhiteSpace()

Project: intellij-community
File: FormatterUtil.java
@Nullable
private static ASTNode findPreviousWhiteSpace(final ASTNode leafElement, final IElementType whiteSpaceTokenType) {
    final int offset = leafElement.getTextRange().getStartOffset() - 1;
    if (offset < 0)
        return null;
    final PsiElement psiElement = SourceTreeToPsiMap.treeElementToPsi(leafElement);
    if (psiElement == null) {
        return null;
    }
    final PsiElement found = psiElement.getContainingFile().findElementAt(offset);
    if (found == null)
        return null;
    final ASTNode treeElement = found.getNode();
    if (treeElement != null && treeElement.getElementType() == whiteSpaceTokenType)
        return treeElement;
    return null;
}

85. GenericDynamicContextProvider#getOffset()

Project: intellij-community
File: GenericDynamicContextProvider.java
@Override
public int getOffset(PsiElement element, int offset, String elementText) {
    final PsiElement[] children = element.getChildren();
    for (PsiElement child : children) {
        if (isDynamic(child)) {
            final int i = child.getStartOffsetInParent();
            if (i == offset) {
                // dynamic context?
                final PsiElement next = child.getNextSibling();
                if (next == null || !next.getText().startsWith("/")) {
                    return -1;
                }
                offset = next.getStartOffsetInParent();
            } else {
                final int pos = PathReferenceProviderBase.getLastPosOfURL(offset, elementText);
                if (pos == -1 || pos > i) {
                    return -1;
                }
                return offset;
            }
        }
    }
    return offset;
}

86. NamedElementDuplicateHandler#findNameIdentifier()

Project: intellij-community
File: NamedElementDuplicateHandler.java
@Nullable
private static PsiElement findNameIdentifier(Editor editor, PsiFile file, TextRange toDuplicate) {
    int nonWs = CharArrayUtil.shiftForward(editor.getDocument().getCharsSequence(), toDuplicate.getStartOffset(), "\n\t ");
    PsiElement psi = file.findElementAt(nonWs);
    PsiElement named = null;
    while (psi != null) {
        TextRange range = psi.getTextRange();
        if (range == null || psi instanceof PsiFile || !toDuplicate.contains(psi.getTextRange())) {
            break;
        }
        if (psi instanceof PsiNameIdentifierOwner) {
            named = ((PsiNameIdentifierOwner) psi).getNameIdentifier();
        }
        psi = psi.getParent();
    }
    return named;
}

87. FlipCommaIntention#swapAtComma()

Project: intellij-community
File: FlipCommaIntention.java
private static void swapAtComma(@NotNull PsiElement comma) {
    PsiElement prev = smartAdvance(comma, false);
    PsiElement next = smartAdvance(comma, true);
    if (prev != null && next != null) {
        if (Flipper.tryFlip(prev, next)) {
            return;
        }
        PsiElement copy = prev.copy();
        prev.replace(next);
        next.replace(copy);
    }
}

88. FindUsagesManager#startFindUsages()

Project: intellij-community
File: FindUsagesManager.java
private void startFindUsages(@NotNull FindUsagesOptions findUsagesOptions, @NotNull FindUsagesHandler handler, PsiFile scopeFile, FileEditor editor) {
    boolean singleFile = scopeFile != null;
    clearFindingNextUsageInFile();
    LOG.assertTrue(handler.getPsiElement().isValid());
    PsiElement[] primaryElements = handler.getPrimaryElements();
    checkNotNull(primaryElements, handler, "getPrimaryElements()");
    PsiElement[] secondaryElements = handler.getSecondaryElements();
    checkNotNull(secondaryElements, handler, "getSecondaryElements()");
    if (singleFile) {
        editor.putUserData(KEY_START_USAGE_AGAIN, null);
        findUsagesInEditor(primaryElements, secondaryElements, handler, scopeFile, FileSearchScope.FROM_START, findUsagesOptions.clone(), editor);
    } else {
        boolean skipResultsWithOneUsage = FindSettings.getInstance().isSkipResultsWithOneUsage();
        findUsages(primaryElements, secondaryElements, handler, findUsagesOptions, skipResultsWithOneUsage);
    }
}

89. FindUsagesManager#findUsageInFile()

Project: intellij-community
File: FindUsagesManager.java
private boolean findUsageInFile(@NotNull FileEditor editor, @NotNull FileSearchScope direction) {
    ApplicationManager.getApplication().assertIsDispatchThread();
    if (myLastSearchInFileData == null)
        return false;
    PsiElement[] primaryElements = myLastSearchInFileData.getPrimaryElements();
    PsiElement[] secondaryElements = myLastSearchInFileData.getSecondaryElements();
    if (primaryElements.length == 0) {
        //all elements have been invalidated
        Messages.showMessageDialog(myProject, FindBundle.message("find.searched.elements.have.been.changed.error"), FindBundle.message("cannot.search.for.usages.title"), Messages.getInformationIcon());
        //clearFindingNextUsageInFile();
        return false;
    }
    //todo
    TextEditor textEditor = (TextEditor) editor;
    Document document = textEditor.getEditor().getDocument();
    PsiFile psiFile = PsiDocumentManager.getInstance(myProject).getPsiFile(document);
    if (psiFile == null)
        return false;
    final FindUsagesHandler handler = getFindUsagesHandler(primaryElements[0], false);
    if (handler == null)
        return false;
    findUsagesInEditor(primaryElements, secondaryElements, handler, psiFile, direction, myLastSearchInFileData.myOptions, textEditor);
    return true;
}

90. GotoImplementationHandler#getSourceAndTargetElements()

Project: intellij-community
File: GotoImplementationHandler.java
@Override
@Nullable
public GotoData getSourceAndTargetElements(@NotNull Editor editor, PsiFile file) {
    int offset = editor.getCaretModel().getOffset();
    PsiElement source = TargetElementUtil.getInstance().findTargetElement(editor, ImplementationSearcher.getFlags(), offset);
    if (source == null)
        return null;
    final PsiReference reference = TargetElementUtil.findReference(editor, offset);
    final TargetElementUtil instance = TargetElementUtil.getInstance();
    PsiElement[] targets = new ImplementationSearcher.FirstImplementationsSearcher() {

        @Override
        protected boolean accept(PsiElement element) {
            return instance.acceptImplementationForReference(reference, element);
        }

        @Override
        protected boolean canShowPopupWithOneItem(PsiElement element) {
            return false;
        }
    }.searchImplementations(editor, source, offset);
    GotoData gotoData = new GotoData(source, targets, Collections.emptyList());
    gotoData.listUpdaterTask = new ImplementationsUpdaterTask(gotoData, editor, offset, reference);
    return gotoData;
}

91. AbstractDocumentationTooltipAction#getDocInfo()

Project: intellij-community
File: AbstractDocumentationTooltipAction.java
@Nullable
private Pair<PsiElement, /* doc anchor */
PsiElement> getDocInfo() {
    PsiElement docAnchor = SoftReference.dereference(myDocAnchor);
    if (docAnchor == null) {
        return null;
    }
    PsiElement originalElement = SoftReference.dereference(myOriginalElement);
    if (originalElement == null) {
        return null;
    }
    return Pair.create(docAnchor, originalElement);
}

92. ParameterInfoController#getPrevOrNextParameterOffset()

Project: intellij-community
File: ParameterInfoController.java
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;
}

93. AbstractElementSignatureProvider#restoreElementInternal()

Project: intellij-community
File: AbstractElementSignatureProvider.java
@Nullable
protected static <T extends PsiNamedElement> T restoreElementInternal(@NotNull PsiElement parent, String name, int index, @NotNull Class<T> hisClass) {
    PsiElement[] children = parent.getChildren();
    for (PsiElement child : children) {
        if (ReflectionUtil.isAssignable(hisClass, child.getClass())) {
            T namedChild = hisClass.cast(child);
            final String childName = namedChild.getName();
            if (Comparing.equal(name, childName)) {
                if (index == 0) {
                    return namedChild;
                }
                index--;
            }
        }
    }
    return null;
}

94. AbstractElementSignatureProvider#getChildIndex()

Project: intellij-community
File: AbstractElementSignatureProvider.java
protected static <T extends PsiNamedElement> int getChildIndex(T element, PsiElement parent, String name, Class<T> hisClass) {
    PsiElement[] children = parent.getChildren();
    int index = 0;
    for (PsiElement child : children) {
        if (ReflectionUtil.isAssignable(hisClass, child.getClass())) {
            T namedChild = hisClass.cast(child);
            final String childName = namedChild.getName();
            if (Comparing.equal(name, childName)) {
                if (namedChild.equals(element)) {
                    return index;
                }
                index++;
            }
        }
    }
    return index;
}

95. MoveElementLeftRightActionHandler#getElementList()

Project: intellij-community
File: MoveElementLeftRightActionHandler.java
@Nullable
private static PsiElement[] getElementList(@NotNull PsiFile file, int rangeStart, int rangeEnd) {
    PsiElement startElement = file.findElementAt(rangeStart);
    if (startElement == null)
        return null;
    if (rangeEnd > rangeStart) {
        PsiElement endElement = file.findElementAt(rangeEnd - 1);
        if (endElement == null)
            return null;
        PsiElement element = PsiTreeUtil.findCommonParent(startElement, endElement);
        return getElementList(element, rangeStart, rangeEnd);
    }
    PsiElement[] list = getElementList(startElement, rangeStart, rangeStart);
    if (list != null || rangeStart <= 0)
        return list;
    startElement = file.findElementAt(rangeStart - 1);
    if (startElement == null)
        return null;
    return getElementList(startElement, rangeStart, rangeStart);
}

96. EnterAfterUnmatchedBraceHandler#calculateOffsetToInsertClosingBrace()

Project: intellij-community
File: EnterAfterUnmatchedBraceHandler.java
/**
   * Current handler inserts closing curly brace (right brace) if necessary. There is a possible case that it should be located
   * more than one line forward.
   * <p/>
   * <b>Example</b>
   * <pre>
   *     if (test1()) {
   *     } else {<caret> if (test2()) {
   *         foo();
   *     }
   * </pre>
   * <p/>
   * We want to get this after the processing:
   * <pre>
   *     if (test1()) {
   *     } else {
   *         if (test2()) {
   *             foo();
   *         }
   *     }
   * </pre>
   * I.e. closing brace should be inserted two lines below current caret line. Hence, we need to calculate correct offset
   * to use for brace inserting. This method is responsible for that.
   * <p/>
   * In essence it inspects PSI structure and finds PSE elements with the max length that starts at caret offset. End offset
   * of that element is used as an insertion point.
   *
   * @param file   target PSI file
   * @param text   text from the given file
   * @param offset target offset where line feed will be inserted
   * @return pair of (element, offset). The element is the '}' owner, if applicable; the offset is the position for inserting closing brace
   */
protected Pair<PsiElement, Integer> calculateOffsetToInsertClosingBrace(@NotNull PsiFile file, @NotNull CharSequence text, final int offset) {
    PsiElement element = PsiUtilCore.getElementAtOffset(file, offset);
    ASTNode node = element.getNode();
    if (node != null && node.getElementType() == TokenType.WHITE_SPACE) {
        return Pair.create(null, CharArrayUtil.shiftForwardUntil(text, offset, "\n"));
    }
    for (PsiElement parent = element.getParent(); parent != null; parent = parent.getParent()) {
        ASTNode parentNode = parent.getNode();
        if (parentNode == null || parentNode.getStartOffset() != offset) {
            break;
        }
        element = parent;
    }
    if (element.getTextOffset() != offset) {
        return Pair.create(null, CharArrayUtil.shiftForwardUntil(text, offset, "\n"));
    }
    return Pair.create(element, calculateOffsetToInsertClosingBraceInsideElement(element));
}

97. EditSourceUtil#getDescriptor()

Project: intellij-community
File: EditSourceUtil.java
@Nullable
public static Navigatable getDescriptor(@NotNull PsiElement element) {
    PsiElement original = getNavigatableOriginalElement(element);
    if (original != null) {
        element = original;
    } else if (!canNavigate(element)) {
        return null;
    }
    if (element instanceof PomTargetPsiElement) {
        return ((PomTargetPsiElement) element).getTarget();
    }
    final PsiElement navigationElement = element.getNavigationElement();
    if (navigationElement instanceof PomTargetPsiElement) {
        return ((PomTargetPsiElement) navigationElement).getTarget();
    }
    final int offset = navigationElement instanceof PsiFile ? -1 : navigationElement.getTextOffset();
    final VirtualFile virtualFile = PsiUtilCore.getVirtualFile(navigationElement);
    if (virtualFile == null || !virtualFile.isValid()) {
        return null;
    }
    OpenFileDescriptor desc = new OpenFileDescriptor(navigationElement.getProject(), virtualFile, offset);
    desc.setUseCurrentWindow(FileEditorManager.USE_CURRENT_WINDOW.isIn(navigationElement));
    return desc;
}

98. CreateElementActionBase#actionPerformed()

Project: intellij-community
File: CreateElementActionBase.java
@Override
public final void actionPerformed(final AnActionEvent e) {
    final IdeView view = e.getData(LangDataKeys.IDE_VIEW);
    if (view == null) {
        return;
    }
    final Project project = e.getProject();
    final PsiDirectory dir = view.getOrChooseDirectory();
    if (dir == null)
        return;
    final PsiElement[] createdElements = invokeDialog(project, dir);
    for (PsiElement createdElement : createdElements) {
        view.selectElement(createdElement);
    }
}

99. BaseElementAtCaretIntentionAction#isAvailable()

Project: intellij-community
File: BaseElementAtCaretIntentionAction.java
@Override
public final boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
    if (!checkFile(file))
        return false;
    useElementToTheLeft = false;
    final PsiElement elementToTheRight = getElementToTheRight(editor, file);
    if (elementToTheRight != null && isAvailable(project, editor, elementToTheRight)) {
        return true;
    }
    final PsiElement elementToTheLeft = getElementToTheLeft(editor, file);
    if (elementToTheLeft != null && isAvailable(project, editor, elementToTheLeft)) {
        useElementToTheLeft = true;
        return true;
    }
    return false;
}

100. StatementUpDownMover#getElementRange()

Project: intellij-community
File: StatementUpDownMover.java
@Nullable
protected static Pair<PsiElement, PsiElement> getElementRange(@NotNull Editor editor, @NotNull PsiFile file, @NotNull LineRange range) {
    final int startOffset = editor.logicalPositionToOffset(new LogicalPosition(range.startLine, 0));
    PsiElement startingElement = firstNonWhiteElement(startOffset, file, true);
    if (startingElement == null)
        return null;
    final int endOffset = editor.logicalPositionToOffset(new LogicalPosition(range.endLine, 0)) - 1;
    PsiElement endingElement = firstNonWhiteElement(endOffset, file, false);
    if (endingElement == null)
        return null;
    if (PsiTreeUtil.isAncestor(startingElement, endingElement, false) || startingElement.getTextRange().getEndOffset() <= endingElement.getTextRange().getStartOffset()) {
        return Pair.create(startingElement, endingElement);
    }
    if (PsiTreeUtil.isAncestor(endingElement, startingElement, false)) {
        return Pair.create(startingElement, endingElement);
    }
    return null;
}