Is it possible to make Visual Studio Code run cargo fmt
on file save?
Asked
Active
Viewed 2.0k times
6 Answers
52
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
}

Delta Kapp
- 677
- 1
- 4
- 7
24
- Install rust-analyzer, if you have not already.
- In Visual Studio Code's settings, enable Editor: Format On Save (
editor.formatOnSave
).

Kevin Reid
- 37,492
- 13
- 80
- 108
-
4I'll also add that you should ensure you don't have "editor.defaultFormatter" set globally. If you have, say, "editor.defaultFormatter": "esbenp.prettier-vscode" (or some other formatter) enabled globally rather than on a per-language basis, VSCode will attempt to use that formatter in lieu of rust-analyzer's on Rust code. I've seen a few JS devs lost 10 or 15 minutes to this when transitioning to a Rust project. – Parker Ziegler Feb 06 '22 at 04:01
18
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
},

James Williams
- 724
- 6
- 20

Ilya Tegmark
- 289
- 2
- 3
9
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
}

German Khokhlov
- 1,724
- 16
- 15

Todd
- 5,017
- 1
- 25
- 16
8
If you have formatOnSaveMode is set to modifications or modificationsIfAvailable, you may need to change it like below.
"[rust]": {
"editor.defaultFormatter": "rust-lang.rust-analyzer",
"editor.formatOnSave": true,
"editor.formatOnSaveMode": "file"
},

atilkan
- 4,527
- 1
- 30
- 35
-
3i just need to add: "editor.formatOnSaveMode": "file" it's the working answer! thank you! – FatihAziz Mar 22 '23 at 00:19
-
1This was it for me, thanks! With modifications set it silently did nothing. – Viktor Hedefalk May 11 '23 at 16:31
-1
Install rust-analyzer and add this to your settings.json
"[rust]": {
"editor.defaultFormatter": "rust-lang.rust-analyzer",
"editor.formatOnSave": true
}

kelsny
- 23,009
- 3
- 19
- 48

TheHolyTachanka
- 7
- 3