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

The following examples show how to use com.intellij.psi.PsiElement#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: PhpHeaderDocumentationProvider.java    From idea-php-advanced-autocomplete with MIT License 6 votes vote down vote up
@Override
public @Nullable PsiElement getCustomDocumentationElement(@NotNull Editor editor, @NotNull PsiFile file, @Nullable PsiElement contextElement) {
    if (!isCallToHeaderFunc(contextElement)) {
        return null;
    }

    if (!(contextElement instanceof StringLiteralExpression)) {
        contextElement = PhpPsiUtil.getParentByCondition(contextElement, true, StringLiteralExpression.INSTANCEOF);
    }

    if (contextElement instanceof StringLiteralExpression) {
        String contents = ((StringLiteralExpression)contextElement).getContents();
        if (!contents.contains(":")) {
            return null;
        }
        String headerName = StringUtils.substringBefore(contents, ":");
        if (headerName.isEmpty() || !isHeaderName(headerName)) {
            return null;
        }
        return new HeaderDocElement(contextElement.getManager(), contextElement.getLanguage(), headerName);
    }
    return null;
}
 
Example 2
Source File: BaseMoveHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
private static PsiFile getRoot(final PsiFile file, final Editor editor) {
  if (file == null) return null;
  int offset = editor.getCaretModel().getOffset();
  if (offset == editor.getDocument().getTextLength()) offset--;
  if (offset<0) return null;
  PsiElement leafElement = file.findElementAt(offset);
  if (leafElement == null) return null;
  if (leafElement.getLanguage() instanceof DependentLanguage) {
    leafElement = file.getViewProvider().findElementAt(offset, file.getViewProvider().getBaseLanguage());
    if (leafElement == null) return null;
  }
  ASTNode node = leafElement.getNode();
  if (node == null) return null;
  return (PsiFile)PsiUtilBase.getRoot(node).getPsi();
}
 
Example 3
Source File: PhpHeaderDocumentationProvider.java    From idea-php-advanced-autocomplete with MIT License 6 votes vote down vote up
@Override
public @Nullable PsiElement getDocumentationElementForLookupItem(PsiManager psiManager, Object object, PsiElement psiElement) {
    if (!(object instanceof String)) {
        return null;
    }

    if (!isCallToHeaderFunc(psiElement)) {
        return null;
    }

    String headerName = StringUtils.strip((String)object, ": ");
    if (!isHeaderName(headerName)) {
        return null;
    }
    return new HeaderDocElement(psiManager, psiElement.getLanguage(), headerName);
}
 
Example 4
Source File: AttrMacroInsertHandler.java    From intellij-latte with MIT License 6 votes vote down vote up
public void handleInsert(@NotNull InsertionContext context, @NotNull LookupElement lookupElement) {
	PsiElement element = context.getFile().findElementAt(context.getStartOffset());
	if (element != null && element.getLanguage() == LatteLanguage.INSTANCE && element.getNode().getElementType() == LatteTypes.T_HTML_TAG_NATTR_NAME) {
		Editor editor = context.getEditor();
		CaretModel caretModel = editor.getCaretModel();
		int offset = caretModel.getOffset();
		if (LatteUtil.isStringAtCaret(editor, "=")) {
			caretModel.moveToOffset(offset + 2);
			return;
		}

		String attrName = LatteUtil.normalizeNAttrNameModifier(element.getText());
		LatteTagSettings macro = LatteConfiguration.getInstance(element.getProject()).getTag(attrName);
		if (macro != null && !macro.hasParameters()) {
			return;
		}

		editor.getDocument().insertString(offset, "=\"\"");
		caretModel.moveToOffset(offset + 2);

		PsiDocumentManager.getInstance(context.getProject()).commitDocument(editor.getDocument());
	}
}
 
Example 5
Source File: StructureAwareNavBarModelExtension.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
@RequiredReadAction
public PsiElement getParent(@Nonnull PsiElement psiElement) {
  if (psiElement.getLanguage() == getLanguage()) {
    PsiFile containingFile = psiElement.getContainingFile();
    if (containingFile == null) {
      return null;
    }

    StructureViewModel model = buildStructureViewModel(containingFile, null);
    if (model != null) {
      PsiElement parentInModel = findParentInModel(model.getRoot(), psiElement);
      if(acceptParentFromModel(parentInModel)) {
        return parentInModel;
      }
    }
  }
  return super.getParent(psiElement);
}
 
Example 6
Source File: JSGraphQLEndpointIconProvider.java    From js-graphql-intellij-plugin with MIT License 6 votes vote down vote up
@Nullable
@Override
public Icon getIcon(@NotNull PsiElement element, @Iconable.IconFlags int flags) {
    if (element.getLanguage() != JSGraphQLEndpointLanguage.INSTANCE) {
        return null;
    }
    if (element instanceof JSGraphQLEndpointNamedTypeDef) {
        if (element.getParent() instanceof JSGraphQLEndpointNamedTypeDefinition) {
            return getTypeDefinitionIcon((JSGraphQLEndpointNamedTypeDefinition) element.getParent());
        }
    }
    if (element instanceof JSGraphQLEndpointNamedTypeDefinition) {
        return getTypeDefinitionIcon((JSGraphQLEndpointNamedTypeDefinition) element);
    }
    if (element instanceof JSGraphQLEndpointProperty) {
        return JSGraphQLIcons.Schema.Field;
    }
    if (element instanceof JSGraphQLEndpointInputValueDefinition) {
        return JSGraphQLIcons.Schema.Attribute;
    }
    if(element instanceof JSGraphQLEndpointImportDeclaration) {
        return JSGraphQLIcons.Files.GraphQLSchema;
    }
    return null;
}
 
Example 7
Source File: StructureAwareNavBarModelExtension.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
@RequiredReadAction
public PsiElement getLeafElement(@Nonnull DataContext dataContext) {
  if (UISettings.getInstance().getShowMembersInNavigationBar()) {
    PsiFile psiFile = dataContext.getData(CommonDataKeys.PSI_FILE);
    Editor editor = dataContext.getData(CommonDataKeys.EDITOR);
    if (psiFile == null || editor == null) return null;
    PsiElement psiElement = psiFile.findElementAt(editor.getCaretModel().getOffset());
    if (psiElement != null && psiElement.getLanguage() == getLanguage()) {
      StructureViewModel model = buildStructureViewModel(psiFile, editor);
      if (model != null) {
        Object currentEditorElement = model.getCurrentEditorElement();
        if (currentEditorElement instanceof PsiElement) {
          return ((PsiElement)currentEditorElement).getOriginalElement();
        }
      }
    }
  }
  return null;
}
 
Example 8
Source File: GenericInlineHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static void collectConflicts(final PsiReference reference,
                                    final PsiElement element,
                                    final Map<Language, InlineHandler.Inliner> inliners,
                                    final MultiMap<PsiElement, String> conflicts) {
  final PsiElement referenceElement = reference.getElement();
  if (referenceElement == null) return;
  final Language language = referenceElement.getLanguage();
  final InlineHandler.Inliner inliner = inliners.get(language);
  if (inliner != null) {
    final MultiMap<PsiElement, String> refConflicts = inliner.getConflicts(reference, element);
    if (refConflicts != null) {
      for (PsiElement psiElement : refConflicts.keySet()) {
        conflicts.putValues(psiElement, refConflicts.get(psiElement));
      }
    }
  }
  else {
    conflicts.putValue(referenceElement, "Cannot inline reference from " + language.getID());
  }
}
 
Example 9
Source File: FluidInjector.java    From idea-php-typo3-plugin with MIT License 6 votes vote down vote up
@Override
public void getLanguagesToInject(@NotNull MultiHostRegistrar registrar, @NotNull PsiElement context) {
    if (context.getLanguage() == XMLLanguage.INSTANCE) return;
    final Project project = context.getProject();
    if (!FluidIndexUtil.hasFluid(project)) return;

    final PsiElement parent = context.getParent();
    if (context instanceof XmlAttributeValueImpl && parent instanceof XmlAttribute) {
        final int length = context.getTextLength();
        final String name = ((XmlAttribute) parent).getName();

        if (isInjectableAttribute(project, length, name)) {
            registrar
                .startInjecting(FluidLanguage.INSTANCE)
                .addPlace(null, null, (PsiLanguageInjectionHost) context, ElementManipulators.getValueTextRange(context))
                .doneInjecting();
        }
    }
}
 
Example 10
Source File: PhpFormatDocumentationProvider.java    From idea-php-advanced-autocomplete with MIT License 6 votes vote down vote up
@Override
public @Nullable PsiElement getDocumentationElementForLookupItem(PsiManager psiManager, Object object, PsiElement psiElement) {
    if (!(object instanceof String)) {
        return null;
    }

    String fqn = getCallToFormatFunc(psiElement);
    if (StringUtil.isNullOrEmpty(fqn)) {
        return null;
    }

    String tokenText = (String)object;

    if ("%%".equals(tokenText)) {
        tokenText = "%";
    }
    else if (!"%".equals(tokenText)) {
        tokenText = StringUtils.strip((String)object, "%");
    }
    String functionName = StringUtils.strip(fqn, "\\");
    return new FormatTokenDocElement(psiManager, psiElement.getLanguage(), tokenText, functionName);
}
 
Example 11
Source File: BlazeAndroidNativeDebuggerLanguageSupport.java    From intellij with Apache License 2.0 5 votes vote down vote up
@Override
public Document createDocument(
    final Project project,
    final String text,
    @Nullable XSourcePosition sourcePosition,
    final EvaluationMode mode) {
  final PsiElement context = OCDebuggerTypesHelper.getContextElement(sourcePosition, project);
  if (context != null && context.getLanguage() == OCLanguage.getInstance()) {
    return new WriteAction<Document>() {
      @Override
      protected void run(Result<Document> result) {
        PsiFile fragment =
            mode == EvaluationMode.EXPRESSION
                ? OCElementFactory.expressionCodeFragment(text, project, context, true, false)
                : OCElementFactory.expressionOrStatementsCodeFragment(
                    text, project, context, true, false);
        //noinspection ConstantConditions
        result.setResult(PsiDocumentManager.getInstance(project).getDocument(fragment));
      }
    }.execute().getResultObject();
  } else {
    final LightVirtualFile plainTextFile =
        new LightVirtualFile("oc-debug-editor-when-no-source-position-available.txt", text);
    //noinspection ConstantConditions
    return FileDocumentManager.getInstance().getDocument(plainTextFile);
  }
}
 
Example 12
Source File: KubernetesYamlDocumentationProvider.java    From intellij-kubernetes with Apache License 2.0 5 votes vote down vote up
@Override
public PsiElement getDocumentationElementForLookupItem(final PsiManager psiManager, final Object object, final PsiElement element) {
    if (element != null && object instanceof PropertyCompletionItem) {
        return new DocElement(psiManager, element.getLanguage(), (PropertyCompletionItem) object);
    }
    return null;
}
 
Example 13
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 14
Source File: CSharpReadWriteAccessDetector.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isReadWriteAccessible(PsiElement element)
{
	if(element instanceof DotNetVariable && element.getLanguage() == CSharpLanguage.INSTANCE)
	{
		return true;
	}
	return false;
}
 
Example 15
Source File: BuckGotoProvider.java    From buck with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
PsiElement getGotoDeclarationTarget(@Nullable PsiElement element) {
  if (element == null || !(element.getLanguage() instanceof BuckLanguage)) {
    return null;
  }
  Project project = element.getProject();
  if (project.isDefault()) {
    return null;
  }
  VirtualFile sourceFile = element.getContainingFile().getVirtualFile();
  if (sourceFile == null) {
    return null;
  }
  BuckLoadArgument buckLoadArgument =
      PsiTreeUtil.getParentOfType(element, BuckLoadArgument.class);
  if (buckLoadArgument != null) {
    return resolveAsLoadArgument(project, sourceFile, buckLoadArgument);
  }
  BuckIdentifier buckIdentifier =
      PsiTreeUtil.getParentOfType(element, BuckIdentifier.class, false);
  if (buckIdentifier != null) {
    return resolveAsIdentifier(project, buckIdentifier);
  }
  BuckString buckString = PsiTreeUtil.getParentOfType(element, BuckString.class, false);
  if (buckString != null) {
    return resolveAsBuckString(project, sourceFile, buckString);
  }
  return null;
}
 
Example 16
Source File: CSharpByGenericParameterWeigher.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@Override
public Comparable weigh(@Nonnull PsiElement psiElement, @Nonnull ProximityLocation proximityLocation)
{
	if(psiElement instanceof DotNetGenericParameterListOwner && psiElement.getLanguage() == CSharpLanguage.INSTANCE)
	{
		return -((DotNetGenericParameterListOwner) psiElement).getGenericParametersCount();
	}
	return 0;
}
 
Example 17
Source File: FormatterUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static boolean spacesOnly(@Nullable TreeElement node) {
  if (node == null) return false;

  if (isWhitespaceOrEmpty(node)) return true;
  PsiElement psi = node.getPsi();
  if (psi == null) {
    return false;
  }
  Language language = psi.getLanguage();
  return WhiteSpaceFormattingStrategyFactory.getStrategy(language).containsWhitespacesOnly(node);
}
 
Example 18
Source File: CppSelectioner.java    From CppTools with Apache License 2.0 4 votes vote down vote up
public boolean canSelect(PsiElement psiElement) {
  return psiElement.getLanguage() == CppSupportLoader.CPP_FILETYPE.getLanguage();
}
 
Example 19
Source File: DocumentationProvider.java    From reasonml-idea-plugin with MIT License 4 votes vote down vote up
@Override
public String generateDoc(PsiElement element, @Nullable PsiElement originalElement) {
    if (element instanceof PsiFakeModule) {
        PsiElement child = element.getContainingFile().getFirstChild();
        String text = "";

        PsiElement nextSibling = child;
        while (nextSibling instanceof PsiComment) {
            if (isSpecialComment(nextSibling)) {
                text = nextSibling.getText();
                nextSibling = null;
            } else {
                // Not a special comment, try with next child until no more comments found
                nextSibling = PsiTreeUtil.nextVisibleLeaf(nextSibling);
            }
        }

        if (!text.isEmpty()) {
            return DocFormatter.format(element.getContainingFile(), element, text);
        }
    } else if (element instanceof PsiUpperSymbol || element instanceof PsiLowerSymbol) {
        element = element.getParent();
        if (element instanceof PsiTypeConstrName) {
            element = element.getParent();
        }

        // If it's an alias, resolve to the alias
        if (element instanceof PsiLet) {
            String alias = ((PsiLet) element).getAlias();
            if (alias != null) {
                Project project = element.getProject();
                PsiFinder psiFinder = PsiFinder.getInstance(project);
                PsiVal valFromAlias = psiFinder.findValFromQn(alias);
                if (valFromAlias == null) {
                    PsiLet letFromAlias = psiFinder.findLetFromQn(alias);
                    if (letFromAlias != null) {
                        element = letFromAlias;
                    }
                } else {
                    element = valFromAlias;
                }
            }
        }

        // Try to find a comment just below (OCaml only)
        if (element.getLanguage() == OclLanguage.INSTANCE) {
            PsiElement belowComment = findBelowComment(element);
            if (belowComment != null) {
                return isSpecialComment(belowComment) ? DocFormatter.format(element.getContainingFile(), element, belowComment.getText()) :
                        belowComment.getText();
            }
        }

        // Else try to find a comment just above
        PsiElement aboveComment = findAboveComment(element);
        if (aboveComment != null) {
            return isSpecialComment(aboveComment) ? DocFormatter.format(element.getContainingFile(), element, aboveComment.getText()) :
                    aboveComment.getText();
        }
    }

    return super.generateDoc(element, originalElement);
}
 
Example 20
Source File: AbstractBatchSuppressByNoInspectionCommentFix.java    From consulo with Apache License 2.0 2 votes vote down vote up
/**
 * @param element quickfix target or existing comment element
 * @return language that will be used for comment creating.
 * In common case language will be the same as language of quickfix target
 */
@Nonnull
protected Language getCommentLanguage(@Nonnull PsiElement element) {
  return element.getLanguage();
}