Is it possible to make Visual Studio Code run cargo fmt
on file save?
Install the extension rust-analyzer (the officially recommended vscode extension), and add the following to settings.json:
"[rust]": {
"editor.defaultFormatter": "rust-lang.rust-analyzer",
"editor.formatOnSave": true
}
- Install rust-analyzer, if you have not already.
- In Visual Studio Code's settings, enable Editor: Format On Save (
editor.formatOnSave
).
This is what worked for me. In the file settings.json somewhere inside the curly braces insert the following :
"editor.formatOnSave": true,
"editor.formatOnType": true,
"rust-analyzer.rustfmt.enableRangeFormatting": true,
"[rust]": {
"editor.defaultFormatter": "rust-lang.rust-analyzer",
"editor.formatOnSave": true
},
If you have formatOnSaveMode is set to modifications or modificationsIfAvailable, you may need to change it to file. This is probably a small issue with the analyzer.
And if you want to leave the default settings unchanged, do it for only rust;
"[rust]": {
"editor.defaultFormatter": "rust-lang.rust-analyzer",
"editor.formatOnSave": true,
"editor.formatOnSaveMode": "file"
},
Current version of the Rust extension > 0.7.8 requires nothing else to be installed. Enable formatOnSave
in VS Code settings.json
file:
"[rust]": {
"editor.formatOnSave": true
}
Posting on behalf of @Stacks. Here's a more complete set of steps that will identify any problems with steps 1-2. Just enabling "format on save" may not always be enough:
- Install rust-analyzer
- Enable
Editor: Format On Save
(as in the other answers) - Test Formatting your code by manually selecting a section of code and either right clicking “Format Code..” or pressing the “Format Code” shortcut (Cntrl-Shift-F or Alt-Shift-F)
- Follow any prompts to select a different formatter if necessary.
The last steps 3-4 are important, because if your formatting preferences are incorrect or if there are duplicate formatters installed, it will fail and prompt you to select the correct one to use.
Install rust-analyzer and add this to your settings.json
"[rust]": {
"editor.defaultFormatter": "rust-lang.rust-analyzer",
"editor.formatOnSave": true
}
© 2022 - 2025 — McMap. All rights reserved.