Sub topic 12
Format on save and inline lints in your editor
Running cargo fmt and cargo clippy by hand works, but you only see the results after you stop typing. Editor integration moves both tools into the editing loop. Formatting happens when you save, and Clippy warnings appear as underlines in the code.
This chapter assumes you have read the earlier chapters on cargo fmt, rustfmt.toml, cargo clippy, lint levels, and the [lints] table. You also need a working Cargo project and an editor with rust-analyzer support. The examples use VS Code and Neovim, and the same settings carry over to other editors.
How the pieces fit together
Your editor does not run rustfmt or Clippy itself. It talks to rust-analyzer, a language server, over the Language Server Protocol (LSP). rust-analyzer then calls the same tools you run in a terminal.
- For formatting, rust-analyzer runs
rustfmton the buffer and returns the formatted text to the editor. - For lints, rust-analyzer runs
cargo checkin the background by default. You can switch that command tocargo clippy. It reads the JSON diagnostics and sends them to the editor as underlines, hover text, and quick fixes.
Because both tools run as usual, they read the same configuration files as the command line: rustfmt.toml, clippy.toml, and the [lints] table in Cargo.toml. You do not configure style or lint policy in the editor. The editor settings only decide when the tools run and which command is used.
Install the components
Check that the toolchain has everything. Editors fail quietly when a component is missing, so do this first.
rustup component add rustfmt clippy rust-analyzer
rustfmt --version
cargo clippy --versionMost editors download their own rust-analyzer binary through an extension. The rust-analyzer rustup component is an alternative. It keeps the server version matched to your toolchain, which helps when you pin a toolchain with rust-toolchain.toml.
Format on save in VS Code
Install the rust-analyzer extension. Then open the settings JSON, either per user or in .vscode/settings.json in the project, and add:
{
"[rust]": {
"editor.defaultFormatter": "rust-lang.rust-analyzer",
"editor.formatOnSave": true
}
}Scoping the settings to [rust] means format on save applies only to Rust files. Other languages keep their own formatters.
If you commit .vscode/settings.json, every contributor gets the same behavior. This is useful for teams, but check that the file does not contain personal paths.
Format on save in Neovim
Neovim has no built-in format-on-save. You create an autocommand that asks the language server to format before each write. This example uses the built-in LSP client and nvim-lspconfig:
require("lspconfig").rust_analyzer.setup({
settings = {
["rust-analyzer"] = {
check = { command = "clippy" },
},
},
})
vim.api.nvim_create_autocmd("BufWritePre", {
pattern = "*.rs",
callback = function()
vim.lsp.buf.format({ async = false })
end,
})async = false matters here. With an asynchronous format, the write can finish before the edits arrive, and you get a file that is saved unformatted and then modified. Newer Neovim releases also offer vim.lsp.config and vim.lsp.enable for server setup. The autocommand part is the same either way.
Other editors follow the same pattern. Helix formats Rust files on save by default through the language server. Zed and JetBrains RustRover have their own switches, and RustRover can run Clippy instead of its built-in checks.
Inline lints: switch the check command to Clippy
By default, rust-analyzer's background check is cargo check. That shows compiler errors and rustc warnings, but not Clippy lints. To see Clippy diagnostics, change the command.
In VS Code:
{
"rust-analyzer.check.command": "clippy"
}Older rust-analyzer versions call this setting rust-analyzer.checkOnSave.command. If your editor ignores the new name, look at the extension's settings UI to see which name your version uses.
After saving a file, rust-analyzer now runs cargo clippy. Try it with the loop from the Clippy chapter:
fn main() {
let v = vec![10, 20, 30];
for i in 0..v.len() {
println!("{}", v[i]);
}
}The 0..v.len() range is underlined. Hovering shows the clippy::needless_range_loop lint with the explanation and the suggested rewrite. Open the code action menu on the underline, which is Ctrl+. in VS Code, and choose the quick fix. The editor applies the suggestion, and the code becomes for item in &v or an equivalent form.
Editor quick fixes come from the same suggestions that cargo clippy --fix uses. Read the resulting diff before you keep it, just as you would with the command-line version.
The editor follows your project configuration
Since rust-analyzer runs Cargo, the project's lint policy applies without extra work:
- Levels set in the
[lints]table inCargo.tomlchange the severity you see. - Crate-level and item-level attributes such as
#[allow(clippy::too_many_arguments)]silence the matching underline. clippy.tomlthresholds andmsrvaffect which diagnostics appear.rustfmt.tomlcontrols how formatting rewrites your code.
If a lint is missing in the editor but appears in CI, or the other way around, compare configuration first. The editor is rarely wrong on its own.
Match the editor to CI
CI usually runs cargo clippy --all-targets --all-features -- -D warnings. The editor's default is narrower. It uses the default feature set and shows lints as warnings. This produces a common mismatch. Code looks clean in the editor and fails in CI, because a lint fires only with a non-default feature, or inside test code that the editor was not checking.
You can narrow the gap with these settings:
{
"rust-analyzer.check.command": "clippy",
"rust-analyzer.check.allTargets": true,
"rust-analyzer.cargo.features": "all"
}check.allTargetsmakes the check include tests, examples, and benchmarks. Its default is alreadytruein current versions, so setting it only protects you against an older default.cargo.featuresset to"all"enables every feature, as--all-featuresdoes in CI. Be careful with this on crates that have mutually exclusive features, because enabling all of them can cause build errors that are not real problems.
If you want warnings to look like errors, pass the flag through check.extraArgs:
{
"rust-analyzer.check.extraArgs": ["--", "-D", "warnings"]
}This turns every warning into a red error in the editor, which matches CI. Many developers find that too noisy while code is half-written. A common compromise is to leave warnings as warnings while editing, and rely on CI for the strict check.
Performance and build lock gotchas
Running Clippy on every save has a cost. Two issues come up often.
First, rust-analyzer's background check and your terminal's cargo build share the target directory. Cargo locks that directory, so one command waits for the other. You will see Blocking waiting for file lock on build directory. Also, Clippy and a normal build use different cached artifacts for the same crate when flags differ, so switching between them can trigger rebuilds. You can give rust-analyzer its own directory:
{
"rust-analyzer.cargo.targetDir": true
}With true, rust-analyzer builds in target/rust-analyzer, which avoids both the lock and the cache churn. The price is extra disk space and a first-time full build in that directory.
Second, on large workspaces a full Clippy run after each save may be slow. Options include limiting the check to the current package with rust-analyzer.check.workspace set to false, or choosing to check only on demand. The first is a good default for big workspaces. The second means running the check yourself through a task or the command line.
Formatting with nightly-only options
The Topic Spine's rustfmt.toml example uses stable options only. If your project also sets unstable options such as imports_granularity, stable rustfmt warns that the option is ignored. The editor's format action then does not match what you expect.
You can make the editor call a nightly rustfmt through rust-analyzer's extra arguments:
{
"rust-analyzer.rustfmt.extraArgs": ["+nightly"]
}This requires the nightly toolchain with the rustfmt component installed. Use it only when the project already formats with nightly. If CI runs stable rustfmt and your editor runs nightly, the two can disagree on a file and every save produces a diff that CI rejects.
Troubleshooting
When something does not work, start with the command line. If the terminal shows the right result, the problem is in the editor wiring.
| Symptom | Likely cause | What to check |
|---|---|---|
| Nothing formats on save | No default formatter set, or format on save is off | The `[rust]` block in settings, and that rust-analyzer is running |
| Formatting ignores `rustfmt.toml` | The file is not in the workspace root or a parent directory | Move the file, or run `rustfmt --print-config current path/to/file.rs` |
| Clippy lints missing in the editor | `check.command` is still `check` | Set it to `clippy` and restart the server |
| Lints appear in CI but not the editor | Features or targets differ | `--all-targets` and `--all-features` in both places |
| Editor hangs on "waiting for file lock" | Terminal build and background check share `target` | Set `rust-analyzer.cargo.targetDir` to `true` |
| Format is correct but unstable options warn | Stable rustfmt ignoring nightly options | Remove the options, or use `+nightly` consistently |
When you suspect a stale state, restart the language server. In VS Code, run "rust-analyzer: Restart server" from the command palette. Most configuration problems clear after a restart.
A practical checklist
- Install
rustfmt,clippy, andrust-analyzerwith rustup. - Set the default Rust formatter and turn on format on save.
- Set
rust-analyzer.check.commandtoclippy. - Make the editor's feature and target settings match your CI command.
- Put configuration in
rustfmt.toml,clippy.toml, andCargo.toml, not in editor settings. - Keep CI as the final gate. Editor settings are personal, and CI applies to everyone.
The last point is the main design rule. The editor gives fast feedback, and CI enforces the policy. Neither replaces the other.
Exercise
You enabled format on save and set rust-analyzer.check.command to clippy. The editor shows no warnings, but CI fails with a Clippy lint inside a function that only compiles when the serde feature is enabled. Name two editor settings that could explain the difference and how you would fix it.
Show answer
The editor is checking only the default feature set, so code behind the serde feature is never compiled and never linted. Set rust-analyzer.cargo.features to "all" (or to the list ["serde"]) so the editor enables the same features as --all-features in CI. A second cause is that the check might skip tests or examples. Make sure rust-analyzer.check.allTargets is true to match --all-targets. Then restart the server and confirm the lint appears, and compare against cargo clippy --all-targets --all-features in the terminal.
Exercise
Why is it better to put max_width = 100 in rustfmt.toml than in your editor settings?
Show answer
The editor calls the real rustfmt, which reads rustfmt.toml from the project. A setting in rustfmt.toml applies to every contributor, every editor, and cargo fmt --all -- --check in CI. A value stored only in your editor settings affects just your machine, so your saved files can differ from what CI expects.