commit 3ad9cb8b473820ec5ea11d85aa72e8ddc83cfa03 (tree)
parent 84f3b3dff2cc8f380a60e920cb1ca76e779571c6
Author: Isaac Freund <ifreund@ifreund.xyz>
Date: Tue, 2 Mar 2021 21:36:25 +0100
zig fmt: allow and trim whitespace around zig fmt: (off|on)
Currently `// zig fmt: off` does not work as there are two spaces
after the `//` instead of one. This can cause confusion, so allow
arbitrary whitespace before the `zig fmt: (off|on)` in the comment but
trim this whitespace to the canonical single space in the output.
Diffstat:
2 files changed, 36 insertions(+), 11 deletions(-)
diff --git a/lib/std/zig/parser_test.zig b/lib/std/zig/parser_test.zig
@@ -1108,6 +1108,25 @@ test "zig fmt: comment to disable/enable zig fmt first" {
);
}
+test "zig fmt: 'zig fmt: (off|on)' can be surrounded by arbitrary whitespace" {
+ try testTransform(
+ \\// Test trailing comma syntax
+ \\// zig fmt: off
+ \\
+ \\const struct_trailing_comma = struct { x: i32, y: i32, };
+ \\
+ \\// zig fmt: on
+ ,
+ \\// Test trailing comma syntax
+ \\// zig fmt: off
+ \\
+ \\const struct_trailing_comma = struct { x: i32, y: i32, };
+ \\
+ \\// zig fmt: on
+ \\
+ );
+}
+
test "zig fmt: comment to disable/enable zig fmt" {
try testTransform(
\\const a = b;
diff --git a/lib/std/zig/render.zig b/lib/std/zig/render.zig
@@ -2352,18 +2352,24 @@ fn renderComments(ais: *Ais, tree: ast.Tree, start: usize, end: usize) Error!boo
}
}
- try ais.writer().print("{s}\n", .{trimmed_comment});
- index = 1 + (newline orelse return true);
-
- if (ais.disabled_offset) |disabled_offset| {
- if (mem.eql(u8, trimmed_comment, "// zig fmt: on")) {
- // write the source for which formatting was disabled directly
- // to the underlying writer, fixing up invaild whitespace
- try writeFixingWhitespace(ais.underlying_writer, tree.source[disabled_offset..index]);
- ais.disabled_offset = null;
- }
- } else if (mem.eql(u8, trimmed_comment, "// zig fmt: off")) {
+ index = 1 + (newline orelse end - 1);
+
+ const comment_content = mem.trimLeft(u8, trimmed_comment["//".len..], &std.ascii.spaces);
+ if (ais.disabled_offset != null and mem.eql(u8, comment_content, "zig fmt: on")) {
+ // Write the source for which formatting was disabled directly
+ // to the underlying writer, fixing up invaild whitespace.
+ const disabled_source = tree.source[ais.disabled_offset.?..comment_start];
+ try writeFixingWhitespace(ais.underlying_writer, disabled_source);
+ ais.disabled_offset = null;
+ // Write with the canonical single space.
+ try ais.writer().writeAll("// zig fmt: on\n");
+ } else if (ais.disabled_offset == null and mem.eql(u8, comment_content, "zig fmt: off")) {
+ // Write with the canonical single space.
+ try ais.writer().writeAll("// zig fmt: off\n");
ais.disabled_offset = index;
+ } else {
+ // Write the comment minus trailing whitespace.
+ try ais.writer().print("{s}\n", .{trimmed_comment});
}
}