Search in sources :

Example 41 with LookupElement

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

the class CfmlComponentReference method buildVariants.

@NotNull
public static Object[] buildVariants(String text, PsiFile containingFile, final Project project, @Nullable CfmlComponentReference reference, final boolean forceQualify) {
    Collection<Object> variants = new THashSet<>();
    String directoryName = "";
    if (text.contains(".")) {
        int i = text.lastIndexOf(".");
        directoryName = text.substring(0, i);
    }
    CfmlProjectConfiguration.State state = CfmlProjectConfiguration.getInstance(project).getState();
    CfmlMappingsConfig mappings = state != null ? state.getMapps().clone() : new CfmlMappingsConfig();
    adjustMappingsIfEmpty(mappings, project);
    if (reference != null)
        addFakeMappingsForImports(reference, mappings);
    List<String> realPossiblePaths = mappings.mapVirtualToReal(directoryName);
    for (String realPath : realPossiblePaths) {
        addVariantsFromPath(variants, directoryName, realPath);
    }
    for (String value : mappings.getServerMappings().keySet()) {
        if (value.startsWith(directoryName) && !value.isEmpty() && (StringUtil.startsWithChar(value, '/') || StringUtil.startsWithChar(value, '\\'))) {
            variants.add(value.replace('\\', '.').replace('/', '.').substring(1));
        }
    }
    containingFile = containingFile == null ? null : containingFile.getOriginalFile();
    if (containingFile != null && containingFile instanceof CfmlFile) {
        CfmlFile cfmlContainingFile = (CfmlFile) containingFile;
        if (directoryName.length() == 0) {
            PsiDirectory directory = cfmlContainingFile.getParent();
            if (directory != null) {
                addVariantsFromPath(variants, "", directory.getVirtualFile().getPresentableUrl());
            }
        } else {
            String dirPath = cfmlContainingFile.getParent().getVirtualFile().getPath() + "/" + directoryName.replaceAll("[./]+", "/");
            addVariantsFromPath(variants, directoryName, dirPath);
        }
    }
    final String finalDirectoryName = directoryName;
    return ContainerUtil.map2Array(variants, new Function<Object, Object>() {

        class DotInsertHandler implements InsertHandler<LookupElement> {

            @Override
            public void handleInsert(InsertionContext context, LookupElement item) {
                Document document = context.getDocument();
                int offset = context.getEditor().getCaretModel().getOffset();
                document.insertString(offset, ".");
                context.getEditor().getCaretModel().moveToOffset(offset + 1);
            }
        }

        public Object fun(final Object object) {
            if (object instanceof VirtualFile) {
                VirtualFile element = (VirtualFile) object;
                String elementNameWithoutExtension = element.getNameWithoutExtension();
                String name = forceQualify ? finalDirectoryName + (finalDirectoryName.length() == 0 ? "" : ".") + elementNameWithoutExtension : elementNameWithoutExtension;
                if (name.length() == 0)
                    name = element.getName();
                if (element.isDirectory()) {
                    return LookupElementBuilder.create(name).withIcon(DIRECTORY_CLOSED_ICON).withInsertHandler(new DotInsertHandler()).withCaseSensitivity(false);
                } else {
                    Icon icon = CLASS_ICON;
                    // choosing correct icon (class or interface)
                    if (CfmlIndex.getInstance(project).getComponentsByNameInScope(elementNameWithoutExtension, GlobalSearchScope.fileScope(project, element)).size() == 1) {
                        icon = CLASS_ICON;
                    } else if (CfmlIndex.getInstance(project).getInterfacesByNameInScope(elementNameWithoutExtension, GlobalSearchScope.fileScope(project, element)).size() == 1) {
                        icon = INTERFACE_ICON;
                    }
                    return LookupElementBuilder.create(name).withIcon(icon).withCaseSensitivity(false);
                }
            } else if (object instanceof String) {
                return LookupElementBuilder.create((String) object).withInsertHandler(new DotInsertHandler()).withCaseSensitivity(false);
            }
            return object;
        }
    });
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) CfmlFile(com.intellij.coldFusion.model.files.CfmlFile) InsertionContext(com.intellij.codeInsight.completion.InsertionContext) LookupElement(com.intellij.codeInsight.lookup.LookupElement) Document(com.intellij.openapi.editor.Document) THashSet(gnu.trove.THashSet) CfmlMappingsConfig(com.intellij.coldFusion.UI.config.CfmlMappingsConfig) CfmlProjectConfiguration(com.intellij.coldFusion.UI.config.CfmlProjectConfiguration) InsertHandler(com.intellij.codeInsight.completion.InsertHandler) NotNull(org.jetbrains.annotations.NotNull)

Example 42 with LookupElement

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

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

the class AndroidLayoutDomTest method doTestTagNameIcons.

private void doTestTagNameIcons(String fileName) throws IOException {
    VirtualFile file = copyFileToProject(fileName);
    myFixture.configureFromExistingVirtualFile(file);
    LookupElement[] elements = myFixture.complete(CompletionType.BASIC);
    Set<String> elementsToCheck = new HashSet<>(Arrays.asList("view", "include", "requestFocus", "fragment", "Button"));
    for (LookupElement element : elements) {
        String s = element.getLookupString();
        Object obj = element.getObject();
        if (elementsToCheck.contains(s)) {
            LookupElementPresentation presentation = new LookupElementPresentation();
            element.renderElement(presentation);
            assertNotNull("no icon for element: " + element, presentation.getIcon());
            if ("Button".equals(s)) {
                assertInstanceOf(obj, PsiClass.class);
            }
        }
    }
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) LookupElementPresentation(com.intellij.codeInsight.lookup.LookupElementPresentation) LookupElement(com.intellij.codeInsight.lookup.LookupElement) HashSet(com.intellij.util.containers.HashSet)

Example 44 with LookupElement

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

the class AndroidLayoutDomTest method testDeprecatedAttributeNamesCompletion.

// Deprecated attributes should be crossed out in the completion
// This test specifically checks for "android:editable" attribute on TextView
public void testDeprecatedAttributeNamesCompletion() throws Throwable {
    myFixture.configureFromExistingVirtualFile(copyFileToProject("text_view_editable.xml"));
    myFixture.complete(CompletionType.BASIC);
    // LookupElement that corresponds to "android:editable" attribute
    LookupElement editableElement = null;
    for (LookupElement element : myFixture.getLookupElements()) {
        if ("android:editable".equals(element.getLookupString())) {
            editableElement = element;
        }
    }
    assertEquals("android:editable", editableElement.getLookupString());
    LookupElementPresentation presentation = new LookupElementPresentation();
    editableElement.renderElement(presentation);
    assertTrue(presentation.isStrikeout());
}
Also used : LookupElementPresentation(com.intellij.codeInsight.lookup.LookupElementPresentation) LookupElement(com.intellij.codeInsight.lookup.LookupElement)

Example 45 with LookupElement

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

the class AndroidCompletionContributor method customizeAddedAttributes.

private static void customizeAddedAttributes(final AndroidFacet facet, CompletionParameters parameters, final XmlAttribute attribute, final CompletionResultSet resultSet) {
    final PsiElement gp = attribute.getParent();
    if (gp == null) {
        return;
    }
    final XmlTag tag = (XmlTag) gp;
    final DomElement element = DomManager.getDomManager(gp.getProject()).getDomElement(tag);
    if (!(element instanceof LayoutElement)) {
        return;
    }
    final boolean localNameCompletion;
    if (attribute.getName().contains(":")) {
        final String nsPrefix = attribute.getNamespacePrefix();
        if (nsPrefix.length() == 0) {
            return;
        }
        if (!SdkConstants.NS_RESOURCES.equals(tag.getNamespaceByPrefix(nsPrefix))) {
            return;
        } else {
            localNameCompletion = true;
        }
    } else {
        localNameCompletion = false;
    }
    final Map<String, String> prefix2ns = new HashMap<String, String>();
    resultSet.runRemainingContributors(parameters, new Consumer<CompletionResult>() {

        @Override
        public void consume(CompletionResult result) {
            LookupElement lookupElement = result.getLookupElement();
            final Object obj = lookupElement.getObject();
            if (obj instanceof String) {
                final String s = (String) obj;
                final int index = s.indexOf(':');
                final String attributeName = s.substring(index + 1);
                if (index > 0) {
                    final String prefix = s.substring(0, index);
                    String ns = prefix2ns.get(prefix);
                    if (ns == null) {
                        ns = tag.getNamespaceByPrefix(prefix);
                        prefix2ns.put(prefix, ns);
                    }
                    if (SdkConstants.NS_RESOURCES.equals(ns)) {
                        final boolean deprecated = isFrameworkAttributeDeprecated(facet, attribute, attributeName);
                        result = customizeLayoutAttributeLookupElement(lookupElement, result, attributeName, deprecated);
                    }
                } else if (localNameCompletion) {
                    result = customizeLayoutAttributeLookupElement(lookupElement, result, attributeName, false);
                }
            }
            resultSet.passResult(result);
        }
    });
}
Also used : LayoutElement(org.jetbrains.android.dom.layout.LayoutElement) LookupElement(com.intellij.codeInsight.lookup.LookupElement) PsiElement(com.intellij.psi.PsiElement)

Aggregations

LookupElement (com.intellij.codeInsight.lookup.LookupElement)183 PsiElement (com.intellij.psi.PsiElement)33 NotNull (org.jetbrains.annotations.NotNull)32 LookupElementBuilder (com.intellij.codeInsight.lookup.LookupElementBuilder)20 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 InsertionContext (com.intellij.codeInsight.completion.InsertionContext)6 PsiTypeLookupItem (com.intellij.codeInsight.lookup.PsiTypeLookupItem)6 VirtualFile (com.intellij.openapi.vfs.VirtualFile)6