Search in sources :

Example 6 with TemplateEditingAdapter

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

the class CreateConstructorFromCallFix method invokeImpl.

@Override
protected void invokeImpl(final PsiClass targetClass) {
    final Project project = myConstructorCall.getProject();
    JVMElementFactory elementFactory = JVMElementFactories.getFactory(targetClass.getLanguage(), project);
    if (elementFactory == null)
        elementFactory = JavaPsiFacade.getElementFactory(project);
    try {
        PsiMethod constructor = (PsiMethod) targetClass.add(elementFactory.createConstructor());
        final PsiFile file = targetClass.getContainingFile();
        TemplateBuilderImpl templateBuilder = new TemplateBuilderImpl(constructor);
        CreateFromUsageUtils.setupMethodParameters(constructor, templateBuilder, myConstructorCall.getArgumentList(), getTargetSubstitutor(myConstructorCall));
        final PsiMethod superConstructor = CreateClassFromNewFix.setupSuperCall(targetClass, constructor, templateBuilder);
        constructor = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(constructor);
        Template template = templateBuilder.buildTemplate();
        final Editor editor = positionCursor(project, targetClass.getContainingFile(), targetClass);
        if (editor == null)
            return;
        final TextRange textRange = constructor.getTextRange();
        editor.getDocument().deleteString(textRange.getStartOffset(), textRange.getEndOffset());
        editor.getCaretModel().moveToOffset(textRange.getStartOffset());
        startTemplate(editor, template, project, new TemplateEditingAdapter() {

            @Override
            public void templateFinished(Template template, boolean brokenOff) {
                ApplicationManager.getApplication().runWriteAction(() -> {
                    try {
                        PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
                        final int offset = editor.getCaretModel().getOffset();
                        PsiMethod constructor1 = PsiTreeUtil.findElementOfClassAtOffset(file, offset, PsiMethod.class, false);
                        if (superConstructor == null) {
                            CreateFromUsageUtils.setupMethodBody(constructor1);
                        } else {
                            OverrideImplementUtil.setupMethodBody(constructor1, superConstructor, targetClass);
                        }
                        CreateFromUsageUtils.setupEditor(constructor1, editor);
                    } catch (IncorrectOperationException e) {
                        LOG.error(e);
                    }
                });
            }
        });
    } catch (IncorrectOperationException e) {
        LOG.error(e);
    }
}
Also used : Project(com.intellij.openapi.project.Project) TemplateBuilderImpl(com.intellij.codeInsight.template.TemplateBuilderImpl) TemplateEditingAdapter(com.intellij.codeInsight.template.TemplateEditingAdapter) TextRange(com.intellij.openapi.util.TextRange) IncorrectOperationException(com.intellij.util.IncorrectOperationException) Editor(com.intellij.openapi.editor.Editor) Template(com.intellij.codeInsight.template.Template)

Example 7 with TemplateEditingAdapter

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

the class CreateConstructorFromThisOrSuperFix method invokeImpl.

@Override
protected void invokeImpl(PsiClass targetClass) {
    final PsiFile callSite = myMethodCall.getContainingFile();
    final Project project = myMethodCall.getProject();
    PsiElementFactory elementFactory = JavaPsiFacade.getInstance(project).getElementFactory();
    IdeDocumentHistory.getInstance(project).includeCurrentPlaceAsChangePlace();
    try {
        PsiMethod constructor = elementFactory.createConstructor();
        constructor = (PsiMethod) targetClass.add(constructor);
        final TemplateBuilderImpl templateBuilder = new TemplateBuilderImpl(constructor);
        CreateFromUsageUtils.setupMethodParameters(constructor, templateBuilder, myMethodCall.getArgumentList(), getTargetSubstitutor(myMethodCall));
        final PsiFile psiFile = myMethodCall.getContainingFile();
        templateBuilder.setEndVariableAfter(constructor.getBody().getLBrace());
        final RangeMarker rangeMarker = psiFile.getViewProvider().getDocument().createRangeMarker(myMethodCall.getTextRange());
        constructor = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(constructor);
        targetClass = constructor.getContainingClass();
        myMethodCall = CodeInsightUtil.findElementInRange(psiFile, rangeMarker.getStartOffset(), rangeMarker.getEndOffset(), myMethodCall.getClass());
        rangeMarker.dispose();
        Template template = templateBuilder.buildTemplate();
        final Editor editor = positionCursor(project, targetClass.getContainingFile(), targetClass);
        if (editor == null)
            return;
        final TextRange textRange = constructor.getTextRange();
        final PsiFile file = targetClass.getContainingFile();
        editor.getDocument().deleteString(textRange.getStartOffset(), textRange.getEndOffset());
        editor.getCaretModel().moveToOffset(textRange.getStartOffset());
        startTemplate(editor, template, project, new TemplateEditingAdapter() {

            @Override
            public void templateFinished(Template template, boolean brokenOff) {
                ApplicationManager.getApplication().runWriteAction(() -> {
                    try {
                        PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
                        final int offset = editor.getCaretModel().getOffset();
                        PsiMethod constructor1 = PsiTreeUtil.findElementOfClassAtOffset(file, offset, PsiMethod.class, false);
                        CreateFromUsageUtils.setupMethodBody(constructor1);
                        CreateFromUsageUtils.setupEditor(constructor1, editor);
                        UndoUtil.markPsiFileForUndo(callSite);
                    } catch (IncorrectOperationException e) {
                        LOG.error(e);
                    }
                });
            }
        });
    } catch (IncorrectOperationException e) {
        LOG.error(e);
    }
}
Also used : TemplateEditingAdapter(com.intellij.codeInsight.template.TemplateEditingAdapter) TextRange(com.intellij.openapi.util.TextRange) RangeMarker(com.intellij.openapi.editor.RangeMarker) 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 8 with TemplateEditingAdapter

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

the class CreateLocalFromUsageFix method invokeImpl.

@Override
protected void invokeImpl(final PsiClass targetClass) {
    if (CreateFromUsageUtils.isValidReference(myReferenceExpression, false)) {
        return;
    }
    final Project project = myReferenceExpression.getProject();
    PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory();
    final PsiFile targetFile = targetClass.getContainingFile();
    PsiType[] expectedTypes = CreateFromUsageUtils.guessType(myReferenceExpression, false);
    final SmartTypePointer defaultType = SmartTypePointerManager.getInstance(project).createSmartTypePointer(expectedTypes[0]);
    final PsiType preferredType = TypeSelectorManagerImpl.getPreferredType(expectedTypes, expectedTypes[0]);
    PsiType type = preferredType != null ? preferredType : expectedTypes[0];
    if (LambdaUtil.notInferredType(type)) {
        type = PsiType.getJavaLangObject(myReferenceExpression.getManager(), targetClass.getResolveScope());
    }
    String varName = myReferenceExpression.getReferenceName();
    PsiExpression initializer = null;
    boolean isInline = false;
    PsiExpression[] expressions = CreateFromUsageUtils.collectExpressions(myReferenceExpression, PsiMember.class, PsiFile.class);
    PsiStatement anchor = getAnchor(expressions);
    if (anchor instanceof PsiExpressionStatement && ((PsiExpressionStatement) anchor).getExpression() instanceof PsiAssignmentExpression) {
        PsiAssignmentExpression assignment = (PsiAssignmentExpression) ((PsiExpressionStatement) anchor).getExpression();
        if (assignment.getLExpression().textMatches(myReferenceExpression)) {
            initializer = assignment.getRExpression();
            isInline = true;
        }
    }
    PsiDeclarationStatement decl = factory.createVariableDeclarationStatement(varName, type, initializer);
    TypeExpression expression = new TypeExpression(project, expectedTypes);
    if (isInline) {
        final PsiExpression expr = ((PsiExpressionStatement) anchor).getExpression();
        final PsiElement semicolon = expr.getNextSibling();
        if (semicolon != null) {
            final PsiElement nextSibling = semicolon.getNextSibling();
            if (nextSibling != null) {
                decl.addRange(nextSibling, anchor.getLastChild());
            }
        }
        decl = (PsiDeclarationStatement) anchor.replace(decl);
    } else {
        decl = (PsiDeclarationStatement) anchor.getParent().addBefore(decl, anchor);
    }
    PsiVariable var = (PsiVariable) decl.getDeclaredElements()[0];
    boolean isFinal = CodeStyleSettingsManager.getSettings(project).GENERATE_FINAL_LOCALS && !CreateFromUsageUtils.isAccessedForWriting(expressions);
    PsiUtil.setModifierProperty(var, PsiModifier.FINAL, isFinal);
    var = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(var);
    if (var == null)
        return;
    TemplateBuilderImpl builder = new TemplateBuilderImpl(var);
    final PsiTypeElement typeElement = var.getTypeElement();
    LOG.assertTrue(typeElement != null);
    builder.replaceElement(typeElement, AbstractJavaInplaceIntroducer.createExpression(expression, typeElement.getText()));
    builder.setEndVariableAfter(var.getNameIdentifier());
    Template template = builder.buildTemplate();
    final Editor newEditor = positionCursor(project, targetFile, var);
    if (newEditor == null)
        return;
    TextRange range = var.getTextRange();
    newEditor.getDocument().deleteString(range.getStartOffset(), range.getEndOffset());
    startTemplate(newEditor, template, project, new TemplateEditingAdapter() {

        @Override
        public void templateFinished(Template template, boolean brokenOff) {
            PsiDocumentManager.getInstance(project).commitDocument(newEditor.getDocument());
            final int offset = newEditor.getCaretModel().getOffset();
            final PsiLocalVariable localVariable = PsiTreeUtil.findElementOfClassAtOffset(targetFile, offset, PsiLocalVariable.class, false);
            if (localVariable != null) {
                TypeSelectorManagerImpl.typeSelected(localVariable.getType(), defaultType.getType());
                ApplicationManager.getApplication().runWriteAction(() -> {
                    CodeStyleManager.getInstance(project).reformat(localVariable);
                });
            }
        }
    });
}
Also used : Template(com.intellij.codeInsight.template.Template) TemplateBuilderImpl(com.intellij.codeInsight.template.TemplateBuilderImpl) TypeExpression(com.intellij.codeInsight.intention.impl.TypeExpression) TemplateEditingAdapter(com.intellij.codeInsight.template.TemplateEditingAdapter) TextRange(com.intellij.openapi.util.TextRange) Project(com.intellij.openapi.project.Project) Editor(com.intellij.openapi.editor.Editor)

Example 9 with TemplateEditingAdapter

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

the class GrCreateSubclassAction method startTemplate.

private static void startTemplate(GrTypeParameterList oldTypeParameterList, final Project project, final GrTypeDefinition psiClass, final GrTypeDefinition targetClass, boolean includeClassName) {
    PsiElementFactory jfactory = JavaPsiFacade.getElementFactory(project);
    final GroovyPsiElementFactory elementFactory = GroovyPsiElementFactory.getInstance(project);
    GrCodeReferenceElement stubRef = elementFactory.createCodeReferenceElementFromClass(psiClass);
    try {
        GrReferenceList clause = psiClass.isInterface() ? targetClass.getImplementsClause() : targetClass.getExtendsClause();
        if (clause == null) {
            GrReferenceList stubRefList = psiClass.isInterface() ? elementFactory.createImplementsClause() : elementFactory.createExtendsClause();
            clause = (GrExtendsClause) targetClass.addAfter(stubRefList, targetClass.getNameIdentifierGroovy());
        }
        GrCodeReferenceElement ref = (GrCodeReferenceElement) clause.add(stubRef);
        if (psiClass.hasTypeParameters() || includeClassName) {
            final Editor editor = CodeInsightUtil.positionCursorAtLBrace(project, targetClass.getContainingFile(), targetClass);
            final TemplateBuilderImpl templateBuilder = editor == null || ApplicationManager.getApplication().isUnitTestMode() ? null : (TemplateBuilderImpl) TemplateBuilderFactory.getInstance().createTemplateBuilder(targetClass);
            if (includeClassName && templateBuilder != null) {
                templateBuilder.replaceElement(targetClass.getNameIdentifier(), targetClass.getName());
            }
            if (oldTypeParameterList != null && oldTypeParameterList.getTypeParameters().length > 0) {
                GrTypeArgumentList existingList = ref.getTypeArgumentList();
                final GrTypeParameterList typeParameterList = (GrTypeParameterList) targetClass.addAfter(elementFactory.createTypeParameterList(), targetClass.getNameIdentifierGroovy());
                GrTypeArgumentList argList;
                if (existingList == null) {
                    GrCodeReferenceElement codeRef = elementFactory.createCodeReferenceElementFromText("A<T>");
                    argList = ((GrTypeArgumentList) ref.add(codeRef.getTypeArgumentList()));
                    argList.getTypeArgumentElements()[0].delete();
                } else {
                    argList = existingList;
                }
                for (PsiTypeParameter parameter : oldTypeParameterList.getTypeParameters()) {
                    final PsiElement param = argList.add(elementFactory.createTypeElement(jfactory.createType(parameter)));
                    if (templateBuilder != null) {
                        templateBuilder.replaceElement(param, param.getText());
                    }
                    typeParameterList.add(elementFactory.createTypeParameter(parameter.getName(), parameter.getExtendsListTypes()));
                }
            }
            if (templateBuilder != null) {
                templateBuilder.setEndVariableBefore(ref);
                final Template template = templateBuilder.buildTemplate();
                template.addEndVariable();
                final PsiFile containingFile = targetClass.getContainingFile();
                PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.getDocument());
                final TextRange textRange = targetClass.getTextRange();
                final RangeMarker startClassOffset = editor.getDocument().createRangeMarker(textRange.getStartOffset(), textRange.getEndOffset());
                startClassOffset.setGreedyToLeft(true);
                startClassOffset.setGreedyToRight(true);
                editor.getDocument().deleteString(textRange.getStartOffset(), textRange.getEndOffset());
                CreateFromUsageBaseFix.startTemplate(editor, template, project, new TemplateEditingAdapter() {

                    @Override
                    public void templateFinished(Template template, boolean brokenOff) {
                        chooseAndImplement(psiClass, project, PsiTreeUtil.getParentOfType(containingFile.findElementAt(startClassOffset.getStartOffset()), GrTypeDefinition.class), editor);
                    }
                }, getTitle(psiClass));
            }
        }
    } catch (IncorrectOperationException e) {
        LOG.error(e);
    }
}
Also used : GrTypeParameterList(org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeParameterList) TemplateEditingAdapter(com.intellij.codeInsight.template.TemplateEditingAdapter) TextRange(com.intellij.openapi.util.TextRange) RangeMarker(com.intellij.openapi.editor.RangeMarker) Template(com.intellij.codeInsight.template.Template) GroovyPsiElementFactory(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory) GrCodeReferenceElement(org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement) TemplateBuilderImpl(com.intellij.codeInsight.template.TemplateBuilderImpl) GroovyPsiElementFactory(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory) GrReferenceList(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrReferenceList) IncorrectOperationException(com.intellij.util.IncorrectOperationException) Editor(com.intellij.openapi.editor.Editor) GrTypeArgumentList(org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeArgumentList)

Example 10 with TemplateEditingAdapter

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

the class GrSetStrongTypeIntention method processIntention.

@Override
protected void processIntention(@NotNull PsiElement element, @NotNull Project project, final Editor editor) throws IncorrectOperationException {
    PsiElement parent = element.getParent();
    PsiElement elementToBuildTemplate;
    GrVariable[] variables;
    if (parent instanceof GrVariable && parent.getParent() instanceof GrVariableDeclaration) {
        variables = ((GrVariableDeclaration) parent.getParent()).getVariables();
        elementToBuildTemplate = parent.getParent();
    } else if (parent instanceof GrVariable && parent.getParent() instanceof GrForInClause) {
        variables = new GrVariable[] { (GrVariable) parent };
        elementToBuildTemplate = parent.getParent().getParent();
    } else if (parent instanceof GrVariableDeclaration) {
        variables = ((GrVariableDeclaration) parent).getVariables();
        elementToBuildTemplate = parent;
    } else if (parent instanceof GrParameter && parent.getParent() instanceof GrParameterList) {
        variables = new GrVariable[] { (GrVariable) parent };
        elementToBuildTemplate = parent.getParent().getParent();
    } else if (parent instanceof GrVariable) {
        variables = new GrVariable[] { ((GrVariable) parent) };
        elementToBuildTemplate = parent;
    } else {
        return;
    }
    ArrayList<TypeConstraint> types = new ArrayList<>();
    if (parent.getParent() instanceof GrForInClause) {
        types.add(SupertypeConstraint.create(PsiUtil.extractIteratedType((GrForInClause) parent.getParent())));
    } else {
        for (GrVariable variable : variables) {
            GrExpression initializer = variable.getInitializerGroovy();
            if (initializer != null) {
                PsiType type = initializer.getType();
                if (type != null) {
                    types.add(SupertypeConstraint.create(type));
                }
            }
            if (variable instanceof GrParameter) {
                final PsiParameter parameter = (PsiParameter) variable;
                final PsiType type = getClosureParameterType(parameter);
                if (type != null) {
                    types.add(SupertypeConstraint.create(type));
                }
            }
        }
    }
    final String originalText = elementToBuildTemplate.getText();
    final TypeInfo typeInfo = getOrCreateTypeElement(parent, elementToBuildTemplate);
    final PsiElement replaceElement = typeInfo.elementToReplace;
    TypeConstraint[] constraints = types.toArray(new TypeConstraint[types.size()]);
    ChooseTypeExpression chooseTypeExpression = new ChooseTypeExpression(constraints, element.getManager(), replaceElement.getResolveScope());
    TemplateBuilderImpl builder = new TemplateBuilderImpl(elementToBuildTemplate);
    builder.replaceElement(replaceElement, chooseTypeExpression);
    final Document document = editor.getDocument();
    final RangeMarker rangeMarker = document.createRangeMarker(elementToBuildTemplate.getTextRange());
    rangeMarker.setGreedyToRight(true);
    rangeMarker.setGreedyToLeft(true);
    final PsiElement afterPostprocess = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(elementToBuildTemplate);
    final Template template = builder.buildTemplate();
    TextRange range = afterPostprocess.getTextRange();
    document.deleteString(range.getStartOffset(), range.getEndOffset());
    TemplateManager templateManager = TemplateManager.getInstance(project);
    templateManager.startTemplate(editor, template, new TemplateEditingAdapter() {

        @Override
        public void templateFinished(Template template, boolean brokenOff) {
            if (brokenOff) {
                ApplicationManager.getApplication().runWriteAction(() -> {
                    if (rangeMarker.isValid()) {
                        document.replaceString(rangeMarker.getStartOffset(), rangeMarker.getEndOffset(), originalText);
                        editor.getCaretModel().moveToOffset(rangeMarker.getStartOffset() + typeInfo.originalOffset);
                    }
                });
            }
        }
    });
}
Also used : GrParameterList(org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameterList) ArrayList(java.util.ArrayList) GrParameter(org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter) Document(com.intellij.openapi.editor.Document) ChooseTypeExpression(org.jetbrains.plugins.groovy.template.expressions.ChooseTypeExpression) Template(com.intellij.codeInsight.template.Template) GrVariable(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable) TemplateBuilderImpl(com.intellij.codeInsight.template.TemplateBuilderImpl) TemplateManager(com.intellij.codeInsight.template.TemplateManager) PsiElement(com.intellij.psi.PsiElement) PsiType(com.intellij.psi.PsiType) TemplateEditingAdapter(com.intellij.codeInsight.template.TemplateEditingAdapter) GrExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression) TextRange(com.intellij.openapi.util.TextRange) RangeMarker(com.intellij.openapi.editor.RangeMarker) GrVariableDeclaration(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration) PsiParameter(com.intellij.psi.PsiParameter) GrForInClause(org.jetbrains.plugins.groovy.lang.psi.api.statements.clauses.GrForInClause) TypeConstraint(org.jetbrains.plugins.groovy.lang.psi.expectedTypes.TypeConstraint)

Aggregations

Template (com.intellij.codeInsight.template.Template)12 TemplateEditingAdapter (com.intellij.codeInsight.template.TemplateEditingAdapter)12 TextRange (com.intellij.openapi.util.TextRange)9 TemplateBuilderImpl (com.intellij.codeInsight.template.TemplateBuilderImpl)8 Editor (com.intellij.openapi.editor.Editor)8 RangeMarker (com.intellij.openapi.editor.RangeMarker)7 Project (com.intellij.openapi.project.Project)6 IncorrectOperationException (com.intellij.util.IncorrectOperationException)5 TemplateManager (com.intellij.codeInsight.template.TemplateManager)3 Document (com.intellij.openapi.editor.Document)3 TypeExpression (com.intellij.codeInsight.intention.impl.TypeExpression)1 FileTemplate (com.intellij.ide.fileTemplates.FileTemplate)1 Result (com.intellij.openapi.application.Result)1 WriteCommandAction (com.intellij.openapi.command.WriteCommandAction)1 UndoManager (com.intellij.openapi.command.undo.UndoManager)1 Computable (com.intellij.openapi.util.Computable)1 PsiElement (com.intellij.psi.PsiElement)1 PsiFile (com.intellij.psi.PsiFile)1 PsiParameter (com.intellij.psi.PsiParameter)1 PsiType (com.intellij.psi.PsiType)1