Visual Studio keeps trying to indent the code inside namespaces.
For example:
namespace Foo
{
void Bar();
void Bar()
{
}
}
Now, if I un-indent it manually then it stays that way. But unfortunately if I add something right before void Bar();
- such as a comment - VS will keep trying to indent it.
This is so annoying that basically because of this only reason I almost never use namespaces in C++. I can't understand why it tries to indent them (what's the point in indenting 1 or even 5 tabs the whole file?), or how to make it stop.
Is there a way to stop this behavior? A config option, an add-in, a registry setting, hell even a hack that modifies devenv.exe directly.
You could also forward declare your types (or whatever) inside the namespace then implement outside like this:
I understand the problem when there are nested namespaces. I used to pack all the
namespace
s in a single line to avoid the multiple indentation. It will leave one level, but that's not as bad as many levels. It's been so long since I have used VS that I hardly remember those days.As KindDragon points out, Visual Studio 2013 Update 2 has an option to stop indenting.
You can uncheck TOOLS -> Options -> Text Editor -> C/C++ -> Formatting -> Indentation -> Indent namespace contents.
Probably not what you wanted to hear, but a lot of people work around this by using macros:
Sounds dumb, but you'd be surprised how many system headers use this. (glibc's stl implentation, for instance, has
_GLIBCXX_BEGIN_NAMESPACE()
for this.)I actually prefer this way, because I always tend to cringe when I see un-indented lines following a
{
. That's just me though.Here is a macro that could help you. It will remove indentation if it detects that you are currently creating a
namespace
. It is not perfect but seems to work so far.Since it is running all the time, you need to make sure you are installing the macro inside in your
EnvironmentEvents
project item inside MyMacros. You can only access this module in the Macro Explorer (Tools->Macros->Macro Explorer).One note, it does not currently support "packed" namespaces such as
EDIT
To support "packed" namespaces such as the example above and/or support comments after the namespace, such as
namespace A { /* Example */
, you can try to use the following line instead:I haven't had the chance to test it a lot yet, but it seems to be working.
Visual Studio 2017
Namespace Indention Menu VS2017
You can get to this "Indent namespace contents" setting under Tools->Options then Text Editor->C/C++->Formatting->Indention. It's deep in the menus but extremely helpful once found.