Search in sources :

Example 1 with InsertionContext

use of com.intellij.codeInsight.completion.InsertionContext 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 2 with InsertionContext

use of com.intellij.codeInsight.completion.InsertionContext in project intellij-community by JetBrains.

the class DefaultXmlTagNameProvider method getRootTagsVariants.

private static List<LookupElement> getRootTagsVariants(final XmlTag tag, final List<LookupElement> elements) {
    elements.add(LookupElementBuilder.create("?xml version=\"1.0\" encoding=\"\" ?>").withPresentableText("<?xml version=\"1.0\" encoding=\"\" ?>").withInsertHandler(new InsertHandler<LookupElement>() {

        @Override
        public void handleInsert(InsertionContext context, LookupElement item) {
            int offset = context.getEditor().getCaretModel().getOffset();
            context.getEditor().getCaretModel().moveToOffset(offset - 4);
            AutoPopupController.getInstance(context.getProject()).scheduleAutoPopup(context.getEditor());
        }
    }));
    final FileBasedIndex fbi = FileBasedIndex.getInstance();
    Collection<String> result = new ArrayList<>();
    Processor<String> processor = Processors.cancelableCollectProcessor(result);
    fbi.processAllKeys(XmlNamespaceIndex.NAME, processor, tag.getProject());
    final GlobalSearchScope scope = new EverythingGlobalScope();
    for (final String ns : result) {
        if (ns.startsWith("file://"))
            continue;
        fbi.processValues(XmlNamespaceIndex.NAME, ns, null, new FileBasedIndex.ValueProcessor<XsdNamespaceBuilder>() {

            @Override
            public boolean process(final VirtualFile file, XsdNamespaceBuilder value) {
                List<String> tags = value.getRootTags();
                for (String s : tags) {
                    elements.add(LookupElementBuilder.create(s).withTypeText(ns).withInsertHandler(new XmlTagInsertHandler() {

                        @Override
                        public void handleInsert(InsertionContext context, LookupElement item) {
                            final Editor editor = context.getEditor();
                            final Document document = context.getDocument();
                            final int caretOffset = editor.getCaretModel().getOffset();
                            final RangeMarker caretMarker = document.createRangeMarker(caretOffset, caretOffset);
                            caretMarker.setGreedyToRight(true);
                            XmlFile psiFile = (XmlFile) context.getFile();
                            boolean incomplete = XmlUtil.getTokenOfType(tag, XmlTokenType.XML_TAG_END) == null && XmlUtil.getTokenOfType(tag, XmlTokenType.XML_EMPTY_ELEMENT_END) == null;
                            XmlNamespaceHelper.getHelper(psiFile).insertNamespaceDeclaration(psiFile, editor, Collections.singleton(ns), null, null);
                            editor.getCaretModel().moveToOffset(caretMarker.getEndOffset());
                            XmlTag rootTag = psiFile.getRootTag();
                            if (incomplete) {
                                XmlToken token = XmlUtil.getTokenOfType(rootTag, XmlTokenType.XML_EMPTY_ELEMENT_END);
                                // remove tag end added by smart attribute adder :(
                                if (token != null)
                                    token.delete();
                                PsiDocumentManager.getInstance(context.getProject()).doPostponedOperationsAndUnblockDocument(document);
                                super.handleInsert(context, item);
                            }
                        }
                    }));
                }
                return true;
            }
        }, scope);
    }
    return elements;
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) XmlFile(com.intellij.psi.xml.XmlFile) EverythingGlobalScope(com.intellij.psi.search.EverythingGlobalScope) XsdNamespaceBuilder(com.intellij.xml.index.XsdNamespaceBuilder) RangeMarker(com.intellij.openapi.editor.RangeMarker) InsertionContext(com.intellij.codeInsight.completion.InsertionContext) LookupElement(com.intellij.codeInsight.lookup.LookupElement) PrioritizedLookupElement(com.intellij.codeInsight.completion.PrioritizedLookupElement) XmlTagInsertHandler(com.intellij.codeInsight.completion.XmlTagInsertHandler) Document(com.intellij.openapi.editor.Document) XmlToken(com.intellij.psi.xml.XmlToken) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) InsertHandler(com.intellij.codeInsight.completion.InsertHandler) XmlTagInsertHandler(com.intellij.codeInsight.completion.XmlTagInsertHandler) Editor(com.intellij.openapi.editor.Editor) FileBasedIndex(com.intellij.util.indexing.FileBasedIndex) XmlTag(com.intellij.psi.xml.XmlTag)

Example 3 with InsertionContext

use of com.intellij.codeInsight.completion.InsertionContext 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 4 with InsertionContext

use of com.intellij.codeInsight.completion.InsertionContext in project intellij-community by JetBrains.

the class MyLookupExpression method initLookupItems.

private static LookupElement[] initLookupItems(LinkedHashSet<String> names, PsiNamedElement elementToRename, PsiElement nameSuggestionContext, final boolean shouldSelectAll) {
    if (names == null) {
        names = new LinkedHashSet<>();
        for (NameSuggestionProvider provider : Extensions.getExtensions(NameSuggestionProvider.EP_NAME)) {
            final SuggestedNameInfo suggestedNameInfo = provider.getSuggestedNames(elementToRename, nameSuggestionContext, names);
            if (suggestedNameInfo != null && provider instanceof PreferrableNameSuggestionProvider && !((PreferrableNameSuggestionProvider) provider).shouldCheckOthers()) {
                break;
            }
        }
    }
    final LookupElement[] lookupElements = new LookupElement[names.size()];
    final Iterator<String> iterator = names.iterator();
    for (int i = 0; i < lookupElements.length; i++) {
        final String suggestion = iterator.next();
        lookupElements[i] = LookupElementBuilder.create(suggestion).withInsertHandler(new InsertHandler<LookupElement>() {

            @Override
            public void handleInsert(InsertionContext context, LookupElement item) {
                if (shouldSelectAll)
                    return;
                final Editor topLevelEditor = InjectedLanguageUtil.getTopLevelEditor(context.getEditor());
                final TemplateState templateState = TemplateManagerImpl.getTemplateState(topLevelEditor);
                if (templateState != null) {
                    final TextRange range = templateState.getCurrentVariableRange();
                    if (range != null) {
                        topLevelEditor.getDocument().replaceString(range.getStartOffset(), range.getEndOffset(), suggestion);
                    }
                }
            }
        });
    }
    return lookupElements;
}
Also used : PreferrableNameSuggestionProvider(com.intellij.refactoring.rename.PreferrableNameSuggestionProvider) NameSuggestionProvider(com.intellij.refactoring.rename.NameSuggestionProvider) TextRange(com.intellij.openapi.util.TextRange) PreferrableNameSuggestionProvider(com.intellij.refactoring.rename.PreferrableNameSuggestionProvider) LookupElement(com.intellij.codeInsight.lookup.LookupElement) InsertionContext(com.intellij.codeInsight.completion.InsertionContext) TemplateState(com.intellij.codeInsight.template.impl.TemplateState) SuggestedNameInfo(com.intellij.psi.codeStyle.SuggestedNameInfo) InsertHandler(com.intellij.codeInsight.completion.InsertHandler) Editor(com.intellij.openapi.editor.Editor)

Example 5 with InsertionContext

use of com.intellij.codeInsight.completion.InsertionContext in project intellij-community by JetBrains.

the class TemplateExpressionLookupElement method handleTemplateInsert.

void handleTemplateInsert(List<? extends LookupElement> elements, final char completionChar) {
    final InsertionContext context = createInsertionContext(this, myState.getPsiFile(), elements, myState.getEditor(), completionChar);
    WriteAction.run(() -> doHandleInsert(context));
    Disposer.dispose(context.getOffsetMap());
    if (handleCompletionChar(context) && !myState.isFinished()) {
        myState.calcResults(true);
        myState.considerNextTabOnLookupItemSelected(getDelegate());
    }
}
Also used : InsertionContext(com.intellij.codeInsight.completion.InsertionContext)

Aggregations

InsertionContext (com.intellij.codeInsight.completion.InsertionContext)10 LookupElement (com.intellij.codeInsight.lookup.LookupElement)9 InsertHandler (com.intellij.codeInsight.completion.InsertHandler)5 Document (com.intellij.openapi.editor.Document)4 Editor (com.intellij.openapi.editor.Editor)3 PrioritizedLookupElement (com.intellij.codeInsight.completion.PrioritizedLookupElement)2 LookupElementBuilder (com.intellij.codeInsight.lookup.LookupElementBuilder)2 CaretModel (com.intellij.openapi.editor.CaretModel)2 VirtualFile (com.intellij.openapi.vfs.VirtualFile)2 PsiElement (com.intellij.psi.PsiElement)2 TrailingPatternConsumer (ool.intellij.plugin.editor.completion.handler.TrailingPatternConsumer)2 NotNull (org.jetbrains.annotations.NotNull)2 OffsetMap (com.intellij.codeInsight.completion.OffsetMap)1 XmlTagInsertHandler (com.intellij.codeInsight.completion.XmlTagInsertHandler)1 CamelHumpMatcher (com.intellij.codeInsight.completion.impl.CamelHumpMatcher)1 ParenthesesInsertHandler (com.intellij.codeInsight.completion.util.ParenthesesInsertHandler)1 TemplateBuilder (com.intellij.codeInsight.template.TemplateBuilder)1 TemplateState (com.intellij.codeInsight.template.impl.TemplateState)1 CfmlMappingsConfig (com.intellij.coldFusion.UI.config.CfmlMappingsConfig)1 CfmlProjectConfiguration (com.intellij.coldFusion.UI.config.CfmlProjectConfiguration)1