s4eed
s4eed

Reputation: 7891

How to run cargo fmt on save in vscode?

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

Upvotes: 55

Views: 41931

Answers (7)

Caleb Stanford
Caleb Stanford

Reputation: 481

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:

  1. Install rust-analyzer
  2. Enable Editor: Format On Save (as in the other answers)
  3. 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)
  4. 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.

Upvotes: 1

atilkan
atilkan

Reputation: 5008

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"
  },

Upvotes: 18

TheHolyTachanka
TheHolyTachanka

Reputation: 15

Install rust-analyzer and add this to your settings.json

"[rust]": {
    "editor.defaultFormatter": "rust-lang.rust-analyzer",
    "editor.formatOnSave": true
}

Upvotes: -1

Ilya Tegmark
Ilya Tegmark

Reputation: 329

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 
    },

Upvotes: 22

Delta Kapp
Delta Kapp

Reputation: 1232

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
}

Upvotes: 106

Todd
Todd

Reputation: 5117

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
    }

Upvotes: 9

Kevin Reid
Kevin Reid

Reputation: 43733

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

Upvotes: 30

Related Questions