Search in sources :

Example 31 with Template

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

the class CompletionData method objectToLookupItem.

public static LookupElement objectToLookupItem(@NotNull final Object object) {
    if (object instanceof LookupElement)
        return (LookupElement) object;
    String s = null;
    TailType tailType = TailType.NONE;
    if (object instanceof PsiElement) {
        s = PsiUtilCore.getName((PsiElement) object);
    } else if (object instanceof PsiMetaData) {
        s = ((PsiMetaData) object).getName();
    } else if (object instanceof String) {
        s = (String) object;
    } else if (object instanceof Template) {
        s = ((Template) object).getKey();
    } else if (object instanceof PresentableLookupValue) {
        s = ((PresentableLookupValue) object).getPresentation();
    }
    if (s == null) {
        throw new AssertionError("Null string for object: " + object + " of class " + object.getClass());
    }
    LookupItem item = new LookupItem(object, s);
    if (object instanceof LookupValueWithUIHint && ((LookupValueWithUIHint) object).isBold()) {
        item.setBold();
    }
    item.setAttribute(LookupItem.TAIL_TYPE_ATTR, tailType);
    return item;
}
Also used : PsiMetaData(com.intellij.psi.meta.PsiMetaData) LookupValueWithUIHint(com.intellij.codeInsight.lookup.LookupValueWithUIHint) LookupItem(com.intellij.codeInsight.lookup.LookupItem) LookupElement(com.intellij.codeInsight.lookup.LookupElement) PresentableLookupValue(com.intellij.codeInsight.lookup.PresentableLookupValue) TailType(com.intellij.codeInsight.TailType) Template(com.intellij.codeInsight.template.Template)

Example 32 with Template

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

the class CreateClassFromNewFix method setupClassFromNewExpression.

protected void setupClassFromNewExpression(final PsiClass psiClass, final PsiNewExpression newExpression) {
    assert ApplicationManager.getApplication().isWriteAccessAllowed();
    final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(newExpression.getProject()).getElementFactory();
    PsiClass aClass = psiClass;
    if (aClass == null)
        return;
    final PsiJavaCodeReferenceElement classReference = newExpression.getClassReference();
    if (classReference != null) {
        classReference.bindToElement(aClass);
    }
    setupInheritance(newExpression, aClass);
    PsiExpressionList argList = newExpression.getArgumentList();
    final Project project = aClass.getProject();
    if (argList != null && argList.getExpressions().length > 0) {
        PsiMethod constructor = elementFactory.createConstructor();
        constructor = (PsiMethod) aClass.add(constructor);
        TemplateBuilderImpl templateBuilder = new TemplateBuilderImpl(aClass);
        CreateFromUsageUtils.setupMethodParameters(constructor, templateBuilder, argList, getTargetSubstitutor(newExpression));
        setupSuperCall(aClass, constructor, templateBuilder);
        getReferenceElement(newExpression).bindToElement(aClass);
        aClass = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(aClass);
        final Template template = templateBuilder.buildTemplate();
        template.setToReformat(true);
        final Editor editor = positionCursor(project, aClass.getContainingFile(), aClass);
        if (editor == null)
            return;
        final RangeMarker textRange = editor.getDocument().createRangeMarker(aClass.getTextRange());
        final Runnable runnable = () -> {
            new WriteCommandAction(project, getText(), getText()) {

                @Override
                protected void run(@NotNull Result result) throws Throwable {
                    try {
                        editor.getDocument().deleteString(textRange.getStartOffset(), textRange.getEndOffset());
                    } finally {
                        textRange.dispose();
                    }
                }
            }.execute();
            startTemplate(editor, template, project, null, getText());
        };
        if (ApplicationManager.getApplication().isUnitTestMode()) {
            runnable.run();
        } else {
            ApplicationManager.getApplication().invokeLater(runnable);
        }
    } else {
        positionCursor(project, aClass.getContainingFile(), ObjectUtils.notNull(aClass.getNameIdentifier(), aClass));
    }
}
Also used : WriteCommandAction(com.intellij.openapi.command.WriteCommandAction) RangeMarker(com.intellij.openapi.editor.RangeMarker) NotNull(org.jetbrains.annotations.NotNull) Template(com.intellij.codeInsight.template.Template) Result(com.intellij.openapi.application.Result) Project(com.intellij.openapi.project.Project) TemplateBuilderImpl(com.intellij.codeInsight.template.TemplateBuilderImpl) Editor(com.intellij.openapi.editor.Editor)

Example 33 with Template

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

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

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

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