5

I am new to Emacs and trying to learn the basics.

I am writing a few C programs and I noticed that the default brace indentation is as follows:

for(i = 0; i < 10; ++i)
    {
        // code 
    }

How would I go about modifying this behaviour to achieve the following instead:

for(i = 0; i < 10; ++i)
{
    // code
}
Scott Weldon
  • 2,695
  • 1
  • 17
  • 31
Q''
  • 173
  • 7

1 Answers1

5

As mentioned in this answer on SO, you can do:

(setq c-default-style "bsd")

This will set the style for all C-based modes. If you want to set it only for one, do e.g.:

(add-to-list 'c-default-style '(c-mode "bsd"))

However, setting c-default-style will change various other style settings, which may not be what you want. To only change the post-for-loop-brace indentation, do:

(add-to-list 'c-offsets-alist '(substatement-open . 0))

(This will shadow the old value, which AFAIK shouldn't cause any problems. See this question and its answers for possible ways to actually replace the old value.)


Now to generalize: how do you find the specific syntactic symbol in the c-offsets-alist that you need to modify?

Note the line that has faulty indentation (in this case, the one with the { after the for loop), and move the point to that line. Then do:

M-x c-show-syntactic-information

(or C-c C-s). This will give you e.g.:

Syntactic analysis: ((substatement-open 16))

Another option is to do M-x c-set-offset (or C-c C-o), which will give you the following prompt:

Syntactic symbol to change: |substatement-open

Here the | marks the position of the cursor, with the relevant symbol auto-filled for you.

Thanks to @nispio for the info!

Scott Weldon
  • 2,695
  • 1
  • 17
  • 31
  • 3
    To find out which offset you need to modify (e.g. `substatement-open`) you can use the command `c-show-syntactic-information` (bound to `C-c C-s` in c-mode) to find out which offsets are in effect, or `c-set-offset` (bound to `C-c C-o`) to change the offset interactively. – nispio May 31 '16 at 23:44
  • @nispio Thanks for the info! After experimenting with those two commands, I've edited some additional information into my answer. – Scott Weldon Jun 01 '16 at 05:22
  • 1
    Thanks for the extremely comprehensive and interesting answer Scott. I tried your suggestions. I was able to achieve the desired behaviour using (setq c-default-style "bsd") but when I tried (add-to-list 'c-offsets-alist '(substatement-open . 0)), this didn't seem to work. – Q'' Jun 01 '16 at 09:55
  • 1
    In order to automate the majority of this `c-set-offset`-work, you could also use something like this: http://emacs.stackexchange.com/questions/20515/setup-c-mode-indentation-braces-and-tabs/20561#20561 – Xaldew Jun 01 '16 at 14:16
  • @user12230 Hmm, that's strange. What is the contents of your `c-offsets-alist` after running that command? – Scott Weldon Jun 01 '16 at 14:57