Search in sources :

Example 6 with Template

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

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

the class CreateFieldFromUsageFix method createFieldFromUsageTemplate.

public static void createFieldFromUsageTemplate(final PsiClass targetClass, final Project project, final ExpectedTypeInfo[] expectedTypes, final PsiField field, final boolean createConstantField, final PsiElement context) {
    final PsiFile targetFile = targetClass.getContainingFile();
    final Editor newEditor = positionCursor(project, targetFile, field);
    if (newEditor == null)
        return;
    Template template = CreateFieldFromUsageHelper.setupTemplate(field, expectedTypes, targetClass, newEditor, context, createConstantField);
    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 PsiField psiField = PsiTreeUtil.findElementOfClassAtOffset(targetFile, offset, PsiField.class, false);
            if (psiField != null) {
                ApplicationManager.getApplication().runWriteAction(() -> {
                    CodeStyleManager.getInstance(project).reformat(psiField);
                });
                newEditor.getCaretModel().moveToOffset(psiField.getTextRange().getEndOffset() - 1);
            }
        }
    });
}
Also used : TemplateEditingAdapter(com.intellij.codeInsight.template.TemplateEditingAdapter) Editor(com.intellij.openapi.editor.Editor) Template(com.intellij.codeInsight.template.Template)

Example 8 with Template

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

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

use of com.intellij.codeInsight.template.Template 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)

Aggregations

Template (com.intellij.codeInsight.template.Template)54 Editor (com.intellij.openapi.editor.Editor)20 TemplateBuilderImpl (com.intellij.codeInsight.template.TemplateBuilderImpl)19 Project (com.intellij.openapi.project.Project)17 TemplateManager (com.intellij.codeInsight.template.TemplateManager)15 TextRange (com.intellij.openapi.util.TextRange)15 TemplateEditingAdapter (com.intellij.codeInsight.template.TemplateEditingAdapter)12 PsiElement (com.intellij.psi.PsiElement)11 RangeMarker (com.intellij.openapi.editor.RangeMarker)9 IncorrectOperationException (com.intellij.util.IncorrectOperationException)9 NotNull (org.jetbrains.annotations.NotNull)5 MacroCallNode (com.intellij.codeInsight.template.impl.MacroCallNode)4 TextExpression (com.intellij.codeInsight.template.impl.TextExpression)4 Document (com.intellij.openapi.editor.Document)4 DartComponent (com.jetbrains.lang.dart.psi.DartComponent)4 Expression (com.intellij.codeInsight.template.Expression)3 SuggestVariableNameMacro (com.intellij.codeInsight.template.macro.SuggestVariableNameMacro)3 LocalQuickFixAndIntentionActionOnPsiElement (com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement)3 OpenFileDescriptor (com.intellij.openapi.fileEditor.OpenFileDescriptor)3 XmlTag (com.intellij.psi.xml.XmlTag)3