How to automatically indent in VSCode in a switch-case statement?
Answer a question
It's a bit frustrating that there are a lot of things that vscode does automatically but when using a switch-case statement it doesn't automatically indent after the colon. This is what I get if I were to type without interfering
int x = 32;
switch (x){
case 33:
break;
case 32:
break;
default:
}
And this is what I would like the to see
int x = 32;
switch (x){
case 33:
break;
case 32:
break;
default:
}
Answers
Clang Format for customizable formatting rules
For any C++ formatting needs I would recommend using Clang Format, which can be seamlessly integrated into VS Code.
In you example you may use the IndentCaseLabels style option:
IndentCaseLabels (bool)
Indent case labels one level from the switch statement.
When
false, use the same indentation level as for the switch statement. Switch statement body is always indented one level more than case labels (except the first block following the case label, which itself indents the code - unless IndentCaseBlocks is enabled).false: true: switch (fool) { vs. switch (fool) { case 1: case 1: bar(); bar(); break; break; default: default: plop(); plop(); } }
Applied to your example:
// IndentCaseLabels: true
int x = 32;
switch (x) {
case 33:
void();
break;
case 32:
break;
default:
}
// IndentCaseLabels: false
int x = 32;
switch (x) {
case 33:
void();
break;
case 32:
break;
default:
}
Integration of Clang Format into VS Code
Citing Edit C++ in Visual Studio Code from the VS Code documentation [emphasis mine]:
[...]
Code formatting
The C/C++ extension for Visual Studio Code supports source code formatting using
clang-formatwhich is included with the extension.You can format an entire file with Format Document (Ctrl+Shift+I) or just the current selection with Format Selection (Ctrl+K Ctrl+F) in right-click context menu. You can also configure auto-formatting with the following settings:
editor.formatOnSave- to format when you save your file.editor.formatOnType- to format as you type (triggered on the;character).By default, the clang-format style is set to "file" which means it looks for a
.clang-formatfile inside your workspace. If the.clang-formatfile is found, formatting is applied according to the settings specified in the file. If no.clang-formatfile is found in your workspace, formatting is applied based on a default style specified in theC_Cpp.clang_format_fallbackStylesetting instead. Currently, the default formatting style is "Visual Studio" which is an approximation of the default code formatter in Visual Studio.[...]
更多推荐
所有评论(0)