c - 如何使用 clang 格式保持标签缩进?
问题描述
goto
Clang-format 删除标签上的缩进。使用// clang-format off
不是首选。如何配置 clang-format 以不更改配置文件中标签的缩进?
期望的输出
标签缩进以匹配函数中的代码。他们应该留在那个缩进中。
int new_foo(foo **bar) {
*bar = malloc(sizeof(foo));
if ( !bar ) {
goto failed;
}
goto done;
failed: {
return -1;
}
done:
return 1;
}
实际输出
这是 clang-format 实际产生的。这是不可取的,因为它会破坏缩进折叠。
int new_foo(foo **bar) {
*bar = malloc(sizeof(foo));
if ( !bar ) {
goto failed;
}
goto done;
failed: {
return -1;
}
done:
return 1;
}
更新
在配置中使用IndentGotoLabels: false
(or true
) 时,.clang-format
这是结果。注意done:
和failed:
标签向左移动。
int new_foo(foo **bar) {
*bar = malloc(sizeof(foo));
if (!bar) {
goto failed;
}
goto done;
failed : { return -1; }
done:
return 1;
}
的内容.clang-format
。
IndentGotoLabels: false
命令是cat test.cc | clang-format
并在存在的同一目录中运行.clang-format
。
解决方案
编辑:我最初的答案是错误的。
看起来无论如何IndentGotoLabels
设置 goto 标签都没有缩进与代码相同的级别。考虑以下代码片段:
int new_foo()
{
{
int *p = malloc(sizeof(int));
if (!p)
goto first_label;
int *q = malloc(sizeof(int));
if (!q)
goto second_label;
return 0;
first_label:
return 1;
}
second_label:
return 2;
}
使用以下配置:
---
Language: Cpp
IndentGotoLabels: false
TabWidth: 4
...
跑步clang-format
会给我们:
int new_foo() {
{
int *p = malloc(sizeof(int));
if (!p)
goto first_label;
int *q = malloc(sizeof(int));
if (!q)
goto second_label;
return 0;
first_label:
return 1;
}
second_label:
return 2;
}
如果我们更改IndentGotoLabels
为,true
我们有:
int new_foo() {
{
int *p = malloc(sizeof(int));
if (!p)
goto first_label;
int *q = malloc(sizeof(int));
if (!q)
goto second_label;
return 0;
first_label:
return 1;
}
second_label:
return 2;
}
标签现在缩进了,但与{
开始代码块的标签处于同一级别,而不是代码本身。
我不知道这是clang-format
不能做的事情,还是我错过了一些选择。即使它实际上并不能解决问题,我也会保留我的答案。它可能被证明是有用的。
如果我们查看文档中的示例,这也是记录在案的行为,因此可能无法更改它。
这属于意见领域,但clang-format
有时可能非常有限。如果您可以自由使用其他代码格式化程序,astyle可能会做您想做的事情--indent-labels
。
初步答案:
在您的文件中设置IndentGotoLabels
为 false 。.clang-format
有关更多信息,请参阅文档。
如果您没有.clang-format
文件,您可以根据预定义的样式生成一个文件:
clang-format -style=llvm -dump-config > .clang-format
推荐阅读
- sql - 如何在雪花中将日期时间更改为 INT?
- c# - 列表的 C# ASP.NET MVC 模型绑定
- python - 为什么我的登录端点在匹配密码时会在我的生产环境中返回 TypeError?
- escaping - 使用 bazel 构建 Envoy 时,genrule cmd 会导致“Missing Terminating '”' 字符
- reactjs - Material UI Grid:扩展网格样式
- postgresql - 无法从 myBinder 连接到托管在 Azure 上的 ubuntu VM 上的 postgres
- c - 为什么http post响应在响应末尾添加随机字符
- c++ - 使用 memcpy 复制地址的内存
- python-3.x - 使用 Numba 提高性能时出错:非常量值
- android - Android 10:dumpsys 输出中不再存在“mAppTransitionState”