Is there any way to make Visual Studio stop indenting namespaces? - c++

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.

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.

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!)

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.

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.

You could also forward declare your types (or whatever) inside the namespace then implement outside like this:
namespace test {
class MyClass;
}
class test::MyClass {
//...
};

Visual Studio 2017+
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.

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();
.....
}}}

Related

Why storage fault in regex destructor?

I am getting a storage fault when my code destructs a regex and I am mystified as to the reason. I suspect I am missing something stupid about regex.
A little background: I am a reasonably experienced C++ developer but this is my first adventure with the regex class. My environment is a little unusual: I edit and alpha test in MS Visual C++ and then take the code to another environment. The other environment is fully Posix-compliant and just happens to be an IBM mainframe. The code works fine on Windows but fails every time on the mainframe. The problem is not something fundamental to my mixed environment: I have been working in this pair of environments in this way for years with complete C++ success.
I define the regex in the class declaration:
#include <regex>
...
class FilterEvalEGNX : public FilterEval
{
...
std::tr1::basic_regex<char> regexObject;
// I also tried plain regex with no difference
Subsequently in the class implementation I assign a pattern to the regex. The code should be more complex than this but I simplified it down to assigning a static string to eliminate any possible side effects from the way the string would be handled in real life.
std::tr1::regex::flag_type flags = std::tr1::regex::extended;
// I have also tried ECMA and it made no difference
try
{
static const char pat[] = "(ISPPROF|SPFTEMP)";
regexObject.assign(pat, flags);
}
catch (std::tr1::regex_error &e)
{
// handle regex error
}
That works without error. Of course, there is subsequent pattern matching code but it is not part of the problem: if I destruct the class immediately after the above code I get the storage fault.
I don't do anything to the regex in my class destructor. The rest of the class has been working for years; I am adding the regex now. I think some "external" overlay of the regex is unlikely.
Here is the traceback of the calls leading up to the fault:
std::tr1::_EBCDIC::_Destroy(std::tr1::_EBCDIC::_Node_base*)
+00000066 40 CRTE128N Exception
std::tr1::_EBCDIC::basic_regex<char,std::tr1::_EBCDIC::regex
+000000C8 2022 FilterEvalEGNX.C Call
std::tr1::_EBCDIC::basic_regex<char,std::tr1::_EBCDIC::regex
+0000007C 1913 FilterEvalEGNX.C Call
FilterEvalEGNX::~FilterEvalEGNX()
The code in the vicinity of line 1913 of regex is
~basic_regex()
{ // destroy the object
_Tidy();
}
The code in the vicinity of line 2022 of regex is
void _Tidy()
{ // free all storage
if (_Rep && --_Rep->_Refs == 0)
_Destroy(_Rep);
_Rep = 0;
}
_Destroy() appears to be implemented in the run-time and I do not think I have the source.
Any ideas? Thanks,
Believe it or not, it appears to be a bug in the C++ runtime. I tweaked my simple example and now I can duplicate the problem in a 15-line main(). I am going to run this by some peers and then report it to IBM. They actually fix this stuff! They don't just respond with "yes, you have found an issue."

Can I programmatically collapse/expand all preprocessor blocks of a certain name in Visual Studio 2012?

My current project has a lot of debug preprocessor blocks scattered throughout the code. These are intentionally named differently to the system _DEBUG and NDEBUG macros, so I have a lot of this:
// Some code here
#ifdef PROJNAME_DEBUG
//unit tests, assumption testing, etc.
#endif
// code continues
These blocks sometimes get rather large, and their presence can sometimes inhibit code readability. In Visual Studio 2012 I can easily collapse these, but it would be nice to automatically have all of them collapsed, allowing me to expand them if I want to see what's in there. However, as I also have a bunch of header guards I don't want to collapse all preprocessor blocks, only the #ifdef PROJNAME_DEBUG ones.
Can I do this?
This is the most easiest scenario you can achive it, I think.
You should create an Add-In first in C#. (in VS 2013 they become deprecated :( )
In the OnConnection method you should add your command:
public void OnConnection( object application, ext_ConnectMode connectMode, object addInInst, ref Array custom )
{
_applicationObject = (DTE2)application;
if (connectMode == ext_ConnectMode.ext_cm_AfterStartup || connectMode == ext_ConnectMode.ext_cm_Startup)
{
Commands2 commands = (Commands2)_applicationObject.Commands;
try
{
//Add a command to the Commands collection:
Command command = commands.AddNamedCommand2(_addInInstance, "MyAddinMenuBar", "MyAddinMenuBar", "Executes the command for MyAddinMenuBar", true, 59, ref contextGUIDS, (int)vsCommandStatus.vsCommandStatusSupported + (int)vsCommandStatus.vsCommandStatusEnabled, (int)vsCommandStyle.vsCommandStylePictAndText, vsCommandControlType.vsCommandControlTypeButton);
}
catch (System.ArgumentException)
{
//If we are here, bla, bla... (Auto generated)
}
}
}
Note: you can find how parameters are act at the reference of AddNamedCommand2
The template created version would be also fine, but naturaly it worth to name your command properly.
After that you need to add your logic to Exec method:
public void Exec( string commandName, vsCommandExecOption executeOption, ref object varIn, ref object varOut, ref bool handled )
{
handled = false;
if (executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault)
{
if (commandName == "MyAddinMenuBar.Connect.MyAddinMenuBar")
{
List<string> args = (varIn as string).Split(' ').ToList();
TextSelection ts;
ts = (TextSelection)_applicationObject.ActiveDocument.Selection;
EditPoint ep = (ts.ActivePoint).CreateEditPoint();
ep.StartOfDocument();
do
{
string actualLine = ep.GetLines(ep.Line, ep.Line + 1);
if (args.TrueForAll(filter => actualLine.Contains(filter)))
{
_applicationObject.ExecuteCommand("Edit.GoTo", ep.Line.ToString());
_applicationObject.ExecuteCommand("Edit.ToggleOutliningExpansion");
}
ep.LineDown();
} while (!ep.AtEndOfDocument);
handled = true;
return;
}
}
}
Note: Name you given to the command is checked in exec.
Than you can build.
Deployment of Add-In can happen through an [ProjectName].AddIn file in ..\Documents\Visaul Studio 20[XY]\AddIns\. (Created by the template, you should copy if you move the Add-In elsewhere)
You should place your Add-In assembly where the Assembly element of the mentioned file you set to point. To change version you should modify the text in Version element.
After you deployed and started Studio, you should activate the Add-In in the manager in Toolsmenu.
You need to expand all collapsable section in your code file (CTRL+M+L with C# IDE settigs).
This is required because I found only a way to invert the state of collapsion. If you find better command, you can change it.
Next you should activate Command Window to use the the created command.
Now only you need to type your commands name, like this:
MyAddinMenuBar.Connect.MyAddinMenuBar #ifdef PROJNAME_DEBUG
Hopefully magic will happen.
This solution is independent of language of code you edit so pretty multifunctional.

How do I write a very simple Visual Studio debugger visualizer?

I'm trying to write an 'autoexp.dat'-based visualizer for a string type. I've scaled-back my ambitions to attempting to write a visualizer for a really simple test type that contains a null-terminated string field:
namespace thizz { namespace izz {
class MyType {
const char* _ptr;
public:
MyType(const char* ptr) : _ptr(ptr) {}
};
}
}
This is my stab at a visualiser, but it has no effect on how Visual Studio (2010) displays an instance of this type:
thizz::izz::MyType
{
preview ([$e._ptr,s])
}
(That's going at the top of the [Visualizers] section in C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\Packages\Debugger\autoexp.dat).
Watching an instance of this type:
thizz::izz::MyType t("testing testing");
Just displays
t | {_ptr=0x0f56a6fc "testing testing" } | thizz::izz::MyType
in the Watch window.
To get an even more versatile viewer try changing to use this:
thizz::izz::MyType {
preview ( #( [$e._ptr,s] ) )
stringview ( #( [$e._ptr,sb] ) )
}
this will also give the magnifying glass icon which will open a larger text view window in the case that you have a longer string. It'll also give you the option of rendering as HTML or XML.
Note that as well as the format of the file being sensitive to whitespace, I've also found that you can't use a colon in the string otherwise it generates parse errors.
The debugger visualisers are incredibly powerful, though the syntax can be quite bewildering. As general advice I would suggest creating some entries first in the [AutoExpand] section to summarise the data types that you are most interested in, and then if you have custom containers then copy and adapt the examples for vector, list, etc, which will give you the largest return for the investment in your time.
I can't give a categorical reason why my original 'code' in autoexp.dat was not working, but I found that the same code worked when all the whitespace was removed.
I then tried re-adding whitespace and found that keeping the initial open brace on the first line was necessary to keep the definition working.

Visual Studio Breakpoint Macro to modify a value?

I'm debugging an application (C++), and I've found a point in the code where I want to change a value (via the debugger). So right now, I've got a breakpoint set, whereupon I do:
Debugger reaches breakpoint
I modify the variable I want to change
I hit F5 to continue running
lather, rinse, repeat
It's hitting this breakpoint a lot, so I would like to automate this. I would like to set the Breakpoint to run a macro, and continue execution.
However, I have no experience writing VisualStudio macros, so I don't know the commands for modifying a variable of the executing program. I've looked around, but haven't found anything helpful online so far.
I found how to do this with a macro. Initially, I tried using Ctrl-Shift-R to record a macro of keystrokes, but it stopped recording when I did Ctrl-Alt-Q. But I was able to edit the macro to get it to work. So here's what I did, in case anyone else wants to do something similar.
Tools -> Macros -> Macro Explorer
Right Click -> New macro
Public Module RecordingModule
Sub setvalue()
DTE.Debugger.ExecuteStatement("variable_name=0")
End Sub
End Module
This macro will execute the assignment statement, setting my variable (in this case, making it a NULL pointer).
Right Click on a BreakPoint -> When Hit...
Check "Run a macro"
Select Macros.MyMacros.RecordingModule.setvalue
Check "Continue execution"
Click OK
Then, I was able to run my program, automatically adjusting a pointer to NULL as it went. This was very useful for testing, and did not require recompiling.
Looking for similar today and found that you can also use the 'Print a message:' option instead of a macro. Values from code can be printed by placing them inside {}. The key is that VS will also evaluate the content as an expression - so {variable_name=0} should achieve the same as the macro example.
If you are think of a macro in the same way as Microsoft excel, then you're out of luck. It doesn't quite work that way.
In C++, a macro refers to a small inline function created with #define. It is a preprocessor, so a macro is like using a replace on all its references with its body.
For example:
#define add(a,b) ((a)+(b))
int main() {
int a=3, b=4, c=5, d=6, e, f;
d = add(a,b);
e = add(c,d);
}
Would like to the c++ compiler as:
int main() {
int a=3, b=4, c=5, ...;
d = ((a)+(b));
e = ((c)+(d));
}
Now, back to your question. If the variable is within scope at this breakpoint, just set it from within your code:
myVar = myValue;
If it is not, but it is guaranteed to exist, you may need a little hack. Say that this variable is an int, make a global int pointer. If this variable is static, make sure to set it to its address, and back to NULL inside it's scope. If it is dynamic, you may need some extra work. Here is an example:
int* globalIntPointer;
void func() {
*globalIntPointer = 3;
//...
}
int main() {
int a = 5;
globalIntPointer = &a;
func();
//...
globalIntPointer = NULL; // for safety sake
return 0;
}
You can execute a VS macro when a breakpoint is hit (open the breakpoints window, right click on the breakpoint in question, and select "When Hit..." off the popup menu). I'm less certain about writing a macro that modifies a variable of the program under debug though -- I've never done that, and a quick try with attempting to record a macro to do it doesn't seem to work (all it records is activating the right window, not changing the value).
Select "Condition..." and write an assignment for the variable in question in the "Condition:" textbox. This will naturally resolve to "true" with it not being an actual conditional test. Therefore, the breakpoint is never hit, and your variable has been set accordingly.

Indention in C++ Builder

In C++ Builder, how can I make sure that even correctly nested code like:
void func () {
...
..
)
C++ Builder correctly nested only doing so:
void func ()
{
...
...
}
This is very stressful, because I always have to correct by hand. So how can I make which indents code as well in the first instance?
The code formatter in C++Builder 2010 should do this automatically for you. (It is invoked with CTRL-D) You’ll have to set the preferences to how you like your code to be formatted, but this is a real time saver new with this most recent release.
Select the block, then press CTRL+SHIFT+I. This is in Borland C++ 6.
I am using this free tools:
http://www.cnpack.org/index.php?lang=en
using tabs to shift marked blocks to left or right.
I don't have a copy of this to run, but the documentation mentions "Indentation, Spaces, and Line breaks" as some of the options under the formatter tab of the "Tools > Options" dialog.
What you're looking for is probably under the "Line Breaks" section.