Java Code Examples for com.intellij.psi.PsiFile#getLanguage()

The following examples show how to use com.intellij.psi.PsiFile#getLanguage() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ErrorFilter.java    From intellij-latte with MIT License 6 votes vote down vote up
public boolean shouldHighlightErrorElement(@NotNull PsiErrorElement element) {
	PsiFile templateLanguageFile = PsiUtilCore.getTemplateLanguageFile(element.getContainingFile());
	if (templateLanguageFile == null) {
		return true;
	}
	Language language = templateLanguageFile.getLanguage();
	if (language != LatteLanguage.INSTANCE) {
		return true;
	}
	if (element.getParent() instanceof XmlElement || element.getParent() instanceof CssElement) {
		return false;
	}
	if (element.getParent().getLanguage() == LatteLanguage.INSTANCE) {
		return true;
	}
	PsiElement nextSibling;
	for (nextSibling = PsiTreeUtil.nextLeaf(element); nextSibling instanceof PsiWhiteSpace; nextSibling = nextSibling.getNextSibling());

	PsiElement psiElement = nextSibling == null ? null : PsiTreeUtil.findCommonParent(nextSibling, element);
	boolean nextIsOuterLanguageElement = nextSibling instanceof OuterLanguageElement || nextSibling instanceof LatteMacroClassic;
	return !nextIsOuterLanguageElement || psiElement == null || psiElement instanceof PsiFile;
}
 
Example 2
Source File: LossyEncodingInspection.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
@Nullable
public ProblemDescriptor[] checkFile(@Nonnull PsiFile file, @Nonnull InspectionManager manager, boolean isOnTheFly) {
  if (InjectedLanguageManager.getInstance(file.getProject()).isInjectedFragment(file)) return null;
  if (!file.isPhysical()) return null;
  FileViewProvider viewProvider = file.getViewProvider();
  if (viewProvider.getBaseLanguage() != file.getLanguage()) return null;
  VirtualFile virtualFile = file.getVirtualFile();
  if (virtualFile == null) return null;
  if (!virtualFile.isInLocalFileSystem()) return null;
  CharSequence text = viewProvider.getContents();
  Charset charset = LoadTextUtil.extractCharsetFromFileContent(file.getProject(), virtualFile, text);

  // no sense in checking transparently decoded file: all characters there are already safely encoded
  if (charset instanceof Native2AsciiCharset) return null;

  List<ProblemDescriptor> descriptors = new SmartList<ProblemDescriptor>();
  boolean ok = checkFileLoadedInWrongEncoding(file, manager, isOnTheFly, virtualFile, charset, descriptors);
  if (ok) {
    checkIfCharactersWillBeLostAfterSave(file, manager, isOnTheFly, text, charset, descriptors);
  }

  return descriptors.toArray(new ProblemDescriptor[descriptors.size()]);
}
 
Example 3
Source File: XQueryXmlSlashTypedHandler.java    From intellij-xquery with Apache License 2.0 6 votes vote down vote up
@Override
public Result beforeCharTyped(final char c, final Project project, final Editor editor, final PsiFile editedFile, final FileType fileType) {
    if ((editedFile.getLanguage() instanceof XQueryLanguage) && c == '/') {
        PsiDocumentManager.getInstance(project).commitAllDocuments();
        PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
        if (file == null) return Result.CONTINUE;
        final int offset = editor.getCaretModel().getOffset();
        FileViewProvider provider = file.getViewProvider();
        PsiElement element = provider.findElementAt(offset, XQueryLanguage.class);
        if (isAtTheSlashOfClosingOfEmptyTag(offset, element)) {
            moveCaretByOne(editor, offset);
            return Result.STOP;
        }
    }
    return Result.CONTINUE;
}
 
Example 4
Source File: XQueryXmlGtTypedHandler.java    From intellij-xquery with Apache License 2.0 6 votes vote down vote up
@Override
public Result beforeCharTyped(final char c, final Project project, final Editor editor, final PsiFile editedFile, final FileType fileType) {
    if ((editedFile.getLanguage() instanceof XQueryLanguage) && c == '>') {
        PsiDocumentManager.getInstance(project).commitAllDocuments();
        PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
        if (file == null) return Result.CONTINUE;
        final int offset = editor.getCaretModel().getOffset();
        FileViewProvider provider = file.getViewProvider();
        PsiElement element = provider.findElementAt(offset, XQueryLanguage.class);

        if (element != null && element.getNode() != null && (
                element.getNode().getElementType() == XQueryTypes.XMLTAGEND ||
                        element.getNode().getElementType() == XQueryTypes.XMLEMPTYELEMENTEND)) {
            EditorModificationUtil.moveCaretRelatively(editor, 1);
            editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
            return Result.STOP;
        }
    }
    return Result.CONTINUE;
}
 
Example 5
Source File: IncompatibleDartPluginNotificationProvider.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public EditorNotificationPanel createNotificationPanel(@NotNull VirtualFile file, @NotNull FileEditor fileEditor) {
  if (!FlutterUtils.isFlutteryFile(file)) return null;

  final PsiFile psiFile = PsiManager.getInstance(myProject).findFile(file);
  if (psiFile == null) return null;

  if (psiFile.getLanguage() != DartLanguage.INSTANCE) return null;

  final Module module = ModuleUtilCore.findModuleForPsiElement(psiFile);
  if (module == null) return null;

  if (!FlutterModuleUtils.isFlutterModule(module)) return null;

  final Version minimumVersion = DartPlugin.getInstance().getMinimumVersion();
  final Version dartVersion = DartPlugin.getInstance().getVersion();
  if (dartVersion.minor == 0 && dartVersion.bugfix == 0) {
    return null; // Running from sources.
  }
  return dartVersion.compareTo(minimumVersion) < 0 ? createUpdateDartPanel(myProject, module, dartVersion.toCompactString(),
                                                                           getPrintableRequiredDartVersion()) : null;
}
 
Example 6
Source File: SdkConfigurationNotificationProvider.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public EditorNotificationPanel createNotificationPanel(@NotNull final VirtualFile file, @NotNull final FileEditor fileEditor) {

  // If this is a Bazel configured Flutter project, exit immediately, neither of the notifications should be shown for this project type.
  if (FlutterModuleUtils.isFlutterBazelProject(project)) return null;

  if (file.getFileType() != DartFileType.INSTANCE) return null;

  final PsiFile psiFile = PsiManager.getInstance(project).findFile(file);
  if (psiFile == null || psiFile.getLanguage() != DartLanguage.INSTANCE) return null;

  final Module module = ModuleUtilCore.findModuleForPsiElement(psiFile);
  if (!FlutterModuleUtils.isFlutterModule(module)) return null;

  final FlutterSdk flutterSdk = FlutterSdk.getFlutterSdk(project);
  if (flutterSdk == null) {
    return createNoFlutterSdkPanel(project);
  }
  else if (!flutterSdk.getVersion().isMinRecommendedSupported()) {
    return createOutOfDateFlutterSdkPanel(flutterSdk);
  }

  return null;
}
 
Example 7
Source File: GeneratedParserUtilBase.java    From intellij-xquery with Apache License 2.0 5 votes vote down vote up
public static void initState(ErrorState state, PsiBuilder builder, IElementType root, TokenSet[] extendsSets) {
    state.extendsSets = extendsSets;
    PsiFile file = builder.getUserDataUnprotected(FileContextUtil.CONTAINING_FILE_KEY);
    state.completionState = file == null? null: file.getUserData(COMPLETION_STATE_KEY);
    Language language = file == null? root.getLanguage() : file.getLanguage();
    state.caseSensitive = language.isCaseSensitive();
    PairedBraceMatcher matcher = LanguageBraceMatching.INSTANCE.forLanguage(language);
    state.braces = matcher == null ? null : matcher.getPairs();
    if (state.braces != null && state.braces.length == 0) state.braces = null;
}
 
Example 8
Source File: GeneratedParserUtilBase.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void initState(ErrorState state, PsiBuilder builder, IElementType root, TokenSet[] extendsSets) {
  state.extendsSets = extendsSets;
  PsiFile file = builder.getUserData(FileContextUtil.CONTAINING_FILE_KEY);
  state.completionState = file == null? null: file.getUserData(COMPLETION_STATE_KEY);
  Language language = file == null? root.getLanguage() : file.getLanguage();
  state.caseSensitive = language.isCaseSensitive();
  PairedBraceMatcher matcher = LanguageBraceMatching.INSTANCE.forLanguage(language);
  state.braces = matcher == null ? null : matcher.getPairs();
  if (state.braces != null && state.braces.length == 0) state.braces = null;
}
 
Example 9
Source File: GeneratedParserUtilBase.java    From Intellij-Dust with MIT License 5 votes vote down vote up
private static void initState(IElementType root, PsiBuilder builder, ErrorState state) {
    PsiFile file = builder.getUserDataUnprotected(FileContextUtil.CONTAINING_FILE_KEY);
    state.completionState = file == null? null: file.getUserData(COMPLETION_STATE_KEY);
    Language language = file == null? root.getLanguage() : file.getLanguage();
    state.caseSensitive = language.isCaseSensitive();
    ParserDefinition parserDefinition = LanguageParserDefinitions.INSTANCE.forLanguage(language);
    if (parserDefinition != null) {
        state.commentTokens = parserDefinition.getCommentTokens();
        state.whitespaceTokens = parserDefinition.getWhitespaceTokens();
    }
    PairedBraceMatcher matcher = LanguageBraceMatching.INSTANCE.forLanguage(language);
    state.braces = matcher == null ? null : matcher.getPairs();
    if (state.braces != null && state.braces.length == 0) state.braces = null;
}
 
Example 10
Source File: XQueryXmlSlashTypedHandler.java    From intellij-xquery with Apache License 2.0 5 votes vote down vote up
@Override
public Result charTyped(char c, final Project project, final @NotNull Editor editor, @NotNull final PsiFile editedFile) {
    if ((editedFile.getLanguage() instanceof XQueryLanguage) && c == '/') {
        PsiDocumentManager.getInstance(project).commitAllDocuments();
        PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
        if (file == null) return Result.CONTINUE;
        FileViewProvider provider = file.getViewProvider();
        final int offset = editor.getCaretModel().getOffset();
        PsiElement element = provider.findElementAt(offset - 1, XQueryLanguage.class);
        if (element == null) return Result.CONTINUE;
        if (!(element.getLanguage() instanceof XQueryLanguage)) return Result.CONTINUE;
        ASTNode prevLeaf = element.getNode();
        if (prevLeaf == null) return Result.CONTINUE;
        final String prevLeafText = prevLeaf.getText();
        if (isStartOfEndOfTag(prevLeaf, prevLeafText)) {
            XQueryXmlFullTag tag = PsiTreeUtil.getParentOfType(element, XQueryXmlFullTag.class);
            if (tag != null) {
                XQueryXmlTagName tagName = tag.getXmlTagNameList().get(0);
                if (hasNoClosingTagName(prevLeaf, tag, tagName)) {
                    finishClosingTag(editor, tagName);
                    return Result.STOP;
                }
            }
        }
        if (!"/".equals(prevLeafText.trim())) return Result.CONTINUE;
        prevLeaf = getPreviousNonWhiteSpaceLeaf(prevLeaf);
        if (prevLeaf == null) return Result.CONTINUE;
        if (PsiTreeUtil.getParentOfType(element, XQueryDirAttributeValue.class) != null) return Result.CONTINUE;
        if (prevLeaf.getElementType() == XQueryTypes.ELEMENTCONTENTCHAR) return Result.CONTINUE;
        XQueryEnclosedExpression parentEnclosedExpression = PsiTreeUtil.getParentOfType(element, XQueryEnclosedExpression.class, true, XQueryXmlFullTag.class);
        XQueryXmlFullTag fullTag = getParentFullTag(prevLeaf);
        if (isInEnclosedExpressionNestedInXmlTag(parentEnclosedExpression, fullTag)) return Result.CONTINUE;
        if (isInUnclosedXmlTag(fullTag)) {
            closeEmptyTag(editor);
            return Result.STOP;
        }
    }
    return Result.CONTINUE;
}
 
Example 11
Source File: FormattingDocumentModelImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
public FormattingDocumentModelImpl(@Nonnull final Document document, PsiFile file) {
  myDocument = document;
  myFile = file;
  if (file != null) {
    Language language = file.getLanguage();
    myWhiteSpaceStrategy = WhiteSpaceFormattingStrategyFactory.getStrategy(language);
  }
  else {
    myWhiteSpaceStrategy = WhiteSpaceFormattingStrategyFactory.getStrategy();
  }
  mySettings = CodeStyleSettingsManager.getSettings(file != null ? file.getProject() : null);
}
 
Example 12
Source File: LastRunReformatCodeOptionsProvider.java    From consulo with Apache License 2.0 5 votes vote down vote up
public ReformatCodeRunOptions getLastRunOptions(@Nonnull PsiFile file) {
  Language language = file.getLanguage();

  ReformatCodeRunOptions settings = new ReformatCodeRunOptions(getLastTextRangeType());
  settings.setOptimizeImports(getLastOptimizeImports());
  settings.setRearrangeCode(isRearrangeCode(language));

  return settings;
}
 
Example 13
Source File: LanguageVersionUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@RequiredReadAction
public static LanguageVersion findLanguageVersion(@Nonnull Language language, @Nonnull PsiFile psiFile) {
  if (psiFile.getLanguage() == language) {
    return psiFile.getLanguageVersion();
  }

  FileViewProvider viewProvider = psiFile.getViewProvider();

  PsiFile psi = viewProvider.getPsi(language);
  if (psi == null) {
    return LanguageVersionResolvers.INSTANCE.forLanguage(language).getLanguageVersion(language, psiFile);
  }
  return psi.getLanguageVersion();
}
 
Example 14
Source File: StubTextInconsistencyException.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void checkStubTextConsistency(@Nonnull PsiFile file) throws StubTextInconsistencyException {
  PsiUtilCore.ensureValid(file);

  FileViewProvider viewProvider = file.getViewProvider();
  if (viewProvider instanceof FreeThreadedFileViewProvider || viewProvider.getVirtualFile() instanceof LightVirtualFile) return;

  PsiFile bindingRoot = viewProvider.getStubBindingRoot();
  if (!(bindingRoot instanceof PsiFileImpl)) return;

  IStubFileElementType fileElementType = ((PsiFileImpl)bindingRoot).getElementTypeForStubBuilder();
  if (fileElementType == null || !fileElementType.shouldBuildStubFor(viewProvider.getVirtualFile())) return;

  List<PsiFileStub> fromText = restoreStubsFromText(viewProvider);

  List<PsiFileStub> fromPsi = ContainerUtil.map(StubTreeBuilder.getStubbedRoots(viewProvider), p -> ((PsiFileImpl)p.getSecond()).calcStubTree().getRoot());

  if (fromPsi.size() != fromText.size()) {
    throw new StubTextInconsistencyException(
            "Inconsistent stub roots: " + "PSI says it's " + ContainerUtil.map(fromPsi, s -> s.getType()) + " but re-parsing the text gives " + ContainerUtil.map(fromText, s -> s.getType()), file,
            fromText, fromPsi);
  }

  for (int i = 0; i < fromPsi.size(); i++) {
    PsiFileStub psiStub = fromPsi.get(i);
    if (!DebugUtil.stubTreeToString(psiStub).equals(DebugUtil.stubTreeToString(fromText.get(i)))) {
      throw new StubTextInconsistencyException("Stub is inconsistent with text in " + file.getLanguage(), file, fromText, fromPsi);
    }
  }
}
 
Example 15
Source File: PsiFileHelper.java    From reasonml-idea-plugin with MIT License 5 votes vote down vote up
@NotNull
public static Collection<PsiNameIdentifierOwner> getExpressions(@Nullable PsiFile file, @NotNull ExpressionScope eScope,
                                                                @Nullable ExpressionFilter filter) {
    ArrayList<PsiNameIdentifierOwner> result = new ArrayList<>();

    if (file != null) {
        PsiFinder psiFinder = PsiFinder.getInstance(file.getProject());
        QNameFinder qnameFinder = file.getLanguage() == RmlLanguage.INSTANCE ? RmlQNameFinder.INSTANCE : OclQNameFinder.INSTANCE;
        processSiblingExpressions(psiFinder, qnameFinder, file.getFirstChild(), eScope, result, filter);
    }

    return result;
}
 
Example 16
Source File: ThriftTypeHandler.java    From intellij-thrift with Apache License 2.0 4 votes vote down vote up
private static boolean isThriftContext(PsiFile file) {
  return file.getLanguage() instanceof ThriftLanguage;
}
 
Example 17
Source File: EditorEventManager.java    From lsp4intellij with Apache License 2.0 4 votes vote down vote up
/**
 * Will show documentation if the mouse doesn't move for a given time (Hover)
 *
 * @param e the event
 */
public void mouseMoved(EditorMouseEvent e) {

    if (e.getEditor() != editor) {
        LOG.error("Wrong editor for EditorEventManager");
        return;
    }

    PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
    if (psiFile == null) {
        return;
    }
    Language language = psiFile.getLanguage();
    if ((!LanguageDocumentation.INSTANCE.allForLanguage(language).isEmpty() && !isSupportedLanguageFile(psiFile))
            || (!getIsCtrlDown() && !EditorSettingsExternalizable.getInstance().isShowQuickDocOnMouseOverElement())) {
        return;
    }

    long curTime = System.nanoTime();
    if (predTime == (-1L) || ctrlTime == (-1L)) {
        predTime = curTime;
        ctrlTime = curTime;
    } else {
        LogicalPosition lPos = getPos(e);
        if (lPos == null || getIsKeyPressed() && !getIsCtrlDown()) {
            return;
        }

        int offset = editor.logicalPositionToOffset(lPos);
        if (getIsCtrlDown() && curTime - ctrlTime > EditorEventManagerBase.CTRL_THRESH) {
            if (getCtrlRange() == null || !getCtrlRange().highlightContainsOffset(offset)) {
                if (currentHint != null) {
                    currentHint.hide();
                }
                currentHint = null;
                if (getCtrlRange() != null) {
                    getCtrlRange().dispose();
                }
                setCtrlRange(null);
                pool(() -> requestAndShowDoc(lPos, e.getMouseEvent().getPoint()));
            } else if (getCtrlRange().definitionContainsOffset(offset)) {
                createAndShowEditorHint(editor, "Click to show usages", editor.offsetToXY(offset));
            } else {
                editor.getContentComponent().setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
            }
            ctrlTime = curTime;
        }
        predTime = curTime;
    }
}
 
Example 18
Source File: AddCustomLatteFunction.java    From intellij-latte with MIT License 4 votes vote down vote up
@Override
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
	return file.getLanguage() == LatteLanguage.INSTANCE;
}
 
Example 19
Source File: AddCustomMacro.java    From intellij-latte with MIT License 4 votes vote down vote up
@Override
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
	return file.getLanguage() == LatteLanguage.INSTANCE;
}
 
Example 20
Source File: IgnoreHighlightRangeExtension.java    From idea-gitignore with MIT License 2 votes vote down vote up
/**
 * Checks if current {@link PsiFile} is allowed to enable range highlighting.
 *
 * @param file current file
 * @return allowed to highlight
 */
@Override
public boolean isForceHighlightParents(@NotNull PsiFile file) {
    return file.getLanguage() instanceof IgnoreLanguage;
}