PsiElement (@NotNull VirtualFile virtualFile, int offset, @NotNull Project project, boolean checkXml) { if (!virtualFile.isValid()) { return null; } Document document = FileDocumentManager.getInstance().getDocument(virtualFile); PsiFile file = document == null ? null : PsiManager.getInstance(project).findFile(virtualFile); if (file == null) { return null; } if (offset < 0) { offset = 0; } if (offset > document.getTextLength()) { offset = document.getTextLength(); } int startOffset = offset; int lineEndOffset = document.getLineEndOffset(document.getLineNumber(offset)); PsiElement result = null; do { PsiElement element = file.findElementAt(offset); if (!(element instanceof PsiWhiteSpace) && !(element instanceof PsiComment)) { result = element; break; } offset = element.getTextRange().getEndOffset() + 1; } while (offset < lineEndOffset); if (result == null) { result = file.findElementAt(startOffset); } if (checkXml && result != null && StdFileTypes.XML.getLanguage().equals(result.getLanguage())) { PsiLanguageInjectionHost parent = PsiTreeUtil.getParentOfType(result, PsiLanguageInjectionHost.class); if (parent != null) { result = InjectedLanguageUtil.findElementInInjected(parent, offset); } } return result; }