In some cases I deal with code that has heavily indented C preprocessor statements and want to setup Emacs to work with it without changing that indentation and follow the same indentation when having to add new one.

The style used in that code is something like that, in the global scope and also inside function scopes:

#ifdef something
  #ifdef something_else
    /* some code here */
    /* some other code here */

Essentially, I'd like Emac to indent the lines as they show above when I press the tab key on lines inside C preprocessor statements.

No need to debate on the C style. I'm aware of the C/C++ debates related to this.

My question is how to easily get Emacs to adapt to that style for both C and C++ major modes.

I tried setting c-cpp-indent-to-body-directives and using c-toggle-cpp-indent-to-body (see Emacs Indenting Directives) but that did not seem to help here.

  • How have you set c-cpp-indent-to-body-directives? Please provide your elisp code.
    – Claudio
    Mar 25, 2023 at 15:21
  • @Claudio I did not write any code for that. It's a customizable user-option. I used the customization buffer to add "ifdef" and "ifndef" to the list value of c-cpp-indent-to-body-directives. The default value was ("pragma") and is now ("pragma" 'ifdef" "ifndef"). I saved and tried in the buffer. I closed Emacs and restarted, looking at its value and tried again. While it held that value I executed c-toggle-cpp-indent-to-body with M-x c-toggle-cpp-indent-to-body and checked again.
    – PRouleau
    Mar 25, 2023 at 19:11
  • Hmmm ....if I understand you right the logic of your expectation is as follows: you expect that "ifdef" in the given code example should be interpreted as a start of a block and at the same time as a command. I smell here an unresolvable contradiction, and you?
    – Claudio
    Mar 25, 2023 at 19:39
  • No, I was just trying to see if that facility of "indent particular preprocessor directives (e.g. #pragma) as though they were statements" would work as if #ifdef was 'interpreted' as the beginning of a C statement. The description of that user option is "This variable is a list of names of CPP directives (not including the introducing ‘#’) which will be indented as though statements. Each element is a string, and must be a valid identifier." There's no concept of command here.
    – PRouleau
    Mar 25, 2023 at 20:04
  • OK ... I should have used the word 'statement' not 'command'. C-statement 'ifdef' won't result in starting of a C-code block, right? So how should be then known that the following code should be indented?
    – Claudio
    Mar 25, 2023 at 20:23


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.