70

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.

5
  • You could disable auto-indenting entirely. Or set it to indent by a smaller amount (say, 2 spaces instead of 1 tab)
    – jalf
    Sep 16, 2010 at 16:48
  • 3
    This (non-configurable indentation settings) is one of many reasons I stopped editing files in Visual Studio years ago... :) Sep 16, 2010 at 17:34
  • 2
    I will award the bounty to whoever finds a solution that has no side effects, or as little side effects as possible. For now the best answer, IMO, is bacar's; if no better answers are provided I will award the answer to him. Sep 18, 2010 at 18:55
  • That's why I'm using Eclipse CDT ;) It is possible to use VS compiler within Eclipse so it may be worth a try.
    – mip
    Sep 23, 2010 at 21:56
  • 2

7 Answers 7

57

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.

7
  • 5
    It seems to have become broken again... At least in Update 4. I hope they fix it.
    – AzP
    Jan 29, 2015 at 10:30
  • 2
    It's indeed broken. Though you can use clang format and simply work around the mess. Feb 28, 2015 at 20:38
  • 1
    I just tried VS2013 Update 5 CTP; it appears to be working again. Hopefully it stays that way for the official Update 5 release.
    – jdknight
    Mar 18, 2015 at 4:50
  • 2
    This is the best answer. Works as I expected in VS 2015. Apr 26, 2017 at 14:58
  • The question is for C++, but does anyone know if there is an option for C# in visual-studio-2019? I looked but cannot find an Indent namespace contents checkbox in the Indentation options.
    – Loathing
    Jan 5, 2021 at 4:51
31

Just don't insert anything before the first line of code. You could try the following approach to insert a null line of code (it seems to work in VS2005):

namespace foo
{; // !<---
void Test();
}

This seems to suppress the indentation, but compilers may issue warnings and code reviewers/maintainers may be surprised! (And quite rightly, in the usual case!)

3
  • 11
    I like this too. Seems like even a macro that expands to nothing is enough to suppress the indentation. So you can #define SUPPRESS_INDENTATION and then open the namespace like namespace foo { SUPPRESS_INDENTATION :)
    – Paul Groke
    Sep 22, 2010 at 23:06
  • Nice - the intent is somewhat clearer and the compiler is hopefully less likely to raise warnings :)
    – bacar
    Sep 23, 2010 at 17:41
  • While this has been my favourite solution, I wanted to mention that this trick does not work in VS2013. There is a user configuration setting in VS2013 which prevents this from happening (when it works; see other answer).
    – jdknight
    Mar 18, 2015 at 4:55
14

Probably not what you wanted to hear, but a lot of people work around this by using macros:

#define BEGIN_NAMESPACE(x) namespace x {
#define END_NAMESPACE }

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.

2
  • 9
    I think this is more for compatibility with old compilers than because of Visual Studio =) Sep 16, 2010 at 16:16
  • 6
    @andreas I think that way you can change the namespace of the whole lib easily without editing all the source files Sep 16, 2010 at 16:29
13
+500

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.

Public Sub aftekeypress(ByVal key As String, ByVal sel As TextSelection, ByVal completion As Boolean) _
        Handles TextDocumentKeyPressEvents.AfterKeyPress
    If (Not completion And key = vbCr) Then
        'Only perform this if we are using smart indent
        If DTE.Properties("TextEditor", "C/C++").Item("IndentStyle").Value = 2 Then
            Dim textDocument As TextDocument = DTE.ActiveDocument.Object("TextDocument")
            Dim startPoint As EditPoint = sel.ActivePoint.CreateEditPoint()
            Dim matchPoint As EditPoint = sel.ActivePoint.CreateEditPoint()
            Dim findOptions As Integer = vsFindOptions.vsFindOptionsMatchCase + vsFindOptions.vsFindOptionsMatchWholeWord + vsFindOptions.vsFindOptionsBackwards
            If startPoint.FindPattern("namespace", findOptions, matchPoint) Then
                Dim lines = matchPoint.GetLines(matchPoint.Line, sel.ActivePoint.Line)
                ' Make sure we are still in the namespace {} but nothing has been typed
                If System.Text.RegularExpressions.Regex.IsMatch(lines, "^[\s]*(namespace[\s\w]+)?[\s\{]+$") Then
                    sel.Unindent()
                End If
            End If
        End If
    End If
End Sub

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

namespace A { namespace B {
...
}
}

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:

 If System.Text.RegularExpressions.Regex.IsMatch(lines, "^[\s]*(namespace.+)?[\s\{]+$") Then

I haven't had the chance to test it a lot yet, but it seems to be working.

3
  • Thank you very much for your answer. There was an error that I now corrected, but besides that it works perfectly. Grats on the bounty. Sep 24, 2010 at 2:32
  • Works fine for typing but not for pasting or e.g. Visual Assist's "Create Implementation" functionality whereas bacar's solution does do the trick there. It is cleaner though.
    – Adversus
    Oct 3, 2012 at 12:35
  • 1
    The question might seems stupid, but I really cannot find an answer: where are we supposed to paste this macro ?
    – Aracthor
    Sep 15, 2015 at 13:25
9

You could also forward declare your types (or whatever) inside the namespace then implement outside like this:

namespace test {
    class MyClass;
}

class test::MyClass {
//...
};
0
8

Visual Studio 2017+

enter image description here 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.

2
  • 1
    please dont't leave just link only answers!
    – monamona
    Jan 23, 2018 at 14:34
  • 1
    You could include the screenshot. Anyway, this is the only correct answer for VS2017+. Dec 9, 2019 at 10:55
3

I understand the problem when there are nested namespaces. I used to pack all the namespaces 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.

namespace outer { namespace middle { namespace inner {
    void Test();
    .....
}}}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.