public static @Nullable PsiFile getPsiFileInEditor(@NotNull Caret caret, final @NotNull Project project) {
    Editor editor = caret.getEditor();
    assertEditorAndProjectConsistent(project, editor);
    final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
    if (file == null) return null;

    PsiUtilCore.ensureValid(file);

    if (file instanceof PsiFileWithOneLanguage) {
      return file;
    }

    final Language language = getLanguageInEditor(caret, project);

    if (language == file.getLanguage()) return file;

    int caretOffset = caret.getOffset();
    int mostProbablyCorrectLanguageOffset = caretOffset == caret.getSelectionEnd() ? caret.getSelectionStart() : caretOffset;
    return getPsiFileAtOffset(file, mostProbablyCorrectLanguageOffset);
  }
public static @Nullable PsiFile getPsiFileInEditor(@NotNull Caret caret, final @NotNull Project project)