Rustfmt: Support directives to control whether rustfmt runs on a section of code

Created on 17 Feb 2017  路  6Comments  路  Source: rust-lang/rustfmt

clang-format allows you to disable formatting on a piece of code temporarily with special clang-format off and clang-format on comments.

http://clang.llvm.org/docs/ClangFormatStyleOptions.html#disabling-formatting-on-a-piece-of-code

Sometimes the output of rustfmt isn't to my liking -- in those cases I'd like the ability to disable it for a section of code.

Most helpful comment

For future visitors here who don't click on the link before trying out the suggestion: that only works in nightly. From there link:

Tips

  • For things you do not want rustfmt to mangle, use one of

    #[rustfmt_skip]  // requires nightly and #![feature(custom_attribute)] in crate root
    #[cfg_attr(rustfmt, rustfmt_skip)]  // works in stable
    
  • When you run rustfmt, place a file named rustfmt.toml or .rustfmt.toml in
    target file directory or its parents to override the default settings of
    rustfmt.
  • After successful compilation, a rustfmt executable can be found in the
    target directory.
  • If you're having issues compiling Rustfmt (or compile errors when trying to
    install), make sure you have the most recent version of Rust installed.

All 6 comments

you can use #[rustfmt_skip] to skip items

Hmm, that sounds very promising! Is that documented anywhere?

And does Rust make it possible for that attribute to be applied to individual blocks or lines of code?

Documented here: https://github.com/rust-lang-nursery/rustfmt#tips

You can apply attributes to blocks and statements (but not individual expressions)

Thanks!

For future visitors here who don't click on the link before trying out the suggestion: that only works in nightly. From there link:

Tips

  • For things you do not want rustfmt to mangle, use one of

    #[rustfmt_skip]  // requires nightly and #![feature(custom_attribute)] in crate root
    #[cfg_attr(rustfmt, rustfmt_skip)]  // works in stable
    
  • When you run rustfmt, place a file named rustfmt.toml or .rustfmt.toml in
    target file directory or its parents to override the default settings of
    rustfmt.
  • After successful compilation, a rustfmt executable can be found in the
    target directory.
  • If you're having issues compiling Rustfmt (or compile errors when trying to
    install), make sure you have the most recent version of Rust installed.

You can just stick #[rustfmt::skip] attribute to statements.

fn main() {
    #[rustfmt::skip]
    println!(
                  "this will not be formatted"
    );
    println!(
                  "this will be formatted"
    );
}
Was this page helpful?
0 / 5 - 0 ratings