Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indent preprocessor directives as C code in emacs

Emacs, by default, does not indent pre-processor code. I know it has historical roots that are obsolete by now.

However, having a code with a lot of #ifdef unindented is hard to read.

So I would like to make emacs automatic indentation give me something like that:

void myfunc() {
    int foo;

    #ifdef BAR
    printf(foo);
    #endif

    return foo;
}

Instead of what I get now :

void myfunc() {
    int foo;

#ifdef BAR
    printf(foo);
#endif

    return foo;
}

Any leads on that issue you emacs hackers :) ?

like image 413
Jocelyn delalande Avatar asked Jan 12 '11 13:01

Jocelyn delalande


People also ask

How do I indent multiple lines in Emacs?

26.3. 2 Indenting Several Lines One way to do this is to use the mark; when the mark is active and the region is non-empty, TAB indents every line in the region. Alternatively, the command C-M-\ ( indent-region ) indents every line in the region, whether or not the mark is active (see Indentation Commands).


1 Answers

You can simply tell Emacs to add an offset to the pre-processor lines.

  • Put the cursor (point) in a pre-processor line
  • then press C-c C-o (control-c control-o)
  • the minibuffer should say Syntactic symbol to change:,
  • type cpp-macro, press Enter
  • Enter the new offset (number - usually 0)

Then a TAB on each pre-processor line should indent it correctly. (or M-xindent-region ...).

To have the change set permanently, you can for instance add the required lines in your .emacs file.
An easy way to copy a previously entered command is c-x ESC ESC and use the arrow keys to find the (c-set-offset ...) Elisp command.

That should be

(c-set-offset (quote cpp-macro) 0 nil)
like image 61
Déjà vu Avatar answered Sep 30 '22 08:09

Déjà vu