22

I often find myself in situations where I would like to indent preprocessor directives like the rest of the code (e.g. #if indented like if). It seems legal, it's common sense that it's sometimes a good thing, but Visual won't make it easy.

Is there a way to prevent the Visual C++ 2010 editor from sticking the code to the left each time I innocently press #? And to not break preprocessor directives indentation with auto-indent (CTRL+K, CTRL+F)? Or even better, to handle preprocessor directives like everything else?

Community
  • 1
  • 1
Laurent Couvidou
  • 32,354
  • 3
  • 30
  • 46

4 Answers4

14

My approach is to keep the # in the first column and indent the subsequent word, as in:

#ifdef FIRST
#  include "first.h"
#else
#  include "second.h"
#endif
Nicola Musatti
  • 17,834
  • 2
  • 46
  • 55
  • 3
    Except you won't be able to select multiple lines and (Shift+)Tab them. – Yakov Galka Sep 04 '12 at 16:31
  • 1
    +1 for good preprocessor style. Boost uses this style and it's much clearer which lines are preprocessor directives while maintaining branching indentation – Pyrce Sep 04 '12 at 16:43
  • +1 as it's indeed a good, often seen, workaround. But I still feel like proper indentation support would make me happier. So I'll wait and see if I get other answers. – Laurent Couvidou Sep 04 '12 at 17:39
  • Looks like that's the best solution until Microsoft decides to add the option. – Laurent Couvidou Sep 27 '12 at 12:14
12

At some point visualstudio (checked in vs2015) acquired options > text editor > c/c++ > formatting > indentation > position of preprocessor directives. Choose 'leave indented'. The sample doesn't look exactly like what you want, but it works, just try it.

zeromus
  • 1,648
  • 13
  • 14
10

In the Visual Studio 2010 options (Tools->Options)

Go to Text Editor -> C/C++ -> Tabs

Under indenting select Block instead of smart.

This will prevent the # key from forcing you to the start of the line, however if you use Ctrl+K Ctrl+F it will still apply smart formatting and remove the tabs.

Edit: This will also disable automatic indenting/unindenting in other places. Beware.

TheSteve
  • 1,138
  • 6
  • 12
3

Workaround: When you first type the # and Visual Studio removes your indentation, press ctrl+z to undo the auto formatting.

DBN
  • 374
  • 4
  • 10