views:

2209

answers:

5

Hi,

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?

+9  A: 

Check out the Emacs wiki on Indenting C

crashmstr
+7  A: 

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.

Alex B
Upvoted for [ctrl-c ctrl-s] tip.
+3  A: 

This is mine... this matches the default setup for visual studio.

(defun my-c-mode-common-hook ()
 ;; my customizations for all of c-mode, c++-mode, objc-mode, java-mode
 (c-set-offset 'substatement-open 0)
 ;; other customizations can go here

 (setq c++-tab-always-indent t)
 (setq c-basic-offset 4)                  ;; Default is 2
 (setq c-indent-level 4)                  ;; Default is 2

 (setq tab-stop-list '(4 8 12 16 20 24 28 32 36 40 44 48 52 56 60))
 (setq tab-width 4)
 (setq indent-tabs-mode t)  ; use spaces only if nil
 )

(add-hook 'c-mode-common-hook 'my-c-mode-common-hook)
justinhj
Thank you so much! I've been looking for this everywhere... For as long as I can remember.
nbolton
+1  A: 

Short answer: Put this line into your .emacs file:

(c-set-offset 'substatement-open 0)

Long answer: ...

For those of us who are new to emacs-lisp, there is a pretty simple method at http://www.cs.cmu.edu/:

  • Go to the line you want to indent

  • Type C-C C-O (that's the letter "O", not zero)

  • Press Enter to accept the default suggestion

  • Type "0" (that's a zero) for no extra indentation, press Enter

  • Type Tab to reindent the line.

  • Future "{" in this situation will have the correct tab setting, until you restart emacs.

The nice thing about this method, is that you can actually see the lisp code that you want to change. You can put in your .emacs file:

(c-set-offset 'SYNTACTIC-SYMBOL OFFSET)

Additionally, you may want to check out the program AStyle to automatically format C++ source outside of emacs.

Colin
A: 

Thank you, this was extremely helpful!

Jonathan Weiss