@NotNull
  private GrVariable insertVariableDefinition(@NotNull GrVariableDeclaration declaration,
                                              @NotNull GrStatement anchor,
                                              @Nullable PsiElement expression) throws IncorrectOperationException {
    GrLabeledStatement labeledStatement = expression != null && expression.getParent() instanceof GrLabeledStatement ? (GrLabeledStatement)expression.getParent() : null;

    boolean expressionMustBeDeleted = expression != null && PsiUtil.isExpressionStatement(expression) && !isSingleGStringInjectionExpr(expression);
    boolean anchorEqualsExpression = anchor == expression || labeledStatement == anchor;

    String usedLabel = labeledStatement != null ? labeledStatement.getName() : null;

    if (expressionMustBeDeleted && !anchorEqualsExpression) {
      expression.delete();
    }

    boolean isInsideControlStatement = isControlStatementBranch(anchor);
    if (isInsideControlStatement) {
      anchor = insertBraces(anchor);
    }

    LOG.assertTrue(myOccurrences.length > 0);

    GrStatementOwner block = (GrStatementOwner)anchor.getParent();

    if (usedLabel != null && expressionMustBeDeleted && anchorEqualsExpression) {
      GrLabeledStatement definitionWithLabel = (GrLabeledStatement)GroovyPsiElementFactory.getInstance(anchor.getProject()).createStatementFromText(usedLabel + ": foo()");
      GrLabeledStatement inserted = insertStatement(definitionWithLabel, anchor, block, true);
      declaration = inserted.getStatement().replaceWithStatement(declaration);
    }
    else {
      declaration = insertStatement(declaration, anchor, block, expressionMustBeDeleted && anchorEqualsExpression);
    }

    final GrVariable variable = declaration.getVariables()[0];
    JavaCodeStyleManager.getInstance(declaration.getProject()).shortenClassReferences(declaration);


    PsiElement markerPlace = expressionMustBeDeleted  ? variable :
                             isInsideControlStatement ? declaration.getParent()
                                                      : expression;
    refreshPositionMarker(markerPlace);

    return variable;
  }
@NotNull
  private GrVariable insertVariableDefinition(@NotNull GrVariableDeclaration declaration,
                                              @NotNull GrStatement anchor,
                                              @Nullable PsiElement expression)