Emacs C++-mode incorrect indentation?

Idan K picture Idan K · Mar 19, 2009 · Viewed 35.7k times · Source

I'm running emacs 23 with c++-mode and having some indentation problems. Suppose I have this code:

void foo()
{
   if (cond)
     { <---
        int i;
        ...
     } <---
}

This seems to be the default behavior of the automatic indentation. However I'd like to change it so it'll be like this:

void foo()
{
   if (cond)
   {
      int i;
      ...
   }
}

Is there a way to do this easily by configuring c++ mode or my .emacs file?

Answer

Alex B picture Alex B · Mar 19, 2009

I have the following in my .emacs file:

(defun my-c++-mode-hook ()
  (setq c-basic-offset 4)
  (c-set-offset 'substatement-open 0))
(add-hook 'c++-mode-hook 'my-c++-mode-hook)

You can determine which offset to edit by hitting [ctrl-c ctrl-s] on any line. On the first line with a brace after the if it will say substatement-open.