Search in sources :

Example 1 with TextExpression

use of com.intellij.codeInsight.template.impl.TextExpression 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 2 with TextExpression

use of com.intellij.codeInsight.template.impl.TextExpression in project intellij-community by JetBrains.

the class StringBasedPostfixTemplate method expandForChooseExpression.

@Override
public final void expandForChooseExpression(@NotNull PsiElement expr, @NotNull Editor editor) {
    Project project = expr.getProject();
    Document document = editor.getDocument();
    PsiElement elementForRemoving = getElementToRemove(expr);
    document.deleteString(elementForRemoving.getTextRange().getStartOffset(), elementForRemoving.getTextRange().getEndOffset());
    TemplateManager manager = TemplateManager.getInstance(project);
    String templateString = getTemplateString(expr);
    if (templateString == null) {
        PostfixTemplatesUtils.showErrorHint(expr.getProject(), editor);
        return;
    }
    Template template = createTemplate(manager, templateString);
    if (shouldAddExpressionToContext()) {
        template.addVariable("expr", new TextExpression(expr.getText()), false);
    }
    setVariables(template, expr);
    manager.startTemplate(editor, template);
}
Also used : Project(com.intellij.openapi.project.Project) TemplateManager(com.intellij.codeInsight.template.TemplateManager) Document(com.intellij.openapi.editor.Document) PsiElement(com.intellij.psi.PsiElement) TextExpression(com.intellij.codeInsight.template.impl.TextExpression) Template(com.intellij.codeInsight.template.Template)

Example 3 with TextExpression

use of com.intellij.codeInsight.template.impl.TextExpression in project intellij-plugins by JetBrains.

the class CreateNamedConstructorFix method buildFunctionsText.

protected Template buildFunctionsText(TemplateManager templateManager, Set<DartComponent> elementsToProcess) {
    final Template template = templateManager.createTemplate(getClass().getName(), DART_TEMPLATE_GROUP);
    template.setToReformat(true);
    //noinspection ConstantConditions
    template.addTextSegment(myDartClass.getName());
    template.addTextSegment(".");
    template.addVariable(new TextExpression("name"), true);
    template.addTextSegment("(");
    for (Iterator<DartComponent> iterator = elementsToProcess.iterator(); iterator.hasNext(); ) {
        DartComponent component = iterator.next();
        template.addTextSegment("this.");
        //noinspection ConstantConditions
        template.addTextSegment(component.getName());
        if (iterator.hasNext()) {
            template.addTextSegment(",");
        }
    }
    template.addTextSegment(");");
    template.addEndVariable();
    // trailing space is removed when auto-reformatting, but it helps to enter line break if needed
    template.addTextSegment(" ");
    return template;
}
Also used : DartComponent(com.jetbrains.lang.dart.psi.DartComponent) TextExpression(com.intellij.codeInsight.template.impl.TextExpression) Template(com.intellij.codeInsight.template.Template)

Example 4 with TextExpression

use of com.intellij.codeInsight.template.impl.TextExpression in project intellij-community by JetBrains.

the class TryWithResourcesPostfixTemplate method expand.

@Override
public void expand(@NotNull PsiElement context, @NotNull Editor editor) {
    PsiExpression expression = JavaPostfixTemplatesUtils.getTopmostExpression(context);
    assert expression != null;
    Project project = context.getProject();
    editor.getDocument().deleteString(expression.getTextRange().getStartOffset(), expression.getTextRange().getEndOffset());
    TemplateManager manager = TemplateManager.getInstance(project);
    Template template = manager.createTemplate("", "");
    template.setToReformat(true);
    template.addTextSegment("try (");
    MacroCallNode name = new MacroCallNode(new SuggestVariableNameMacro());
    template.addVariable("type", new TypeExpression(project, new PsiType[] { expression.getType() }), false);
    template.addTextSegment(" ");
    template.addVariable("name", name, name, true);
    template.addTextSegment(" = ");
    template.addVariable("variable", new TextExpression(expression.getText()), false);
    template.addTextSegment(") {\n");
    template.addEndVariable();
    template.addTextSegment("\n}");
    Collection<PsiClassType> unhandled = getUnhandled(expression);
    for (PsiClassType exception : unhandled) {
        MacroCallNode variable = new MacroCallNode(new SuggestVariableNameMacro());
        template.addTextSegment("catch(");
        template.addVariable("type " + exception.getClassName(), new TypeExpression(project, new PsiType[] { exception }), false);
        template.addTextSegment(" ");
        template.addVariable("name " + exception.getClassName(), variable, variable, false);
        template.addTextSegment(") {}");
    }
    manager.startTemplate(editor, template);
}
Also used : Project(com.intellij.openapi.project.Project) TypeExpression(com.intellij.codeInsight.intention.impl.TypeExpression) TemplateManager(com.intellij.codeInsight.template.TemplateManager) SuggestVariableNameMacro(com.intellij.codeInsight.template.macro.SuggestVariableNameMacro) MacroCallNode(com.intellij.codeInsight.template.impl.MacroCallNode) TextExpression(com.intellij.codeInsight.template.impl.TextExpression) Template(com.intellij.codeInsight.template.Template)

Example 5 with TextExpression

use of com.intellij.codeInsight.template.impl.TextExpression in project intellij-community by JetBrains.

the class DefineParamsDefaultValueAction method startTemplate.

public static void startTemplate(@NotNull Project project, Editor editor, PsiExpression[] argsToBeDelegated, PsiMethod delegateMethod) {
    TemplateBuilderImpl builder = new TemplateBuilderImpl(delegateMethod);
    RangeMarker rangeMarker = editor.getDocument().createRangeMarker(delegateMethod.getTextRange());
    for (final PsiExpression exprToBeDefault : argsToBeDelegated) {
        builder.replaceElement(exprToBeDefault, new TextExpression(""));
    }
    Template template = builder.buildTemplate();
    editor.getCaretModel().moveToOffset(rangeMarker.getStartOffset());
    PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.getDocument());
    editor.getDocument().deleteString(rangeMarker.getStartOffset(), rangeMarker.getEndOffset());
    rangeMarker.dispose();
    CreateFromUsageBaseFix.startTemplate(editor, template, project);
}
Also used : TemplateBuilderImpl(com.intellij.codeInsight.template.TemplateBuilderImpl) RangeMarker(com.intellij.openapi.editor.RangeMarker) TextExpression(com.intellij.codeInsight.template.impl.TextExpression) Template(com.intellij.codeInsight.template.Template)

Aggregations

TextExpression (com.intellij.codeInsight.template.impl.TextExpression)5 Template (com.intellij.codeInsight.template.Template)4 Project (com.intellij.openapi.project.Project)3 TemplateBuilderImpl (com.intellij.codeInsight.template.TemplateBuilderImpl)2 TemplateManager (com.intellij.codeInsight.template.TemplateManager)2 Document (com.intellij.openapi.editor.Document)2 PsiElement (com.intellij.psi.PsiElement)2 AutoPopupController (com.intellij.codeInsight.AutoPopupController)1 CodeInsightSettings (com.intellij.codeInsight.CodeInsightSettings)1 com.intellij.codeInsight.completion (com.intellij.codeInsight.completion)1 ParenthesesInsertHandler (com.intellij.codeInsight.completion.util.ParenthesesInsertHandler)1 TypeExpression (com.intellij.codeInsight.intention.impl.TypeExpression)1 LookupElement (com.intellij.codeInsight.lookup.LookupElement)1 LookupElementBuilder (com.intellij.codeInsight.lookup.LookupElementBuilder)1 TemplateBuilderFactory (com.intellij.codeInsight.template.TemplateBuilderFactory)1 MacroCallNode (com.intellij.codeInsight.template.impl.MacroCallNode)1 SuggestVariableNameMacro (com.intellij.codeInsight.template.macro.SuggestVariableNameMacro)1 AllIcons (com.intellij.icons.AllIcons)1 HtmlFileType (com.intellij.ide.highlighter.HtmlFileType)1 VirtualFileWindow (com.intellij.injected.editor.VirtualFileWindow)1