TextRange (final PsiFile file, final TextRange selectedRange) { if (!(file instanceof XmlFile)) return selectedRange; int startOffset = selectedRange.getStartOffset(); int endOffset = selectedRange.getEndOffset(); PsiElement element1 = file.findElementAt(startOffset); PsiElement element2 = file.findElementAt(endOffset - 1); Language lang1 = getLanguage(element1); Language lang2 = getLanguage(element2); if (element1 instanceof PsiWhiteSpace && isLanguageWithWSSignificant(lang1) ) { startOffset = element1.getTextRange().getEndOffset(); element1 = file.findElementAt(startOffset); } if (element2 instanceof PsiWhiteSpace && isLanguageWithWSSignificant(lang2) ) { endOffset = element2.getTextRange().getStartOffset(); element2 = file.findElementAt(endOffset); } lang1 = getLanguage(element1); lang2 = getLanguage(element2); if(lang1 != lang2) return null; TextRange.assertProperRange(startOffset, endOffset, "Wrong offsets for " + selectedRange.substring(file.getText())); return new TextRange(startOffset, endOffset); }