IDE Code formatting: Zig formatter is in my way

Hi,
there are things which I don’t want to format. I.e., a chess board arrangement:

pub const Square = enum(u6) {
        a1, b1, c1, d1, e1, f1, g1, h1,
        a2, b2, c2, d2, e2, f2, g2, h2,
        a3, b3, c3, d3, e3, f3, g3, h3,
        a4, b4, c4, d4, e4, f4, g4, h4,
        a5, b5, c5, d5, e5, f5, g5, h5,
        a6, b6, c6, d6, e6, f6, g6, h6,
        a7, b7, c7, d7, e7, f7, g7, h7,
        a8, b8, c8, d8, e8, f8, g8, h8,
};

The problem is, that this is turned into following by the Zig formatter:

pub const Square = enum(u6) {
        a1,
        b1,
        c1,
        d1,
        e1,
        f1,
        g1,
        h1,
        a2,
        b2,
        c2,
        d2,
        e2,
        f2,
        g2,
        h2,
        a3,
        b3,
        c3,
        d3,
        e3,
        f3,
        g3,
        h3,
        a4,
        b4,
        c4,
        d4,
        e4,
        f4,
        g4,
        h4,
        a5,
        b5,
        c5,
        d5,
        e5,
        f5,
        g5,
        h5,
        a6,
        b6,
        c6,
        d6,
        e6,
        f6,
        g6,
        h6,
        a7,
        b7,
        c7,
        d7,
        e7,
        f7,
        g7,
        h7,
        a8,
        b8,
        c8,
        d8,
        e8,
        f8,
        g8,
        h8,
    };

How can I prevent this?

1 Like

You can turn off formatter with // zig fmt: off and then turning back it on with // zig fmt: on like:

// zig fmt: off
pub const Square = enum(u6) {
        a1, b1, c1, d1, e1, f1, g1, h1,
        a2, b2, c2, d2, e2, f2, g2, h2,
        a3, b3, c3, d3, e3, f3, g3, h3,
        a4, b4, c4, d4, e4, f4, g4, h4,
        a5, b5, c5, d5, e5, f5, g5, h5,
        a6, b6, c6, d6, e6, f6, g6, h6,
        a7, b7, c7, d7, e7, f7, g7, h7,
        a8, b8, c8, d8, e8, f8, g8, h8,
};
// zig fmt: on
6 Likes

Thank you, that worked! :smile:

3 Likes

Apart from zig fmt: off/on I would really like the zig formatter being a bit smarter when it comes to table-data, ideally honoring the existing number of columns, and aligning the columns vertically by the delimiter (might be a bit much to ask though - so maybe zig fmt: off/on is indeed the better solution.

3 Likes

I’ve noticed that the formatter will preserve some table data, especially in array initialization. In this case it’s an enum which I think the formatter will always try to place each value on separate lines. So some of it depends on the kind of token it is looking at.
But I agree, having it preserve the number of columns even in the case of Enums would be nice.

1 Like

Relevant proposal: zig fmt: embrace alignment · Issue #17145 · ziglang/zig · GitHub

Currently, only array initializers have special logic for aligning elements like table. All other comma-separated list constructs can only be formatted as a single row/column.

4 Likes