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.
This commit is contained in:
Isaac Freund 2021-03-02 21:36:25 +01:00
parent 84f3b3dff2
commit 3ad9cb8b47
2 changed files with 35 additions and 10 deletions

View file

@ -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;

View file

@ -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);
index = 1 + (newline orelse end - 1);
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")) {
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});
}
}