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