DEV Community

Max
Max

Posted on

Quick tip: if Rust stopped formatting your code ...

Sometimes Rust Analyzer stops formatting my VS Code document and there is no message or explanation why.

This is just one ugly example - lines 46-53 are all over the place.

My ugly code

No matter how many times I press Ctrl+Shift+I the IDE would not fix the formatting or tell me what's wrong.

Turns out there is a simple way to find out why Rust Analyzer fails to format the document: cargo fmt. It will tell you exactly what's broken.

cargo fmt workaround

In this case it was a comment on line 44 that got in the way. The document started formatting again as soon as I removed it.

My tidy code

Beware, cargo fmt will attempt to reformat the entire project. Read more about it in https://github.com/rust-lang/rustfmt or run cargo fmt -- --help for options.

I went back to several other files that were not formatting properly, ran cargo fmt on them and quickly fixed the problems. Happy coding!

Top comments (3)

Collapse
 
netr profile image
netr

For anyone who is using vs code and has this issue:

Look for trailing spaces extension. It will highlight all trailing spaces in red and has a feature to quickly delete them all.

Collapse
 
sixvxsh profile image
Siavash Soleimanpour

it was useful for me. thanks

Collapse
 
richardwu profile image
Richard Wu

Thank you for figuring this out 🙏