use of com.intellij.codeInsight.template.Template in project intellij-community by JetBrains.
the class GroovyCreateFieldFromUsageHelper method setupTemplateImpl.
@Override
public Template setupTemplateImpl(PsiField f, Object expectedTypes, PsiClass targetClass, Editor editor, PsiElement context, boolean createConstantField, PsiSubstitutor substitutor) {
GrVariableDeclaration fieldDecl = (GrVariableDeclaration) f.getParent();
GrField field = (GrField) fieldDecl.getVariables()[0];
TemplateBuilderImpl builder = new TemplateBuilderImpl(fieldDecl);
Project project = context.getProject();
GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(project);
if (expectedTypes instanceof TypeConstraint[]) {
GrTypeElement typeElement = fieldDecl.getTypeElementGroovy();
assert typeElement != null;
ChooseTypeExpression expr = new ChooseTypeExpression((TypeConstraint[]) expectedTypes, PsiManager.getInstance(project), typeElement.getResolveScope());
builder.replaceElement(typeElement, expr);
} else if (expectedTypes instanceof ExpectedTypeInfo[]) {
new GuessTypeParameters(factory).setupTypeElement(field.getTypeElement(), (ExpectedTypeInfo[]) expectedTypes, substitutor, builder, context, targetClass);
}
if (createConstantField) {
field.setInitializerGroovy(factory.createExpressionFromText("0", null));
builder.replaceElement(field.getInitializerGroovy(), new EmptyExpression());
}
fieldDecl = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(fieldDecl);
Template template = builder.buildTemplate();
TextRange range = fieldDecl.getTextRange();
editor.getDocument().deleteString(range.getStartOffset(), range.getEndOffset());
if (expectedTypes instanceof ExpectedTypeInfo[]) {
if (((ExpectedTypeInfo[]) expectedTypes).length > 1)
template.setToShortenLongNames(false);
}
return template;
}
use of com.intellij.codeInsight.template.Template in project intellij-community by JetBrains.
the class CreateLocalVariableFromUsageFix method processIntention.
@Override
protected void processIntention(@NotNull PsiElement element, @NotNull Project project, Editor editor) throws IncorrectOperationException {
final PsiFile file = element.getContainingFile();
PsiClassType type = JavaPsiFacade.getInstance(project).getElementFactory().createTypeByFQClassName("Object", GlobalSearchScope.allScope(project));
GrVariableDeclaration decl = GroovyPsiElementFactory.getInstance(project).createVariableDeclaration(ArrayUtil.EMPTY_STRING_ARRAY, "", type, myRefExpression.getReferenceName());
int offset = myRefExpression.getTextRange().getStartOffset();
GrStatement anchor = findAnchor(file, offset);
TypeConstraint[] constraints = GroovyExpectedTypesProvider.calculateTypeConstraints(myRefExpression);
if (myRefExpression.equals(anchor)) {
decl = myRefExpression.replaceWithStatement(decl);
} else {
decl = myOwner.addVariableDeclarationBefore(decl, anchor);
}
GrTypeElement typeElement = decl.getTypeElementGroovy();
assert typeElement != null;
ChooseTypeExpression expr = new ChooseTypeExpression(constraints, PsiManager.getInstance(project), typeElement.getResolveScope());
TemplateBuilderImpl builder = new TemplateBuilderImpl(decl);
builder.replaceElement(typeElement, expr);
decl = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(decl);
Template template = builder.buildTemplate();
Editor newEditor = positionCursor(project, myOwner.getContainingFile(), decl);
TextRange range = decl.getTextRange();
newEditor.getDocument().deleteString(range.getStartOffset(), range.getEndOffset());
TemplateManager manager = TemplateManager.getInstance(project);
manager.startTemplate(newEditor, template);
}
use of com.intellij.codeInsight.template.Template in project intellij-community by JetBrains.
the class CreateVariableFix method invoke.
public void invoke(@NotNull final Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
editor = editor instanceof EditorWindow ? ((EditorWindow) editor).getDelegate() : editor;
XmlTag tag = PsiTreeUtil.getContextOfType(myReference, XmlTag.class, true);
if (tag == null)
return;
XmlTag xmlTag = tag.createChildTag("variable", XsltSupport.XSLT_NS, null, false);
xmlTag.setAttribute("name", myReference.getReferencedName());
xmlTag.setAttribute("select", "dummy");
final XmlAttribute select = xmlTag.getAttribute("select", null);
assert select != null;
final PsiElement dummy = XsltSupport.getAttValueToken(select);
assert dummy != null;
final TemplateBuilderImpl builder = createTemplateBuilder(xmlTag);
builder.replaceElement(dummy, new MacroCallNode(new CompleteMacro()));
builder.setEndVariableAfter(select);
final Template template = builder.buildTemplate();
template.addTextSegment("\n");
template.setToIndent(true);
final XmlTag insertionPoint = findVariableInsertionPoint(tag);
moveTo(editor, insertionPoint);
TemplateManager.getInstance(project).startTemplate(editor, template);
}
use of com.intellij.codeInsight.template.Template 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);
}
}
use of com.intellij.codeInsight.template.Template 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);
}
});
}
}
});
}
Aggregations