Search in sources :

Example 1 with CompletionParameters

use of com.intellij.codeInsight.completion.CompletionParameters in project intellij-plugins by JetBrains.

the class LanguageListCompletionTest method testCustomCompletionProvider.

public void testCustomCompletionProvider() {
    try {
        PlatformTestUtil.registerExtension(CodeFenceLanguageProvider.EP_NAME, new CodeFenceLanguageProvider() {

            @Nullable
            @Override
            public Language getLanguageByInfoString(@NotNull String infoString) {
                return null;
            }

            @NotNull
            @Override
            public List<LookupElement> getCompletionVariantsForInfoString(@NotNull CompletionParameters parameters) {
                return Collections.singletonList(LookupElementBuilder.create("{js is a great ecma}").withInsertHandler((context, item) -> {
                    context.getDocument().insertString(context.getEditor().getCaretModel().getOffset(), "Customized insertion");
                    context.getEditor().getCaretModel().moveCaretRelatively("Customized insertion".length(), 0, true, false, true);
                }));
            }
        }, myFixture.getTestRootDisposable());
        LanguageGuesser.INSTANCE.resetCodeFenceLanguageProviders();
        configure();
        myFixture.completeBasic();
        assertContainsElements(myFixture.getLookupElementStrings(), "js", "javascript", "{js is a great ecma}");
        myFixture.type("ecm\t");
        checkResult();
    } finally {
        LanguageGuesser.INSTANCE.resetCodeFenceLanguageProviders();
    }
}
Also used : CodeFenceLanguageProvider(org.intellij.plugins.markdown.injection.CodeFenceLanguageProvider) CompletionParameters(com.intellij.codeInsight.completion.CompletionParameters) Language(com.intellij.lang.Language) JavascriptLanguage(com.intellij.lang.javascript.JavascriptLanguage) List(java.util.List) NotNull(org.jetbrains.annotations.NotNull) Nullable(org.jetbrains.annotations.Nullable)

Example 2 with CompletionParameters

use of com.intellij.codeInsight.completion.CompletionParameters in project oxy-template-support-plugin by mutant-industries.

the class JavaContext method fillCompletionVariants.

@Override
public void fillCompletionVariants(@NotNull CompletionParameters parameters, @NotNull CompletionResultSet result) {
    Module module;
    PsiElement element = parameters.getOriginalFile().getViewProvider().findElementAt(parameters.getOffset() - 1, OxyTemplateInnerJs.INSTANCE);
    if (element == null || element.getNode().getElementType() != JSTokenTypes.DOT && (element = element.getPrevSibling()) == null) {
        return;
    }
    if (element.getNode().getElementType() == TokenType.WHITE_SPACE) {
        element = element.getPrevSibling();
    }
    while (element != null && element.getNode().getElementType() != JSTokenTypes.DOT) {
        element = element.getLastChild();
        if (element instanceof PsiErrorElement) {
            element = element.getPrevSibling();
        }
    }
    if (element == null || element.getNode().getElementType() != JSTokenTypes.DOT || (element = element.getPrevSibling()) == null) {
        return;
    }
    if (element.getNode().getElementType() == TokenType.WHITE_SPACE) {
        element = element.getPrevSibling();
    }
    if (!(element instanceof JSExpression) || (module = ModuleUtilCore.findModuleForPsiElement(parameters.getOriginalFile())) == null) {
        return;
    }
    JSSimpleTypeProcessor typeProcessor = new JSSimpleTypeProcessor();
    JSTypeEvaluator.evaluateTypes((JSExpression) element, parameters.getOriginalFile().getViewProvider().getPsi(OxyTemplateInnerJs.INSTANCE), typeProcessor);
    JSType type = typeProcessor.getType();
    List<String> possibleJavaTypes = new LinkedList<>();
    if (type != null) {
        if (type instanceof JSCompositeTypeImpl) {
            possibleJavaTypes.addAll(((JSCompositeTypeImpl) type).getTypes().stream().filter(jsType -> jsType instanceof JSTypeImpl).map(JSType::getTypeText).collect(Collectors.toList()));
        } else if (type instanceof JSTypeImpl) {
            possibleJavaTypes.add(type.getTypeText());
        }
    }
    JavaPsiFacade facade = JavaPsiFacade.getInstance(parameters.getOriginalFile().getProject());
    GlobalSearchScope scope = GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module);
    List<PsiClass> possibleInstancesOf = new LinkedList<>();
    boolean suggestionsFound = false;
    PsiClass aClass;
    for (String possibleType : possibleJavaTypes) {
        if ((aClass = facade.findClass(possibleType, scope)) != null) {
            possibleInstancesOf.add(aClass);
            possibleInstancesOf.addAll(ExtenderProvider.getExtenders(aClass));
        }
    }
    for (PsiClass psiClass : possibleInstancesOf) {
        List<String> alreadySuggested = new LinkedList<>();
        for (PsiMethod method : psiClass.getAllMethods()) {
            if (method.getContainingClass() == null || Object.class.getName().equals(method.getContainingClass().getQualifiedName()) || method.getReturnType() == null || shippedBaseExtenderMethods.contains(method.getName()) || !method.getModifierList().hasModifierProperty(PsiModifier.PUBLIC) || InheritanceUtil.isInheritor(method.getContainingClass(), EXTENDER_INTERFACE_FQN) && !InheritanceUtil.isInheritor(method.getContainingClass(), EXTENDER_BASE_CLASS_FQN)) {
                continue;
            }
            String insertText = method.getName();
            String presentableText = method.getName();
            if (insertText.matches("((^is)|(^get)|(^set))[A-Z].*")) {
                insertText = presentableText = StringUtils.decapitalize(insertText.replaceFirst("(^is)|(^get)|(^set)", ""));
            } else {
                presentableText = method.getPresentation() == null ? presentableText + "()" : method.getPresentation().getPresentableText();
                insertText += "()";
            }
            if (alreadySuggested.contains(insertText)) {
                continue;
            }
            result.consume(LookupElementBuilder.create(method, insertText).withIcon(method.getIcon(0)).withTypeText(method.getReturnType().getPresentableText(), true).withTailText(" (" + psiClass.getContainingFile().getName() + ")", true).withPresentableText(presentableText).withInsertHandler(new TrailingPatternConsumer(INSERT_CONSUME)).withAutoCompletionPolicy(AutoCompletionPolicy.GIVE_CHANCE_TO_OVERWRITE));
            alreadySuggested.add(insertText);
            suggestionsFound = true;
        }
    }
    if (suggestionsFound) {
        result.stopHere();
    }
}
Also used : Arrays(java.util.Arrays) PsiErrorElement(com.intellij.psi.PsiErrorElement) JSTypeEvaluator(com.intellij.lang.javascript.psi.resolve.JSTypeEvaluator) StringUtils(com.sun.xml.internal.ws.util.StringUtils) JavaPsiFacade(com.intellij.psi.JavaPsiFacade) CompletionParameters(com.intellij.codeInsight.completion.CompletionParameters) JSCompositeTypeImpl(com.intellij.lang.javascript.psi.types.JSCompositeTypeImpl) Extender(ool.web.model.Extender) TokenType(com.intellij.psi.TokenType) PsiModifier(com.intellij.psi.PsiModifier) CompletionResultSet(com.intellij.codeInsight.completion.CompletionResultSet) CompletionContributor(com.intellij.codeInsight.completion.CompletionContributor) PsiClass(com.intellij.psi.PsiClass) JSTokenTypes(com.intellij.lang.javascript.JSTokenTypes) PsiElement(com.intellij.psi.PsiElement) InheritanceUtil(com.intellij.psi.util.InheritanceUtil) JSExpression(com.intellij.lang.javascript.psi.JSExpression) JSType(com.intellij.lang.javascript.psi.JSType) LinkedList(java.util.LinkedList) Module(com.intellij.openapi.module.Module) OxyTemplateInnerJs(ool.intellij.plugin.lang.OxyTemplateInnerJs) JSSimpleTypeProcessor(com.intellij.lang.javascript.psi.resolve.JSSimpleTypeProcessor) LookupElementBuilder(com.intellij.codeInsight.lookup.LookupElementBuilder) ModuleUtilCore(com.intellij.openapi.module.ModuleUtilCore) PsiMethod(com.intellij.psi.PsiMethod) ExtenderProvider(ool.intellij.plugin.psi.reference.innerjs.ExtenderProvider) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) Collectors(java.util.stream.Collectors) AutoCompletionPolicy(com.intellij.codeInsight.lookup.AutoCompletionPolicy) List(java.util.List) TrailingPatternConsumer(ool.intellij.plugin.editor.completion.handler.TrailingPatternConsumer) Pattern(java.util.regex.Pattern) BaseExtender(ool.web.model.BaseExtender) NotNull(org.jetbrains.annotations.NotNull) JSTypeImpl(com.intellij.lang.javascript.psi.types.JSTypeImpl) JavaPsiFacade(com.intellij.psi.JavaPsiFacade) JSType(com.intellij.lang.javascript.psi.JSType) PsiMethod(com.intellij.psi.PsiMethod) PsiClass(com.intellij.psi.PsiClass) JSExpression(com.intellij.lang.javascript.psi.JSExpression) LinkedList(java.util.LinkedList) PsiErrorElement(com.intellij.psi.PsiErrorElement) JSTypeImpl(com.intellij.lang.javascript.psi.types.JSTypeImpl) JSCompositeTypeImpl(com.intellij.lang.javascript.psi.types.JSCompositeTypeImpl) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) TrailingPatternConsumer(ool.intellij.plugin.editor.completion.handler.TrailingPatternConsumer) JSSimpleTypeProcessor(com.intellij.lang.javascript.psi.resolve.JSSimpleTypeProcessor) Module(com.intellij.openapi.module.Module) PsiElement(com.intellij.psi.PsiElement)

Example 3 with CompletionParameters

use of com.intellij.codeInsight.completion.CompletionParameters in project component-runtime by Talend.

the class PropertiesCompletionProvider method addCompletions.

@Override
protected void addCompletions(final CompletionParameters completionParameters, final ProcessingContext processingContext, final CompletionResultSet resultSet) {
    final PsiElement element = completionParameters.getPosition();
    if (!LeafPsiElement.class.isInstance(element)) {
        // ignore comment
        return;
    }
    final Project project = element.getProject();
    final Module module = findModule(element);
    final SuggestionService service = ServiceManager.getService(project, SuggestionService.class);
    if ((module == null || !service.isSupported(completionParameters))) {
        // limit suggestion to Messages
        return;
    }
    if (PropertyValueImpl.class.isInstance(element)) {
        ofNullable(PropertyValueImpl.class.cast(element).getPrevSibling()).map(PsiElement::getPrevSibling).map(PsiElement::getText).ifPresent(text -> resultSet.addAllElements(service.computeValueSuggestions(text)));
    } else if (PropertyKeyImpl.class.isInstance(element)) {
        final List<String> containerElements = PropertiesFileImpl.class.cast(element.getContainingFile()).getProperties().stream().filter(p -> !Objects.equals(p.getKey(), element.getText())).map(IProperty::getKey).collect(toList());
        resultSet.addAllElements(service.computeKeySuggestions(project, module, getPropertiesPackage(module, completionParameters), containerElements, truncateIdeaDummyIdentifier(element)));
    }
}
Also used : ProcessingContext(com.intellij.util.ProcessingContext) Optional.ofNullable(java.util.Optional.ofNullable) CompletionParameters(com.intellij.codeInsight.completion.CompletionParameters) LeafPsiElement(com.intellij.psi.impl.source.tree.LeafPsiElement) SuggestionService(org.talend.sdk.component.intellij.service.SuggestionService) PropertyKeyImpl(com.intellij.lang.properties.psi.impl.PropertyKeyImpl) PsiUtil.truncateIdeaDummyIdentifier(org.talend.sdk.component.intellij.util.PsiUtil.truncateIdeaDummyIdentifier) Objects(java.util.Objects) CompletionResultSet(com.intellij.codeInsight.completion.CompletionResultSet) PropertyValueImpl(com.intellij.lang.properties.psi.impl.PropertyValueImpl) Collectors.toList(java.util.stream.Collectors.toList) List(java.util.List) IProperty(com.intellij.lang.properties.IProperty) ServiceManager(com.intellij.openapi.components.ServiceManager) PsiUtil.findModule(org.talend.sdk.component.intellij.util.PsiUtil.findModule) CompletionProvider(com.intellij.codeInsight.completion.CompletionProvider) PsiElement(com.intellij.psi.PsiElement) Project(com.intellij.openapi.project.Project) Module(com.intellij.openapi.module.Module) PropertiesFileImpl(com.intellij.lang.properties.psi.impl.PropertiesFileImpl) Project(com.intellij.openapi.project.Project) LeafPsiElement(com.intellij.psi.impl.source.tree.LeafPsiElement) IProperty(com.intellij.lang.properties.IProperty) Collectors.toList(java.util.stream.Collectors.toList) List(java.util.List) SuggestionService(org.talend.sdk.component.intellij.service.SuggestionService) PsiUtil.findModule(org.talend.sdk.component.intellij.util.PsiUtil.findModule) Module(com.intellij.openapi.module.Module) LeafPsiElement(com.intellij.psi.impl.source.tree.LeafPsiElement) PsiElement(com.intellij.psi.PsiElement) PropertyValueImpl(com.intellij.lang.properties.psi.impl.PropertyValueImpl) PropertyKeyImpl(com.intellij.lang.properties.psi.impl.PropertyKeyImpl)

Example 4 with CompletionParameters

use of com.intellij.codeInsight.completion.CompletionParameters in project android by JetBrains.

the class EditLogFilterDialog method createEditorFields.

private void createEditorFields() {
    myNameFieldLabel.setLabelFor(myFilterNameField);
    myLogMessageField = new RegexFilterComponent(LOG_FILTER_MESSAGE_HISTORY, FILTER_HISTORY_SIZE);
    myLogMessageFieldWrapper.add(myLogMessageField);
    myLogMessageLabel.setLabelFor(myLogMessageField);
    myTagField = new RegexFilterComponent(LOG_FILTER_TAG_HISTORY, FILTER_HISTORY_SIZE);
    myTagFieldWrapper.add(myTagField);
    myLogTagLabel.setLabelFor(myTagField);
    myPidField = new TextFieldWithAutoCompletion<>(myProject, new TextFieldWithAutoCompletion.StringsCompletionProvider(null, null) {

        @NotNull
        @Override
        public Collection<String> getItems(String prefix, boolean cached, CompletionParameters parameters) {
            parseExistingMessagesIfNecessary();
            setItems(myUsedPids);
            return super.getItems(prefix, cached, parameters);
        }

        @Override
        public int compare(String item1, String item2) {
            final int pid1 = Integer.parseInt(item1);
            final int pid2 = Integer.parseInt(item2);
            return Comparing.compare(pid1, pid2);
        }
    }, true, null);
    myPidFieldWrapper.add(myPidField);
    myPidLabel.setLabelFor(myPidField);
    myPackageNameField = new RegexFilterComponent(LOG_FILTER_PACKAGE_NAME_HISTORY, FILTER_HISTORY_SIZE);
    myPackageNameFieldWrapper.add(myPackageNameField);
    myPackageNameLabel.setLabelFor(myPackageNameField);
    myLogLevelCombo.setModel(new EnumComboBoxModel<>(Log.LogLevel.class));
    myLogLevelCombo.setRenderer(new ListCellRendererWrapper() {

        @Override
        public void customize(JList list, Object value, int index, boolean selected, boolean hasFocus) {
            if (value != null) {
                setText(StringUtil.capitalize(((Log.LogLevel) value).getStringValue().toLowerCase()));
            }
        }
    });
    myLogLevelCombo.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            if (myActiveFilter == null) {
                return;
            }
            Log.LogLevel selectedItem = (Log.LogLevel) myLogLevelCombo.getSelectedItem();
            myActiveFilter.setLogLevel(selectedItem.getStringValue());
        }
    });
    final Key<JComponent> componentKey = new Key<>("myComponent");
    myFilterNameField.getDocument().putUserData(componentKey, myFilterNameField);
    myPidField.getDocument().putUserData(componentKey, myPidField);
    DocumentListener l = new DocumentListener() {

        @Override
        public void documentChanged(DocumentEvent e) {
            if (myActiveFilter == null) {
                return;
            }
            String text = e.getDocument().getText().trim();
            JComponent src = e.getDocument().getUserData(componentKey);
            if (src == myPidField) {
                myActiveFilter.setPid(text);
            } else if (src == myFilterNameField) {
                int index = myFiltersList.getSelectedIndex();
                if (index != -1) {
                    myFiltersListModel.setElementAt(text, index);
                }
                myActiveFilter.setName(text);
            }
        }
    };
    myFilterNameField.getDocument().addDocumentListener(l);
    myPidField.getDocument().addDocumentListener(l);
    RegexFilterComponent.Listener rl = new RegexFilterComponent.Listener() {

        @Override
        public void filterChanged(RegexFilterComponent filter) {
            if (myActiveFilter == null) {
                return;
            }
            if (filter == myTagField) {
                myActiveFilter.setLogTagPattern(filter.getFilter());
                myActiveFilter.setLogTagIsRegex(filter.isRegex());
            } else if (filter == myLogMessageField) {
                myActiveFilter.setLogMessagePattern(filter.getFilter());
                myActiveFilter.setLogMessageIsRegex(filter.isRegex());
            } else if (filter == myPackageNameField) {
                myActiveFilter.setPackageNamePattern(filter.getFilter());
                myActiveFilter.setPackageNameIsRegex(filter.isRegex());
            }
        }
    };
    myTagField.addRegexListener(rl);
    myLogMessageField.addRegexListener(rl);
    myPackageNameField.addRegexListener(rl);
}
Also used : DocumentListener(com.intellij.openapi.editor.event.DocumentListener) DocumentListener(com.intellij.openapi.editor.event.DocumentListener) ActionListener(java.awt.event.ActionListener) ListSelectionListener(javax.swing.event.ListSelectionListener) Log(com.android.ddmlib.Log) ActionEvent(java.awt.event.ActionEvent) DocumentEvent(com.intellij.openapi.editor.event.DocumentEvent) CompletionParameters(com.intellij.codeInsight.completion.CompletionParameters) ActionListener(java.awt.event.ActionListener) Key(com.intellij.openapi.util.Key)

Example 5 with CompletionParameters

use of com.intellij.codeInsight.completion.CompletionParameters in project intellij-plugins by JetBrains.

the class CfmlTagNamesCompletionProvider method addCompletionsFromDirectory.

private void addCompletionsFromDirectory(CompletionResultSet result, CompletionParameters parameters, String libtag, String prefix) {
    final PsiFile originalFile = parameters.getOriginalFile();
    final VirtualFile folder = CfmlUtil.findFileByLibTag(originalFile, libtag);
    if (folder != null && folder.isDirectory()) {
        final Set<String> names = new THashSet<>(CfmlIndex.getInstance(originalFile.getProject()).getAllComponentsNames());
        names.retainAll(ContainerUtil.map(folder.getChildren(), virtualFile -> FileUtil.getNameWithoutExtension(virtualFile.getName()).toLowerCase()));
        for (String componentName : names) {
            result.addElement(LookupElementBuilder.create(prefix + ':' + componentName).withCaseSensitivity(false));
        }
    }
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) ProcessingContext(com.intellij.util.ProcessingContext) LookupElementBuilder(com.intellij.codeInsight.lookup.LookupElementBuilder) CfmlUtil(com.intellij.coldFusion.model.CfmlUtil) VirtualFile(com.intellij.openapi.vfs.VirtualFile) CompletionParameters(com.intellij.codeInsight.completion.CompletionParameters) Set(java.util.Set) THashSet(gnu.trove.THashSet) ContainerUtil(com.intellij.util.containers.ContainerUtil) CompletionResultSet(com.intellij.codeInsight.completion.CompletionResultSet) PsiTreeUtil(com.intellij.psi.util.PsiTreeUtil) CfmlIndex(com.intellij.coldFusion.model.psi.stubs.CfmlIndex) CompletionProvider(com.intellij.codeInsight.completion.CompletionProvider) Function(com.intellij.util.Function) PsiFile(com.intellij.psi.PsiFile) CfmlImport(com.intellij.coldFusion.model.psi.CfmlImport) FileUtil(com.intellij.openapi.util.io.FileUtil) NotNull(org.jetbrains.annotations.NotNull) CfmlFileViewProvider(com.intellij.coldFusion.model.files.CfmlFileViewProvider) PsiFile(com.intellij.psi.PsiFile) THashSet(gnu.trove.THashSet)

Aggregations

CompletionParameters (com.intellij.codeInsight.completion.CompletionParameters)5 CompletionResultSet (com.intellij.codeInsight.completion.CompletionResultSet)3 List (java.util.List)3 NotNull (org.jetbrains.annotations.NotNull)3 CompletionProvider (com.intellij.codeInsight.completion.CompletionProvider)2 LookupElementBuilder (com.intellij.codeInsight.lookup.LookupElementBuilder)2 Module (com.intellij.openapi.module.Module)2 PsiElement (com.intellij.psi.PsiElement)2 ProcessingContext (com.intellij.util.ProcessingContext)2 Log (com.android.ddmlib.Log)1 CompletionContributor (com.intellij.codeInsight.completion.CompletionContributor)1 AutoCompletionPolicy (com.intellij.codeInsight.lookup.AutoCompletionPolicy)1 CfmlUtil (com.intellij.coldFusion.model.CfmlUtil)1 CfmlFileViewProvider (com.intellij.coldFusion.model.files.CfmlFileViewProvider)1 CfmlImport (com.intellij.coldFusion.model.psi.CfmlImport)1 CfmlIndex (com.intellij.coldFusion.model.psi.stubs.CfmlIndex)1 Language (com.intellij.lang.Language)1 JSTokenTypes (com.intellij.lang.javascript.JSTokenTypes)1 JavascriptLanguage (com.intellij.lang.javascript.JavascriptLanguage)1 JSExpression (com.intellij.lang.javascript.psi.JSExpression)1