Search in sources :

Example 11 with LookupElementBuilder

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

the class CompleteReferenceExpression method createPropertyLookupElement.

@Nullable
public static LookupElementBuilder createPropertyLookupElement(@NotNull PsiMethod accessor, @Nullable GroovyResolveResult resolveResult, @Nullable PrefixMatcher matcher) {
    String propName;
    PsiType propType;
    final boolean getter = GroovyPropertyUtils.isSimplePropertyGetter(accessor, null);
    if (getter) {
        propName = GroovyPropertyUtils.getPropertyNameByGetter(accessor);
    } else if (GroovyPropertyUtils.isSimplePropertySetter(accessor, null)) {
        propName = GroovyPropertyUtils.getPropertyNameBySetter(accessor);
    } else {
        return null;
    }
    assert propName != null;
    if (!PsiUtil.isValidReferenceName(propName)) {
        propName = "'" + propName + "'";
    }
    if (matcher != null && !matcher.prefixMatches(propName)) {
        return null;
    }
    if (getter) {
        propType = PsiUtil.getSmartReturnType(accessor);
    } else {
        propType = accessor.getParameterList().getParameters()[0].getType();
    }
    final PsiType substituted = resolveResult != null ? resolveResult.getSubstitutor().substitute(propType) : propType;
    LookupElementBuilder builder = LookupElementBuilder.create(generatePropertyResolveResult(propName, accessor, propType, resolveResult), propName).withIcon(JetgroovyIcons.Groovy.Property);
    if (substituted != null) {
        builder = builder.withTypeText(substituted.getPresentableText());
    }
    return builder;
}
Also used : LookupElementBuilder(com.intellij.codeInsight.lookup.LookupElementBuilder) Nullable(org.jetbrains.annotations.Nullable)

Example 12 with LookupElementBuilder

use of com.intellij.codeInsight.lookup.LookupElementBuilder in project intellij-plugins by JetBrains.

the class DartServerCompletionContributor method createLookupElement.

private static LookupElement createLookupElement(@NotNull final Project project, @NotNull final CompletionSuggestion suggestion) {
    final Element element = suggestion.getElement();
    final Location location = element == null ? null : element.getLocation();
    final DartLookupObject lookupObject = new DartLookupObject(project, location);
    final String lookupString = suggestion.getCompletion();
    LookupElementBuilder lookup = LookupElementBuilder.create(lookupObject, lookupString);
    // keywords are bold
    if (suggestion.getKind().equals(CompletionSuggestionKind.KEYWORD)) {
        lookup = lookup.bold();
    }
    final int dotIndex = lookupString.indexOf('.');
    if (dotIndex > 0 && dotIndex < lookupString.length() - 1 && StringUtil.isJavaIdentifier(lookupString.substring(0, dotIndex)) && StringUtil.isJavaIdentifier(lookupString.substring(dotIndex + 1))) {
        // 'path.Context' should match 'Conte' prefix
        lookup = lookup.withLookupString(lookupString.substring(dotIndex + 1));
    }
    boolean shouldSetSelection = true;
    if (element != null) {
        // @deprecated
        if (element.isDeprecated()) {
            lookup = lookup.strikeout();
        }
        // append type parameters
        final String typeParameters = element.getTypeParameters();
        if (typeParameters != null) {
            lookup = lookup.appendTailText(typeParameters, false);
        }
        // append parameters
        final String parameters = element.getParameters();
        if (parameters != null) {
            lookup = lookup.appendTailText(parameters, false);
        }
        // append return type
        final String returnType = element.getReturnType();
        if (!StringUtils.isEmpty(returnType)) {
            lookup = lookup.withTypeText(returnType, true);
        }
        // icon
        Icon icon = getBaseImage(element);
        if (icon != null) {
            icon = applyVisibility(icon, element.isPrivate());
            icon = applyOverlay(icon, element.isFinal(), AllIcons.Nodes.FinalMark);
            icon = applyOverlay(icon, element.isConst(), AllIcons.Nodes.FinalMark);
            lookup = lookup.withIcon(icon);
        }
        // Prepare for typing arguments, if any.
        if (CompletionSuggestionKind.INVOCATION.equals(suggestion.getKind())) {
            shouldSetSelection = false;
            final List<String> parameterNames = suggestion.getParameterNames();
            if (parameterNames != null) {
                lookup = lookup.withInsertHandler((context, item) -> {
                    // like in JavaCompletionUtil.insertParentheses()
                    final boolean needRightParenth = CodeInsightSettings.getInstance().AUTOINSERT_PAIR_BRACKET || parameterNames.isEmpty() && context.getCompletionChar() != '(';
                    if (parameterNames.isEmpty()) {
                        final ParenthesesInsertHandler<LookupElement> handler = ParenthesesInsertHandler.getInstance(false, false, false, needRightParenth, false);
                        handler.handleInsert(context, item);
                    } else {
                        final ParenthesesInsertHandler<LookupElement> handler = ParenthesesInsertHandler.getInstance(true, false, false, needRightParenth, false);
                        handler.handleInsert(context, item);
                        // Show parameters popup.
                        final Editor editor = context.getEditor();
                        final PsiElement psiElement = lookupObject.getElement();
                        if (DartCodeInsightSettings.getInstance().INSERT_DEFAULT_ARG_VALUES) {
                            // Insert argument defaults if provided.
                            final String argumentListString = suggestion.getDefaultArgumentListString();
                            if (argumentListString != null) {
                                final Document document = editor.getDocument();
                                int offset = editor.getCaretModel().getOffset();
                                // At this point caret is expected to be right after the opening paren.
                                // But if user was completing using Tab over the existing method call with arguments then old arguments are still there,
                                // if so, skip inserting argumentListString
                                final CharSequence text = document.getCharsSequence();
                                if (text.charAt(offset - 1) == '(' && text.charAt(offset) == ')') {
                                    document.insertString(offset, argumentListString);
                                    PsiDocumentManager.getInstance(project).commitDocument(document);
                                    final TemplateBuilderImpl builder = (TemplateBuilderImpl) TemplateBuilderFactory.getInstance().createTemplateBuilder(context.getFile());
                                    final int[] ranges = suggestion.getDefaultArgumentListTextRanges();
                                    // Only proceed if ranges are provided and well-formed.
                                    if (ranges != null && (ranges.length & 1) == 0) {
                                        int index = 0;
                                        while (index < ranges.length) {
                                            final int start = ranges[index];
                                            final int length = ranges[index + 1];
                                            final String arg = argumentListString.substring(start, start + length);
                                            final TextExpression expression = new TextExpression(arg);
                                            final TextRange range = new TextRange(offset + start, offset + start + length);
                                            index += 2;
                                            builder.replaceRange(range, "group_" + (index - 1), expression, true);
                                        }
                                        builder.run(editor, true);
                                    }
                                }
                            }
                        }
                        AutoPopupController.getInstance(project).autoPopupParameterInfo(editor, psiElement);
                    }
                });
            }
        }
    }
    // Use selection offset / length.
    if (shouldSetSelection) {
        lookup = lookup.withInsertHandler((context, item) -> {
            final Editor editor = context.getEditor();
            final int startOffset = context.getStartOffset() + suggestion.getSelectionOffset();
            final int endOffset = startOffset + suggestion.getSelectionLength();
            editor.getCaretModel().moveToOffset(startOffset);
            if (endOffset > startOffset) {
                editor.getSelectionModel().setSelection(startOffset, endOffset);
            }
        });
    }
    return PrioritizedLookupElement.withPriority(lookup, suggestion.getRelevance());
}
Also used : Language(com.intellij.lang.Language) InjectedLanguageManager(com.intellij.lang.injection.InjectedLanguageManager) VirtualFileWindow(com.intellij.injected.editor.VirtualFileWindow) DartResolveUtil(com.jetbrains.lang.dart.util.DartResolveUtil) DartSdk(com.jetbrains.lang.dart.sdk.DartSdk) AllIcons(com.intellij.icons.AllIcons) DartUriElement(com.jetbrains.lang.dart.psi.DartUriElement) VirtualFile(com.intellij.openapi.vfs.VirtualFile) Document(com.intellij.openapi.editor.Document) XMLLanguage(com.intellij.lang.xml.XMLLanguage) StringUtils(org.apache.commons.lang3.StringUtils) RowIcon(com.intellij.ui.RowIcon) AutoPopupController(com.intellij.codeInsight.AutoPopupController) org.dartlang.analysis.server.protocol(org.dartlang.analysis.server.protocol) ProcessingContext(com.intellij.util.ProcessingContext) LookupElementBuilder(com.intellij.codeInsight.lookup.LookupElementBuilder) PsiMultiReference(com.intellij.psi.impl.source.resolve.reference.impl.PsiMultiReference) DartYamlFileTypeFactory(com.jetbrains.lang.dart.DartYamlFileTypeFactory) CodeInsightSettings(com.intellij.codeInsight.CodeInsightSettings) PsiReference(com.intellij.psi.PsiReference) PlatformPatterns.psiElement(com.intellij.patterns.PlatformPatterns.psiElement) TextRange(com.intellij.openapi.util.TextRange) HtmlFileType(com.intellij.ide.highlighter.HtmlFileType) DartNewExpression(com.jetbrains.lang.dart.psi.DartNewExpression) com.intellij.codeInsight.completion(com.intellij.codeInsight.completion) Nullable(org.jetbrains.annotations.Nullable) List(java.util.List) DartLanguage(com.jetbrains.lang.dart.DartLanguage) NotNull(org.jetbrains.annotations.NotNull) DartStringLiteralExpression(com.jetbrains.lang.dart.psi.DartStringLiteralExpression) TemplateBuilderImpl(com.intellij.codeInsight.template.TemplateBuilderImpl) ParenthesesInsertHandler(com.intellij.codeInsight.completion.util.ParenthesesInsertHandler) DartCodeInsightSettings(com.jetbrains.lang.dart.ide.codeInsight.DartCodeInsightSettings) PsiElement(com.intellij.psi.PsiElement) Project(com.intellij.openapi.project.Project) PsiFile(com.intellij.psi.PsiFile) TemplateBuilderFactory(com.intellij.codeInsight.template.TemplateBuilderFactory) TextExpression(com.intellij.codeInsight.template.impl.TextExpression) PsiDocumentManager(com.intellij.psi.PsiDocumentManager) PlatformIcons(com.intellij.util.PlatformIcons) StandardPatterns.or(com.intellij.patterns.StandardPatterns.or) LookupElement(com.intellij.codeInsight.lookup.LookupElement) StringUtil(com.intellij.openapi.util.text.StringUtil) DartAnalysisServerService(com.jetbrains.lang.dart.analyzer.DartAnalysisServerService) HTMLLanguage(com.intellij.lang.html.HTMLLanguage) Editor(com.intellij.openapi.editor.Editor) PlatformPatterns.psiFile(com.intellij.patterns.PlatformPatterns.psiFile) PubspecYamlUtil(com.jetbrains.lang.dart.util.PubspecYamlUtil) Pair(com.intellij.openapi.util.Pair) LayeredIcon(com.intellij.ui.LayeredIcon) javax.swing(javax.swing) DartUriElement(com.jetbrains.lang.dart.psi.DartUriElement) PlatformPatterns.psiElement(com.intellij.patterns.PlatformPatterns.psiElement) PsiElement(com.intellij.psi.PsiElement) LookupElement(com.intellij.codeInsight.lookup.LookupElement) TextRange(com.intellij.openapi.util.TextRange) ParenthesesInsertHandler(com.intellij.codeInsight.completion.util.ParenthesesInsertHandler) Document(com.intellij.openapi.editor.Document) TextExpression(com.intellij.codeInsight.template.impl.TextExpression) TemplateBuilderImpl(com.intellij.codeInsight.template.TemplateBuilderImpl) LookupElementBuilder(com.intellij.codeInsight.lookup.LookupElementBuilder) RowIcon(com.intellij.ui.RowIcon) LayeredIcon(com.intellij.ui.LayeredIcon) Editor(com.intellij.openapi.editor.Editor) PsiElement(com.intellij.psi.PsiElement)

Example 13 with LookupElementBuilder

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

the class FileReferenceCompletionImpl method getFileReferenceCompletionVariants.

@NotNull
@Override
public Object[] getFileReferenceCompletionVariants(final FileReference reference) {
    final String s = reference.getText();
    if (s != null && s.equals("/")) {
        return ArrayUtil.EMPTY_OBJECT_ARRAY;
    }
    final CommonProcessors.CollectUniquesProcessor<PsiFileSystemItem> collector = new CommonProcessors.CollectUniquesProcessor<>();
    final PsiElementProcessor<PsiFileSystemItem> processor = new PsiElementProcessor<PsiFileSystemItem>() {

        @Override
        public boolean execute(@NotNull PsiFileSystemItem fileSystemItem) {
            return new FilteringProcessor<>(reference.getFileReferenceSet().getReferenceCompletionFilter(), collector).process(FileReference.getOriginalFile(fileSystemItem));
        }
    };
    List<Object> additionalItems = ContainerUtil.newArrayList();
    for (PsiFileSystemItem context : reference.getContexts()) {
        for (final PsiElement child : context.getChildren()) {
            if (child instanceof PsiFileSystemItem) {
                processor.execute((PsiFileSystemItem) child);
            }
        }
        if (context instanceof FileReferenceResolver) {
            additionalItems.addAll(((FileReferenceResolver) context).getVariants(reference));
        }
    }
    final FileType[] types = reference.getFileReferenceSet().getSuitableFileTypes();
    final THashSet<PsiElement> set = new THashSet<>(collector.getResults(), VARIANTS_HASHING_STRATEGY);
    final PsiElement[] candidates = PsiUtilCore.toPsiElementArray(set);
    final Object[] variants = new Object[candidates.length + additionalItems.size()];
    for (int i = 0; i < candidates.length; i++) {
        PsiElement candidate = candidates[i];
        Object item = reference.createLookupItem(candidate);
        if (item == null) {
            item = FileInfoManager.getFileLookupItem(candidate);
        }
        if (candidate instanceof PsiFile && item instanceof LookupElement && types.length > 0 && ArrayUtil.contains(((PsiFile) candidate).getFileType(), types)) {
            item = PrioritizedLookupElement.withPriority((LookupElement) item, Double.MAX_VALUE);
        }
        variants[i] = item;
    }
    for (int i = 0; i < additionalItems.size(); i++) {
        variants[i + candidates.length] = additionalItems.get(i);
    }
    if (!reference.getFileReferenceSet().isUrlEncoded()) {
        return variants;
    }
    List<Object> encodedVariants = new ArrayList<>(variants.length + additionalItems.size());
    for (int i = 0; i < candidates.length; i++) {
        final PsiElement element = candidates[i];
        if (element instanceof PsiNamedElement) {
            final PsiNamedElement psiElement = (PsiNamedElement) element;
            String name = psiElement.getName();
            final String encoded = reference.encode(name, psiElement);
            if (encoded == null)
                continue;
            if (!encoded.equals(name)) {
                final Icon icon = psiElement.getIcon(Iconable.ICON_FLAG_READ_STATUS | Iconable.ICON_FLAG_VISIBILITY);
                LookupElementBuilder item = FileInfoManager.getFileLookupItem(candidates[i], encoded, icon);
                encodedVariants.add(item.withTailText(" (" + name + ")"));
            } else {
                encodedVariants.add(variants[i]);
            }
        }
    }
    encodedVariants.addAll(additionalItems);
    return ArrayUtil.toObjectArray(encodedVariants);
}
Also used : PsiNamedElement(com.intellij.psi.PsiNamedElement) ArrayList(java.util.ArrayList) PsiFileSystemItem(com.intellij.psi.PsiFileSystemItem) NotNull(org.jetbrains.annotations.NotNull) PsiElementProcessor(com.intellij.psi.search.PsiElementProcessor) PsiFile(com.intellij.psi.PsiFile) CommonProcessors(com.intellij.util.CommonProcessors) PsiElement(com.intellij.psi.PsiElement) LookupElement(com.intellij.codeInsight.lookup.LookupElement) PrioritizedLookupElement(com.intellij.codeInsight.completion.PrioritizedLookupElement) THashSet(gnu.trove.THashSet) FileType(com.intellij.openapi.fileTypes.FileType) LookupElementBuilder(com.intellij.codeInsight.lookup.LookupElementBuilder) NotNull(org.jetbrains.annotations.NotNull)

Example 14 with LookupElementBuilder

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

the class DefaultTextCompletionValueDescriptor method createLookupBuilder.

@NotNull
@Override
public LookupElementBuilder createLookupBuilder(@NotNull T item) {
    LookupElementBuilder builder = LookupElementBuilder.create(item, getLookupString(item)).withIcon(getIcon(item));
    InsertHandler<LookupElement> handler = createInsertHandler(item);
    if (handler != null) {
        builder = builder.withInsertHandler(handler);
    }
    String tailText = getTailText(item);
    if (tailText != null) {
        builder = builder.withTailText(tailText, true);
    }
    String typeText = getTypeText(item);
    if (typeText != null) {
        builder = builder.withTypeText(typeText);
    }
    return builder;
}
Also used : LookupElementBuilder(com.intellij.codeInsight.lookup.LookupElementBuilder) LookupElement(com.intellij.codeInsight.lookup.LookupElement) NotNull(org.jetbrains.annotations.NotNull)

Example 15 with LookupElementBuilder

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

the class JavaGenerateMemberCompletionContributor method createGenerateMethodElement.

private static LookupElementBuilder createGenerateMethodElement(PsiMethod prototype, PsiSubstitutor substitutor, Icon icon, String typeText, InsertHandler<LookupElement> insertHandler) {
    String methodName = prototype.getName();
    String visibility = VisibilityUtil.getVisibilityModifier(prototype.getModifierList());
    String modifiers = (visibility == PsiModifier.PACKAGE_LOCAL ? "" : visibility + " ");
    PsiType type = substitutor.substitute(prototype.getReturnType());
    String signature = modifiers + (type == null ? "" : type.getPresentableText() + " ") + methodName;
    String parameters = PsiFormatUtil.formatMethod(prototype, substitutor, PsiFormatUtilBase.SHOW_PARAMETERS, PsiFormatUtilBase.SHOW_NAME);
    // leading space to make it a middle match, under all annotation suggestions
    String overrideSignature = " @Override " + signature;
    LookupElementBuilder element = LookupElementBuilder.create(prototype, signature).withLookupString(methodName).withLookupString(signature).withLookupString(overrideSignature).withInsertHandler(insertHandler).appendTailText(parameters, false).appendTailText(" {...}", true).withTypeText(typeText).withIcon(icon);
    if (prototype.isDeprecated()) {
        element = element.setStrikeout(true);
    }
    element.putUserData(GENERATE_ELEMENT, true);
    return element;
}
Also used : LookupElementBuilder(com.intellij.codeInsight.lookup.LookupElementBuilder)

Aggregations

LookupElementBuilder (com.intellij.codeInsight.lookup.LookupElementBuilder)57 LookupElement (com.intellij.codeInsight.lookup.LookupElement)20 NotNull (org.jetbrains.annotations.NotNull)16 PsiElement (com.intellij.psi.PsiElement)13 Nullable (org.jetbrains.annotations.Nullable)9 PsiFile (com.intellij.psi.PsiFile)7 Document (com.intellij.openapi.editor.Document)5 ArrayList (java.util.ArrayList)5 PlainPrefixMatcher (com.intellij.codeInsight.completion.PlainPrefixMatcher)3 PrioritizedLookupElement (com.intellij.codeInsight.completion.PrioritizedLookupElement)3 Editor (com.intellij.openapi.editor.Editor)3 TextRange (com.intellij.openapi.util.TextRange)3 PsiPresentableMetaData (com.intellij.psi.meta.PsiPresentableMetaData)3 XmlFile (com.intellij.psi.xml.XmlFile)3 XmlExtension (com.intellij.xml.XmlExtension)3 com.intellij.codeInsight.completion (com.intellij.codeInsight.completion)2 CompletionResultSet (com.intellij.codeInsight.completion.CompletionResultSet)2 InsertionContext (com.intellij.codeInsight.completion.InsertionContext)2 ParenthesesInsertHandler (com.intellij.codeInsight.completion.util.ParenthesesInsertHandler)2 AutoCompletionPolicy (com.intellij.codeInsight.lookup.AutoCompletionPolicy)2