use of com.intellij.codeInsight.template.TemplateBuilderImpl in project intellij-community by JetBrains.
the class CreateSubclassAction method startTemplate.
private static void startTemplate(PsiTypeParameterList oldTypeParameterList, final Project project, final PsiClass psiClass, final PsiClass targetClass, final boolean includeClassName) {
final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(project).getElementFactory();
PsiJavaCodeReferenceElement ref = elementFactory.createClassReferenceElement(psiClass);
try {
if (psiClass.isInterface()) {
ref = (PsiJavaCodeReferenceElement) targetClass.getImplementsList().add(ref);
} else {
ref = (PsiJavaCodeReferenceElement) targetClass.getExtendsList().add(ref);
}
if (psiClass.hasTypeParameters() || includeClassName) {
final Editor editor = CodeInsightUtil.positionCursorAtLBrace(project, targetClass.getContainingFile(), targetClass);
final TemplateBuilderImpl templateBuilder = editor != null ? (TemplateBuilderImpl) TemplateBuilderFactory.getInstance().createTemplateBuilder(targetClass) : null;
if (includeClassName && templateBuilder != null) {
templateBuilder.replaceElement(targetClass.getNameIdentifier(), targetClass.getName());
}
if (oldTypeParameterList != null) {
for (PsiTypeParameter parameter : oldTypeParameterList.getTypeParameters()) {
final PsiElement param = ref.getParameterList().add(elementFactory.createTypeElement(elementFactory.createType(parameter)));
if (templateBuilder != null) {
templateBuilder.replaceElement(param, param.getText());
}
}
}
replaceTypeParamsList(targetClass, oldTypeParameterList);
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) {
try {
LOG.assertTrue(startClassOffset.isValid(), startClassOffset);
final PsiElement psiElement = containingFile.findElementAt(startClassOffset.getStartOffset());
final PsiClass aTargetClass = PsiTreeUtil.getParentOfType(psiElement, PsiClass.class);
LOG.assertTrue(aTargetClass != null, psiElement);
if (!brokenOff) {
TransactionGuard.getInstance().submitTransactionAndWait(() -> chooseAndImplement(psiClass, project, aTargetClass, editor));
}
} finally {
startClassOffset.dispose();
}
}
}, getTitle(psiClass));
}
}
} catch (IncorrectOperationException e) {
LOG.error(e);
}
}
use of com.intellij.codeInsight.template.TemplateBuilderImpl 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));
}
}
use of com.intellij.codeInsight.template.TemplateBuilderImpl 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);
}
}
use of com.intellij.codeInsight.template.TemplateBuilderImpl 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);
}
}
use of com.intellij.codeInsight.template.TemplateBuilderImpl 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);
});
}
}
});
}
Aggregations