Search in sources :

Example 6 with TemplateBuilderImpl

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

the class AddMissingRequiredAnnotationParametersFix method invoke.

@Override
public void invoke(@NotNull final Project project, final Editor editor, final PsiFile file) throws IncorrectOperationException {
    final PsiNameValuePair[] addedParameters = myAnnotation.getParameterList().getAttributes();
    final TObjectIntHashMap<String> annotationsOrderMap = getAnnotationsOrderMap();
    final SortedSet<Pair<String, PsiAnnotationMemberValue>> newParameters = new TreeSet<>(Comparator.comparingInt(o -> annotationsOrderMap.get(o.getFirst())));
    final boolean order = isAlreadyAddedOrdered(annotationsOrderMap, addedParameters);
    if (order) {
        if (addedParameters.length != 0) {
            final PsiAnnotationParameterList parameterList = myAnnotation.getParameterList();
            parameterList.deleteChildRange(addedParameters[0], addedParameters[addedParameters.length - 1]);
            for (final PsiNameValuePair addedParameter : addedParameters) {
                final String name = addedParameter.getName();
                final PsiAnnotationMemberValue value = addedParameter.getValue();
                if (name == null || value == null) {
                    LOG.error(String.format("Invalid annotation parameter name = %s, value = %s", name, value));
                    continue;
                }
                newParameters.add(Pair.create(name, value));
            }
        }
    }
    final PsiExpression nullValue = JavaPsiFacade.getElementFactory(project).createExpressionFromText(PsiKeyword.NULL, null);
    for (final String misssedParameter : myMissedElements) {
        newParameters.add(Pair.create(misssedParameter, nullValue));
    }
    TemplateBuilderImpl builder = null;
    for (final Pair<String, PsiAnnotationMemberValue> newParameter : newParameters) {
        final PsiAnnotationMemberValue value = myAnnotation.setDeclaredAttributeValue(newParameter.getFirst(), newParameter.getSecond());
        if (myMissedElements.contains(newParameter.getFirst())) {
            if (builder == null) {
                builder = new TemplateBuilderImpl(myAnnotation.getParameterList());
            }
            builder.replaceElement(value, new EmptyExpression(), true);
        }
    }
    editor.getCaretModel().moveToOffset(myAnnotation.getParameterList().getTextRange().getStartOffset());
    final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
    final Document document = documentManager.getDocument(file);
    if (document == null) {
        throw new IllegalStateException();
    }
    documentManager.doPostponedOperationsAndUnblockDocument(document);
    TemplateManager.getInstance(project).startTemplate(editor, builder.buildInlineTemplate(), null);
}
Also used : QuickFixBundle(com.intellij.codeInsight.daemon.QuickFixBundle) IncorrectOperationException(com.intellij.util.IncorrectOperationException) SortedSet(java.util.SortedSet) StringUtil(com.intellij.openapi.util.text.StringUtil) TObjectIntHashMap(gnu.trove.TObjectIntHashMap) Document(com.intellij.openapi.editor.Document) Collection(java.util.Collection) TemplateBuilderImpl(com.intellij.codeInsight.template.TemplateBuilderImpl) ContainerUtil(com.intellij.util.containers.ContainerUtil) Editor(com.intellij.openapi.editor.Editor) TreeSet(java.util.TreeSet) TemplateManager(com.intellij.codeInsight.template.TemplateManager) Pair(com.intellij.openapi.util.Pair) Project(com.intellij.openapi.project.Project) IntentionAction(com.intellij.codeInsight.intention.IntentionAction) com.intellij.psi(com.intellij.psi) Logger(com.intellij.openapi.diagnostic.Logger) NotNull(org.jetbrains.annotations.NotNull) Comparator(java.util.Comparator) Document(com.intellij.openapi.editor.Document) TemplateBuilderImpl(com.intellij.codeInsight.template.TemplateBuilderImpl) TreeSet(java.util.TreeSet) Pair(com.intellij.openapi.util.Pair)

Example 7 with TemplateBuilderImpl

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

the class JavaCreateFieldFromUsageHelper method setupTemplateImpl.

@Override
public Template setupTemplateImpl(PsiField field, Object expectedTypes, PsiClass targetClass, Editor editor, PsiElement context, boolean createConstantField, PsiSubstitutor substitutor) {
    PsiElementFactory factory = JavaPsiFacade.getElementFactory(field.getProject());
    field = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(field);
    TemplateBuilderImpl builder = new TemplateBuilderImpl(field);
    if (!(expectedTypes instanceof ExpectedTypeInfo[])) {
        expectedTypes = ExpectedTypeInfo.EMPTY_ARRAY;
    }
    new GuessTypeParameters(factory).setupTypeElement(field.getTypeElement(), (ExpectedTypeInfo[]) expectedTypes, substitutor, builder, context, targetClass);
    if (createConstantField) {
        field.setInitializer(factory.createExpressionFromText("0", null));
        builder.replaceElement(field.getInitializer(), new EmptyExpression());
        PsiIdentifier identifier = field.getNameIdentifier();
        builder.setEndVariableAfter(identifier);
        field = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(field);
    }
    editor.getCaretModel().moveToOffset(field.getTextRange().getStartOffset());
    Template template = builder.buildInlineTemplate();
    if (((ExpectedTypeInfo[]) expectedTypes).length > 1)
        template.setToShortenLongNames(false);
    return template;
}
Also used : TemplateBuilderImpl(com.intellij.codeInsight.template.TemplateBuilderImpl) ExpectedTypeInfo(com.intellij.codeInsight.ExpectedTypeInfo) Template(com.intellij.codeInsight.template.Template)

Example 8 with TemplateBuilderImpl

use of com.intellij.codeInsight.template.TemplateBuilderImpl 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 9 with TemplateBuilderImpl

use of com.intellij.codeInsight.template.TemplateBuilderImpl in project go-lang-idea-plugin by go-lang-plugin-org.

the class GoCreateWrapperTypeQuickFix method invoke.

@Override
public void invoke(@NotNull Project project, @NotNull PsiFile file, @Nullable("is null when called from inspection") Editor editor, @NotNull PsiElement startElement, @NotNull PsiElement endElement) {
    if (editor == null) {
        LOG.error("Cannot run quick fix without editor: " + getClass().getSimpleName(), AttachmentFactory.createAttachment(file.getVirtualFile()));
        return;
    }
    if (!(startElement instanceof GoType))
        return;
    GoType type = (GoType) startElement;
    PsiElement anchor = PsiTreeUtil.findPrevParent(file, type);
    String name = "TypeName";
    GoTypeDeclaration decl = (GoTypeDeclaration) file.addBefore(GoElementFactory.createTypeDeclaration(project, name, type), anchor);
    if (decl == null)
        return;
    decl = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(decl);
    if (decl == null)
        return;
    GoTypeSpec spec = ContainerUtil.getFirstItem(decl.getTypeSpecList());
    if (spec == null)
        return;
    TemplateBuilderImpl builder = new TemplateBuilderImpl(file);
    builder.replaceElement(type, OTHER_NAME, INPUT_NAME, false);
    builder.replaceElement(spec.getIdentifier(), INPUT_NAME, new ConstantNode(name), true);
    editor.getCaretModel().moveToOffset(file.getTextRange().getStartOffset());
    Template template = builder.buildInlineTemplate();
    editor.getCaretModel().moveToOffset(file.getTextRange().getStartOffset());
    TemplateManager.getInstance(project).startTemplate(editor, template);
}
Also used : GoTypeDeclaration(com.goide.psi.GoTypeDeclaration) TemplateBuilderImpl(com.intellij.codeInsight.template.TemplateBuilderImpl) ConstantNode(com.intellij.codeInsight.template.impl.ConstantNode) GoTypeSpec(com.goide.psi.GoTypeSpec) GoType(com.goide.psi.GoType) LocalQuickFixAndIntentionActionOnPsiElement(com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement) PsiElement(com.intellij.psi.PsiElement) Template(com.intellij.codeInsight.template.Template)

Example 10 with TemplateBuilderImpl

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

the class HighlightUtil method showRenameTemplate.

public static void showRenameTemplate(PsiElement context, PsiNameIdentifierOwner element) {
    context = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(context);
    final Query<PsiReference> query = ReferencesSearch.search(element, element.getUseScope());
    final Collection<PsiReference> references = query.findAll();
    final Project project = context.getProject();
    final FileEditorManager fileEditorManager = FileEditorManager.getInstance(project);
    final Editor editor = fileEditorManager.getSelectedTextEditor();
    if (editor == null) {
        return;
    }
    final TemplateBuilderImpl builder = new TemplateBuilderImpl(context);
    final Expression macroCallNode = new MacroCallNode(new SuggestVariableNameMacro());
    final PsiElement identifier = element.getNameIdentifier();
    builder.replaceElement(identifier, "PATTERN", macroCallNode, true);
    for (PsiReference reference : references) {
        builder.replaceElement(reference, "PATTERN", "PATTERN", false);
    }
    final Template template = builder.buildInlineTemplate();
    final TextRange textRange = context.getTextRange();
    final int startOffset = textRange.getStartOffset();
    editor.getCaretModel().moveToOffset(startOffset);
    final TemplateManager templateManager = TemplateManager.getInstance(project);
    templateManager.startTemplate(editor, template);
}
Also used : PsiReference(com.intellij.psi.PsiReference) TextRange(com.intellij.openapi.util.TextRange) Template(com.intellij.codeInsight.template.Template) Project(com.intellij.openapi.project.Project) FileEditorManager(com.intellij.openapi.fileEditor.FileEditorManager) TemplateBuilderImpl(com.intellij.codeInsight.template.TemplateBuilderImpl) Expression(com.intellij.codeInsight.template.Expression) TemplateManager(com.intellij.codeInsight.template.TemplateManager) SuggestVariableNameMacro(com.intellij.codeInsight.template.macro.SuggestVariableNameMacro) MacroCallNode(com.intellij.codeInsight.template.impl.MacroCallNode) Editor(com.intellij.openapi.editor.Editor) PsiElement(com.intellij.psi.PsiElement)

Aggregations

TemplateBuilderImpl (com.intellij.codeInsight.template.TemplateBuilderImpl)24 Template (com.intellij.codeInsight.template.Template)19 Editor (com.intellij.openapi.editor.Editor)15 TextRange (com.intellij.openapi.util.TextRange)13 Project (com.intellij.openapi.project.Project)11 TemplateEditingAdapter (com.intellij.codeInsight.template.TemplateEditingAdapter)8 RangeMarker (com.intellij.openapi.editor.RangeMarker)8 TemplateManager (com.intellij.codeInsight.template.TemplateManager)7 PsiElement (com.intellij.psi.PsiElement)7 Document (com.intellij.openapi.editor.Document)6 IncorrectOperationException (com.intellij.util.IncorrectOperationException)6 MacroCallNode (com.intellij.codeInsight.template.impl.MacroCallNode)4 GrVariableDeclaration (org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration)3 TypeConstraint (org.jetbrains.plugins.groovy.lang.psi.expectedTypes.TypeConstraint)3 ChooseTypeExpression (org.jetbrains.plugins.groovy.template.expressions.ChooseTypeExpression)3 ExpectedTypeInfo (com.intellij.codeInsight.ExpectedTypeInfo)2 LookupElement (com.intellij.codeInsight.lookup.LookupElement)2 Expression (com.intellij.codeInsight.template.Expression)2 TextExpression (com.intellij.codeInsight.template.impl.TextExpression)2 CompleteMacro (com.intellij.codeInsight.template.macro.CompleteMacro)2