Search in sources :

Example 1 with KtIfExpression

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;
}
Also used : KtIfExpression(org.jetbrains.kotlin.psi.KtIfExpression) KtExpression(org.jetbrains.kotlin.psi.KtExpression) KtBlockExpression(org.jetbrains.kotlin.psi.KtBlockExpression) TextRange(com.intellij.openapi.util.TextRange) Nullable(org.jetbrains.annotations.Nullable)

Aggregations

TextRange (com.intellij.openapi.util.TextRange)1 Nullable (org.jetbrains.annotations.Nullable)1 KtBlockExpression (org.jetbrains.kotlin.psi.KtBlockExpression)1 KtExpression (org.jetbrains.kotlin.psi.KtExpression)1 KtIfExpression (org.jetbrains.kotlin.psi.KtIfExpression)1