28

Is it possible to make Visual Studio Code run cargo fmt on file save?

s4eed
  • 7,173
  • 9
  • 67
  • 104

6 Answers6

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
  1. Install rust-analyzer, if you have not already.
  2. In Visual Studio Code's settings, enable Editor: Format On Save (editor.formatOnSave).
Kevin Reid
  • 37,492
  • 13
  • 80
  • 108
  • 4
    I'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
-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