use of org.jetbrains.kotlin.psi.KtIfExpression in project kotlin by JetBrains.
the class KotlinIfSurrounderBase method surroundStatements.
@Nullable
@Override
protected TextRange surroundStatements(Project project, Editor editor, PsiElement container, PsiElement[] statements) {
statements = MoveDeclarationsOutHelper.move(container, statements, isGenerateDefaultInitializers());
if (statements.length == 0) {
KotlinSurrounderUtils.showErrorHint(project, editor, KotlinSurrounderUtils.SURROUND_WITH_ERROR);
return null;
}
KtIfExpression ifExpression = (KtIfExpression) KtPsiFactoryKt.KtPsiFactory(project).createExpression(getCodeTemplate());
ifExpression = (KtIfExpression) container.addAfter(ifExpression, statements[statements.length - 1]);
// TODO move a comment for first statement
KtBlockExpression thenBranch = (KtBlockExpression) ifExpression.getThen();
assert thenBranch != null : "Then branch should exist for created if expression: " + ifExpression.getText();
// Add statements in then branch of created if
KotlinSurrounderUtils.addStatementsInBlock(thenBranch, statements);
// Delete statements from original code
container.deleteChildRange(statements[0], statements[statements.length - 1]);
ifExpression = CodeInsightUtilBase.forcePsiPostprocessAndRestoreElement(ifExpression);
KtExpression condition = ifExpression.getCondition();
assert condition != null : "Condition should exists for created if expression: " + ifExpression.getText();
// Delete condition from created if
TextRange range = condition.getTextRange();
TextRange textRange = new TextRange(range.getStartOffset(), range.getStartOffset());
editor.getDocument().deleteString(range.getStartOffset(), range.getEndOffset());
return textRange;
}
Aggregations