void (@NotNull PsiFile psiFile, @NotNull List<? super @NotNull PsiElement> elements, int start, int end) { int modifiedEnd = end; int length = psiFile.getTextLength(); if (end > length) { LOG.error("Range extends beyond the PSI file range. Maybe PSI file is not actual"); } if (end == length) { modifiedEnd--; } PsiElement startElement = psiFile.findElementAt(start); PsiElement endElement = psiFile.findElementAt(modifiedEnd); if (startElement == null || endElement == null) { return; } // PsiFileImpl.findElementAt may return element from another language, for example, JS element when called for an HTML file. // Such an element would belong to a sister psi file. // If startElement and endElement belong to different files, then findCommonParent doesn't work correctly, so we have to use // AbstractFileViewProvider.findElementAt which always returns psi elements from an original file. if (startElement.getContainingFile() != endElement.getContainingFile()) { startElement = AbstractFileViewProvider.findElementAt(psiFile, start); endElement = AbstractFileViewProvider.findElementAt(psiFile, modifiedEnd); if (startElement == null || endElement == null) { return; } } final PsiElement parent = PsiTreeUtil.findCommonParent(startElement, endElement); if (parent == null) { return; } final PsiElement[] children = parent.getChildren(); TextRange range = new TextRange(start, end); if (children.length == 0) { if (parent.getContainingFile() != null && range.intersects(parent.getTextRange())) { elements.add(parent); } } else { for (PsiElement child : children) { TextRange childRange = child.getTextRange(); if (!(child instanceof PsiWhiteSpace) && child.getContainingFile() != null && childRange != null && range.intersects(childRange)) { elements.add(child); } } } }