如何重新格式化 VIM 中的 C 源代码“{”位置?
How can you reformat C source code '{' placements in VIM?
我想更改以下代码:
if (test)
{
statements;
}
else
{
statements;
}
以下内容:
if (test) {
statements;
} else {
statements;
}
使用“=”不会执行此功能(据我所知)。
有什么巧妙的 VIM 命令可以做到这一点吗?
您可以玩正则表达式。在这里,它将是:
:%s/\_s*{/ {/g
:%s/}\zs\_s*\ze\(else\|while\)/ /g
秘密在 /\_s
中,它类似于 /\s
(匹配空格),但也匹配换行符。
如果您还想转换 { return foo; }
之类的内容,则还必须插入换行符,然后重新缩进所有内容。
:%s/\_s*{\_s*/ {\r/g
gg=G
您还可以查看 vim 集成了 AStyle 或 clang-format 等工具的插件,它们应该会提供更好的结果。
PS: lh-cpp and mu-template snippets have an option (through :AddStyle
) 让最终用户指定是否插入换行符。有时,更好的方法是生成符合项目风格的代码。
我想更改以下代码:
if (test)
{
statements;
}
else
{
statements;
}
以下内容:
if (test) {
statements;
} else {
statements;
}
使用“=”不会执行此功能(据我所知)。 有什么巧妙的 VIM 命令可以做到这一点吗?
您可以玩正则表达式。在这里,它将是:
:%s/\_s*{/ {/g
:%s/}\zs\_s*\ze\(else\|while\)/ /g
秘密在 /\_s
中,它类似于 /\s
(匹配空格),但也匹配换行符。
如果您还想转换 { return foo; }
之类的内容,则还必须插入换行符,然后重新缩进所有内容。
:%s/\_s*{\_s*/ {\r/g
gg=G
您还可以查看 vim 集成了 AStyle 或 clang-format 等工具的插件,它们应该会提供更好的结果。
PS: lh-cpp and mu-template snippets have an option (through :AddStyle
) 让最终用户指定是否插入换行符。有时,更好的方法是生成符合项目风格的代码。