Steering Zig Fmt
Steering Zig Fmt
Two tips on using zig fmt effectively. Read this if you are writing Zig, or if you are implementing a code formatter. For me, zig fmt is better than any other formatter I used: rustfmt, the one in IntelliJ, deno fmt.
关于如何高效使用 zig fmt 的两个技巧。如果你正在编写 Zig 代码,或者正在实现一个代码格式化工具,请阅读本文。对我而言,zig fmt 比我用过的任何其他格式化工具都要好:包括 rustfmt、IntelliJ 自带的格式化工具以及 deno fmt。
zig fmt is steerable. For every syntactic construct, it has several variations for how it might be laid out. The variation used is selected by looking at what’s currently in a file. Easier to show a pair of examples:
zig fmt 是可控的。对于每一种语法结构,它都有几种不同的布局方式。它会通过观察文件中现有的代码来选择使用哪种变体。通过一对例子来展示会更直观:
f(1, 2, 3); // -> zig fmt -> f(1, 2, 3);
f(1, 2, 3,); // -> zig fmt -> f( 1, 2, 3, );
(代码示例:f(1, 2, 3); 经 zig fmt 处理后保持不变;而 f(1, 2, 3,); 经 zig fmt 处理后会变为每行一个参数的格式。)
Depending on the trailing comma, function call is formatted on a single line, or with one argument per line. The way this plays out in practice is that you decide how you want to lay out the code, add a couple of ,, hit the reformat shortcut (, p is mine), and zig fmt does the rest.
根据是否带有尾随逗号,函数调用会被格式化为单行,或者每个参数占一行。在实际操作中,这意味着你可以决定代码的布局方式,添加几个逗号,按下格式化快捷键(我的是 , p),剩下的就交给 zig fmt 了。
For me, this works better than the alternative of the formatter guessing. 90% of great formatting are blank lines between logical blocks and tasteful choice of intermediate variables, so you might as well lean into key choices, rather than eliminate them. 对我来说,这种方式比让格式化工具去“猜”要好得多。优秀的格式化 90% 取决于逻辑块之间的空行以及对中间变量的巧妙选择,所以你最好还是坚持这些关键的选择,而不是消除它们。
I know of one non-trivial formatting customization point: columnar layout for arrays: 我知道一个非平凡的格式化自定义点:数组的列式布局:
.{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, }; (代码示例:数组的列式布局)
One would think that trailing comma would lead to a number-per-line layout, but, for arrays, zig fmt also takes note of the first line break. In this case, the line break comes after the first three items, so we get three numbers per line, aligned:
人们可能会认为尾随逗号会导致“每行一个数字”的布局,但对于数组,zig fmt 还会注意第一个换行符的位置。在这种情况下,换行符出现在前三个元素之后,因此我们得到了每行三个数字且对齐的布局:
.{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, }; (代码示例:每行三个数字且对齐的布局)
How cool is that! Furthermore, with judicious use of ++ (array concatenation), you can vary the number of items per line. When I need to pass —key value pairs to subprocess, I often go for formatting like this:
这太酷了!此外,通过明智地使用 ++(数组拼接),你可以改变每行的元素数量。当需要向子进程传递 --key value 键值对时,我经常采用这样的格式:
try run(&(.{ “aws”, “s3”, “sync”, path, url } ++ .{ “—include”, “.html”, “—include”, “.xml”, “—metadata-directive”, “REPLACE”, “—cache-control”, “max-age=0”, }));
(代码示例:使用 ++ 拼接数组以实现自定义的参数布局)