PsiElement (PsiExpression @NotNull [] occurrences, PsiElement scope) { PsiElement anchor = null; for (PsiExpression occurrence : occurrences) { if (scope != null && !PsiTreeUtil.isAncestor(scope, occurrence, false)) { continue; } PsiElement anchor1 = getParentExpressionAnchorElement(occurrence); if (anchor1 == null) { if (occurrence.isPhysical()) return null; continue; } if (anchor == null) { anchor = anchor1; } else { PsiElement commonParent = PsiTreeUtil.findCommonParent(anchor, anchor1); if (commonParent == null || anchor.getTextRange() == null || anchor1.getTextRange() == null) return null; PsiElement firstAnchor = anchor.getTextRange().getStartOffset() < anchor1.getTextRange().getStartOffset() ? anchor : anchor1; if (commonParent.equals(firstAnchor)) { anchor = firstAnchor; } else { if (commonParent instanceof PsiStatement) { anchor = commonParent; } else { PsiElement parent = firstAnchor; while (!parent.getParent().equals(commonParent)) { parent = parent.getParent(); } final PsiElement newAnchor = getParentExpressionAnchorElement(parent); if (newAnchor != null) { anchor = newAnchor; } else { anchor = parent; } } } } } if (anchor == null) return null; if (occurrences.length > 1 && anchor.getParent().getParent() instanceof PsiSwitchStatement switchStatement) { if (switchStatement.getBody().equals(anchor.getParent())) { int startOffset = occurrences[0].getTextRange().getStartOffset(); int endOffset = occurrences[occurrences.length - 1].getTextRange().getEndOffset(); PsiStatement[] statements = switchStatement.getBody().getStatements(); boolean isInDifferentCases = false; for (PsiStatement statement : statements) { if (statement instanceof PsiSwitchLabelStatement) { int caseOffset = statement.getTextRange().getStartOffset(); if (startOffset < caseOffset && caseOffset < endOffset) { isInDifferentCases = true; break; } } } if (isInDifferentCases) { anchor = switchStatement; } } } return anchor; }