Proper way to test language in file editor provider?

What is the proper way to test for file’s language in FileEditorProvider?

Since I have a fair amount of history my code has tried to evolve with the API and currently here is what I use:

public class MdPreviewFileEditorProvider extends WeighedFileEditorProvider {
    public boolean accept(@NotNull Project project, @NotNull VirtualFile file) {
        if (file instanceof LightVirtualFile) {
            if (((LightVirtualFile) file).getAssignedFileType() instanceof MdFileType) return true;

        FileType fileType = file.getFileType();
        if (fileType instanceof MdFileType) return true;
        Language language = ScratchFileService.getInstance().getScratchesMapping().getMapping(file);
        boolean scratchMd = language == MdLanguage.INSTANCE;

        // NOTE: scratch file mapping is only present using New Scratch File action and is not properly set if using New File action on Scratches directory
        boolean oldScratchMd = scratchMd || LanguageUtil.getLanguageForPsi(project, file) == MdLanguage.INSTANCE;
        return oldScratchMd;

I had to add the last test using LanguageUtil.getLanguageForPsi because in 2020.1 scratch files created using New File action on Scratches directory in project view does not setup the proper mapping in the ScratchFileService. The file icon and file type the context menu action"Change Language (Markdown)…" shows markdown.

However, only after changing the language to markdown from the contex menu would the scratch file be recognized as markdown without the LanguageUtil.getLanguageForPsi code.

I was wondering if there is a reason to have any tests other than the LanguageUtil.getLanguageForPsi code?

Please sign in to leave a comment.