com.intellij.psi.util.PsiTreeUtil#getNextSiblingOfType ( )源码实例Demo

下面列出了com.intellij.psi.util.PsiTreeUtil#getNextSiblingOfType ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

private boolean completeAnnotations(@NotNull CompletionResultSet result, boolean autoImport, PsiFile file, PsiElement completionElement) {
	final JSGraphQLEndpointFieldDefinition field = PsiTreeUtil.getNextSiblingOfType(completionElement, JSGraphQLEndpointFieldDefinition.class);
	final JSGraphQLEndpointProperty property = PsiTreeUtil.getNextSiblingOfType(completionElement, JSGraphQLEndpointProperty.class);
	final JSGraphQLEndpointAnnotation nextAnnotation = PsiTreeUtil.getNextSiblingOfType(completionElement, JSGraphQLEndpointAnnotation.class);
	final boolean afterAtAnnotation = completionElement.getNode().getElementType() == JSGraphQLEndpointTokenTypes.AT_ANNOTATION;
	final boolean isTopLevelCompletion = completionElement.getParent() instanceof JSGraphQLEndpointFile;
	if (afterAtAnnotation || isTopLevelCompletion || field != null || nextAnnotation != null || property != null) {
		final JSGraphQLConfigurationProvider configurationProvider = JSGraphQLConfigurationProvider.getService(file.getProject());
		for (JSGraphQLSchemaEndpointAnnotation endpointAnnotation : configurationProvider.getEndpointAnnotations(file)) {
			String completion = endpointAnnotation.name;
			if (!afterAtAnnotation) {
				completion = "@" + completion;
			}
			LookupElementBuilder element = LookupElementBuilder.create(completion).withIcon(JSGraphQLIcons.Schema.Attribute);
			if(endpointAnnotation.arguments != null && endpointAnnotation.arguments.size() > 0) {
				element = element.withInsertHandler(ParenthesesInsertHandler.WITH_PARAMETERS);
			}
			result.addElement(element);
		}
		return true;
	}
	return false;
}
 
@Nullable
@Override
public String getQuickNavigateInfo(PsiElement element, PsiElement originalElement) {
    if (ServiceManager.getService(element.getProject(), CamelService.class).isCamelPresent()) {
        PsiExpressionList exps = PsiTreeUtil.getNextSiblingOfType(originalElement, PsiExpressionList.class);
        if (exps != null) {
            if (exps.getExpressions().length >= 1) {
                // grab first string parameter (as the string would contain the camel endpoint uri
                final PsiClassType stringType = PsiType.getJavaLangString(element.getManager(), element.getResolveScope());
                PsiExpression exp = Arrays.stream(exps.getExpressions()).filter(
                    e -> e.getType() != null && stringType.isAssignableFrom(e.getType()))
                    .findFirst().orElse(null);
                if (exp instanceof PsiLiteralExpression) {
                    Object o = ((PsiLiteralExpression) exp).getValue();
                    String val = o != null ? o.toString() : null;
                    // okay only allow this popup to work when its from a RouteBuilder class
                    PsiClass clazz = PsiTreeUtil.getParentOfType(originalElement, PsiClass.class);
                    if (clazz != null) {
                        PsiClassType[] types = clazz.getExtendsListTypes();
                        boolean found = Arrays.stream(types).anyMatch(p -> p.getClassName().equals("RouteBuilder"));
                        if (found) {
                            String componentName = asComponentName(val);
                            if (componentName != null) {
                                // the quick info cannot be so wide so wrap at 120 chars
                                return generateCamelComponentDocumentation(componentName, val, 120, element.getProject());
                            }
                        }
                    }
                }
            }
        }
    }

    return null;
}
 
@Override
public void visitElement(@NotNull PsiElement element) {
    Variable iconFolder = PsiTreeUtil.findChildOfType(element, Variable.class);
    if (iconFolder == null || !iconFolder.getName().equals("iconFolder")) {
        // Something changed - dynamic parsing failed.
        return;
    }

    StringLiteralExpression iconFolderValueString = PsiTreeUtil.getNextSiblingOfType(iconFolder, StringLiteralExpression.class);
    if (iconFolderValueString == null) {
        return;
    }

    String iconFolderValue = iconFolderValueString.getContents();

    Statement parentStatement = PsiTreeUtil.getParentOfType(iconFolder, Statement.class);
    Statement iconArrayAssignment = PsiTreeUtil.getNextSiblingOfType(
            parentStatement,
            Statement.class
    );
    if (iconArrayAssignment == null) {
        return;
    }

    Variable iconArray = PsiTreeUtil.findChildOfType(iconArrayAssignment, Variable.class);
    if (iconArray == null) {
        // something changed, meh. dynamic parsing failed.
        return;
    }

    ClassConstantReference iconProvider = PsiTreeUtil.findChildOfType(element, ClassConstantReference.class);
    if (iconProvider == null) {
        // something changed. - ...
        return;
    }

    ArrayCreationExpression flagsArray = PsiTreeUtil.getNextSiblingOfType(iconArray, ArrayCreationExpression.class);
    if (flagsArray == null) {
        return;
    }

    Collection<StringLiteralExpression> flagNames = PsiTreeUtil.findChildrenOfType(flagsArray, StringLiteralExpression.class);
    for (StringLiteralExpression flagNameExpression : flagNames) {
        String countryAbbreviation = flagNameExpression.getContents();

        this.createFlagIcon(iconProvider, iconFolderValue, countryAbbreviation, flagNameExpression);
    }
}
 
public JSGraphQLEndpointDocCompletionContributor() {

		CompletionProvider<CompletionParameters> provider = new CompletionProvider<CompletionParameters>() {
			@SuppressWarnings("unchecked")
			@Override
			protected void addCompletions(@NotNull final CompletionParameters parameters, ProcessingContext context, @NotNull CompletionResultSet result) {

				final PsiFile file = parameters.getOriginalFile();

				if (!(file instanceof JSGraphQLEndpointDocFile)) {
					return;
				}

				final PsiElement completionElement = Optional.ofNullable(parameters.getOriginalPosition()).orElse(parameters.getPosition());
				if (completionElement != null) {
					final PsiComment comment = PsiTreeUtil.getContextOfType(completionElement, PsiComment.class);
					if (comment != null && JSGraphQLEndpointDocPsiUtil.isDocumentationComment(comment)) {

						if (completionElement.getNode().getElementType() == JSGraphQLEndpointDocTokenTypes.DOCVALUE) {
							final JSGraphQLEndpointFieldDefinition fieldDefinition = PsiTreeUtil.getNextSiblingOfType(comment, JSGraphQLEndpointFieldDefinition.class);
							if (fieldDefinition != null && fieldDefinition.getArgumentsDefinition() != null) {
								final List<String> otherDocTagValues = JSGraphQLEndpointDocPsiUtil.getOtherDocTagValues(comment);
								for (JSGraphQLEndpointInputValueDefinition arg : PsiTreeUtil.findChildrenOfType(fieldDefinition.getArgumentsDefinition(), JSGraphQLEndpointInputValueDefinition.class)) {
									final String argName = arg.getInputValueDefinitionIdentifier().getText();
									if (!otherDocTagValues.contains(argName)) {
										result.addElement(LookupElementBuilder.create(argName).withInsertHandler(AddSpaceInsertHandler.INSTANCE));
									}
								}
							}
							return;
						}

						final JSGraphQLEndpointDocTag tagBefore = PsiTreeUtil.getPrevSiblingOfType(completionElement, JSGraphQLEndpointDocTag.class);
						final JSGraphQLEndpointDocTag tagParent = PsiTreeUtil.getParentOfType(completionElement, JSGraphQLEndpointDocTag.class);
						if (tagBefore == null || tagParent != null) {
							String completion = "param";
							final boolean includeAt = completionElement.getNode().getElementType() != JSGraphQLEndpointDocTokenTypes.DOCNAME;
							if (includeAt) {
								completion = "@" + completion;
							}
							result.addElement(LookupElementBuilder.create(completion).withInsertHandler(AddSpaceInsertHandler.INSTANCE_WITH_AUTO_POPUP));
						}
					}
				}
			}
		};

		extend(CompletionType.BASIC, PlatformPatterns.psiElement(), provider);

	}
 
@SuppressWarnings("unchecked")
@Override
public void annotate(@NotNull PsiElement element, @NotNull AnnotationHolder holder) {

	final IElementType elementType = element.getNode().getElementType();

       // highlight TO-DO items
       if(elementType == JSGraphQLEndpointDocTokenTypes.DOCTEXT) {
		final String elementText = element.getText().toLowerCase();
		if(isTodoToken(elementText)) {
			setTextAttributes(element, holder, CodeInsightColors.TODO_DEFAULT_ATTRIBUTES);
               holder.getCurrentAnnotationSession().putUserData(TODO_ELEMENT, element);
			return;
		} else {
               PsiElement prevSibling = element.getPrevSibling();
               while (prevSibling != null) {
                   if(prevSibling == holder.getCurrentAnnotationSession().getUserData(TODO_ELEMENT)) {
                       setTextAttributes(element, holder, CodeInsightColors.TODO_DEFAULT_ATTRIBUTES);
                       return;
                   }
                   prevSibling = prevSibling.getPrevSibling();
               }
           }
	}

	final PsiComment comment = PsiTreeUtil.getContextOfType(element, PsiComment.class);
	if (comment != null && JSGraphQLEndpointDocPsiUtil.isDocumentationComment(comment)) {
		final TextAttributesKey textAttributesKey = ATTRIBUTES.get(elementType);
		if (textAttributesKey != null) {
			setTextAttributes(element, holder, textAttributesKey);
		}
		// highlight invalid argument names after @param
		if(elementType == JSGraphQLEndpointDocTokenTypes.DOCVALUE) {
			final JSGraphQLEndpointFieldDefinition field = PsiTreeUtil.getNextSiblingOfType(comment, JSGraphQLEndpointFieldDefinition.class);
			if(field != null) {
				final JSGraphQLEndpointDocTag tag = PsiTreeUtil.getParentOfType(element, JSGraphQLEndpointDocTag.class);
				if(tag != null && tag.getDocName().getText().equals("@param")) {
					final String paramName = element.getText();
					final JSGraphQLEndpointInputValueDefinitions arguments = PsiTreeUtil.findChildOfType(field, JSGraphQLEndpointInputValueDefinitions.class);
					if(arguments == null) {
						// no arguments so invalid use of @param
						holder.createErrorAnnotation(element, "Invalid use of @param. The property has no arguments");
					} else {
						final JSGraphQLEndpointInputValueDefinition[] inputValues = PsiTreeUtil.getChildrenOfType(arguments, JSGraphQLEndpointInputValueDefinition.class);
						boolean found = false;
						if(inputValues != null) {
							for (JSGraphQLEndpointInputValueDefinition inputValue: inputValues) {
								if(inputValue.getInputValueDefinitionIdentifier().getText().equals(paramName)) {
									found = true;
									break;
								}
							}
						}
						if(!found) {
							holder.createErrorAnnotation(element, "@param name '" + element.getText() + "' doesn't match any of the field arguments");
						}

					}
				}
			}
		}
	}
}
 
源代码6 项目: intellij-xquery   文件: XQueryContextType.java
protected boolean isNotBeforeModuleDeclaration(PsiElement topmostElement) {
    PsiElement[] moduleKeywords = XQueryPsiImplUtil.findChildrenOfType(topmostElement, XQueryTypes.K_MODULE);
    PsiElement nextModuleDeclaration = PsiTreeUtil.getNextSiblingOfType(topmostElement, XQueryModuleDecl.class);
    return moduleKeywords.length == 0&& nextModuleDeclaration == null;
}
 
源代码7 项目: idea-php-symfony2-plugin   文件: ProfilerUtil.java
/**
 * ["foo/foo.html.twig": 1]
 *
 * <tr>
 *  <td>@Twig/Exception/traces_text.html.twig</td>
 *  <td class="font-normal">1</td>
 * </tr>
 */
public static Map<String, Integer> getRenderedElementTwigTemplates(@NotNull Project project, @NotNull String html) {
    HtmlFileImpl htmlFile = (HtmlFileImpl) PsiFileFactory.getInstance(project).createFileFromText(HTMLLanguage.INSTANCE, html);

    final XmlTag[] xmlTag = new XmlTag[1];
    PsiTreeUtil.processElements(htmlFile, psiElement -> {
        if(!(psiElement instanceof XmlTag) || !"h2".equals(((XmlTag) psiElement).getName())) {
            return true;
        }

        XmlTagValue keyTag = ((XmlTag) psiElement).getValue();
        String contents = StringUtils.trim(keyTag.getText());
        if(!"Rendered Templates".equalsIgnoreCase(contents)) {
            return true;
        }

        xmlTag[0] = (XmlTag) psiElement;

        return true;
    });

    if(xmlTag[0] == null) {
        return Collections.emptyMap();
    }

    XmlTag tableTag = PsiTreeUtil.getNextSiblingOfType(xmlTag[0], XmlTag.class);
    if(tableTag == null || !"table".equals(tableTag.getName())) {
        return Collections.emptyMap();
    }

    XmlTag tbody = tableTag.findFirstSubTag("tbody");
    if(tbody == null) {
        return Collections.emptyMap();
    }

    Map<String, Integer> templates = new HashMap<>();

    for (XmlTag tag : PsiTreeUtil.getChildrenOfTypeAsList(tbody, XmlTag.class)) {
        if(!"tr".equals(tag.getName())) {
            continue;
        }

        XmlTag[] tds = tag.findSubTags("td");
        if(tds.length < 2) {
            continue;
        }

        String template = stripHtmlTags(StringUtils.trim(tds[0].getValue().getText()));
        if(StringUtils.isBlank(template)) {
            continue;
        }

        Integer count;
        try {
            count = Integer.valueOf(stripHtmlTags(StringUtils.trim(tds[1].getValue().getText())));
        } catch (NumberFormatException e) {
            count = 0;
        }

        templates.put(template, count);
    }

    return templates;
}