@Override
  protected void reformat(PsiElement atCaret) throws IncorrectOperationException {
    PsiElement parent = atCaret.getParent();
    if (parent instanceof GrCodeBlock) {
      final GrCodeBlock block = (GrCodeBlock) parent;
      if (block.getStatements().length > 0 && block.getStatements()[0] == atCaret) {
        atCaret = block;
      }
    } else if (parent instanceof GrForStatement) {
      atCaret = parent;
    }

    super.reformat(atCaret);
  }
  @Nullable
  protected PsiElement getStatementAtCaret(Editor editor, PsiFile psiFile) {
    final PsiElement atCaret = super.getStatementAtCaret(editor, psiFile);

    if (atCaret instanceof PsiWhiteSpace) return null;
    if (atCaret == null) return null;

    final GrCodeBlock codeBlock =
        PsiTreeUtil.getParentOfType(atCaret, GrCodeBlock.class, false, GrControlStatement.class);
    if (codeBlock != null) {
      for (GrStatement statement : codeBlock.getStatements()) {
        if (PsiTreeUtil.isAncestor(statement, atCaret, true)) {
          return statement;
        }
      }
    }

    PsiElement statementAtCaret =
        PsiTreeUtil.getParentOfType(
            atCaret, GrStatement.class, GrCodeBlock.class, PsiMember.class, GrDocComment.class);

    if (statementAtCaret instanceof GrBlockStatement) return null;
    if (statementAtCaret == null) return null;

    GrControlStatement controlStatement =
        PsiTreeUtil.getParentOfType(statementAtCaret, GrControlStatement.class);

    if (controlStatement != null && !PsiTreeUtil.hasErrorElements(statementAtCaret)) {
      return controlStatement;
    }

    return statementAtCaret instanceof GrStatement || statementAtCaret instanceof GrMember
        ? statementAtCaret
        : null;
  }
 @Nullable
 private static GrStatement getFirstStatement(GrCodeBlock block) {
   GrStatement[] statements = block.getStatements();
   if (statements.length == 0) return null;
   return statements[0];
 }