use of com.intellij.openapi.editor.actions.EnterAction in project intellij-community by JetBrains.
the class CreateLocalVarFromInstanceofAction method invoke.
@Override
public void invoke(@NotNull final Project project, final Editor editor, final PsiFile file) {
PsiInstanceOfExpression instanceOfExpression = getInstanceOfExpressionAtCaret(editor, file);
assert instanceOfExpression.getContainingFile() == file : instanceOfExpression.getContainingFile() + "; file=" + file;
try {
final PsiStatement statementInside = isNegated(instanceOfExpression) ? null : getExpressionStatementInside(file, editor, instanceOfExpression.getOperand());
PsiDeclarationStatement decl = createLocalVariableDeclaration(instanceOfExpression, statementInside);
if (decl == null)
return;
decl = (PsiDeclarationStatement) CodeStyleManager.getInstance(project).reformat(decl);
decl = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(decl);
PsiLocalVariable localVariable = (PsiLocalVariable) decl.getDeclaredElements()[0];
TemplateBuilderImpl builder = new TemplateBuilderImpl(localVariable);
builder.setEndVariableAfter(localVariable.getNameIdentifier());
Template template = generateTemplate(project, localVariable.getInitializer(), localVariable.getType());
Editor newEditor = CreateFromUsageBaseFix.positionCursor(project, file, localVariable.getNameIdentifier());
if (newEditor == null)
return;
TextRange range = localVariable.getNameIdentifier().getTextRange();
newEditor.getDocument().deleteString(range.getStartOffset(), range.getEndOffset());
CreateFromUsageBaseFix.startTemplate(newEditor, template, project, new TemplateEditingAdapter() {
@Override
public void templateFinished(Template template, boolean brokenOff) {
ApplicationManager.getApplication().runWriteAction(() -> {
PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
CaretModel caretModel = editor.getCaretModel();
PsiElement elementAt = file.findElementAt(caretModel.getOffset());
PsiDeclarationStatement declarationStatement = PsiTreeUtil.getParentOfType(elementAt, PsiDeclarationStatement.class);
if (declarationStatement != null) {
caretModel.moveToOffset(declarationStatement.getTextRange().getEndOffset());
}
new EnterAction().actionPerformed(editor, DataManager.getInstance().getDataContext());
});
}
});
} catch (IncorrectOperationException e) {
LOG.error(e);
}
}
Aggregations