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

The following examples show how to use com.intellij.psi.PsiElement#getText() . 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: ORUtil.java    From reasonml-idea-plugin with MIT License 8 votes vote down vote up
@NotNull
public static String getTextUntilClass(@NotNull PsiElement root, @Nullable Class clazz) {
    String text = root.getText();

    PsiElement sibling = root.getNextSibling();
    while (sibling != null) {
        if (sibling.getClass().isAssignableFrom(clazz)) {
            sibling = null;
        } else {
            text += sibling.getText();
            sibling = sibling.getNextSibling();
        }
    }

    return text.trim();
}
 
Example 2
Source File: ProblemDescriptorUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static String extractHighlightedText(@Nonnull CommonProblemDescriptor descriptor, PsiElement psiElement) {
  if (psiElement == null || !psiElement.isValid()) return "";
  String ref = psiElement.getText();
  if (descriptor instanceof ProblemDescriptorBase) {
    TextRange textRange = ((ProblemDescriptorBase)descriptor).getTextRange();
    final TextRange elementRange = psiElement.getTextRange();
    if (textRange != null && elementRange != null) {
      textRange = textRange.shiftRight(-elementRange.getStartOffset());
      if (textRange.getStartOffset() >= 0 && textRange.getEndOffset() <= elementRange.getLength()) {
        ref = textRange.substring(ref);
      }
    }
  }
  ref = StringUtil.replaceChar(ref, '\n', ' ').trim();
  ref = StringUtil.first(ref, 100, true);
  return ref;
}
 
Example 3
Source File: HaxeParameterInfoHandler.java    From intellij-haxe with Apache License 2.0 6 votes vote down vote up
private int getArgumentIndexUnderCaret(@NotNull PsiElement place, List<HaxeExpression> expressionList) {
  HaxeExpression expression = getExpressionAtPlace(place, expressionList);

  if (expression != null) {
    int expressionIndex = expressionList.indexOf(expression);
    if (expressionIndex >= 0) {
      return expressionIndex;
    }
  }
  else {
    final String tokenText = place.getText();

    if (tokenText.equals(HaxeTokenTypes.PRPAREN.toString())) {
      return getExpressionIndexBeforeRightParen(expressionList);
    }
    else {
      return getExpressionIndexAtPlace(place, expressionList);
    }
  }

  return -1;
}
 
Example 4
Source File: CSharpPreprocessorDefineImpl.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@RequiredReadAction
@Nullable
@Override
public String getVarName()
{
	PsiElement nameIdentifier = getVarElement();
	return nameIdentifier != null ? nameIdentifier.getText() : null;
}
 
Example 5
Source File: CSharpLightFieldDeclarationBuilder.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@Override
public String getName()
{
	PsiElement nameIdentifier = getNameIdentifier();
	if(nameIdentifier != null)
	{
		return nameIdentifier.getText();
	}
	return super.getName();
}
 
Example 6
Source File: BashTrapCommandImpl.java    From BashSupport with Apache License 2.0 5 votes vote down vote up
@Override
public PsiElement getSignalHandlerElement() {
    //the first element after the "trap" command element
    PsiElement firstParam = BashPsiUtils.findNextSibling(getFirstChild(), BashTokenTypes.WHITESPACE);
    if (firstParam == null) {
        return null;
    }

    String text = firstParam.getText();
    if (text.startsWith("-p") || text.startsWith("-l")) {
        return null;
    }

    //the string/word container is embedded in a structure of "simple command" -> "generic command element"
    //extract it without relying too much on the defined structure
    PsiElement child = firstParam;
    while (child.getTextRange().equals(firstParam.getTextRange())) {
        PsiElement firstChild = child.getFirstChild();
        if (firstChild == null || firstChild instanceof LeafPsiElement) {
            break;
        }

        child = child.getFirstChild();
    }

    return child;
}
 
Example 7
Source File: PsiExternalImpl.java    From reasonml-idea-plugin with MIT License 5 votes vote down vote up
@Override
public String getName() {
    PsiElement nameIdentifier = getNameIdentifier();
    if (nameIdentifier == null) {
        return "unknown";
    }

    return nameIdentifier.getText();
}
 
Example 8
Source File: ConfigEntityTypeAnnotationIndex.java    From idea-php-drupal-symfony2-bridge with MIT License 5 votes vote down vote up
@Override
public void visitElement(PsiElement element) {
    if(!(element instanceof PhpDocTag)) {
        super.visitElement(element);
        return;
    }

    String annotationName = StringUtils.stripStart(((PhpDocTag) element).getName(), "@");
    if(!"ConfigEntityType".equals(annotationName)) {
        super.visitElement(element);
        return;
    }

    PsiElement phpDocComment = element.getParent();
    if(!(phpDocComment instanceof PhpDocComment)) {
        super.visitElement(element);
        return;
    }

    PhpPsiElement phpClass = ((PhpDocComment) phpDocComment).getNextPsiSibling();
    if(!(phpClass instanceof PhpClass)) {
        super.visitElement(element);
        return;
    }

    String tagValue = element.getText();
    Matcher matcher = Pattern.compile("id\\s*=\\s*\"([\\w\\.-]+)\"").matcher(tagValue);
    if (matcher.find()) {
        map.put(matcher.group(1), StringUtils.stripStart(((PhpClass) phpClass).getFQN(), "\\"));
    }

    super.visitElement(element);
}
 
Example 9
Source File: MockJSElementInterfaceUtil.java    From needsmoredojo with Apache License 2.0 5 votes vote down vote up
public static String printTree(MockJSElementInterface element)
{
    PsiElement nextSibling = element.getNextSibling();
    String result = element.getText();

    while(nextSibling != null)
    {
        result += nextSibling.getText();
        nextSibling = nextSibling.getNextSibling();
    }

    return result;
}
 
Example 10
Source File: TSAnnotator.java    From Custom-Syntax-Highlighter with MIT License 5 votes vote down vote up
@Override
public TextAttributesKey getKeywordKind(@NotNull final PsiElement element) {
  TextAttributesKey kind = null;
  switch (element.getText()) {
    case "public":
    case "protected":
    case "private":
      kind = PRIVATE;
      break;
  }
  return kind;
}
 
Example 11
Source File: GutterPsiElementListCellRenderer.java    From camel-idea-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public String getElementText(PsiElement element) {
    if (element instanceof PsiLiteralExpression) {
        return ((PsiLiteralExpression) element).getValue().toString();
    }
    return element.getText();
}
 
Example 12
Source File: TwigFoldingBuilder.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
private void attachConstantFoldingDescriptors(PsiElement psiElement, List<FoldingDescriptor> descriptors) {
    // find path calls in file
    PsiElement[] constantReferences = PsiTreeUtil.collectElements(psiElement, psiElement1 ->
        TwigPattern.getPrintBlockOrTagFunctionPattern("constant").accepts(psiElement1)
    );

    if(constantReferences.length == 0) {
        return;
    }

    for(PsiElement fileReference: constantReferences) {
        String contents = fileReference.getText();
        if(StringUtils.isNotBlank(contents) && contents.contains(":")) {
            final String[] parts = contents.split("::");
            if(parts.length == 2) {
                descriptors.add(new FoldingDescriptor(fileReference.getNode(),
                    new TextRange(fileReference.getTextRange().getStartOffset(), fileReference.getTextRange().getEndOffset())) {
                    @Nullable
                    @Override
                    public String getPlaceholderText() {
                        return parts[1];
                    }
                });
            }

        }

    }

}
 
Example 13
Source File: PropertyRegistrarMatcher.java    From idea-php-annotation-plugin with MIT License 4 votes vote down vote up
@Override
public boolean matches(@NotNull LanguageMatcherParameter parameter) {

    List<JsonSignature> filter = ContainerUtil.filter(parameter.getSignatures(), jsonSignature -> "annotation".equals(jsonSignature.getType()) &&
    StringUtils.isNotBlank(jsonSignature.getField()) &&
    StringUtils.isNotBlank(jsonSignature.getClassName()));

    if(filter.size() == 0) {
        return false;
    }

    PsiElement phpDocString = parameter.getElement().getParent();
    if(!(phpDocString instanceof StringLiteralExpression)) {
        return false;
    }

    boolean accepts = AnnotationPattern.getTextIdentifier().accepts(parameter.getElement());
    if(!accepts) {
        return false;
    }

    PsiElement propertyName = PhpElementsUtil.getPrevSiblingOfPatternMatch(
        phpDocString,
        PlatformPatterns.psiElement(PhpDocTokenTypes.DOC_IDENTIFIER)
    );

    if(propertyName == null) {
        return false;
    }

    String fieldName = propertyName.getText();
    if(StringUtils.isBlank(fieldName)) {
        return false;
    }

    for (JsonSignature signature : filter) {
        if(!fieldName.equals(signature.getField())) {
            continue;
        }

        PhpClass phpClass = AnnotationUtil.getAnnotationReference(PsiTreeUtil.getParentOfType(phpDocString, PhpDocTag.class));
        if(phpClass == null) {
            continue;
        }

        if(StringUtils.stripStart(phpClass.getFQN(), "\\").equals(StringUtils.stripStart(signature.getClassName(), "\\"))) {
            return true;
        }
    }

    return false;
}
 
Example 14
Source File: TemplateDefinitionReference.java    From bamboo-soy with Apache License 2.0 4 votes vote down vote up
public TemplateDefinitionReference(PsiElement element, TextRange textRange) {
  super(element, textRange);
  this.templateName = element.getText();
}
 
Example 15
Source File: PsiPhpHelper.java    From yiistorm with MIT License 4 votes vote down vote up
public static String getSuperClassName(PsiElement child) {
    PsiElement superclass = PsiPhpHelper.getSuperClassElement(child);
    return superclass.getText();
}
 
Example 16
Source File: ThriftFindUsagesProvider.java    From intellij-thrift with Apache License 2.0 4 votes vote down vote up
@NotNull
@Override
public String getNodeText(@NotNull PsiElement element, boolean useFullName) {
  String result = element instanceof ThriftDefinitionName ? ((ThriftDefinitionName)element).getName() : element.getText();
  return StringUtil.notNullize(result);
}
 
Example 17
Source File: DoctrineTypeDeprecatedInspection.java    From idea-php-annotation-plugin with MIT License 4 votes vote down vote up
@Override
public void visitElement(PsiElement element) {
    if (!(element instanceof StringLiteralExpression) || element.getNode().getElementType() != PhpDocElementTypes.phpDocString) {
        super.visitElement(element);
        return;
    }

    String contents = ((StringLiteralExpression) element).getContents();
    if (StringUtils.isBlank(contents)) {
        super.visitElement(element);
        return;
    }

    PhpDocTag phpDocTag = PsiTreeUtil.getParentOfType(element, PhpDocTag.class);
    if (phpDocTag == null) {
        super.visitElement(element);
        return;
    }

    PsiElement propertyName = PhpElementsUtil.getPrevSiblingOfPatternMatch(element, PlatformPatterns.psiElement(PhpDocTokenTypes.DOC_IDENTIFIER));
    if(propertyName == null) {
        super.visitElement(element);
        return;
    }

    String text = propertyName.getText();
    if ("type".equalsIgnoreCase(text)) {
        PhpDocTagAnnotation phpDocAnnotationContainer = AnnotationUtil.getPhpDocAnnotationContainer(phpDocTag);
        if (phpDocAnnotationContainer != null) {
            PhpClass tagPhpClass = phpDocAnnotationContainer.getPhpClass();
            if (PhpLangUtil.equalsClassNames(tagPhpClass.getPresentableFQN(), "Doctrine\\ORM\\Mapping\\Column")) {
                for (PhpClass columnPhpClass : DoctrineUtil.getColumnTypesTargets(holder.getProject(), contents)) {
                    if (!columnPhpClass.isDeprecated()) {
                        continue;
                    }

                    String deprecationMessage = PhpElementsUtil.getClassDeprecatedMessage(columnPhpClass);

                    holder.registerProblem(
                        element,
                        "[Annotations] " + (deprecationMessage != null ? deprecationMessage : String.format("Field '%s' is deprecated", text)),
                        ProblemHighlightType.LIKE_DEPRECATED
                    );

                    break;
                }
            }
        }
    }

    super.visitElement(element);
}
 
Example 18
Source File: QueryAction.java    From jetbrains-plugin-graph-database-support with Apache License 2.0 4 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent e) {
    Analytics.event("query", getQueryExecutionAction(e));

    Project project = getEventProject(e);
    Editor editor = e.getData(CommonDataKeys.EDITOR_EVEN_IF_INACTIVE);
    PsiFile psiFile = e.getData(CommonDataKeys.PSI_FILE);

    if (isNull(project)) {
        Notifier.error(QUERY_EXECUTION_ERROR_TITLE, NO_PROJECT_PRESENT_MESSAGE);
        return;
    }
    if (isNull(editor)) {
        Notifier.error(QUERY_EXECUTION_ERROR_TITLE, NO_EDITOR_PRESENT_MESSAGE);
        return;
    }

    String query = null;
    String analyticsEvent;
    Map<String, Object> parameters = Collections.emptyMap();
    if (preSetQuery == null) {
        Caret caret = editor.getCaretModel().getPrimaryCaret();
        analyticsEvent = caret.hasSelection() ? CONTENT_FROM_SELECT_ACTION : CONTENT_FROM_CARET_ACTION;

        if (caret.hasSelection()) {
            query = caret.getSelectedText();
        } else if (nonNull(psiFile)) {
            String languageId = psiFile.getLanguage().getID();
            if (isSupported(languageId)) {
                PsiElement cypherStatement = getCypherStatementAtOffset(psiFile, caret.getOffset());
                if (nonNull(cypherStatement)) {
                    query = cypherStatement.getText();
                    parameters = getParametersFromQuery(cypherStatement, project, editor);
                }
            }
        }
    } else {
        analyticsEvent = CONTENT_FROM_LINE_MARKER_ACTION;
        query = preSetQuery.getText();
        parameters = getParametersFromQuery(preSetQuery, project, editor);
    }

    Analytics.event("query-content", analyticsEvent);

    if (isNull(query)) {
        Notifier.error(QUERY_EXECUTION_ERROR_TITLE, NO_QUERY_SELECTED_MESSAGE);
        return;
    }

    actionPerformed(e, project, editor, query, parameters);
}
 
Example 19
Source File: PsiVariantDeclaration.java    From reasonml-idea-plugin with MIT License 4 votes vote down vote up
@Override
public String getName() {
    PsiElement nameIdentifier = getNameIdentifier();
    return nameIdentifier == null ? "" : nameIdentifier.getText();
}
 
Example 20
Source File: WidgetCallReferenceProvider.java    From yiistorm with MIT License 4 votes vote down vote up
@NotNull
@Override
public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull ProcessingContext context) {
    project = element.getProject();
    String elname = element.getClass().getName();
    properties = PropertiesComponent.getInstance(project);
    projectPath = project.getBaseDir().getCanonicalPath();
    if (elname.endsWith("StringLiteralExpressionImpl")) {

        try {
            PsiFile file = element.getContainingFile();
            VirtualFile vfile = file.getVirtualFile();
            if (vfile != null) {
                String path = vfile.getPath();

                VirtualFile baseDir = project.getBaseDir();
                if (baseDir != null) {
                    String inProtectedPath = path.replace(projectPath, "");
                    String protectedPath = CommonHelper.searchCurrentProtected(inProtectedPath);
                    String widgetPath = element.getText().replace("'", "");
                    String widgetFilePath = "";
                    if (widgetPath.matches("^components.+")) {
                        widgetFilePath = protectedPath + "/" + widgetPath.replace(".", "/") + ".php";
                    } else if (widgetPath.matches("^ext\\..+")) {
                        widgetFilePath = (protectedPath + "/" + widgetPath.replace(".", "/")).replace("/ext/", "/extensions/") + ".php";
                    } else if (widgetPath.matches("^app\\..+")) {
                        widgetFilePath = widgetPath.replace(".", "/").replace("app", protectedPath) + ".php";
                    } else if (widgetPath.matches("^application.+")) {
                        widgetFilePath = widgetPath.replace(".", "/").replace("application", protectedPath) + ".php";
                    } else {
                        if (!widgetPath.contains(".")) {
                            String currentFolder = inProtectedPath.replaceAll("[a-z0-9A-Z_]+?.php", "");
                            VirtualFile existsNear = baseDir.findFileByRelativePath(currentFolder + widgetPath + ".php");
                            if (existsNear == null) {
                                VirtualFile existsInParentDir = baseDir.findFileByRelativePath(currentFolder + ".." + "/"
                                        + widgetPath + ".php");
                                if (existsInParentDir != null) {
                                    widgetFilePath = currentFolder + ".." + "/" + widgetPath + ".php";
                                } else {
                                    VirtualFile existsInProtectedComponents = baseDir.findFileByRelativePath(protectedPath
                                            + "/" + "components" + "/" + widgetPath + ".php");
                                    if (existsInProtectedComponents != null) {
                                        widgetFilePath = protectedPath + "/" + "components" + "/" + widgetPath + ".php";
                                    }
                                }
                            } else {
                                widgetFilePath = currentFolder + widgetPath + ".php";
                            }
                        }
                    }
                    VirtualFile widgetfile = baseDir.findFileByRelativePath(widgetFilePath);
                    VirtualFile protectedPathDir = (!protectedPath.equals("")) ? baseDir.findFileByRelativePath(protectedPath) : null;

                    String str = element.getText();
                    TextRange textRange = CommonHelper.getTextRange(element, str);
                    String uri = str.substring(textRange.getStartOffset(), textRange.getEndOffset());
                    int start = textRange.getStartOffset();
                    int len = textRange.getLength();

                    if (widgetfile != null) {
                        PsiReference ref = new FileReference(widgetfile, uri, element,
                                new TextRange(start, start + len), project, protectedPathDir, protectedPathDir);
                        return new PsiReference[]{ref};
                    }
                    return PsiReference.EMPTY_ARRAY;
                }
            }
        } catch (Exception e) {
            System.err.println("error" + e.getMessage());
        }
    }
    return PsiReference.EMPTY_ARRAY;
}