defaulting to using braces enclosing each case in switch statements in Visual Studio Code - c++

In C++ or C#, it's generally a good practice to enclose each case within curly braces (e.g., see C# switch statement with curly braces for each case/default block within the switch statement?).
But Visual Studio Code defaults to creating a template that leaves them out.
What UI preferences can I change so that they are included by default?
Edit: I am not interested in a debate about whether adding curly braces should always be done or not, but rather knowing how to change VS Code's UI for this context.

You should add a snippet by yourself.
Select Command palette (F1) -> Preferences: Configure User Snippets -> C++ and add the following code.
"switch2": {
"prefix": "switch2",
"body": "switch (${1:expression}) {\n\tcase ${2:/* constant-expression */}: {\n\t\t${3:/* code */}\n\t\tbreak;\n\t}\n\tdefault: {\n\t\tbreak;\n\t}\n}"
}

Ended up slightly modifying #umitu's answer. Posting it here just in case someone else finds it useful as well:
"switch2": {
"prefix": "switch2",
"body": "switch (${1:expression}) {\ncase ${2:/* constant-expression */}: {\n\t${3:/* code */}\n\t} break;\ncase ${4:/* constant-expression */}: {\n\t${5:/* code */}\n\t} break;\ndefault: {\n\t${6:/* code */}\n\t} break;\n}"
}
And now the default snippet looks like the following:

Related

How to make VSCode indent an if statement without brackets?

I'd like for VSCode to indent automatically indent when I create a newline in the following case:
if(statement)
func();
The default functionality does the following when hitting newline:
if(statement)
func();
This is a longstanding issue in VSCode: https://github.com/microsoft/vscode/issues/43244
I'd appreciate any kind of hack/extension that can accomplish this behavior. There are other instances of indentation getting mangled in the github issue link, but I only really care about this simple case.
Figured out how to do this without installing an extension. There may be a better way that can be done in settings.json but I couldn't find it. You can modify a languages configuration directly from the source, which for me was C:\Program Files\Microsoft VS Code\resources\app\extensions\cpp\language-configuration.json. There is a guide for these files settings. I added the following to my c++ language configuration:
"onEnterRules": [
{
"beforeText": "^\\s*(?:if|while)\\(.*\\)\\s*$",
"action": {
"indent": "indent"
}
},
{
"beforeText": "(?=)",
"previousLineText": "^\\s*(?:if|while)\\(.*\\)\\s*$",
"action": {
"indent": "outdent"
}
}
]
This works, but unfortunately the official c++ vscode extension C/C++ for Visual Studio Code breaks it for some reason.
Below was my initial method of doing this, which breaks too many things to be useful.
"indentationRules": {
"increaseIndentPattern": "^\\s*if\\(.*\\)\\s*$",
"decreaseIndentPattern": "(?!)"
}
The field decreaseIndentPattern must be set (here the regex will never capture anything), otherwise it ignores the indentationRules field (I guess they never tested whether just one would be set?) Note that these edits need to be done with administrative privleges, and I found VSCode pretty convenient for making them. Also these changes do not take effect until VSCode is closed.
So as it turns out I've run into the same issues mentioned in this PR: https://github.com/microsoft/vscode/pull/115454. This fix breaks too much other vscode indentation behavior, such as deindenting after the first properly indented line in if statements.

Visual Studio 2017: Ruleset won't execute

I want to define a custom set of rules to be checked at compile time. But it seems not to work.
Example:
I choose one rule directly and I'll get the expected warning.
But when I instead create a custom ruleset containing the exact same rule then I won't get the expected warning.
What could be wrong?
Edit:
void f(std::string& i) {
std::string s = i;
cout << s;
}
int main()
{
std::string s ("abc");
f(s);
}
This gives me the expected warning Warnung C26460 The reference argument 'i' for function 'f' can be marked as const (con.3). in the first case.
Even if I create a custom ruleset including all available rules, I won't get any warnings.
Here you see me selecting the custom ruleset:
Edit: The ruleset action must change one time to enable it.
When I create a new ruleset containing only the const-checks then I will get a .ruleset that does not work and look like this:
In the ruleset editor it looks like this:
When I then change its action from Warning to Error:
Then the .ruleset gets additional lines for each test case:
When I change the action back to warning it looks like this:
Now it is working as expected.
I've been able to reproduce your error with Visual Studio 2017. I don't know exactly what I changed (or if I changed anything at all), but I am able to see the code analysis warning you expect with a custom rule set.
Things I would try:
Double check the Error List window is visible and not hiding somewhere.
Open the rule set file, change the Action to Error and then back to Warning and save it. I wouldn't expect this to be the problem but it's one of the things I did and after which I started seeing the Error List window.

How to stop resharper removing empty switch default case

Assume I've got the following code:
public static void PrintFoo(int i)
{
switch (i)
{
case 0:
Console.WriteLine("bar!");
break;
case 1:
Console.WriteLine("baz!");
break;
default:
// do nothing
break;
}
}
I want the "default" switch case there with the comment as it shows I'm deliberately not processing any values other than 0 and 1. If I leave out the default case, it's not clear if I meant to do nothing, or just forgot. Indeed, if I delete the default case, I get errors from "IDE0010 Populate switch" showing up in the errors window.
By default Resharper considers this an error, so I have turned off that inspection (Resharper options -> Inspection Severity -> C# -> Redundancies in Code -> Redundant empty switch section).
The problem I have is that when I run code cleanup, it deletes the default case, including the comment. In general I still want code cleanup to fix all the other redundancies in the file, so turning off "Remove code redundancies" in the code cleanup profile isn't an option. Is there a way to get it not to remove the default case in the switch statement?
EDIT: It seems that the default case is only removed if, in the code cleanup window, I select to "Remove code redundancies" and any child of "Code style". If I deselect all the code style items, the default case is not removed, or if I deselect the code redundancies it is not deleted either. Looks like I might have to raise this as a bug with Resharper.
So I reported this to jetbrains who looked into the problem. It turned out that the setting for "Redundant empty switch section" was stored in the "Team shared" settings layer and the code cleanup was pulling the setting from the wrong layer.
The solution was to go to Resharper -> Manage options -> double click on "this computer" and change the setting there.
Thanks to Alexander Kurakin for solving the issue.

How to type a close brace `}` when clion doesn't understand your code and reformats it wrong?

I have some code that compiles fine but I type the closing brace } for the else, it moves all the code from the else { all the way to the left and throws away all indentation.
if (some_condition) {
some_real_code();
} else {
obj.some(stuff);
obj(some,other(stuff));
and when I type the final } I get:
if (some_condition) {
some_real_code();
} else {
obj.
some(stuff);
obj(
some,
other(stuff));
}
The only way I've found to deal with this when it happens is to select a brace in my code, copy it to my clipboard, then do a right-click "paste simple" in clion, which doesn't do any reformatting.
Is there any better way? For example, an a phone, if it autocorrects you and you delete the autocorrected word and retype the same word again, it won't re-autocorrect you because it figures you actually knew what you meant when you do it the second time.
Thank you.
edit: I'm not saying clion is bad or wrong for not understanding my code because in my real code I use language features that it doesn't claim to have support for. I'm just looking for how to work around it's rather aggressive lack of support.
Please, switch off "Reformat block on typing '}'":
Seems that you would be interested in for-IDE-stub implementation in guarded block (Per-ide variable: in CLion it’s CLION_IDE , in AppCode – APPCODE_IDE , in Android Studio – STUDIO_IDE)
I would not turn autoformatting off, because in the majority of cases it is useful. But when this undesired autoformatting happens, I just do the following workaround:
Cancel the autoformatting (Ctrl+Z). The curly bracket is cancelled too.
Instead of typing bare }, I type it commented: //}.
Then just uncomment this line (Ctrl+/ or remove the slashes).
Profit! :)

Visual Studio Auto Format Curly Brace on Next Line

I am so used to code like this:
if (...)
{
//somecode
}
that I simply have to change the following to the above:
if (...){
//somecode
}
I get a lot of code from other people that I have to go through and sometimes this is what I get. Is it possible to auto-format that in Visual Studio 2008 for C++?
Now some may think I should get used to it. Believe me, I am trying, but it is very distracting and I hope there is a simple solution.
VS2008 has a simple formatter (Edit menu, Advanced, Format Selection), but it doesn't move braces.
Check out astyle and its --style=ansi flag.