Skip to content

Configurable per-object item wrap count via #[rustfmt::items(10)] (for better displaying large vectors, arrays, & matrices) #5553

Open
@tgross35

Description

@tgross35

Hello everyone,

It was suggested on Reddit (and pretty well received) to add a macro config option that allows specifying items per row within a vector or array, and aligns the items at the comma. This would be useful for formatting large collections of numbers, especially matrices where columns and rows are significant.

Here's the quote that started the discussion:

Yeah, exactly. I love using rustfmt, but just like unsafe, people shouldn't be scared to use rustfmt::skip when necessary.

For example, dealing with math heavy code, rustfmt will always reformat any large array declaration into one item per line, but there are plenty of situations where those arrays are actually matrices and formatting them accordingly is helpful. There's no way for rustfmt to ever know this.

The current behavior appears to be to use the full line then wrap if all items are short, or one item per line if any of the items excedes a limit: Example rustfmt output:

let v1 = vec![
    1i32, 2, 3, 4, 5, -34, 78, 5, 4, 6, 7, 8, 87, 5, 43, 45, 67, 8, 76, 543, 4, 567, 8, 7,
    6543, -45, 456, 7, -4, 2, 3, 45, 64, -9, 909, -940, 185, -9849484, 984, 9898, -598,
];

let v2 = vec![
    1798798798797i64,
    268763876278189,
    -29873267368763,
    782687289780998,
    -2976173718798,
    1987897,
];

// Adding a larger number to v1 makes a 40 item long vector (truncated here)
let v3 = vec![
    ...
    7,
    6543,
    -45,
    456,
    7,
    -4,
    2,
    3,
    45,
    64,
    -9,
    909,
    -940,
    185,
    -9849484,
    984,
    9898,
    -590909023328,
];

This change would allow the user to specify that they desire N items per row:

#[rustfmt::items(10)]
let v1 = vec![
    1i32,   2,   3,   4,   5, -34,  78,   5,
       4,   6,   7,   8,  87,   5,  43,  45,
      67,   8,  76, 543,   4, 567,   8,   7,
];

#[rustfmt::items(2)]
let v2 = vec![
    1798798798797i64,  268763876278189,
     -29873267368763,  782687289780998,
      -2976173718798,          1987897,
];

Even outside of matricies, this would be a nice option to enable rustfmt to make use of more horizontal space.

Metadata

Metadata

Assignees

No one assigned

    Labels

    community drivenIssues the rustfmt team will not work on directly. Intended for contributors!feature-requestp-low

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions