use of com.intellij.codeInsight.template.impl.TemplateState in project intellij-community by JetBrains.
the class ReassignVariableUtil method finishTemplate.
private static void finishTemplate(Editor editor) {
final TemplateState templateState = TemplateManagerImpl.getTemplateState(editor);
final InplaceRefactoring renamer = editor.getUserData(InplaceRefactoring.INPLACE_RENAMER);
if (templateState != null && renamer != null) {
templateState.gotoEnd(true);
editor.putUserData(InplaceRefactoring.INPLACE_RENAMER, null);
}
}
use of com.intellij.codeInsight.template.impl.TemplateState in project intellij-community by JetBrains.
the class DataPointHolderConversionIntentionTest method testNameTyping.
public void testNameTyping() {
configureByFile(getBasePath() + "/beforeNameTyping.java");
TemplateManagerImpl.setTemplateTesting(getProject(), getTestRootDisposable());
doAction("Replace by @DataPoint method");
final TemplateState state = TemplateManagerImpl.getTemplateState(getEditor());
assertNotNull(state);
type("typedMethodNameFromTemplates");
state.nextTab();
assertTrue(state.isFinished());
checkResultByFile(getBasePath() + "/afterNameTyping.java");
}
use of com.intellij.codeInsight.template.impl.TemplateState in project intellij-community by JetBrains.
the class InplaceIntroduceVariableTest method doTestTypeChange.
private void doTestTypeChange(final String newType) {
final Pass<AbstractInplaceIntroducer> typeChanger = new Pass<AbstractInplaceIntroducer>() {
@Override
public void pass(AbstractInplaceIntroducer inplaceIntroduceFieldPopup) {
type(newType);
}
};
String name = getTestName(true);
configureByFile(getBasePath() + name + getExtension());
final boolean enabled = getEditor().getSettings().isVariableInplaceRenameEnabled();
try {
TemplateManagerImpl.setTemplateTesting(getProject(), getTestRootDisposable());
getEditor().getSettings().setVariableInplaceRenameEnabled(true);
final AbstractInplaceIntroducer introducer = invokeRefactoring();
TemplateState state = TemplateManagerImpl.getTemplateState(getEditor());
assert state != null;
state.previousTab();
typeChanger.pass(introducer);
state.gotoEnd(false);
checkResultByFile(getBasePath() + name + "_after" + getExtension());
} finally {
getEditor().getSettings().setVariableInplaceRenameEnabled(enabled);
}
}
use of com.intellij.codeInsight.template.impl.TemplateState in project intellij-community by JetBrains.
the class CreatePropertyFromUsageFix method invokeImpl.
@Override
protected void invokeImpl(PsiClass targetClass) {
PsiManager manager = myMethodCall.getManager();
final Project project = manager.getProject();
PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
boolean isStatic = false;
PsiExpression qualifierExpression = myMethodCall.getMethodExpression().getQualifierExpression();
if (qualifierExpression != null) {
PsiReference reference = qualifierExpression.getReference();
if (reference != null) {
isStatic = reference.resolve() instanceof PsiClass;
}
} else {
PsiMethod method = PsiTreeUtil.getParentOfType(myMethodCall, PsiMethod.class);
if (method != null) {
isStatic = method.hasModifierProperty(PsiModifier.STATIC);
}
}
String fieldName = getVariableName(myMethodCall, isStatic);
LOG.assertTrue(fieldName != null);
String callText = myMethodCall.getMethodExpression().getReferenceName();
LOG.assertTrue(callText != null, myMethodCall.getMethodExpression());
PsiType[] expectedTypes;
PsiType type;
PsiField field = targetClass.findFieldByName(fieldName, true);
if (callText.startsWith(GET_PREFIX)) {
expectedTypes = field != null ? new PsiType[] { field.getType() } : CreateFromUsageUtils.guessType(myMethodCall, false);
type = expectedTypes[0];
} else if (callText.startsWith(IS_PREFIX)) {
type = PsiType.BOOLEAN;
expectedTypes = new PsiType[] { type };
} else {
type = RefactoringUtil.getTypeByExpression(myMethodCall.getArgumentList().getExpressions()[0]);
if (type == null || PsiType.NULL.equals(type))
type = PsiType.getJavaLangObject(manager, myMethodCall.getResolveScope());
expectedTypes = new PsiType[] { type };
}
positionCursor(project, targetClass.getContainingFile(), targetClass);
IdeDocumentHistory.getInstance(project).includeCurrentPlaceAsChangePlace();
if (field == null) {
field = factory.createField(fieldName, type);
PsiUtil.setModifierProperty(field, PsiModifier.STATIC, isStatic);
}
PsiMethod accessor;
PsiElement fieldReference;
PsiElement typeReference;
PsiCodeBlock body;
if (callText.startsWith(GET_PREFIX) || callText.startsWith(IS_PREFIX)) {
accessor = (PsiMethod) targetClass.add(GenerateMembersUtil.generateSimpleGetterPrototype(field));
body = accessor.getBody();
LOG.assertTrue(body != null, accessor.getText());
fieldReference = ((PsiReturnStatement) body.getStatements()[0]).getReturnValue();
typeReference = accessor.getReturnTypeElement();
} else {
accessor = (PsiMethod) targetClass.add(GenerateMembersUtil.generateSimpleSetterPrototype(field, targetClass));
body = accessor.getBody();
LOG.assertTrue(body != null, accessor.getText());
PsiAssignmentExpression expr = (PsiAssignmentExpression) ((PsiExpressionStatement) body.getStatements()[0]).getExpression();
fieldReference = ((PsiReferenceExpression) expr.getLExpression()).getReferenceNameElement();
typeReference = accessor.getParameterList().getParameters()[0].getTypeElement();
}
accessor.setName(callText);
PsiUtil.setModifierProperty(accessor, PsiModifier.STATIC, isStatic);
TemplateBuilderImpl builder = new TemplateBuilderImpl(accessor);
builder.replaceElement(typeReference, TYPE_VARIABLE, new TypeExpression(project, expectedTypes), true);
builder.replaceElement(fieldReference, FIELD_VARIABLE, new FieldExpression(field, targetClass, expectedTypes), true);
builder.setEndVariableAfter(body.getLBrace());
accessor = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(accessor);
LOG.assertTrue(accessor != null);
targetClass = accessor.getContainingClass();
LOG.assertTrue(targetClass != null);
Template template = builder.buildTemplate();
TextRange textRange = accessor.getTextRange();
final PsiFile file = targetClass.getContainingFile();
final Editor editor = positionCursor(project, targetClass.getContainingFile(), accessor);
if (editor == null)
return;
editor.getDocument().deleteString(textRange.getStartOffset(), textRange.getEndOffset());
editor.getCaretModel().moveToOffset(textRange.getStartOffset());
final boolean isStatic1 = isStatic;
startTemplate(editor, template, project, new TemplateEditingAdapter() {
@Override
public void beforeTemplateFinished(final TemplateState state, Template template) {
ApplicationManager.getApplication().runWriteAction(() -> {
String fieldName1 = state.getVariableValue(FIELD_VARIABLE).getText();
if (!PsiNameHelper.getInstance(project).isIdentifier(fieldName1))
return;
String fieldType = state.getVariableValue(TYPE_VARIABLE).getText();
PsiElement element = file.findElementAt(editor.getCaretModel().getOffset());
PsiClass aClass = PsiTreeUtil.getParentOfType(element, PsiClass.class);
if (aClass == null)
return;
PsiField field1 = aClass.findFieldByName(fieldName1, true);
if (field1 != null) {
CreatePropertyFromUsageFix.this.beforeTemplateFinished(aClass, field1);
return;
}
PsiElementFactory factory1 = JavaPsiFacade.getInstance(aClass.getProject()).getElementFactory();
try {
PsiType type1 = factory1.createTypeFromText(fieldType, aClass);
try {
field1 = factory1.createField(fieldName1, type1);
field1 = (PsiField) aClass.add(field1);
PsiUtil.setModifierProperty(field1, PsiModifier.STATIC, isStatic1);
CreatePropertyFromUsageFix.this.beforeTemplateFinished(aClass, field1);
} catch (IncorrectOperationException e) {
LOG.error(e);
}
} catch (IncorrectOperationException e) {
}
});
}
@Override
public void templateFinished(Template template, boolean brokenOff) {
PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
final int offset = editor.getCaretModel().getOffset();
final PsiMethod generatedMethod = PsiTreeUtil.findElementOfClassAtOffset(file, offset, PsiMethod.class, false);
if (generatedMethod != null) {
ApplicationManager.getApplication().runWriteAction(() -> {
CodeStyleManager.getInstance(project).reformat(generatedMethod);
});
}
}
});
}
use of com.intellij.codeInsight.template.impl.TemplateState in project intellij-plugins by JetBrains.
the class GrStepDefinitionCreator method createStepDefinition.
@Override
public boolean createStepDefinition(@NotNull GherkinStep step, @NotNull final PsiFile file) {
if (!(file instanceof GroovyFile))
return false;
final Project project = file.getProject();
final VirtualFile vFile = ObjectUtils.assertNotNull(file.getVirtualFile());
final OpenFileDescriptor descriptor = new OpenFileDescriptor(project, vFile);
FileEditorManager.getInstance(project).getAllEditors(vFile);
FileEditorManager.getInstance(project).openTextEditor(descriptor, true);
final Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
if (editor != null) {
final TemplateManager templateManager = TemplateManager.getInstance(file.getProject());
final TemplateState templateState = TemplateManagerImpl.getTemplateState(editor);
final Template template = templateManager.getActiveTemplate(editor);
if (templateState != null && template != null) {
templateState.gotoEnd();
}
}
// snippet text
final GrMethodCall element = buildStepDefinitionByStep(step);
GrMethodCall methodCall = (GrMethodCall) ((GroovyFile) file).addStatementBefore(element, null);
JavaCodeStyleManager.getInstance(project).shortenClassReferences(methodCall);
methodCall = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(methodCall);
PsiDocumentManager.getInstance(project).commitAllDocuments();
if (ApplicationManager.getApplication().isUnitTestMode())
return true;
final TemplateBuilderImpl builder = (TemplateBuilderImpl) TemplateBuilderFactory.getInstance().createTemplateBuilder(methodCall);
// regexp str
GrLiteral pattern = GrCucumberUtil.getStepDefinitionPattern(methodCall);
assert pattern != null;
String patternText = pattern.getText();
builder.replaceElement(pattern, new TextRange(1, patternText.length() - 1), patternText.substring(1, patternText.length() - 1));
// block vars
GrClosableBlock closure = methodCall.getClosureArguments()[0];
final GrParameter[] blockVars = closure.getAllParameters();
for (GrParameter var : blockVars) {
PsiElement identifier = var.getNameIdentifierGroovy();
builder.replaceElement(identifier, identifier.getText());
}
TemplateManager manager = TemplateManager.getInstance(project);
final Editor editorToRunTemplate;
if (editor == null) {
editorToRunTemplate = IntentionUtils.positionCursor(project, file, methodCall);
} else {
editorToRunTemplate = editor;
}
Template template = builder.buildTemplate();
TextRange range = methodCall.getTextRange();
editorToRunTemplate.getDocument().deleteString(range.getStartOffset(), range.getEndOffset());
editorToRunTemplate.getCaretModel().moveToOffset(range.getStartOffset());
manager.startTemplate(editorToRunTemplate, template, new TemplateEditingAdapter() {
@Override
public void templateFinished(Template template, boolean brokenOff) {
if (brokenOff)
return;
ApplicationManager.getApplication().runWriteAction(() -> {
PsiDocumentManager.getInstance(project).commitDocument(editorToRunTemplate.getDocument());
final int offset = editorToRunTemplate.getCaretModel().getOffset();
GrMethodCall methodCall1 = PsiTreeUtil.findElementOfClassAtOffset(file, offset - 1, GrMethodCall.class, false);
if (methodCall1 != null) {
GrClosableBlock[] closures = methodCall1.getClosureArguments();
if (closures.length == 1) {
GrClosableBlock closure1 = closures[0];
selectBody(closure1, editor);
}
}
});
}
});
return true;
}
Aggregations