PsiElement (@NotNull PsiElement scope, @NotNull PsiElement start, @NotNull PsiElement end) { List<PsiElement> parentsOfStart = new ArrayList<>(); PsiElement currentElement = start.getParent(); while (currentElement != null && currentElement != scope) { parentsOfStart.add(currentElement); currentElement = currentElement.getParent(); } PsiElement broadEnd = end; currentElement = end.getParent(); while (currentElement != null && currentElement != scope && !parentsOfStart.contains(currentElement)) { if (currentElement instanceof PsiLoopStatement) { broadEnd = currentElement; } currentElement = currentElement.getParent(); } return broadEnd; }