PsiElement (List<? extends PsiElement> occurrences) { PsiElement anchor = occurrences.get(0); final Pair<PsiElement, TextRange> data = anchor.getUserData(PyReplaceExpressionUtil.SELECTION_BREAKS_AST_NODE); // Search anchor in the origin file, not in dummy.py, if selection breaks statement and thus element was generated if (data != null && occurrences.size() == 1) { return PsiTreeUtil.getParentOfType(data.getFirst(), PyStatement.class); } next: do { final PyStatement statement = PsiTreeUtil.getParentOfType(anchor, PyStatement.class); if (statement != null) { final PsiElement parent = statement.getParent(); for (PsiElement element : occurrences) { if (!PsiTreeUtil.isAncestor(parent, element, true)) { anchor = statement; continue next; } } } return statement; } while (true); }