Search in sources :

Example 1 with TemplateBuilderImpl

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

the class PyRenameArgumentQuickFix method applyFix.

@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
    final PsiElement element = descriptor.getPsiElement();
    if (!(element instanceof PsiNamedElement))
        return;
    final VirtualFile virtualFile = element.getContainingFile().getVirtualFile();
    if (virtualFile != null) {
        final Editor editor = FileEditorManager.getInstance(project).openTextEditor(new OpenFileDescriptor(project, virtualFile), true);
        final TemplateBuilderImpl builder = new TemplateBuilderImpl(element);
        final String name = ((PsiNamedElement) element).getName();
        assert name != null;
        assert editor != null;
        builder.replaceElement(element, TextRange.create(0, name.length()), name);
        builder.run(editor, false);
    }
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) TemplateBuilderImpl(com.intellij.codeInsight.template.TemplateBuilderImpl) PsiNamedElement(com.intellij.psi.PsiNamedElement) OpenFileDescriptor(com.intellij.openapi.fileEditor.OpenFileDescriptor) Editor(com.intellij.openapi.editor.Editor) PsiElement(com.intellij.psi.PsiElement)

Example 2 with TemplateBuilderImpl

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

the class CreateEnumConstantFromUsageFix method invokeImpl.

@Override
protected void invokeImpl(final PsiClass targetClass) {
    LOG.assertTrue(targetClass.isEnum());
    final String name = myReferenceExpression.getReferenceName();
    LOG.assertTrue(name != null);
    final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(myReferenceExpression.getProject()).getElementFactory();
    PsiEnumConstant enumConstant = elementFactory.createEnumConstantFromText(name, null);
    enumConstant = (PsiEnumConstant) targetClass.add(enumConstant);
    final PsiMethod[] constructors = targetClass.getConstructors();
    if (constructors.length > 0) {
        final PsiMethod constructor = constructors[0];
        final PsiParameter[] parameters = constructor.getParameterList().getParameters();
        if (parameters.length > 0) {
            final String params = StringUtil.join(parameters, psiParameter -> psiParameter.getName(), ",");
            enumConstant = (PsiEnumConstant) enumConstant.replace(elementFactory.createEnumConstantFromText(name + "(" + params + ")", null));
            final TemplateBuilderImpl builder = new TemplateBuilderImpl(enumConstant);
            final PsiExpressionList argumentList = enumConstant.getArgumentList();
            LOG.assertTrue(argumentList != null);
            for (PsiExpression expression : argumentList.getExpressions()) {
                builder.replaceElement(expression, new EmptyExpression());
            }
            enumConstant = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(enumConstant);
            final Template template = builder.buildTemplate();
            final Project project = targetClass.getProject();
            final Editor newEditor = positionCursor(project, targetClass.getContainingFile(), enumConstant);
            if (newEditor != null) {
                final TextRange range = enumConstant.getTextRange();
                newEditor.getDocument().deleteString(range.getStartOffset(), range.getEndOffset());
                startTemplate(newEditor, template, project);
            }
        }
    }
}
Also used : TextRange(com.intellij.openapi.util.TextRange) Template(com.intellij.codeInsight.template.Template) Project(com.intellij.openapi.project.Project) TemplateBuilderImpl(com.intellij.codeInsight.template.TemplateBuilderImpl) Editor(com.intellij.openapi.editor.Editor)

Example 3 with TemplateBuilderImpl

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

the class CreateMethodFromUsageFix method doCreate.

public static void doCreate(PsiClass targetClass, PsiMethod method, boolean shouldBeAbstract, List<Pair<PsiExpression, PsiType>> arguments, PsiSubstitutor substitutor, ExpectedTypeInfo[] expectedTypes, @Nullable final PsiElement context) {
    method = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(method);
    if (method == null) {
        return;
    }
    final Project project = targetClass.getProject();
    final PsiFile targetFile = targetClass.getContainingFile();
    Document document = PsiDocumentManager.getInstance(project).getDocument(targetFile);
    if (document == null)
        return;
    TemplateBuilderImpl builder = new TemplateBuilderImpl(method);
    CreateFromUsageUtils.setupMethodParameters(method, builder, context, substitutor, arguments);
    final PsiTypeElement returnTypeElement = method.getReturnTypeElement();
    if (returnTypeElement != null) {
        new GuessTypeParameters(JavaPsiFacade.getInstance(project).getElementFactory()).setupTypeElement(returnTypeElement, expectedTypes, substitutor, builder, context, targetClass);
    }
    PsiCodeBlock body = method.getBody();
    builder.setEndVariableAfter(shouldBeAbstract || body == null ? method : body.getLBrace());
    method = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(method);
    if (method == null)
        return;
    RangeMarker rangeMarker = document.createRangeMarker(method.getTextRange());
    final Editor newEditor = positionCursor(project, targetFile, method);
    if (newEditor == null)
        return;
    Template template = builder.buildTemplate();
    newEditor.getCaretModel().moveToOffset(rangeMarker.getStartOffset());
    newEditor.getDocument().deleteString(rangeMarker.getStartOffset(), rangeMarker.getEndOffset());
    rangeMarker.dispose();
    if (!shouldBeAbstract) {
        startTemplate(newEditor, template, project, new TemplateEditingAdapter() {

            @Override
            public void templateFinished(Template template, boolean brokenOff) {
                if (brokenOff)
                    return;
                WriteCommandAction.runWriteCommandAction(project, () -> {
                    PsiDocumentManager.getInstance(project).commitDocument(newEditor.getDocument());
                    final int offset = newEditor.getCaretModel().getOffset();
                    PsiMethod method1 = PsiTreeUtil.findElementOfClassAtOffset(targetFile, offset - 1, PsiMethod.class, false);
                    if (method1 != null) {
                        try {
                            CreateFromUsageUtils.setupMethodBody(method1);
                        } catch (IncorrectOperationException e) {
                            LOG.error(e);
                        }
                        CreateFromUsageUtils.setupEditor(method1, newEditor);
                    }
                });
            }
        });
    } else {
        startTemplate(newEditor, template, project);
    }
}
Also used : TemplateEditingAdapter(com.intellij.codeInsight.template.TemplateEditingAdapter) RangeMarker(com.intellij.openapi.editor.RangeMarker) Document(com.intellij.openapi.editor.Document) Template(com.intellij.codeInsight.template.Template) Project(com.intellij.openapi.project.Project) TemplateBuilderImpl(com.intellij.codeInsight.template.TemplateBuilderImpl) IncorrectOperationException(com.intellij.util.IncorrectOperationException) Editor(com.intellij.openapi.editor.Editor)

Example 4 with TemplateBuilderImpl

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

the class RenameWrongRefFix method invoke.

@Override
public void invoke(@NotNull Project project, final Editor editor, PsiFile file) {
    PsiReferenceExpression[] refs = CreateFromUsageUtils.collectExpressions(myRefExpr, PsiMember.class, PsiFile.class);
    PsiElement element = PsiTreeUtil.getParentOfType(myRefExpr, PsiMember.class, PsiFile.class);
    LookupElement[] items = collectItems();
    ReferenceNameExpression refExpr = new ReferenceNameExpression(items, myRefExpr.getReferenceName());
    TemplateBuilderImpl builder = new TemplateBuilderImpl(element);
    for (PsiReferenceExpression expr : refs) {
        if (!expr.equals(myRefExpr)) {
            builder.replaceElement(expr.getReferenceNameElement(), OTHER_VARIABLE_NAME, INPUT_VARIABLE_NAME, false);
        } else {
            builder.replaceElement(expr.getReferenceNameElement(), INPUT_VARIABLE_NAME, refExpr, true);
        }
    }
    final float proportion = EditorUtil.calcVerticalScrollProportion(editor);
    editor.getCaretModel().moveToOffset(element.getTextRange().getStartOffset());
    /*for (int i = refs.length - 1; i >= 0; i--) {
      TextRange range = refs[i].getReferenceNameElement().getTextRange();
      document.deleteString(range.getStartOffset(), range.getEndOffset());
    }
*/
    Template template = builder.buildInlineTemplate();
    editor.getCaretModel().moveToOffset(element.getTextRange().getStartOffset());
    TemplateManager.getInstance(project).startTemplate(editor, template);
    EditorUtil.setVerticalScrollProportion(editor, proportion);
}
Also used : TemplateBuilderImpl(com.intellij.codeInsight.template.TemplateBuilderImpl) LookupElement(com.intellij.codeInsight.lookup.LookupElement) Template(com.intellij.codeInsight.template.Template)

Example 5 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)

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