Search in sources :

Example 6 with LookupElement

use of com.intellij.codeInsight.lookup.LookupElement in project intellij-elixir by KronicDeth.

the class CallDefinitionClause method callDefinitionClauseLookupElements.

/*
     * Private Instance Methods
     */
@NotNull
private static Iterable<LookupElement> callDefinitionClauseLookupElements(@NotNull Call scope) {
    Call[] childCalls = macroChildCalls(scope);
    List<LookupElement> lookupElementList = null;
    if (childCalls != null && childCalls.length > 0) {
        for (Call childCall : childCalls) {
            if (org.elixir_lang.structure_view.element.CallDefinitionClause.is(childCall)) {
                Pair<String, IntRange> nameArityRange = nameArityRange(childCall);
                if (nameArityRange != null) {
                    String name = nameArityRange.first;
                    if (name != null) {
                        if (lookupElementList == null) {
                            lookupElementList = new ArrayList<LookupElement>();
                        }
                        lookupElementList.add(org.elixir_lang.code_insight.lookup.element.CallDefinitionClause.createWithSmartPointer(nameArityRange.first, childCall));
                    }
                }
            }
        }
    }
    if (lookupElementList == null) {
        lookupElementList = Collections.emptyList();
    }
    return lookupElementList;
}
Also used : Call(org.elixir_lang.psi.call.Call) IntRange(org.apache.commons.lang.math.IntRange) LookupElement(com.intellij.codeInsight.lookup.LookupElement) NotNull(org.jetbrains.annotations.NotNull)

Example 7 with LookupElement

use of com.intellij.codeInsight.lookup.LookupElement in project intellij-elixir by KronicDeth.

the class Variants method executeOnVariable.

/*
     *
     * Instance Methods
     *
     */
/*
     * Protected Instance Methods
     */
/**
     * Decides whether {@code match} matches the criteria being searched for.  All other {@link #execute} methods
     * eventually end here.
     *
     * @return {@code false}, as all variables should be found.  Prefix filtering will be done later by IDEA core.
     */
@Override
protected boolean executeOnVariable(@NotNull PsiNamedElement match, @NotNull ResolveState state) {
    PsiReference reference = match.getReference();
    String name = null;
    PsiElement declaration = match;
    if (reference != null) {
        PsiElement resolved = reference.resolve();
        if (resolved != null) {
            declaration = resolved;
            if (resolved instanceof PsiNamedElement) {
                PsiNamedElement namedResolved = (PsiNamedElement) resolved;
                name = namedResolved.getName();
            }
        }
    }
    if (name == null) {
        name = match.getName();
    }
    if (name != null) {
        if (lookupElementByElement == null) {
            lookupElementByElement = new THashMap<PsiElement, LookupElement>();
        }
        if (!lookupElementByElement.containsKey(declaration)) {
            final String finalName = name;
            lookupElementByElement.put(declaration, LookupElementBuilder.createWithSmartPointer(name, declaration).withRenderer(new org.elixir_lang.code_insight.lookup.element_renderer.Variable(finalName)));
        }
    }
    return true;
}
Also used : Variable(org.elixir_lang.psi.scope.Variable) PsiNamedElement(com.intellij.psi.PsiNamedElement) PsiReference(com.intellij.psi.PsiReference) LookupElement(com.intellij.codeInsight.lookup.LookupElement) PsiElement(com.intellij.psi.PsiElement)

Example 8 with LookupElement

use of com.intellij.codeInsight.lookup.LookupElement 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 9 with LookupElement

use of com.intellij.codeInsight.lookup.LookupElement in project intellij-community by JetBrains.

the class PydevConsoleReference method getVariants.

@NotNull
public Object[] getVariants() {
    Map<String, LookupElement> variants = Maps.newHashMap();
    try {
        final List<PydevCompletionVariant> completions = myCommunication.getCompletions(getText(), myPrefix);
        for (PydevCompletionVariant completion : completions) {
            final PsiManager manager = myElement.getManager();
            final String name = completion.getName();
            final int type = completion.getType();
            LookupElementBuilder builder = LookupElementBuilder.create(new PydevConsoleElement(manager, name, completion.getDescription())).withIcon(PyCodeCompletionImages.getImageForType(type));
            String args = completion.getArgs();
            if (args.equals("(%)")) {
                builder.withPresentableText("%" + completion.getName());
                builder = builder.withInsertHandler(new InsertHandler<LookupElement>() {

                    @Override
                    public void handleInsert(InsertionContext context, LookupElement item) {
                        final Editor editor = context.getEditor();
                        final Document document = editor.getDocument();
                        int offset = context.getStartOffset();
                        if (offset == 0 || !"%".equals(document.getText(TextRange.from(offset - 1, 1)))) {
                            document.insertString(offset, "%");
                        }
                    }
                });
                args = "";
            } else if (!StringUtil.isEmptyOrSpaces(args)) {
                builder = builder.withTailText(args);
            }
            // Set function insert handler
            if (type == IToken.TYPE_FUNCTION || args.endsWith(")")) {
                builder = builder.withInsertHandler(ParenthesesInsertHandler.WITH_PARAMETERS);
            }
            variants.put(name, builder);
        }
    } catch (Exception e) {
    //LOG.error(e);
    }
    return variants.values().toArray();
}
Also used : LookupElement(com.intellij.codeInsight.lookup.LookupElement) InsertionContext(com.intellij.codeInsight.completion.InsertionContext) Document(com.intellij.openapi.editor.Document) PydevCompletionVariant(com.jetbrains.python.console.pydev.PydevCompletionVariant) LookupElementBuilder(com.intellij.codeInsight.lookup.LookupElementBuilder) InsertHandler(com.intellij.codeInsight.completion.InsertHandler) ParenthesesInsertHandler(com.intellij.codeInsight.completion.util.ParenthesesInsertHandler) Editor(com.intellij.openapi.editor.Editor) NotNull(org.jetbrains.annotations.NotNull)

Example 10 with LookupElement

use of com.intellij.codeInsight.lookup.LookupElement in project intellij-community by JetBrains.

the class PyTestCase method completeCaretWithMultipleVariants.

/**
   * When you have more than one completion variant, you may use this method providing variant to choose.
   * It only works for one caret (multiple carets not supported) and since it puts tab after completion, be sure to limit
   * line somehow (i.e. with comment).
   * <br/>
   * Example: "user.n[caret]." There are "name" and "nose" fields.
   * By calling this function with "nose" you will end with "user.nose  ".
   */
protected final void completeCaretWithMultipleVariants(@NotNull final String... desiredVariants) {
    final LookupElement[] lookupElements = myFixture.completeBasic();
    final LookupEx lookup = myFixture.getLookup();
    if (lookupElements != null && lookupElements.length > 1) {
        // More than one element returned, check directly because completion can't work in this case
        for (final LookupElement element : lookupElements) {
            final String suggestedString = element.getLookupString();
            if (Arrays.asList(desiredVariants).contains(suggestedString)) {
                myFixture.getLookup().setCurrentItem(element);
                lookup.setCurrentItem(element);
                myFixture.completeBasicAllCarets('\t');
                return;
            }
        }
    }
}
Also used : LookupElement(com.intellij.codeInsight.lookup.LookupElement) LookupEx(com.intellij.codeInsight.lookup.LookupEx)

Aggregations

LookupElement (com.intellij.codeInsight.lookup.LookupElement)182 PsiElement (com.intellij.psi.PsiElement)32 NotNull (org.jetbrains.annotations.NotNull)32 LookupElementBuilder (com.intellij.codeInsight.lookup.LookupElementBuilder)19 Nullable (org.jetbrains.annotations.Nullable)17 ArrayList (java.util.ArrayList)14 Project (com.intellij.openapi.project.Project)12 LookupElementPresentation (com.intellij.codeInsight.lookup.LookupElementPresentation)10 Document (com.intellij.openapi.editor.Document)10 PsiFile (com.intellij.psi.PsiFile)10 Editor (com.intellij.openapi.editor.Editor)9 THashSet (gnu.trove.THashSet)8 LinkedHashSet (java.util.LinkedHashSet)8 PrioritizedLookupElement (com.intellij.codeInsight.completion.PrioritizedLookupElement)7 XmlTag (com.intellij.psi.xml.XmlTag)7 Consumer (com.intellij.util.Consumer)7 HashSet (java.util.HashSet)7 PsiTypeLookupItem (com.intellij.codeInsight.lookup.PsiTypeLookupItem)6 VirtualFile (com.intellij.openapi.vfs.VirtualFile)6 com.intellij.psi (com.intellij.psi)6