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