]> git.lizzy.rs Git - rust.git/blob - docs/user/manual.adoc
Merge #8214
[rust.git] / docs / user / manual.adoc
1 = User Manual
2 :toc: preamble
3 :sectanchors:
4 :page-layout: post
5 :icons: font
6 :source-highlighter: rouge
7 :experimental:
8
9 // Master copy of this document lives in the https://github.com/rust-analyzer/rust-analyzer repository
10
11 At its core, rust-analyzer is a *library* for semantic analysis of Rust code as it changes over time.
12 This manual focuses on a specific usage of the library -- running it as part of a server that implements the
13 https://microsoft.github.io/language-server-protocol/[Language Server Protocol] (LSP).
14 The LSP allows various code editors, like VS Code, Emacs or Vim, to implement semantic features like completion or goto definition by talking to an external language server process.
15
16 [TIP]
17 ====
18 [.lead]
19 To improve this document, send a pull request: +
20 https://github.com/rust-analyzer/rust-analyzer/blob/master/docs/user/manual.adoc[https://github.com/rust-analyzer/.../manual.adoc]
21
22 The manual is written in https://asciidoc.org[AsciiDoc] and includes some extra files which are generated from the source code. Run `cargo test` and `cargo test -p xtask` to create these and then `asciidoctor manual.adoc` to create an HTML copy.
23
24 ====
25
26 If you have questions about using rust-analyzer, please ask them in the https://users.rust-lang.org/c/ide/14["`IDEs and Editors`"] topic of Rust users forum.
27
28 == Installation
29
30 In theory, one should be able to just install the <<rust-analyzer-language-server-binary,`rust-analyzer` binary>> and have it automatically work with any editor.
31 We are not there yet, so some editor specific setup is required.
32
33 Additionally, rust-analyzer needs the sources of the standard library.
34 If the source code is not present, rust-analyzer will attempt to install it automatically.
35
36 To add the sources manually, run the following command:
37
38 ```bash
39 $ rustup component add rust-src
40 ```
41
42 === VS Code
43
44 This is the best supported editor at the moment.
45 The rust-analyzer plugin for VS Code is maintained
46 https://github.com/rust-analyzer/rust-analyzer/tree/master/editors/code[in tree].
47
48 You can install the latest release of the plugin from
49 https://marketplace.visualstudio.com/items?itemName=matklad.rust-analyzer[the marketplace].
50
51 Note that the plugin may cause conflicts with the
52 https://marketplace.visualstudio.com/items?itemName=rust-lang.rust[official Rust plugin].
53 It is recommended to disable the Rust plugin when using the rust-analyzer extension.
54
55 By default, the plugin will prompt you to download the matching version of the server as well:
56
57 image::https://user-images.githubusercontent.com/9021944/75067008-17502500-54ba-11ea-835a-f92aac50e866.png[]
58
59 [NOTE]
60 ====
61 To disable this notification put the following to `settings.json`
62
63 [source,json]
64 ----
65 { "rust-analyzer.updates.askBeforeDownload": false }
66 ----
67 ====
68
69 The server binary is stored in:
70
71 * Linux: `~/.config/Code/User/globalStorage/matklad.rust-analyzer`
72 * Linux (Remote, such as WSL): `~/.vscode-server/data/User/globalStorage/matklad.rust-analyzer`
73 * macOS: `~/Library/Application\ Support/Code/User/globalStorage/matklad.rust-analyzer`
74 * Windows: `%APPDATA%\Code\User\globalStorage\matklad.rust-analyzer`
75
76 Note that we only support two most recent versions of VS Code.
77
78 ==== Updates
79
80 The extension will be updated automatically as new versions become available.
81 It will ask your permission to download the matching language server version binary if needed.
82
83 ===== Nightly
84
85 We ship nightly releases for VS Code.
86 To help us out with testing the newest code and follow the bleeding edge of our `master`, please use the following config:
87
88 [source,json]
89 ----
90 { "rust-analyzer.updates.channel": "nightly" }
91 ----
92
93 You will be prompted to install the `nightly` extension version.
94 Just click `Download now` and from that moment you will get automatic updates every 24 hours.
95
96 If you don't want to be asked for `Download now` every day when the new nightly version is released add the following to your `settings.json`:
97 [source,json]
98 ----
99 { "rust-analyzer.updates.askBeforeDownload": false }
100 ----
101
102 NOTE: Nightly extension should **only** be installed via the `Download now` action from VS Code.
103
104 ==== Manual installation
105
106 Alternatively, procure both `rust-analyzer.vsix` and your platform's matching `rust-analyzer-{platform}`, for example from the
107 https://github.com/rust-analyzer/rust-analyzer/releases[releases] page.
108
109 Install the extension with the `Extensions: Install from VSIX` command within VS Code, or from the command line via:
110 [source]
111 ----
112 $ code --install-extension /path/to/rust-analyzer.vsix
113 ----
114
115 Copy the `rust-analyzer-{platform}` binary anywhere, then add the path to your settings.json, for example:
116 [source,json]
117 ----
118 { "rust-analyzer.server.path": "~/.local/bin/rust-analyzer-linux" }
119 ----
120
121 ==== Building From Source
122
123 Alternatively, both the server and the Code plugin can be installed from source:
124
125 [source]
126 ----
127 $ git clone https://github.com/rust-analyzer/rust-analyzer.git && cd rust-analyzer
128 $ cargo xtask install
129 ----
130
131 You'll need Cargo, nodejs and npm for this.
132
133 Note that installing via `xtask install` does not work for VS Code Remote, instead you'll need to install the `.vsix` manually.
134
135 If you're not using Code, you can compile and install only the LSP server:
136
137 [source]
138 ----
139 $ cargo xtask install --server
140 ----
141
142 ==== Troubleshooting
143
144 Here are some useful self-diagnostic commands:
145
146 * **Rust Analyzer: Show RA Version** shows the version of `rust-analyzer` binary.
147 * **Rust Analyzer: Status** prints some statistics about the server, and dependency information for the current file.
148 * To enable server-side logging, run with `env RA_LOG=info` and see `Output > Rust Analyzer Language Server` in VS Code's panel.
149 * To log project loading (sysroot & `cargo metadata`), set `RA_LOG=project_model=debug`.
150 * To log all LSP requests, add `"rust-analyzer.trace.server": "verbose"` to the settings and look for `Rust Analyzer Language Server Trace` in the panel.
151 * To enable client-side logging, add `"rust-analyzer.trace.extension": true` to the settings and open `Output > Rust Analyzer Client` in the panel.
152
153 === rust-analyzer Language Server Binary
154
155 Other editors generally require the `rust-analyzer` binary to be in `$PATH`.
156 You can download the pre-built binary from the https://github.com/rust-analyzer/rust-analyzer/releases[releases] page.
157 Typically, you then need to rename the binary for your platform, e.g. `rust-analyzer-mac` if you're on Mac OS, to `rust-analyzer` and make it executable in addition to moving it into a directory in your `$PATH`.
158
159 On Linux to install the `rust-analyzer` binary into `~/.local/bin`, this commands could be used
160
161 [source,bash]
162 ----
163 $ curl -L https://github.com/rust-analyzer/rust-analyzer/releases/latest/download/rust-analyzer-linux -o ~/.local/bin/rust-analyzer
164 $ chmod +x ~/.local/bin/rust-analyzer
165 ----
166
167 Ensure `~/.local/bin` is listed in the `$PATH` variable.
168
169 Alternatively, you can install it from source using the command below.
170 You'll need the latest stable version of the Rust toolchain.
171
172 [source,bash]
173 ----
174 $ git clone https://github.com/rust-analyzer/rust-analyzer.git && cd rust-analyzer
175 $ cargo xtask install --server
176 ----
177
178 If your editor can't find the binary even though the binary is on your `$PATH`, the likely explanation is that it doesn't see the same `$PATH` as the shell, see https://github.com/rust-analyzer/rust-analyzer/issues/1811[this issue].
179 On Unix, running the editor from a shell or changing the `.desktop` file to set the environment should help.
180
181 ==== `rustup`
182
183 `rust-analyzer` is available in `rustup`, but only in the nightly toolchain:
184
185 [source,bash]
186 ---
187 $ rustup +nightly component add rust-analyzer-preview
188 ---
189
190 ==== Arch Linux
191
192 The `rust-analyzer` binary can be installed from the repos or AUR (Arch User Repository):
193
194 - https://www.archlinux.org/packages/community/x86_64/rust-analyzer/[`rust-analyzer`] (built from latest tagged source)
195 - https://aur.archlinux.org/packages/rust-analyzer-git[`rust-analyzer-git`] (latest Git version)
196
197 Install it with pacman, for example:
198
199 [source,bash]
200 ----
201 $ pacman -S rust-analyzer
202 ----
203
204 === Emacs
205
206 Note this excellent https://robert.kra.hn/posts/2021-02-07_rust-with-emacs/[guide] from https://github.com/rksm[@rksm].
207
208 Prerequisites: You have installed the <<rust-analyzer-language-server-binary,`rust-analyzer` binary>>.
209
210 Emacs support is maintained as part of the https://github.com/emacs-lsp/lsp-mode[Emacs-LSP] package in https://github.com/emacs-lsp/lsp-mode/blob/master/lsp-rust.el[lsp-rust.el].
211
212 1. Install the most recent version of `emacs-lsp` package by following the https://github.com/emacs-lsp/lsp-mode[Emacs-LSP instructions].
213 2. Set `lsp-rust-server` to `'rust-analyzer`.
214 3. Run `lsp` in a Rust buffer.
215 4. (Optionally) bind commands like `lsp-rust-analyzer-join-lines`, `lsp-extend-selection` and `lsp-rust-analyzer-expand-macro` to keys.
216
217 === Vim/NeoVim
218
219 Prerequisites: You have installed the <<rust-analyzer-language-server-binary,`rust-analyzer` binary>>.
220 Not needed if the extension can install/update it on its own, coc-rust-analyzer is one example.
221
222 The are several LSP client implementations for vim or neovim:
223
224 ==== coc-rust-analyzer
225
226 1. Install coc.nvim by following the instructions at
227    https://github.com/neoclide/coc.nvim[coc.nvim]
228    (Node.js required)
229 2. Run `:CocInstall coc-rust-analyzer` to install
230    https://github.com/fannheyward/coc-rust-analyzer[coc-rust-analyzer],
231    this extension implements _most_ of the features supported in the VSCode extension:
232    * automatically install and upgrade stable/nightly releases
233    * same configurations as VSCode extension, `rust-analyzer.server.path`, `rust-analyzer.cargo.features` etc.
234    * same commands too, `rust-analyzer.analyzerStatus`, `rust-analyzer.ssr` etc.
235    * inlay hints for variables and method chaining, _Neovim Only_
236    * semantic highlighting is not implemented yet
237
238 Note: for code actions, use `coc-codeaction-cursor` and `coc-codeaction-selected`; `coc-codeaction` and `coc-codeaction-line` are unlikely to be useful.
239
240 ==== LanguageClient-neovim
241
242 1. Install LanguageClient-neovim by following the instructions
243    https://github.com/autozimu/LanguageClient-neovim[here]
244    * The GitHub project wiki has extra tips on configuration
245
246 2. Configure by adding this to your vim/neovim config file (replacing the existing Rust-specific line if it exists):
247 +
248 [source,vim]
249 ----
250 let g:LanguageClient_serverCommands = {
251 \ 'rust': ['rust-analyzer'],
252 \ }
253 ----
254
255 ==== YouCompleteMe
256
257 1. Install YouCompleteMe by following the instructions
258   https://github.com/ycm-core/lsp-examples#rust-rust-analyzer[here]
259
260 2. Configure by adding this to your vim/neovim config file (replacing the existing Rust-specific line if it exists):
261 +
262 [source,vim]
263 ----
264 let g:ycm_language_server =
265 \ [
266 \   {
267 \     'name': 'rust',
268 \     'cmdline': ['rust-analyzer'],
269 \     'filetypes': ['rust'],
270 \     'project_root_files': ['Cargo.toml']
271 \   }
272 \ ]
273 ----
274
275 ==== ALE
276
277 To use the LSP server in https://github.com/dense-analysis/ale[ale]:
278
279 [source,vim]
280 ----
281 let g:ale_linters = {'rust': ['analyzer']}
282 ----
283
284 ==== nvim-lsp
285
286 NeoVim 0.5 (not yet released) has built-in language server support.
287 For a quick start configuration of rust-analyzer, use https://github.com/neovim/nvim-lspconfig#rust_analyzer[neovim/nvim-lspconfig].
288 Once `neovim/nvim-lspconfig` is installed, use `+lua require'lspconfig'.rust_analyzer.setup({})+` in your `init.vim`.
289
290 You can also pass LSP settings to the server:
291
292 [source,vim]
293 ----
294 lua << EOF
295 local nvim_lsp = require'lspconfig'
296
297 local on_attach = function(client)
298     require'completion'.on_attach(client)
299 end
300
301 nvim_lsp.rust_analyzer.setup({
302     on_attach=on_attach,
303     settings = {
304         ["rust-analyzer"] = {
305             assist = {
306                 importMergeBehavior = "last",
307                 importPrefix = "by_self",
308             },
309             cargo = {
310                 loadOutDirsFromCheck = true
311             },
312             procMacro = {
313                 enable = true
314             },
315         }
316     }
317 })
318 EOF
319 ----
320
321 See https://sharksforarms.dev/posts/neovim-rust/ for more tips on getting started.
322
323 ==== vim-lsp
324
325 vim-lsp is installed by following https://github.com/prabirshrestha/vim-lsp[the plugin instructions].
326 It can be as simple as adding this line to your `.vimrc`:
327
328 [source,vim]
329 ----
330 Plug 'prabirshrestha/vim-lsp'
331 ----
332
333 Next you need to register the `rust-analyzer` binary.
334 If it is available in `$PATH`, you may want to add this to your `.vimrc`:
335
336 [source,vim]
337 ----
338 if executable('rust-analyzer')
339   au User lsp_setup call lsp#register_server({
340         \   'name': 'Rust Language Server',
341         \   'cmd': {server_info->['rust-analyzer']},
342         \   'whitelist': ['rust'],
343         \ })
344 endif
345 ----
346
347 There is no dedicated UI for the server configuration, so you would need to send any options as a value of the `initialization_options` field, as described in the <<_configuration,Configuration>> section.
348 Here is an example of how to enable the proc-macro support:
349
350 [source,vim]
351 ----
352 if executable('rust-analyzer')
353   au User lsp_setup call lsp#register_server({
354         \   'name': 'Rust Language Server',
355         \   'cmd': {server_info->['rust-analyzer']},
356         \   'whitelist': ['rust'],
357         \   'initialization_options': {
358         \     'cargo': {
359         \       'loadOutDirsFromCheck': v:true,
360         \     },
361         \     'procMacro': {
362         \       'enable': v:true,
363         \     },
364         \   },
365         \ })
366 endif
367 ----
368
369 === Sublime Text 3
370
371 Prerequisites: You have installed the <<rust-analyzer-language-server-binary,`rust-analyzer` binary>>.
372
373 You also need the `LSP` package.
374 To install it:
375
376 1. If you've never installed a Sublime Text package, install Package Control:
377    * Open the command palette (Win/Linux: `ctrl+shift+p`, Mac: `cmd+shift+p`)
378    * Type `Install Package Control`, press enter
379 2. In the command palette, run `Package control: Install package`, and in the list that pops up, type `LSP` and press enter.
380
381 Finally, with your Rust project open, in the command palette, run `LSP: Enable Language Server In Project` or `LSP: Enable Language Server Globally`, then select `rust-analyzer` in the list that pops up to enable the rust-analyzer LSP.
382 The latter means that rust-analyzer is enabled by default in Rust projects.
383
384 If it worked, you should see "rust-analyzer, Line X, Column Y" on the left side of the bottom bar, and after waiting a bit, functionality like tooltips on hovering over variables should become available.
385
386 If you get an error saying `No such file or directory: 'rust-analyzer'`, see the <<rust-analyzer-language-server-binary,`rust-analyzer` binary>> section on installing the language server binary.
387
388 === GNOME Builder
389
390 GNOME Builder 3.37.1 and newer has native `rust-analyzer` support.
391 If the LSP binary is not available, GNOME Builder can install it when opening a Rust file.
392
393
394 === Eclipse IDE
395
396 Support for Rust development in the Eclipse IDE is provided by link:https://github.com/eclipse/corrosion[Eclipse Corrosion].
397 If available in PATH or in some standard location, `rust-analyzer` is detected and powers editing of Rust files without further configuration.
398 If `rust-analyzer` is not detected, Corrosion will prompt you for configuration of your Rust toolchain and language server with a link to the __Window > Preferences > Rust__ preference page; from here a button allows to download and configure `rust-analyzer`, but you can also reference another installation.
399 You'll need to close and reopen all .rs and Cargo files, or to restart the IDE, for this change to take effect.
400
401 == Configuration
402
403 **Source:** https://github.com/rust-analyzer/rust-analyzer/blob/master/crates/rust-analyzer/src/config.rs[config.rs]
404
405 The <<_installation,Installation>> section contains details on configuration for some of the editors.
406 In general `rust-analyzer` is configured via LSP messages, which means that it's up to the editor to decide on the exact format and location of configuration files.
407
408 Some clients, such as <<vs-code,VS Code>> or <<coc-rust-analyzer,COC plugin in Vim>> provide `rust-analyzer` specific configuration UIs. Others may require you to know a bit more about the interaction with `rust-analyzer`.
409
410 For the later category, it might help to know that the initial configuration is specified as a value of the `initializationOptions` field of the https://microsoft.github.io/language-server-protocol/specifications/specification-current/#initialize[`InitializeParams` message, in the LSP protocol].
411 The spec says that the field type is `any?`, but `rust-analyzer` is looking for a JSON object that is constructed using settings from the list below.
412 Name of the setting, ignoring the `rust-analyzer.` prefix, is used as a path, and value of the setting becomes the JSON property value.
413
414 For example, a very common configuration is to enable proc-macro support, can be achieved by sending this JSON:
415
416 [source,json]
417 ----
418 {
419   "cargo": {
420     "loadOutDirsFromCheck": true,
421   },
422   "procMacro": {
423     "enable": true,
424   }
425 }
426 ----
427
428 Please consult your editor's documentation to learn more about how to configure https://microsoft.github.io/language-server-protocol/[LSP servers].
429
430 To verify which configuration is actually used by `rust-analyzer`, set `RA_LOG` environment variable to `rust_analyzer=info` and look for config-related messages.
431 Logs should show both the JSON that `rust-analyzer` sees as well as the updated config.
432
433 This is the list of config options `rust-analyzer` supports:
434
435 include::./generated_config.adoc[]
436
437 == Non-Cargo Based Projects
438
439 rust-analyzer does not require Cargo.
440 However, if you use some other build system, you'll have to describe the structure of your project for rust-analyzer in the `rust-project.json` format:
441
442 [source,TypeScript]
443 ----
444 interface JsonProject {
445     /// Path to the directory with *source code* of sysroot crates.
446     ///
447     /// It should point to the directory where std, core, and friends can be found:
448     /// https://github.com/rust-lang/rust/tree/master/library.
449     ///
450     /// If provided, rust-analyzer automatically adds dependencies on sysroot
451     /// crates. Conversely, if you omit this path, you can specify sysroot
452     /// dependencies yourself and, for example, have several different "sysroots" in
453     /// one graph of crates.
454     sysroot_src?: string;
455     /// The set of crates comprising the current project.
456     /// Must include all transitive dependencies as well as sysroot crate (libstd, libcore and such).
457     crates: Crate[];
458 }
459
460 interface Crate {
461     /// Optional crate name used for display purposes, without affecting semantics.
462     /// See the `deps` key for semantically-significant crate names.
463     display_name?: string;
464     /// Path to the root module of the crate.
465     root_module: string;
466     /// Edition of the crate.
467     edition: "2015" | "2018" | "2021";
468     /// Dependencies
469     deps: Dep[];
470     /// Should this crate be treated as a member of current "workspace".
471     ///
472     /// By default, inferred from the `root_module` (members are the crates which reside
473     /// inside the directory opened in the editor).
474     ///
475     /// Set this to `false` for things like standard library and 3rd party crates to
476     /// enable performance optimizations (rust-analyzer assumes that non-member crates
477     /// don't change).
478     is_workspace_member?: boolean;
479     /// Optionally specify the (super)set of `.rs` files comprising this crate.
480     ///
481     /// By default, rust-analyzer assumes that only files under `root_module.parent` can belong to a crate.
482     /// `include_dirs` are included recursively, unless a subdirectory is in `exclude_dirs`.
483     ///
484     /// Different crates can share the same `source`.
485     ///
486     /// If two crates share an `.rs` file in common, they *must* have the same `source`.
487     /// rust-analyzer assumes that files from one source can't refer to files in another source.
488     source?: {
489         include_dirs: string[],
490         exclude_dirs: string[],
491     },
492     /// The set of cfgs activated for a given crate, like `["unix", "feature=\"foo\"", "feature=\"bar\""]`.
493     cfg: string[];
494     /// Target triple for this Crate.
495     ///
496     /// Used when running `rustc --print cfg` to get target-specific cfgs.
497     target?: string;
498     /// Environment variables, used for the `env!` macro
499     env: : { [key: string]: string; },
500
501     /// For proc-macro crates, path to compiles proc-macro (.so file).
502     proc_macro_dylib_path?: string;
503 }
504
505 interface Dep {
506     /// Index of a crate in the `crates` array.
507     crate: number,
508     /// Name as should appear in the (implicit) `extern crate name` declaration.
509     name: string,
510 }
511 ----
512
513 This format is provisional and subject to change.
514 Specifically, the `roots` setup will be different eventually.
515
516 There are tree ways to feed `rust-project.json` to rust-analyzer:
517
518 * Place `rust-project.json` file at the root of the project, and rust-anlayzer will discover it.
519 * Specify `"rust-analyzer.linkedProjects": [ "path/to/rust-project.json" ]` in the settings (and make sure that your LSP client sends settings as a part of initialize request).
520 * Specify `"rust-analyzer.linkedProjects": [ { "roots": [...], "crates": [...] }]` inline.
521
522 Relative paths are interpreted relative to `rust-project.json` file location or (for inline JSON) relative to `rootUri`.
523
524 See https://github.com/rust-analyzer/rust-project.json-example for a small example.
525
526 You can set `RA_LOG` environmental variable to `rust_analyzer=info` to inspect how rust-analyzer handles config and project loading.
527
528 == Security
529
530 At the moment, rust-analyzer assumes that all code is trusted.
531 Here is a **non-exhaustive** list of ways to make rust-analyzer execute arbitrary code:
532
533 * proc macros and build scripts are executed by default
534 * `.cargo/config` can override `rustc` with an arbitrary executable
535 * VS Code plugin reads configuration from project directory, and that can be used to override paths to various executables, like `rustfmt` or `rust-analyzer` itself.
536 * rust-analyzer's syntax trees library uses a lot of `unsafe` and hasn't been properly audited for memory safety.
537
538 rust-analyzer itself doesn't access the network.
539 The VS Code plugin doesn't access the network unless the nightly channel is selected in the settings.
540 In that case, the plugin uses the GitHub API to check for and download updates.
541
542 == Features
543
544 include::./generated_features.adoc[]
545
546 == Assists (Code Actions)
547
548 Assists, or code actions, are small local refactorings, available in a particular context.
549 They are usually triggered by a shortcut or by clicking a light bulb icon in the editor.
550 Cursor position or selection is signified by `┃` character.
551
552 include::./generated_assists.adoc[]
553
554 == Diagnostics
555
556 While most errors and warnings provided by rust-analyzer come from the `cargo check` integration, there's a growing number of diagnostics implemented using rust-analyzer's own analysis.
557 These diagnostics don't respect `#[allow]` or `#[deny]` attributes yet, but can be turned off using the `rust-analyzer.diagnostics.enable`, `rust-analyzer.diagnostics.enableExperimental` or `rust-analyzer.diagnostics.disabled` settings.
558
559 include::./generated_diagnostic.adoc[]
560
561 == Editor Features
562 === VS Code
563
564 ==== Color configurations
565
566 It is possible to change the foreground/background color of inlay hints.
567 Just add this to your `settings.json`:
568
569 [source,jsonc]
570 ----
571 {
572   "workbench.colorCustomizations": {
573     // Name of the theme you are currently using
574     "[Default Dark+]": {
575       "rust_analyzer.inlayHints.foreground": "#868686f0",
576       "rust_analyzer.inlayHints.background": "#3d3d3d48",
577
578       // Overrides for specific kinds of inlay hints
579       "rust_analyzer.inlayHints.foreground.typeHints": "#fdb6fdf0",
580       "rust_analyzer.inlayHints.foreground.paramHints": "#fdb6fdf0",
581       "rust_analyzer.inlayHints.background.chainingHints": "#6b0c0c81"
582     }
583   }
584 }
585 ----
586
587 ==== Semantic style customizations
588
589 You can customize the look of different semantic elements in the source code.
590 For example, mutable bindings are underlined by default and you can override this behavior by adding the following section to your `settings.json`:
591
592 [source,jsonc]
593 ----
594 {
595   "editor.semanticTokenColorCustomizations": {
596     "rules": {
597       "*.mutable": {
598         "fontStyle": "", // underline is the default
599       },
600     }
601   },
602 }
603 ----
604
605 ==== Special `when` clause context for keybindings.
606 You may use `inRustProject` context to configure keybindings for rust projects only.
607 For example:
608
609 [source,json]
610 ----
611 {
612   "key": "ctrl+i",
613   "command": "rust-analyzer.toggleInlayHints",
614   "when": "inRustProject"
615 }
616 ----
617 More about `when` clause contexts https://code.visualstudio.com/docs/getstarted/keybindings#_when-clause-contexts[here].
618
619 ==== Setting runnable environment variables
620 You can use "rust-analyzer.runnableEnv" setting to define runnable environment-specific substitution variables.
621 The simplest way for all runnables in a bunch:
622 ```jsonc
623 "rust-analyzer.runnableEnv": {
624     "RUN_SLOW_TESTS": "1"
625 }
626 ```
627
628 Or it is possible to specify vars more granularly:
629 ```jsonc
630 "rust-analyzer.runnableEnv": [
631     {
632         // "mask": null, // null mask means that this rule will be applied for all runnables
633         env: {
634              "APP_ID": "1",
635              "APP_DATA": "asdf"
636         }
637     },
638     {
639         "mask": "test_name",
640         "env": {
641              "APP_ID": "2", // overwrites only APP_ID
642         }
643     }
644 ]
645 ```
646
647 You can use any valid regular expression as a mask.
648 Also note that a full runnable name is something like *run bin_or_example_name*, *test some::mod::test_name* or *test-mod some::mod*, so it is possible to distinguish binaries, single tests, and test modules with this masks: `"^run"`, `"^test "` (the trailing space matters!), and `"^test-mod"` respectively.
649
650 ==== Compiler feedback from external commands
651
652 Instead of relying on the built-in `cargo check`, you can configure Code to run a command in the background and use the `$rustc-watch` problem matcher to generate inline error markers from its output.
653
654 To do this you need to create a new https://code.visualstudio.com/docs/editor/tasks[VS Code Task] and set `rust-analyzer.checkOnSave.enable: false` in preferences.
655
656 For example, if you want to run https://crates.io/crates/cargo-watch[`cargo watch`] instead, you might add the following to `.vscode/tasks.json`:
657
658 ```json
659 {
660     "label": "Watch",
661     "group": "build",
662     "type": "shell",
663     "command": "cargo watch",
664     "problemMatcher": "$rustc-watch",
665     "isBackground": true
666 }
667 ```