Search in sources :

Example 1 with LeafElement

use of com.intellij.psi.impl.source.tree.LeafElement in project intellij-community by JetBrains.

the class MavenGroovyPomCompletionContributor method fillCompletionVariants.

@Override
public void fillCompletionVariants(@NotNull CompletionParameters parameters, @NotNull CompletionResultSet result) {
    final PsiElement position = parameters.getPosition();
    if (!(position instanceof LeafElement))
        return;
    Project project = position.getProject();
    VirtualFile virtualFile = parameters.getOriginalFile().getVirtualFile();
    if (virtualFile == null)
        return;
    MavenProject mavenProject = MavenProjectsManager.getInstance(project).findProject(virtualFile);
    if (mavenProject == null)
        return;
    List<String> methodCallInfo = MavenGroovyPomUtil.getGroovyMethodCalls(position);
    if (methodCallInfo.isEmpty())
        return;
    StringBuilder buf = new StringBuilder();
    for (String s : methodCallInfo) {
        buf.append('<').append(s).append('>');
    }
    for (String s : ContainerUtil.reverse(methodCallInfo)) {
        buf.append('<').append(s).append("/>");
    }
    PsiFile psiFile = PsiFileFactory.getInstance(project).createFileFromText("pom.xml", XMLLanguage.INSTANCE, buf);
    psiFile.putUserData(ORIGINAL_POM_FILE, virtualFile);
    List<Object> variants = ContainerUtil.newArrayList();
    String lastMethodCall = ContainerUtil.getLastItem(methodCallInfo);
    Ref<Boolean> completeDependency = Ref.create(false);
    Ref<Boolean> completeVersion = Ref.create(false);
    psiFile.accept(new PsiRecursiveElementVisitor(true) {

        @Override
        public void visitElement(PsiElement element) {
            super.visitElement(element);
            if (!completeDependency.get() && element.getParent() instanceof XmlTag && "dependency".equals(((XmlTag) element.getParent()).getName())) {
                if ("artifactId".equals(lastMethodCall) || "groupId".equals(lastMethodCall)) {
                    completeDependency.set(true);
                } else if ("version".equals(lastMethodCall) || "dependency".equals(lastMethodCall)) {
                    completeVersion.set(true);
                //completeDependency.set(true);
                }
            }
            if (!completeDependency.get() && !completeVersion.get()) {
                PsiReference[] references = getReferences(element);
                for (PsiReference each : references) {
                    if (each instanceof GenericDomValueReference) {
                        Collections.addAll(variants, each.getVariants());
                    }
                }
            }
        }
    });
    for (Object variant : variants) {
        if (variant instanceof LookupElement) {
            result.addElement((LookupElement) variant);
        } else {
            result.addElement(LookupElementBuilder.create(variant));
        }
    }
    if (completeDependency.get()) {
        MavenProjectIndicesManager indicesManager = MavenProjectIndicesManager.getInstance(project);
        for (String groupId : indicesManager.getGroupIds()) {
            for (String artifactId : indicesManager.getArtifactIds(groupId)) {
                LookupElement builder = LookupElementBuilder.create(groupId + ':' + artifactId).withIcon(AllIcons.Nodes.PpLib).withInsertHandler(MavenDependencyInsertHandler.INSTANCE);
                result.addElement(builder);
            }
        }
    }
    if (completeVersion.get()) {
        consumeDependencyElement(position, closableBlock -> {
            String groupId = null;
            String artifactId = null;
            for (GrMethodCall methodCall : PsiTreeUtil.findChildrenOfType(closableBlock, GrMethodCall.class)) {
                GroovyPsiElement[] arguments = methodCall.getArgumentList().getAllArguments();
                if (arguments.length != 1)
                    continue;
                PsiReference reference = arguments[0].getReference();
                if (reference == null)
                    continue;
                String callExpression = methodCall.getInvokedExpression().getText();
                String argumentValue = reference.getCanonicalText();
                if ("groupId".equals(callExpression)) {
                    groupId = argumentValue;
                } else if ("artifactId".equals(callExpression)) {
                    artifactId = argumentValue;
                }
            }
            completeVersions(result, project, groupId, artifactId, "");
        }, element -> {
            if (element.getParent() instanceof PsiLiteral) {
                Object value = ((PsiLiteral) element.getParent()).getValue();
                if (value == null)
                    return;
                String[] mavenCoordinates = value.toString().split(":");
                if (mavenCoordinates.length < 3)
                    return;
                String prefix = mavenCoordinates[0] + ':' + mavenCoordinates[1] + ':';
                completeVersions(result, project, mavenCoordinates[0], mavenCoordinates[1], prefix);
            }
        });
    }
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) GrMethodCall(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall) MavenProject(org.jetbrains.idea.maven.project.MavenProject) GenericDomValueReference(com.intellij.util.xml.impl.GenericDomValueReference) GroovyPsiElement(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement) MavenProjectIndicesManager(org.jetbrains.idea.maven.indices.MavenProjectIndicesManager) GroovyPsiElement(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement) LookupElement(com.intellij.codeInsight.lookup.LookupElement) Project(com.intellij.openapi.project.Project) MavenProject(org.jetbrains.idea.maven.project.MavenProject) LeafElement(com.intellij.psi.impl.source.tree.LeafElement) XmlTag(com.intellij.psi.xml.XmlTag)

Example 2 with LeafElement

use of com.intellij.psi.impl.source.tree.LeafElement in project intellij-community by JetBrains.

the class XmlProcessingInstructionManipulator method handleContentChange.

@Override
public XmlProcessingInstruction handleContentChange(@NotNull XmlProcessingInstruction element, @NotNull TextRange range, String newContent) throws IncorrectOperationException {
    CheckUtil.checkWritable(element);
    final CompositeElement attrNode = (CompositeElement) element.getNode();
    final ASTNode valueNode = attrNode.findLeafElementAt(range.getStartOffset());
    LOG.assertTrue(valueNode != null, "Leaf not found in " + attrNode + " at offset " + range.getStartOffset() + " in element " + element);
    final PsiElement elementToReplace = valueNode.getPsi();
    String text;
    try {
        text = elementToReplace.getText();
        final int offsetInParent = elementToReplace.getStartOffsetInParent();
        String textBeforeRange = text.substring(0, range.getStartOffset() - offsetInParent);
        String textAfterRange = text.substring(range.getEndOffset() - offsetInParent, text.length());
        newContent = element.getText().startsWith("'") || element.getText().endsWith("'") ? newContent.replace("'", "&apos;") : newContent.replace("\"", "&quot;");
        text = textBeforeRange + newContent + textAfterRange;
    } catch (StringIndexOutOfBoundsException e) {
        LOG.error("Range: " + range + " in text: '" + element.getText() + "'", e);
        throw e;
    }
    final CharTable charTableByTree = SharedImplUtil.findCharTableByTree(attrNode);
    final LeafElement newValueElement = Factory.createSingleLeafElement(XmlTokenType.XML_TAG_CHARACTERS, text, charTableByTree, element.getManager());
    attrNode.replaceChildInternal(valueNode, newValueElement);
    return element;
}
Also used : ASTNode(com.intellij.lang.ASTNode) CompositeElement(com.intellij.psi.impl.source.tree.CompositeElement) CharTable(com.intellij.util.CharTable) PsiElement(com.intellij.psi.PsiElement) LeafElement(com.intellij.psi.impl.source.tree.LeafElement)

Example 3 with LeafElement

use of com.intellij.psi.impl.source.tree.LeafElement in project intellij-community by JetBrains.

the class XmlParsingTest method _testPerformance2.

public void _testPerformance2() throws Exception {
    final String text = loadFile("performance2.xml");
    long time = System.currentTimeMillis();
    final PsiFile file = createFile("test.xml", text);
    transformAllChildren(file.getNode());
    System.out.println("Old parsing took " + (System.currentTimeMillis() - time) + "ms");
    int index = 0;
    while (index++ < 10) {
        newParsing(text);
    }
    LeafElement firstLeaf = TreeUtil.findFirstLeaf(file.getNode());
    index = 0;
    do {
        index++;
    } while ((firstLeaf = TreeUtil.nextLeaf(firstLeaf, null)) != null);
    System.out.println("For " + index + " lexems");
}
Also used : PsiFile(com.intellij.psi.PsiFile) LeafElement(com.intellij.psi.impl.source.tree.LeafElement)

Example 4 with LeafElement

use of com.intellij.psi.impl.source.tree.LeafElement in project intellij-community by JetBrains.

the class PsiParserFacadeImpl method createWhiteSpaceFromText.

@Override
@NotNull
public PsiElement createWhiteSpaceFromText(@NotNull @NonNls String text) throws IncorrectOperationException {
    final FileElement holderElement = DummyHolderFactory.createHolder(myManager, null).getTreeElement();
    final LeafElement newElement = ASTFactory.leaf(TokenType.WHITE_SPACE, holderElement.getCharTable().intern(text));
    holderElement.rawAddChildren(newElement);
    GeneratedMarkerVisitor.markGenerated(newElement.getPsi());
    return newElement.getPsi();
}
Also used : FileElement(com.intellij.psi.impl.source.tree.FileElement) LeafElement(com.intellij.psi.impl.source.tree.LeafElement) NotNull(org.jetbrains.annotations.NotNull)

Example 5 with LeafElement

use of com.intellij.psi.impl.source.tree.LeafElement in project intellij-community by JetBrains.

the class CodeEditUtil method replaceChild.

public static void replaceChild(ASTNode parent, @NotNull ASTNode oldChild, @NotNull ASTNode newChild) {
    saveWhitespacesInfo(oldChild);
    saveWhitespacesInfo(newChild);
    checkForOuters(oldChild);
    checkForOuters(newChild);
    LeafElement oldFirst = TreeUtil.findFirstLeaf(oldChild);
    parent.replaceChild(oldChild, newChild);
    final LeafElement firstLeaf = TreeUtil.findFirstLeaf(newChild);
    final ASTNode prevToken = TreeUtil.prevLeaf(newChild);
    if (firstLeaf != null) {
        final ASTNode nextLeaf = TreeUtil.nextLeaf(newChild);
        makePlaceHolderBetweenTokens(prevToken, firstLeaf, isFormattingRequired(prevToken, newChild), false);
        if (nextLeaf != null && !CharArrayUtil.containLineBreaks(nextLeaf.getText())) {
            makePlaceHolderBetweenTokens(TreeUtil.prevLeaf(nextLeaf), nextLeaf, false, false);
        }
    } else {
        if (oldFirst != null && prevToken == null) {
            ASTNode whitespaceNode = newChild.getTreeNext();
            if (whitespaceNode != null && whitespaceNode.getElementType() == TokenType.WHITE_SPACE) {
                // Replacing non-empty prefix to empty shall remove whitespace
                parent.removeChild(whitespaceNode);
            }
        }
        makePlaceHolderBetweenTokens(prevToken, TreeUtil.nextLeaf(newChild), isFormattingRequired(prevToken, newChild), false);
    }
}
Also used : LeafElement(com.intellij.psi.impl.source.tree.LeafElement)

Aggregations

LeafElement (com.intellij.psi.impl.source.tree.LeafElement)41 ASTNode (com.intellij.lang.ASTNode)15 PsiElement (com.intellij.psi.PsiElement)9 NotNull (org.jetbrains.annotations.NotNull)8 Nullable (org.jetbrains.annotations.Nullable)6 TreeElement (com.intellij.psi.impl.source.tree.TreeElement)4 IElementType (com.intellij.psi.tree.IElementType)4 PsiFragment (com.intellij.dupLocator.util.PsiFragment)3 CompositeElement (com.intellij.psi.impl.source.tree.CompositeElement)3 FileElement (com.intellij.psi.impl.source.tree.FileElement)3 EquivalenceDescriptorProvider (com.intellij.dupLocator.equivalence.EquivalenceDescriptorProvider)2 Project (com.intellij.openapi.project.Project)2 VirtualFile (com.intellij.openapi.vfs.VirtualFile)2 PsiFile (com.intellij.psi.PsiFile)2 PsiWhiteSpace (com.intellij.psi.PsiWhiteSpace)2 LeafPsiElement (com.intellij.psi.impl.source.tree.LeafPsiElement)2 CharTable (com.intellij.util.CharTable)2 LookupElement (com.intellij.codeInsight.lookup.LookupElement)1 LocalQuickFix (com.intellij.codeInspection.LocalQuickFix)1 ProblemDescriptor (com.intellij.codeInspection.ProblemDescriptor)1