【问题标题】:How to automatically indent in VSCode in a switch-case statement?如何在 switch-case 语句中自动缩进 VSCode?
【发布时间】:2020-06-28 20:20:01
【问题描述】:

令人沮丧的是,vscode 会自动执行很多操作,但是当使用 switch-case 语句时,它不会在冒号后自动缩进。 如果我在不干扰的情况下打字,这就是我得到的结果

int x = 32;
switch (x){
    case 33:
    break;
    case 32:
    break;
    default:
}

这就是我希望看到的

int x = 32;
switch (x){
    case 33:
        break;
    case 32:
        break;
    default:
}

【问题讨论】:

  • 如果Visual Studio没有按照你输入的方式缩进上面的代码,那么这是VS的默认缩进。
  • 我个人将case 标签与switch 和右大括号对齐。你知道的课程的马。

标签: c++ c visual-studio-code


【解决方案1】:

用于自定义格式规则的 Clang 格式

对于任何 C++ 格式化需求,我建议使用 Clang Format,它可以无缝集成到 VS Code 中。

在您的示例中,您可以使用IndentCaseLabels style option

IndentCaseLabels (bool)

从 switch 语句开始缩进 case 标签。

false 时,使用与 switch 语句相同的缩进级别。 Switch 语句体总是缩进一级 比案例标签(案例标签后面的第一个块除外, 它本身会缩进代码 - 除非启用 IndentCaseBlocks)。

false:                                 true:
switch (fool) {                vs.     switch (fool) {
case 1:                                  case 1:
  bar();                                   bar();
  break;                                   break;
default:                                 default:
  plop();                                  plop();
}                                      }

应用于您的示例:

//  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:
}

将 Clang 格式集成到 VS 代码中

引用Edit C++ in Visual Studio Code from the VS Code documentation [强调我的]:

[...]

代码格式

Visual Studio Code 的 C/C++ 扩展支持源代码 使用clang-format 进行格式化,该clang-format 包含在扩展程序中

您可以使用格式化文档 (Ctrl+Shift+I) 或 仅使用格式选择 (Ctrl+K Ctrl+F) 的当前选择 右键单击上下文菜单。 您还可以配置自动格式化 以下设置:

  • editor.formatOnSave - 在保存文件时进行格式化
  • editor.formatOnType - 在您键入时进行格式化(在 ; 字符上触发)。

默认情况下,clang 格式样式设置为“文件”,这意味着它会在您的工作区中查找.clang-format 文件。如果找到.clang-format 文件,则会根据文件中指定的设置应用格式设置。 如果在您的工作区中找不到.clang-format 文件,则会根据C_Cpp.clang_format_fallbackStyle 设置中指定的默认样式应用格式设置。目前,默认格式样式是“Visual Studio”,它是 Visual Studio 中默认代码格式化程序的近似值。

[...]

【讨论】:

  • 这是一个很好的起点,但我需要有关如何集成它的具体说明。没有任何消息来源对此给出任何明确的建议。据我了解,我需要安装marketplace.visualstudio.com/items?itemName=xaver.clang-format,然后在工作区的根目录中创建一个名为.clang-format 的文件,并在其中添加IndentCaseLabels: true,但这不起作用。
  • @Managor 在尝试自定义您的 .clang-format 文件之前,请确保甚至调用了 clang-format(例如在保存时)。有关详细信息,另请参阅Clang Format's documentation。我自己在使用 Emacs,但恕我直言,如何集成它的说明(如上所示)似乎很清楚(鉴于您还阅读了有关 Clang 格式本身的一些内容),而且我知道我自己使用过它们(一些几个月前)帮助同事使用 VS Code 设置 Clang 格式。
  • 啊,editor.formatOnType 需要自己在 vscode 设置中设置。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-09-24
  • 1970-01-01
  • 1970-01-01
  • 2014-08-05
  • 2019-04-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多