TextRange (@NotNull Caret caret, @NotNull Project project) { Document document = caret.getEditor().getDocument(); PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(document); if (file == null) return null; int caretOffset = adjustCaretOffset(caret); PsiElement element = findElementAt(file, caretOffset); if (element == null) { return null; } if (element instanceof PsiWhiteSpace && caretOffset > 0) { PsiElement anotherElement = findElementAt(file, caretOffset - 1); if (!(anotherElement instanceof PsiWhiteSpace)) { element = anotherElement; } } if (!(element instanceof PsiWhiteSpace && SelectWordUtil.canWhiteSpaceBeExpanded((PsiWhiteSpace) element, caretOffset, caret, caret.getEditor()))) { while (element instanceof PsiWhiteSpace || element != null && StringUtil.isEmptyOrSpaces(element.getText())) { while (element.getNextSibling() == null) { if (element instanceof PsiFile) return null; final PsiElement parent = element.getParent(); final PsiElement[] children = parent.getChildren(); if (children.length > 0 && children[children.length - 1] == element) { element = parent; } else { element = parent; break; } } if (element instanceof PsiFile) return null; element = element.getNextSibling(); if (element == null) return null; TextRange range = element.getTextRange(); if (range == null) return null; // Fix NPE (EA-29110) caretOffset = range.getStartOffset(); } } if (element instanceof OuterLanguageElement) { PsiElement elementInOtherTree = file.getViewProvider().findElementAt(element.getTextOffset(), element.getLanguage()); if (elementInOtherTree != null && elementInOtherTree.getContainingFile() != element.getContainingFile()) { while (elementInOtherTree != null && elementInOtherTree.getPrevSibling() == null) { elementInOtherTree = elementInOtherTree.getParent(); } if (elementInOtherTree != null) { if (elementInOtherTree.getTextOffset() == caretOffset) element = elementInOtherTree; } } } checkElementRange(document, element); final TextRange selectionRange = new TextRange(caret.getSelectionStart(), caret.getSelectionEnd()); final Ref<TextRange> minimumRange = new Ref<>(new TextRange(0, document.getTextLength())); SelectWordUtil.processRanges(element, document.getCharsSequence(), caretOffset, caret.getEditor(), range -> { if (range.contains(selectionRange) && !range.equals(selectionRange)) { if (minimumRange.get().contains(range)) { minimumRange.set(range); return true; } } return false; }); return minimumRange.get(); }