How can I switch off rustfmt for a region of code instead of a single item?

16.6k Views Asked by At

#[rustfmt::skip] allows you to skip a "block" of code while formatting, but this requires putting skip on each {} instead of Clang-style on/off

Consider this code:

fn add(a : i32, b : i32) -> i32 { a + b }
fn sub(a : i32, b : i32) -> i32 { a - b }

rustfmt will format this to:

fn add(a: i32, b: i32) -> i32 {
    a + b
}
fn sub(a: i32, b: i32) -> i32 {
    a - b
}

One needs two #[rustfmt::skip] attributes instead of a single on/off.

There is a rustfmt option for single-line functions, but this example is for demonstration purposes only. I want to control any possible rustfmt setting in the region.

2

There are 2 best solutions below

0
On

You could put the functions you do not want to format in a module, tag the entire module with a #[rustfmt::skip], then pull in the items to the parent module with use.

#[rustfmt::skip]
mod unformatted {
    pub fn add(a : i32, b : i32) -> i32 { a + b }
    pub fn sub(a : i32, b : i32) -> i32 { a - b }
}

use unformatted::*;

fn main() {
    dbg!(add(2, 3));
}
0
On

One approach is to put all rustfmt_skipped code-blocks into a single file and then record the filename in ignore.