diff --git a/.gitignore b/.gitignore index 68c87a6b1ed4..3d724585a368 100644 --- a/.gitignore +++ b/.gitignore @@ -7,10 +7,12 @@ crates/*/target *.log *.iml .vscode/settings.json -generated_assists.adoc -generated_features.adoc -generated_diagnostic.adoc +generated_assists.md +generated_features.md +generated_diagnostics.md +generated_config.md .DS_Store /out/ /dump.lsif .envrc +docs/manual/book/ diff --git a/crates/ide-assists/src/handlers/auto_import.rs b/crates/ide-assists/src/handlers/auto_import.rs index e257218ba937..49b463506281 100644 --- a/crates/ide-assists/src/handlers/auto_import.rs +++ b/crates/ide-assists/src/handlers/auto_import.rs @@ -38,7 +38,7 @@ use crate::{AssistContext, AssistId, AssistKind, Assists, GroupLabel}; // use super::AssistContext; // ``` // -// .Import Granularity +// ### Import Granularity // // It is possible to configure how use-trees are merged with the `imports.granularity.group` setting. // It has the following configurations: @@ -52,7 +52,7 @@ use crate::{AssistContext, AssistId, AssistKind, Assists, GroupLabel}; // // In `VS Code` the configuration for this is `rust-analyzer.imports.granularity.group`. // -// .Import Prefix +// ### Import Prefix // // The style of imports in the same crate is configurable through the `imports.prefix` setting. // It has the following configurations: @@ -66,7 +66,7 @@ use crate::{AssistContext, AssistId, AssistKind, Assists, GroupLabel}; // // In `VS Code` the configuration for this is `rust-analyzer.imports.prefix`. // -// image::https://user-images.githubusercontent.com/48062697/113020673-b85be580-917a-11eb-9022-59585f35d4f8.gif[] +// ![Auto Import](https://user-images.githubusercontent.com/48062697/113020673-b85be580-917a-11eb-9022-59585f35d4f8.gif) // Assist: auto_import // diff --git a/crates/ide-assists/src/tests/sourcegen.rs b/crates/ide-assists/src/tests/sourcegen.rs index 070b83d3c16b..bb5a2cc0f337 100644 --- a/crates/ide-assists/src/tests/sourcegen.rs +++ b/crates/ide-assists/src/tests/sourcegen.rs @@ -55,7 +55,7 @@ r#####" "sourcegen_assists_docs", assists.into_iter().map(|it| it.to_string()).collect::>().join("\n\n"), ); - let dst = project_root().join("docs/user/generated_assists.adoc"); + let dst = project_root().join("docs/manual/src/generated_assists.md"); fs::write(dst, contents).unwrap(); } } @@ -142,7 +142,7 @@ impl fmt::Display for Assist { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let _ = writeln!( f, - "[discrete]\n=== `{}` + "## `{}`\n\n **Source:** {}", self.id, self.location, ); @@ -155,11 +155,13 @@ impl fmt::Display for Assist { " {} -.Before +### Before + ```rust {}``` -.After +### After + ```rust {}```", section.doc, diff --git a/crates/ide-completion/src/completions/flyimport.rs b/crates/ide-completion/src/completions/flyimport.rs index 364969af9c9a..61c13649efbf 100644 --- a/crates/ide-completion/src/completions/flyimport.rs +++ b/crates/ide-completion/src/completions/flyimport.rs @@ -86,19 +86,19 @@ use super::Completions; // NOTE: currently, if an assoc item comes from a trait that's not currently imported, and it also has an unresolved and/or partially-qualified path, // no imports will be proposed. // -// .Fuzzy search details +// ### Fuzzy search details // // To avoid an excessive amount of the results returned, completion input is checked for inclusion in the names only // (i.e. in `HashMap` in the `std::collections::HashMap` path). // For the same reasons, avoids searching for any path imports for inputs with their length less than 2 symbols // (but shows all associated items for any input length). // -// .Import configuration +// ### Import configuration // // It is possible to configure how use-trees are merged with the `imports.granularity.group` setting. // Mimics the corresponding behavior of the `Auto Import` feature. // -// .LSP and performance implications +// ### LSP and performance implications // // The feature is enabled only if the LSP client supports LSP protocol version 3.16+ and reports the `additionalTextEdits` // (case-sensitive) resolve client capability in its client capabilities. @@ -106,7 +106,7 @@ use super::Completions; // For clients with no such support, all edits have to be calculated on the completion request, including the fuzzy search completion ones, // which might be slow ergo the feature is automatically disabled. // -// .Feature toggle +// ### Feature toggle // // The feature can be forcefully turned off in the settings with the `rust-analyzer.completion.autoimport.enable` flag. // Note that having this flag set to `true` does not guarantee that the feature is enabled: your client needs to have the corresponding diff --git a/crates/ide-completion/src/completions/postfix/format_like.rs b/crates/ide-completion/src/completions/postfix/format_like.rs index b43bdb9ab9d1..b2ac1b415373 100644 --- a/crates/ide-completion/src/completions/postfix/format_like.rs +++ b/crates/ide-completion/src/completions/postfix/format_like.rs @@ -8,13 +8,13 @@ // * `panic` -> `panic!(...)` // * `println` -> `println!(...)` // * `log`: -// ** `logd` -> `log::debug!(...)` -// ** `logt` -> `log::trace!(...)` -// ** `logi` -> `log::info!(...)` -// ** `logw` -> `log::warn!(...)` -// ** `loge` -> `log::error!(...)` +// * `logd` -> `log::debug!(...)` +// * `logt` -> `log::trace!(...)` +// * `logi` -> `log::info!(...)` +// * `logw` -> `log::warn!(...)` +// * `loge` -> `log::error!(...)` // -// image::https://user-images.githubusercontent.com/48062697/113020656-b560f500-917a-11eb-87de-02991f61beb8.gif[] +// ![Format String Completion](https://user-images.githubusercontent.com/48062697/113020656-b560f500-917a-11eb-87de-02991f61beb8.gif) use ide_db::{ syntax_helpers::format_string_exprs::{parse_format_exprs, with_placeholders}, diff --git a/crates/ide-completion/src/lib.rs b/crates/ide-completion/src/lib.rs index 8d21f4fce0a2..802ea2455cf0 100644 --- a/crates/ide-completion/src/lib.rs +++ b/crates/ide-completion/src/lib.rs @@ -72,11 +72,13 @@ pub use crate::{ // // There also snippet completions: // -// .Expressions +// ## Expressions +// // - `pd` -> `eprintln!(" = {:?}", );` // - `ppd` -> `eprintln!(" = {:#?}", );` // -// .Items +// ## Items +// // - `tfn` -> `#[test] fn feature(){}` // - `tmod` -> // ```rust @@ -93,7 +95,7 @@ pub use crate::{ // Those are the additional completion options with automatic `use` import and options from all project importable items, // fuzzy matched against the completion input. // -// image::https://user-images.githubusercontent.com/48062697/113020667-b72ab880-917a-11eb-8778-716cf26a0eb3.gif[] +// ![Magic Completions](https://user-images.githubusercontent.com/48062697/113020667-b72ab880-917a-11eb-8778-716cf26a0eb3.gif) /// Main entry point for completion. We run completion as a two-phase process. /// diff --git a/crates/ide-completion/src/snippet.rs b/crates/ide-completion/src/snippet.rs index f3b8eae4fe8c..618fd3b81f48 100644 --- a/crates/ide-completion/src/snippet.rs +++ b/crates/ide-completion/src/snippet.rs @@ -8,8 +8,7 @@ // // A custom snippet can be defined by adding it to the `rust-analyzer.completion.snippets.custom` object respectively. // -// [source,json] -// ---- +// ```json // { // "rust-analyzer.completion.snippets.custom": { // "thread spawn": { @@ -25,7 +24,7 @@ // } // } // } -// ---- +// ``` // // In the example above: // @@ -43,8 +42,8 @@ // the items aren't yet in scope. // // * `scope` is an optional filter for when the snippet should be applicable. Possible values are: -// ** for Snippet-Scopes: `expr`, `item` (default: `item`) -// ** for Postfix-Snippet-Scopes: `expr`, `type` (default: `expr`) +// * for Snippet-Scopes: `expr`, `item` (default: `item`) +// * for Postfix-Snippet-Scopes: `expr`, `type` (default: `expr`) // // The `body` field also has access to placeholders as visible in the example as `$0`. // These placeholders take the form of `$number` or `${number:placeholder_text}` which can be traversed as tabstop in ascending order starting from 1, @@ -55,8 +54,8 @@ // // For the VSCode editor, rust-analyzer also ships with a small set of defaults which can be removed // by overwriting the settings object mentioned above, the defaults are: -// [source,json] -// ---- +// +// ```json // { // "Arc::new": { // "postfix": "arc", @@ -98,7 +97,7 @@ // "scope": "expr" // } // } -// ---- +// ``` use ide_db::imports::import_assets::LocatedImport; use itertools::Itertools; diff --git a/crates/ide-db/src/apply_change.rs b/crates/ide-db/src/apply_change.rs index b1ee9b58d5ba..a05f6bccaeaa 100644 --- a/crates/ide-db/src/apply_change.rs +++ b/crates/ide-db/src/apply_change.rs @@ -42,12 +42,11 @@ impl RootDatabase { // // Clears rust-analyzer's internal database and prints memory usage statistics. // - // |=== - // | Editor | Action Name + // | Editor | Action Name | + // |---------|-------------| + // | VS Code | **rust-analyzer: Memory Usage (Clears Database)** | // - // | VS Code | **rust-analyzer: Memory Usage (Clears Database)** - // |=== - // image::https://user-images.githubusercontent.com/48062697/113065592-08559f00-91b1-11eb-8c96-64b88068ec02.gif[] + // ![Memory Usage](https://user-images.githubusercontent.com/48062697/113065592-08559f00-91b1-11eb-8c96-64b88068ec02.gif) pub fn per_query_memory_usage(&mut self) -> Vec<(String, Bytes)> { let mut acc: Vec<(String, Bytes)> = vec![]; macro_rules! purge_each_query { diff --git a/crates/ide-db/src/symbol_index.rs b/crates/ide-db/src/symbol_index.rs index bfb003127710..c91985db4b37 100644 --- a/crates/ide-db/src/symbol_index.rs +++ b/crates/ide-db/src/symbol_index.rs @@ -173,11 +173,9 @@ impl std::ops::Deref for Snap { // the filtering via the `rust-analyzer.workspace.symbol.search.scope` and // `rust-analyzer.workspace.symbol.search.kind` settings. // -// |=== -// | Editor | Shortcut -// -// | VS Code | kbd:[Ctrl+T] -// |=== +// | Editor | Shortcut | +// |---------|----------| +// | VS Code | Ctrl+T | pub fn world_symbols(db: &RootDatabase, query: Query) -> Vec { let _p = profile::span("world_symbols").detail(|| query.query.clone()); diff --git a/crates/ide-diagnostics/src/tests/sourcegen.rs b/crates/ide-diagnostics/src/tests/sourcegen.rs index ec6558a46efb..ea918773bd1e 100644 --- a/crates/ide-diagnostics/src/tests/sourcegen.rs +++ b/crates/ide-diagnostics/src/tests/sourcegen.rs @@ -10,7 +10,7 @@ fn sourcegen_diagnostic_docs() { let contents = diagnostics.into_iter().map(|it| it.to_string()).collect::>().join("\n\n"); let contents = sourcegen::add_preamble("sourcegen_diagnostic_docs", contents); - let dst = project_root().join("docs/user/generated_diagnostic.adoc"); + let dst = project_root().join("docs/manual/src/generated_diagnostics.md"); fs::write(&dst, &contents).unwrap(); } @@ -68,6 +68,6 @@ fn is_valid_diagnostic_name(diagnostic: &str) -> Result<(), String> { impl fmt::Display for Diagnostic { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - writeln!(f, "=== {}\n**Source:** {}\n{}", self.id, self.location, self.doc) + writeln!(f, "## {}\n**Source:** {}\n{}", self.id, self.location, self.doc) } } diff --git a/crates/ide-ssr/src/lib.rs b/crates/ide-ssr/src/lib.rs index d9834ee63adc..1cbb849bca18 100644 --- a/crates/ide-ssr/src/lib.rs +++ b/crates/ide-ssr/src/lib.rs @@ -35,12 +35,10 @@ // // Supported constraints: // -// |=== -// | Constraint | Restricts placeholder -// -// | kind(literal) | Is a literal (e.g. `42` or `"forty two"`) -// | not(a) | Negates the constraint `a` -// |=== +// | Constraint | Restricts placeholder | +// |---------------|-----------------------| +// | kind(literal) | Is a literal (e.g. `42` or `"forty two"`) | +// | not(a) | Negates the constraint `a` | // // Available via the command `rust-analyzer.ssr`. // @@ -54,11 +52,9 @@ // String::from((y + 5).foo(z)) // ``` // -// |=== -// | Editor | Action Name -// -// | VS Code | **rust-analyzer: Structural Search Replace** -// |=== +// | Editor | Action Name | +// |---------|--------------| +// | VS Code | **rust-analyzer: Structural Search Replace** | // // Also available as an assist, by writing a comment containing the structural // search and replace rule. You will only see the assist if the comment can diff --git a/crates/ide/src/annotations.rs b/crates/ide/src/annotations.rs index bfbe0db6e4b8..d333448d5080 100644 --- a/crates/ide/src/annotations.rs +++ b/crates/ide/src/annotations.rs @@ -20,7 +20,7 @@ use crate::{ // Provides user with annotations above items for looking up references or impl blocks // and running/debugging binaries. // -// image::https://user-images.githubusercontent.com/48062697/113020672-b7c34f00-917a-11eb-8f6e-858735660a0e.png[] +// ![Annotations](https://user-images.githubusercontent.com/48062697/113020672-b7c34f00-917a-11eb-8f6e-858735660a0e.png) #[derive(Debug)] pub struct Annotation { pub range: TextRange, diff --git a/crates/ide/src/expand_macro.rs b/crates/ide/src/expand_macro.rs index 93252339cd4a..e1c87500e5e2 100644 --- a/crates/ide/src/expand_macro.rs +++ b/crates/ide/src/expand_macro.rs @@ -16,13 +16,11 @@ pub struct ExpandedMacro { // // Shows the full macro expansion of the macro at current cursor. // -// |=== -// | Editor | Action Name +// | Editor | Action Name | +// |--------|-------------| +// | VS Code | **rust-analyzer: Expand macro recursively** | // -// | VS Code | **rust-analyzer: Expand macro recursively** -// |=== -// -// image::https://user-images.githubusercontent.com/48062697/113020648-b3973180-917a-11eb-84a9-ecb921293dc5.gif[] +// ![Expand Macro Recursively](https://user-images.githubusercontent.com/48062697/113020648-b3973180-917a-11eb-84a9-ecb921293dc5.gif) pub(crate) fn expand_macro(db: &RootDatabase, position: FilePosition) -> Option { let sema = Semantics::new(db); let file = sema.parse(position.file_id); diff --git a/crates/ide/src/extend_selection.rs b/crates/ide/src/extend_selection.rs index 45f1fd74841c..128918ff2ece 100644 --- a/crates/ide/src/extend_selection.rs +++ b/crates/ide/src/extend_selection.rs @@ -19,13 +19,11 @@ use crate::FileRange; // // This is a standard LSP feature and not a protocol extension. // -// |=== -// | Editor | Shortcut +// | Editor | Shortcut | +// |--------|-------------| +// | VS Code | Alt+Shift+→, Alt+Shift+← | // -// | VS Code | kbd:[Alt+Shift+→], kbd:[Alt+Shift+←] -// |=== -// -// image::https://user-images.githubusercontent.com/48062697/113020651-b42fc800-917a-11eb-8a4f-cf1a07859fac.gif[] +// ![Expand and Shrink Selection](https://user-images.githubusercontent.com/48062697/113020651-b42fc800-917a-11eb-8a4f-cf1a07859fac.gif) pub(crate) fn extend_selection(db: &RootDatabase, frange: FileRange) -> TextRange { let sema = Semantics::new(db); let src = sema.parse(frange.file_id); diff --git a/crates/ide/src/file_structure.rs b/crates/ide/src/file_structure.rs index 68fd0952b488..99a8157e9f13 100644 --- a/crates/ide/src/file_structure.rs +++ b/crates/ide/src/file_structure.rs @@ -30,13 +30,11 @@ pub enum StructureNodeKind { // * draw breadcrumbs to describe the context around the cursor // * draw outline of the file // -// |=== -// | Editor | Shortcut +// | Editor | Shortcut | +// |---------|----------| +// | VS Code | Ctrl+Shift+O | // -// | VS Code | kbd:[Ctrl+Shift+O] -// |=== -// -// image::https://user-images.githubusercontent.com/48062697/113020654-b42fc800-917a-11eb-8388-e7dc4d92b02e.gif[] +// ![File Structure](https://user-images.githubusercontent.com/48062697/113020654-b42fc800-917a-11eb-8388-e7dc4d92b02e.gif) pub(crate) fn file_structure(file: &SourceFile) -> Vec { let mut res = Vec::new(); diff --git a/crates/ide/src/goto_definition.rs b/crates/ide/src/goto_definition.rs index 36a648fe4a8e..7ad52bc5b26f 100644 --- a/crates/ide/src/goto_definition.rs +++ b/crates/ide/src/goto_definition.rs @@ -17,13 +17,11 @@ use syntax::{ast, AstNode, AstToken, SyntaxKind::*, SyntaxToken, TextRange, T}; // // For outline modules, this will navigate to the source file of the module. // -// |=== -// | Editor | Shortcut +// | Editor | Shortcut | +// |---------|----------| +// | VS Code | F12 | // -// | VS Code | kbd:[F12] -// |=== -// -// image::https://user-images.githubusercontent.com/48062697/113065563-025fbe00-91b1-11eb-83e4-a5a703610b23.gif[] +// ![Go to Definition](https://user-images.githubusercontent.com/48062697/113065563-025fbe00-91b1-11eb-83e4-a5a703610b23.gif) pub(crate) fn goto_definition( db: &RootDatabase, position: FilePosition, diff --git a/crates/ide/src/goto_implementation.rs b/crates/ide/src/goto_implementation.rs index b3f711b6b88c..4c36559cb410 100644 --- a/crates/ide/src/goto_implementation.rs +++ b/crates/ide/src/goto_implementation.rs @@ -13,13 +13,11 @@ use crate::{FilePosition, NavigationTarget, RangeInfo, TryToNav}; // // Navigates to the impl blocks of types. // -// |=== -// | Editor | Shortcut +// | Editor | Shortcut | +// |---------|----------| +// | VS Code | Ctrl+F12 | // -// | VS Code | kbd:[Ctrl+F12] -// |=== -// -// image::https://user-images.githubusercontent.com/48062697/113065566-02f85480-91b1-11eb-9288-aaad8abd8841.gif[] +// ![Go to Implementation](https://user-images.githubusercontent.com/48062697/113065566-02f85480-91b1-11eb-9288-aaad8abd8841.gif) pub(crate) fn goto_implementation( db: &RootDatabase, position: FilePosition, diff --git a/crates/ide/src/goto_type_definition.rs b/crates/ide/src/goto_type_definition.rs index 55cdb3200eac..7dfc386c7726 100644 --- a/crates/ide/src/goto_type_definition.rs +++ b/crates/ide/src/goto_type_definition.rs @@ -7,13 +7,11 @@ use crate::{FilePosition, NavigationTarget, RangeInfo, TryToNav}; // // Navigates to the type of an identifier. // -// |=== -// | Editor | Action Name +// | Editor | Action Name | +// |---------|-------------| +// | VS Code | **Go to Type Definition* | // -// | VS Code | **Go to Type Definition* -// |=== -// -// image::https://user-images.githubusercontent.com/48062697/113020657-b560f500-917a-11eb-9007-0f809733a338.gif[] +// ![Go to Type Definition](https://user-images.githubusercontent.com/48062697/113020657-b560f500-917a-11eb-9007-0f809733a338.gif) pub(crate) fn goto_type_definition( db: &RootDatabase, position: FilePosition, diff --git a/crates/ide/src/highlight_related.rs b/crates/ide/src/highlight_related.rs index 1bdd626f1e83..2bf75b7fffec 100644 --- a/crates/ide/src/highlight_related.rs +++ b/crates/ide/src/highlight_related.rs @@ -37,10 +37,10 @@ pub struct HighlightRelatedConfig { // // Highlights constructs related to the thing under the cursor: // -// . if on an identifier, highlights all references to that identifier in the current file -// . if on an `async` or `await token, highlights all yield points for that async context -// . if on a `return` or `fn` keyword, `?` character or `->` return type arrow, highlights all exit points for that context -// . if on a `break`, `loop`, `while` or `for` token, highlights all break points for that loop or block context +// * if on an identifier, highlights all references to that identifier in the current file +// * if on an `async` or `await token, highlights all yield points for that async context +// * if on a `return` or `fn` keyword, `?` character or `->` return type arrow, highlights all exit points for that context +// * if on a `break`, `loop`, `while` or `for` token, highlights all break points for that loop or block context // // Note: `?` and `->` do not currently trigger this behavior in the VSCode editor. pub(crate) fn highlight_related( diff --git a/crates/ide/src/hover.rs b/crates/ide/src/hover.rs index 3687b597fc64..a4867df95ae0 100644 --- a/crates/ide/src/hover.rs +++ b/crates/ide/src/hover.rs @@ -87,7 +87,7 @@ pub struct HoverResult { // Shows additional information, like the type of an expression or the documentation for a definition when "focusing" code. // Focusing is usually hovering with a mouse, but can also be triggered with a shortcut. // -// image::https://user-images.githubusercontent.com/48062697/113020658-b5f98b80-917a-11eb-9f88-3dbc27320c95.gif[] +// ![Hover](https://user-images.githubusercontent.com/48062697/113020658-b5f98b80-917a-11eb-9f88-3dbc27320c95.gif) pub(crate) fn hover( db: &RootDatabase, FileRange { file_id, range }: FileRange, diff --git a/crates/ide/src/inlay_hints.rs b/crates/ide/src/inlay_hints.rs index 08363d21e89b..0c1e9e4a23cc 100644 --- a/crates/ide/src/inlay_hints.rs +++ b/crates/ide/src/inlay_hints.rs @@ -176,7 +176,7 @@ impl fmt::Debug for InlayHintLabelPart { // * elided lifetimes // * compiler inserted reborrows // -// image::https://user-images.githubusercontent.com/48062697/113020660-b5f98b80-917a-11eb-8d70-3be3fd558cdd.png[] +// ![Inlay Hints](https://user-images.githubusercontent.com/48062697/113020660-b5f98b80-917a-11eb-8d70-3be3fd558cdd.png) pub(crate) fn inlay_hints( db: &RootDatabase, file_id: FileId, diff --git a/crates/ide/src/join_lines.rs b/crates/ide/src/join_lines.rs index edc48e84d725..409ced954b5a 100644 --- a/crates/ide/src/join_lines.rs +++ b/crates/ide/src/join_lines.rs @@ -22,16 +22,14 @@ pub struct JoinLinesConfig { // Join selected lines into one, smartly fixing up whitespace, trailing commas, and braces. // // See -// https://user-images.githubusercontent.com/1711539/124515923-4504e800-dde9-11eb-8d58-d97945a1a785.gif[this gif] +// [this gif](https://user-images.githubusercontent.com/1711539/124515923-4504e800-dde9-11eb-8d58-d97945a1a785.gif) // for the cases handled specially by joined lines. // -// |=== -// | Editor | Action Name +// | Editor | Action Name | +// |---------|-------------| +// | VS Code | **rust-analyzer: Join lines** | // -// | VS Code | **rust-analyzer: Join lines** -// |=== -// -// image::https://user-images.githubusercontent.com/48062697/113020661-b6922200-917a-11eb-87c4-b75acc028f11.gif[] +// ![Join Lines](https://user-images.githubusercontent.com/48062697/113020661-b6922200-917a-11eb-87c4-b75acc028f11.gif) pub(crate) fn join_lines( config: &JoinLinesConfig, file: &SourceFile, diff --git a/crates/ide/src/matching_brace.rs b/crates/ide/src/matching_brace.rs index 6e8a6d020cc7..2bef6b6b58a5 100644 --- a/crates/ide/src/matching_brace.rs +++ b/crates/ide/src/matching_brace.rs @@ -9,13 +9,11 @@ use syntax::{ // moves cursor to the matching brace. It uses the actual parser to determine // braces, so it won't confuse generics with comparisons. // -// |=== -// | Editor | Action Name +// | Editor | Action Name | +// |---------|----------| +// | VS Code | **rust-analyzer: Find matching brace** | // -// | VS Code | **rust-analyzer: Find matching brace** -// |=== -// -// image::https://user-images.githubusercontent.com/48062697/113065573-04298180-91b1-11eb-8dec-d4e2a202f304.gif[] +// ![Matching Brace](https://user-images.githubusercontent.com/48062697/113065573-04298180-91b1-11eb-8dec-d4e2a202f304.gif) pub(crate) fn matching_brace(file: &SourceFile, offset: TextSize) -> Option { const BRACES: &[SyntaxKind] = &[T!['{'], T!['}'], T!['['], T![']'], T!['('], T![')'], T![<], T![>], T![|], T![|]]; diff --git a/crates/ide/src/move_item.rs b/crates/ide/src/move_item.rs index ffc4bdd7da33..6462c0428e09 100644 --- a/crates/ide/src/move_item.rs +++ b/crates/ide/src/move_item.rs @@ -16,14 +16,12 @@ pub enum Direction { // // Move item under cursor or selection up and down. // -// |=== -// | Editor | Action Name +// | Editor | Action Name | +// |---------|----------| +// | VS Code | **rust-analyzer: Move item up** | +// | VS Code | **rust-analyzer: Move item down** | // -// | VS Code | **rust-analyzer: Move item up** -// | VS Code | **rust-analyzer: Move item down** -// |=== -// -// image::https://user-images.githubusercontent.com/48062697/113065576-04298180-91b1-11eb-91ce-4505e99ed598.gif[] +// ![Move Item](https://user-images.githubusercontent.com/48062697/113065576-04298180-91b1-11eb-91ce-4505e99ed598.gif) pub(crate) fn move_item( db: &RootDatabase, range: FileRange, diff --git a/crates/ide/src/parent_module.rs b/crates/ide/src/parent_module.rs index 8f3cc86873f5..fe4e68af45e2 100644 --- a/crates/ide/src/parent_module.rs +++ b/crates/ide/src/parent_module.rs @@ -15,13 +15,11 @@ use crate::NavigationTarget; // // Navigates to the parent module of the current module. // -// |=== -// | Editor | Action Name +// | Editor | Action Name | +// |---------|----------| +// | VS Code | **rust-analyzer: Locate parent module** | // -// | VS Code | **rust-analyzer: Locate parent module** -// |=== -// -// image::https://user-images.githubusercontent.com/48062697/113065580-04c21800-91b1-11eb-9a32-00086161c0bd.gif[] +// ![Parent Module](https://user-images.githubusercontent.com/48062697/113065580-04c21800-91b1-11eb-9a32-00086161c0bd.gif) /// This returns `Vec` because a module may be included from several places. pub(crate) fn parent_module(db: &RootDatabase, position: FilePosition) -> Vec { diff --git a/crates/ide/src/references.rs b/crates/ide/src/references.rs index e942413c1105..c92e83347a2d 100644 --- a/crates/ide/src/references.rs +++ b/crates/ide/src/references.rs @@ -43,13 +43,11 @@ pub struct Declaration { // // Shows all references of the item at the cursor location // -// |=== -// | Editor | Shortcut +// | Editor | Shortcut | +// |--------|----------| +// | VS Code | Shift+Alt+F12 | // -// | VS Code | kbd:[Shift+Alt+F12] -// |=== -// -// image::https://user-images.githubusercontent.com/48062697/113020670-b7c34f00-917a-11eb-8003-370ac5f2b3cb.gif[] +// ![Find All References](https://user-images.githubusercontent.com/48062697/113020670-b7c34f00-917a-11eb-8003-370ac5f2b3cb.gif) pub(crate) fn find_all_refs( sema: &Semantics<'_, RootDatabase>, position: FilePosition, diff --git a/crates/ide/src/rename.rs b/crates/ide/src/rename.rs index fe44856dcad2..fba5937d746e 100644 --- a/crates/ide/src/rename.rs +++ b/crates/ide/src/rename.rs @@ -66,13 +66,11 @@ pub(crate) fn prepare_rename( // // Renames the item below the cursor and all of its references // -// |=== -// | Editor | Shortcut +// | Editor | Shortcut | +// |---------|----------| +// | VS Code | F2 | // -// | VS Code | kbd:[F2] -// |=== -// -// image::https://user-images.githubusercontent.com/48062697/113065582-055aae80-91b1-11eb-8ade-2b58e6d81883.gif[] +// ![Rename](https://user-images.githubusercontent.com/48062697/113065582-055aae80-91b1-11eb-8ade-2b58e6d81883.gif) pub(crate) fn rename( db: &RootDatabase, position: FilePosition, diff --git a/crates/ide/src/runnables.rs b/crates/ide/src/runnables.rs index 0181c6b8e456..1f9860baad10 100644 --- a/crates/ide/src/runnables.rs +++ b/crates/ide/src/runnables.rs @@ -113,12 +113,11 @@ impl Runnable { // location**. Super useful for repeatedly running just a single test. Do bind this // to a shortcut! // -// |=== -// | Editor | Action Name +// | Editor | Action Name | +// |---------|----------| +// | VS Code | **rust-analyzer: Run** | // -// | VS Code | **rust-analyzer: Run** -// |=== -// image::https://user-images.githubusercontent.com/48062697/113065583-055aae80-91b1-11eb-958f-d67efcaf6a2f.gif[] +// ![Run](https://user-images.githubusercontent.com/48062697/113065583-055aae80-91b1-11eb-958f-d67efcaf6a2f.gif) pub(crate) fn runnables(db: &RootDatabase, file_id: FileId) -> Vec { let sema = Semantics::new(db); @@ -199,11 +198,9 @@ pub(crate) fn runnables(db: &RootDatabase, file_id: FileId) -> Vec { // - Right-click on the selected item. The context menu opens. // - Select **Peek related tests** // -// |=== -// | Editor | Action Name -// -// | VS Code | **rust-analyzer: Peek related tests** -// |=== +// | Editor | Action Name | +// |---------|----------| +// | VS Code | **rust-analyzer: Peek related tests** | pub(crate) fn related_tests( db: &RootDatabase, position: FilePosition, diff --git a/crates/ide/src/shuffle_crate_graph.rs b/crates/ide/src/shuffle_crate_graph.rs index 2d86627643d7..04015bb60899 100644 --- a/crates/ide/src/shuffle_crate_graph.rs +++ b/crates/ide/src/shuffle_crate_graph.rs @@ -9,11 +9,9 @@ use ide_db::{ // // Randomizes all crate IDs in the crate graph, for debugging. // -// |=== -// | Editor | Action Name -// -// | VS Code | **rust-analyzer: Shuffle Crate Graph** -// |=== +// | Editor | Action Name | +// |---------|-------------| +// | VS Code | **rust-analyzer: Shuffle Crate Graph** | pub(crate) fn shuffle_crate_graph(db: &mut RootDatabase) { let crate_graph = db.crate_graph(); diff --git a/crates/ide/src/status.rs b/crates/ide/src/status.rs index f4d0387440d4..bbea23cf21a1 100644 --- a/crates/ide/src/status.rs +++ b/crates/ide/src/status.rs @@ -26,12 +26,11 @@ fn macro_syntax_tree_stats(db: &RootDatabase) -> SyntaxTreeStats { // // Shows internal statistic about memory usage of rust-analyzer. // -// |=== -// | Editor | Action Name +// | Editor | Action Name | +// |---------|-------------| +// | VS Code | **rust-analyzer: Status** | // -// | VS Code | **rust-analyzer: Status** -// |=== -// image::https://user-images.githubusercontent.com/48062697/113065584-05f34500-91b1-11eb-98cc-5c196f76be7f.gif[] +// ![Status](https://user-images.githubusercontent.com/48062697/113065584-05f34500-91b1-11eb-98cc-5c196f76be7f.gif) pub(crate) fn status(db: &RootDatabase, file_id: Option) -> String { let mut buf = String::new(); format_to!(buf, "{}\n", FileTextQuery.in_db(db).entries::()); diff --git a/crates/ide/src/syntax_highlighting.rs b/crates/ide/src/syntax_highlighting.rs index 50371d620eb2..66a83ef941ab 100644 --- a/crates/ide/src/syntax_highlighting.rs +++ b/crates/ide/src/syntax_highlighting.rs @@ -66,113 +66,102 @@ pub struct HighlightConfig { // The general rule is that a reference to an entity gets colored the same way as the entity itself. // We also give special modifier for `mut` and `&mut` local variables. // -// -// .Token Tags +// ## Token Tags // // Rust-analyzer currently emits the following token tags: // -// - For items: -// + -// [horizontal] -// attribute:: Emitted for attribute macros. -// enum:: Emitted for enums. -// function:: Emitted for free-standing functions. -// derive:: Emitted for derive macros. -// macro:: Emitted for function-like macros. -// method:: Emitted for associated functions, also knowns as methods. -// namespace:: Emitted for modules. -// struct:: Emitted for structs. -// trait:: Emitted for traits. -// typeAlias:: Emitted for type aliases and `Self` in `impl`s. -// union:: Emitted for unions. +// ### For items: +// +// * **attribute** Emitted for attribute macros. +// * **enum** Emitted for enums. +// * **function** Emitted for free-standing functions. +// * **derive** Emitted for derive macros. +// * **macro** Emitted for function-like macros. +// * **method** Emitted for associated functions, also knowns as methods. +// * **namespace** Emitted for modules. +// * **struct** Emitted for structs. +// * **trait** Emitted for traits. +// * **typeAlias** Emitted for type aliases and `Self` in `impl`s. +// * **union** Emitted for unions. // -// - For literals: -// + -// [horizontal] -// boolean:: Emitted for the boolean literals `true` and `false`. -// character:: Emitted for character literals. -// number:: Emitted for numeric literals. -// string:: Emitted for string literals. -// escapeSequence:: Emitted for escaped sequences inside strings like `\n`. -// formatSpecifier:: Emitted for format specifiers `{:?}` in `format!`-like macros. +// ### For literals: // -// - For operators: -// + -// [horizontal] -// operator:: Emitted for general operators. -// arithmetic:: Emitted for the arithmetic operators `+`, `-`, `*`, `/`, `+=`, `-=`, `*=`, `/=`. -// bitwise:: Emitted for the bitwise operators `|`, `&`, `!`, `^`, `|=`, `&=`, `^=`. -// comparison:: Emitted for the comparison operators `>`, `<`, `==`, `>=`, `<=`, `!=`. -// logical:: Emitted for the logical operators `||`, `&&`, `!`. +// * **boolean** Emitted for the boolean literals `true` and `false`. +// * **character** Emitted for character literals. +// * **number** Emitted for numeric literals. +// * **string** Emitted for string literals. +// * **escapeSequence** Emitted for escaped sequences inside strings like `\n`. +// * **formatSpecifier** Emitted for format specifiers `{:?}` in `format!`-like macros. // -// - For punctuation: -// + -// [horizontal] -// punctuation:: Emitted for general punctuation. -// attributeBracket:: Emitted for attribute invocation brackets, that is the `#[` and `]` tokens. -// angle:: Emitted for `<>` angle brackets. -// brace:: Emitted for `{}` braces. -// bracket:: Emitted for `[]` brackets. -// parenthesis:: Emitted for `()` parentheses. -// colon:: Emitted for the `:` token. -// comma:: Emitted for the `,` token. -// dot:: Emitted for the `.` token. -// semi:: Emitted for the `;` token. -// macroBang:: Emitted for the `!` token in macro calls. +// ### For operators: // -// //- +// * **operator** Emitted for general operators. +// * **arithmetic** Emitted for the arithmetic operators `+`, `-`, `*`, `/`, `+=`, `-=`, `*=`, `/=`. +// * **bitwise** Emitted for the bitwise operators `|`, `&`, `!`, `^`, `|=`, `&=`, `^=`. +// * **comparison** Emitted for the comparison operators `>`, `<`, `==`, `>=`, `<=`, `!=`. +// * **logical** Emitted for the logical operators `||`, `&&`, `!`. // -// [horizontal] -// builtinAttribute:: Emitted for names to builtin attributes in attribute path, the `repr` in `#[repr(u8)]` for example. -// builtinType:: Emitted for builtin types like `u32`, `str` and `f32`. -// comment:: Emitted for comments. -// constParameter:: Emitted for const parameters. -// deriveHelper:: Emitted for derive helper attributes. -// enumMember:: Emitted for enum variants. -// generic:: Emitted for generic tokens that have no mapping. -// keyword:: Emitted for keywords. -// label:: Emitted for labels. -// lifetime:: Emitted for lifetimes. -// parameter:: Emitted for non-self function parameters. -// property:: Emitted for struct and union fields. -// selfKeyword:: Emitted for the self function parameter and self path-specifier. -// selfTypeKeyword:: Emitted for the Self type parameter. -// toolModule:: Emitted for tool modules. -// typeParameter:: Emitted for type parameters. -// unresolvedReference:: Emitted for unresolved references, names that rust-analyzer can't find the definition of. -// variable:: Emitted for locals, constants and statics. +// ### For punctuation: // +// * **punctuation** Emitted for general punctuation. +// * **attributeBracket** Emitted for attribute invocation brackets, that is the `#[` and `]` tokens. +// * **angle** Emitted for `<>` angle brackets. +// * **brace** Emitted for `{}` braces. +// * **bracket** Emitted for `[]` brackets. +// * **parenthesis** Emitted for `()` parentheses. +// * **colon** Emitted for the `:` token. +// * **comma** Emitted for the `,` token. +// * **dot** Emitted for the `.` token. +// * **semi** Emitted for the `;` token. +// * **macroBang** Emitted for the `!` token in macro calls. // -// .Token Modifiers +// * **builtinAttribute** Emitted for names to builtin attributes in attribute path, the `repr` in `#[repr(u8)]` for example. +// * **builtinType** Emitted for builtin types like `u32`, `str` and `f32`. +// * **comment** Emitted for comments. +// * **constParameter** Emitted for const parameters. +// * **deriveHelper** Emitted for derive helper attributes. +// * **enumMember** Emitted for enum variants. +// * **generic** Emitted for generic tokens that have no mapping. +// * **keyword** Emitted for keywords. +// * **label** Emitted for labels. +// * **lifetime** Emitted for lifetimes. +// * **parameter** Emitted for non-self function parameters. +// * **property** Emitted for struct and union fields. +// * **selfKeyword** Emitted for the self function parameter and self path-specifier. +// * **selfTypeKeyword** Emitted for the Self type parameter. +// * **toolModule** Emitted for tool modules. +// * **typeParameter** Emitted for type parameters. +// * **unresolvedReference** Emitted for unresolved references, names that rust-analyzer can't find the definition of. +// * **variable** Emitted for locals, constants and statics. +// +// ## Token Modifiers // // Token modifiers allow to style some elements in the source code more precisely. // // Rust-analyzer currently emits the following token modifiers: // -// [horizontal] -// async:: Emitted for async functions and the `async` and `await` keywords. -// attribute:: Emitted for tokens inside attributes. -// callable:: Emitted for locals whose types implements one of the `Fn*` traits. -// constant:: Emitted for consts. -// consuming:: Emitted for locals that are being consumed when use in a function call. -// controlFlow:: Emitted for control-flow related tokens, this includes the `?` operator. -// crateRoot:: Emitted for crate names, like `serde` and `crate`. -// declaration:: Emitted for names of definitions, like `foo` in `fn foo() {}`. -// defaultLibrary:: Emitted for items from built-in crates (std, core, alloc, test and proc_macro). -// documentation:: Emitted for documentation comments. -// injected:: Emitted for doc-string injected highlighting like rust source blocks in documentation. -// intraDocLink:: Emitted for intra doc links in doc-strings. -// library:: Emitted for items that are defined outside of the current crate. -// mutable:: Emitted for mutable locals and statics as well as functions taking `&mut self`. -// public:: Emitted for items that are from the current crate and are `pub`. -// reference:: Emitted for locals behind a reference and functions taking `self` by reference. -// static:: Emitted for "static" functions, also known as functions that do not take a `self` param, as well as statics and consts. -// trait:: Emitted for associated trait items. -// unsafe:: Emitted for unsafe operations, like unsafe function calls, as well as the `unsafe` token. -// +// * **async** Emitted for async functions and the `async` and `await` keywords. +// * **attribute** Emitted for tokens inside attributes. +// * **callable** Emitted for locals whose types implements one of the `Fn*` traits. +// * **constant** Emitted for consts. +// * **consuming** Emitted for locals that are being consumed when use in a function call. +// * **controlFlow** Emitted for control-flow related tokens, this includes the `?` operator. +// * **crateRoot** Emitted for crate names, like `serde` and `crate`. +// * **declaration** Emitted for names of definitions, like `foo` in `fn foo() {}`. +// * **defaultLibrary** Emitted for items from built-in crates (std, core, alloc, test and proc_macro). +// * **documentation** Emitted for documentation comments. +// * **injected** Emitted for doc-string injected highlighting like rust source blocks in documentation. +// * **intraDocLink** Emitted for intra doc links in doc-strings. +// * **library** Emitted for items that are defined outside of the current crate. +// * **mutable** Emitted for mutable locals and statics as well as functions taking `&mut self`. +// * **public** Emitted for items that are from the current crate and are `pub`. +// * **reference** Emitted for locals behind a reference and functions taking `self` by reference. +// * **static** Emitted for "static" functions, also known as functions that do not take a `self` param, as well as statics and consts. +// * **trait** Emitted for associated trait items. +// * **unsafe** Emitted for unsafe operations, like unsafe function calls, as well as the `unsafe` token. // -// image::https://user-images.githubusercontent.com/48062697/113164457-06cfb980-9239-11eb-819b-0f93e646acf8.png[] -// image::https://user-images.githubusercontent.com/48062697/113187625-f7f50100-9250-11eb-825e-91c58f236071.png[] +// ![Semantic Syntax Highlighting 1](https://user-images.githubusercontent.com/48062697/113164457-06cfb980-9239-11eb-819b-0f93e646acf8.png) +// ![Semantic Syntax Highlighting 2](https://user-images.githubusercontent.com/48062697/113187625-f7f50100-9250-11eb-825e-91c58f236071.png) pub(crate) fn highlight( db: &RootDatabase, config: HighlightConfig, diff --git a/crates/ide/src/syntax_tree.rs b/crates/ide/src/syntax_tree.rs index 4256fea0f81e..67f2167ffb50 100644 --- a/crates/ide/src/syntax_tree.rs +++ b/crates/ide/src/syntax_tree.rs @@ -9,12 +9,11 @@ use syntax::{ // Shows the parse tree of the current file. It exists mostly for debugging // rust-analyzer itself. // -// |=== -// | Editor | Action Name +// | Editor | Action Name | +// |---------|-------------| +// | VS Code | **rust-analyzer: Show Syntax Tree** | // -// | VS Code | **rust-analyzer: Show Syntax Tree** -// |=== -// image::https://user-images.githubusercontent.com/48062697/113065586-068bdb80-91b1-11eb-9507-fee67f9f45a0.gif[] +// ![Show Syntax Tree](https://user-images.githubusercontent.com/48062697/113065586-068bdb80-91b1-11eb-9507-fee67f9f45a0.gif) pub(crate) fn syntax_tree( db: &RootDatabase, file_id: FileId, diff --git a/crates/ide/src/typing.rs b/crates/ide/src/typing.rs index 9118f3c699c0..19325ddb6c95 100644 --- a/crates/ide/src/typing.rs +++ b/crates/ide/src/typing.rs @@ -53,13 +53,12 @@ struct ExtendedTextEdit { // VS Code:: // // Add the following to `settings.json`: -// [source,json] -// ---- +// ```json // "editor.formatOnType": true, -// ---- +// ``` // -// image::https://user-images.githubusercontent.com/48062697/113166163-69758500-923a-11eb-81ee-eb33ec380399.gif[] -// image::https://user-images.githubusercontent.com/48062697/113171066-105c2000-923f-11eb-87ab-f4a263346567.gif[] +// ![On Typing Assists 1](https://user-images.githubusercontent.com/48062697/113166163-69758500-923a-11eb-81ee-eb33ec380399.gif) +// ![On Typing Assists 2](https://user-images.githubusercontent.com/48062697/113171066-105c2000-923f-11eb-87ab-f4a263346567.gif) pub(crate) fn on_char_typed( db: &RootDatabase, position: FilePosition, diff --git a/crates/ide/src/typing/on_enter.rs b/crates/ide/src/typing/on_enter.rs index 48c1713270b6..fd620effb8ef 100644 --- a/crates/ide/src/typing/on_enter.rs +++ b/crates/ide/src/typing/on_enter.rs @@ -15,12 +15,12 @@ use text_edit::TextEdit; // Feature: On Enter // -// rust-analyzer can override kbd:[Enter] key to make it smarter: +// rust-analyzer can override Enter key to make it smarter: // -// - kbd:[Enter] inside triple-slash comments automatically inserts `///` -// - kbd:[Enter] in the middle or after a trailing space in `//` inserts `//` -// - kbd:[Enter] inside `//!` doc comments automatically inserts `//!` -// - kbd:[Enter] after `{` indents contents and closing `}` of single-line block +// - Enter inside triple-slash comments automatically inserts `///` +// - Enter in the middle or after a trailing space in `//` inserts `//` +// - Enter inside `//!` doc comments automatically inserts `//!` +// - Enter after `{` indents contents and closing `}` of single-line block // // This action needs to be assigned to shortcut explicitly. // @@ -31,26 +31,26 @@ use text_edit::TextEdit; // VS Code:: // // Add the following to `keybindings.json`: -// [source,json] -// ---- +// +// ```json // { // "key": "Enter", // "command": "rust-analyzer.onEnter", // "when": "editorTextFocus && !suggestWidgetVisible && editorLangId == rust" // } -// ---- +// ``` // // When using the Vim plugin: -// [source,json] -// ---- +// +// ```json // { // "key": "Enter", // "command": "rust-analyzer.onEnter", // "when": "editorTextFocus && !suggestWidgetVisible && editorLangId == rust && vim.mode == 'Insert'" // } -// ---- +// ``` // -// image::https://user-images.githubusercontent.com/48062697/113065578-04c21800-91b1-11eb-82b8-22b8c481e645.gif[] +// ![On Enter](https://user-images.githubusercontent.com/48062697/113065578-04c21800-91b1-11eb-82b8-22b8c481e645.gif) pub(crate) fn on_enter(db: &RootDatabase, position: FilePosition) -> Option { let parse = db.parse(position.file_id); let file = parse.tree(); diff --git a/crates/ide/src/view_crate_graph.rs b/crates/ide/src/view_crate_graph.rs index 17a1e385b772..acf14ded9248 100644 --- a/crates/ide/src/view_crate_graph.rs +++ b/crates/ide/src/view_crate_graph.rs @@ -14,11 +14,9 @@ use stdx::hash::NoHashHashSet; // // Only workspace crates are included, no crates.io dependencies or sysroot crates. // -// |=== -// | Editor | Action Name -// -// | VS Code | **rust-analyzer: View Crate Graph** -// |=== +// | Editor | Action Name | +// |---------|-------------| +// | VS Code | **rust-analyzer: View Crate Graph** | pub(crate) fn view_crate_graph(db: &RootDatabase, full: bool) -> Result { let crate_graph = db.crate_graph(); let crates_to_render = crate_graph diff --git a/crates/ide/src/view_hir.rs b/crates/ide/src/view_hir.rs index d2bbbf6d26ab..4f399594b235 100644 --- a/crates/ide/src/view_hir.rs +++ b/crates/ide/src/view_hir.rs @@ -5,12 +5,11 @@ use syntax::{algo::find_node_at_offset, ast, AstNode}; // Feature: View Hir // -// |=== -// | Editor | Action Name +// | Editor | Action Name | +// |---------|-------------| +// | VS Code | **rust-analyzer: View Hir** | // -// | VS Code | **rust-analyzer: View Hir** -// |=== -// image::https://user-images.githubusercontent.com/48062697/113065588-068bdb80-91b1-11eb-9a78-0b4ef1e972fb.gif[] +// ![View Hir](https://user-images.githubusercontent.com/48062697/113065588-068bdb80-91b1-11eb-9a78-0b4ef1e972fb.gif) pub(crate) fn view_hir(db: &RootDatabase, position: FilePosition) -> String { body_hir(db, position).unwrap_or_else(|| "Not inside a function body".to_string()) } diff --git a/crates/ide/src/view_item_tree.rs b/crates/ide/src/view_item_tree.rs index 9c1f93356ee2..694f0949eab8 100644 --- a/crates/ide/src/view_item_tree.rs +++ b/crates/ide/src/view_item_tree.rs @@ -6,11 +6,9 @@ use ide_db::RootDatabase; // // Displays the ItemTree of the currently open file, for debugging. // -// |=== -// | Editor | Action Name -// -// | VS Code | **rust-analyzer: Debug ItemTree** -// |=== +// | Editor | Action Name | +// |--------|-------------| +// | VS Code | **rust-analyzer: Debug ItemTree** | pub(crate) fn view_item_tree(db: &RootDatabase, file_id: FileId) -> String { db.file_item_tree(file_id.into()).pretty_print() } diff --git a/crates/rust-analyzer/src/config.rs b/crates/rust-analyzer/src/config.rs index 5d99d2fb1193..ddf5a2a905db 100644 --- a/crates/rust-analyzer/src/config.rs +++ b/crates/rust-analyzer/src/config.rs @@ -2001,21 +2001,9 @@ fn manual(fields: &[(&'static str, &'static str, &[&str], &str)]) -> String { let name = format!("rust-analyzer.{}", field.replace('_', ".")); let doc = doc_comment_to_string(*doc); if default.contains('\n') { - format!( - r#"[[{}]]{}:: -+ --- -Default: ----- -{} ----- -{} --- -"#, - name, name, default, doc - ) + format!("## **{}**\n\n default:\n```\n{}\n```\n\n{}\n\n", name, default, doc) } else { - format!("[[{}]]{} (default: `{}`)::\n+\n--\n{}--\n", name, name, default, doc) + format!("## **{}**\n\n (default: `{}`)\n\n{}\n\n", name, default, doc) } }) .collect::() @@ -2089,7 +2077,7 @@ mod tests { #[test] fn generate_config_documentation() { - let docs_path = project_root().join("docs/user/generated_config.adoc"); + let docs_path = project_root().join("docs/manual/src/generated_config.md"); let expected = ConfigData::manual(); ensure_file_contents(&docs_path, &expected); } diff --git a/crates/rust-analyzer/tests/slow-tests/sourcegen.rs b/crates/rust-analyzer/tests/slow-tests/sourcegen.rs index e6ac018a05fe..253e2ba3578d 100644 --- a/crates/rust-analyzer/tests/slow-tests/sourcegen.rs +++ b/crates/rust-analyzer/tests/slow-tests/sourcegen.rs @@ -8,12 +8,12 @@ fn sourcegen_feature_docs() { let contents = features.into_iter().map(|it| it.to_string()).collect::>().join("\n\n"); let contents = format!( " -// Generated file, do not edit by hand, see `sourcegen_feature_docs`. + {} ", contents.trim() ); - let dst = sourcegen::project_root().join("docs/user/generated_features.adoc"); + let dst = sourcegen::project_root().join("docs/manual/src/generated_features.md"); fs::write(&dst, &contents).unwrap(); } @@ -75,6 +75,6 @@ fn is_valid_feature_name(feature: &str) -> Result<(), String> { impl fmt::Display for Feature { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - writeln!(f, "=== {}\n**Source:** {}\n{}", self.id, self.location, self.doc) + writeln!(f, "## {}\n**Source:** {}\n{}", self.id, self.location, self.doc) } } diff --git a/crates/rust-analyzer/tests/slow-tests/tidy.rs b/crates/rust-analyzer/tests/slow-tests/tidy.rs index 58099a58de05..629d68b0f7e5 100644 --- a/crates/rust-analyzer/tests/slow-tests/tidy.rs +++ b/crates/rust-analyzer/tests/slow-tests/tidy.rs @@ -41,8 +41,11 @@ fn check_lsp_extensions_docs() { }; let actual_hash = { - let lsp_extensions_md = - sh.read_file(sourcegen::project_root().join("docs/dev/lsp-extensions.md")).unwrap(); + let lsp_extensions_md = sh + .read_file( + sourcegen::project_root().join("docs/manual/src/contributing/lsp-extensions.md"), + ) + .unwrap(); let text = lsp_extensions_md .lines() .find_map(|line| line.strip_prefix("lsp_ext.rs hash:")) diff --git a/crates/sourcegen/src/lib.rs b/crates/sourcegen/src/lib.rs index 4e0ee63f32f2..736a619a52dd 100644 --- a/crates/sourcegen/src/lib.rs +++ b/crates/sourcegen/src/lib.rs @@ -127,10 +127,10 @@ impl fmt::Display for Location { let name = self.file.file_name().unwrap(); write!( f, - "https://github.com/rust-lang/rust-analyzer/blob/master/{}#L{}[{}]", + "[{}](https://github.com/rust-lang/rust-analyzer/blob/master/{}#L{})", + name.to_str().unwrap(), path, self.line, - name.to_str().unwrap() ) } } diff --git a/docs/manual/book.toml b/docs/manual/book.toml new file mode 100644 index 000000000000..b6d8ab94ef76 --- /dev/null +++ b/docs/manual/book.toml @@ -0,0 +1,39 @@ +[book] +authors = ["The rust-analyzer developers"] +language = "en" +multilingual = false +src = "src" +title = "The Rust Analyzer Book" + +[rust] +edition = "2021" + +[output.html] +edit-url-template = "https://github.com/rust-analyzer/rust-analyzer/edit/master/manual/{path}" +git-repository-url = "https://github.com/rust-analyzer/rust-analyzer/tree/master/manual" +mathjax-support = true +site-url = "/rust-analyzer/" + +[output.html.playground] +editable = true +line-numbers = true + +[output.html.search] +boost-hierarchy = 2 +boost-paragraph = 1 +boost-title = 2 +expand = true +heading-split-level = 2 +limit-results = 20 +use-boolean-and = true + +[ouput.html.redirect] +"/manual.html" = "/index.html" + +[output.html.fold] +enable = true + +[preprocessor.toc] +command = "mdbook-toc" +renderer = ["html"] +max-level = 2 diff --git a/docs/manual/src/README.md b/docs/manual/src/README.md new file mode 100644 index 000000000000..1c3dbffdc3bd --- /dev/null +++ b/docs/manual/src/README.md @@ -0,0 +1,20 @@ + +![rust-analyzer](https://rust-analyzer.github.io/assets/rust-analyzer.svg) + +At its core, rust-analyzer is a **library** for semantic analysis of +Rust code as it changes over time. This manual focuses on a specific +usage of the library — running it as part of a server that implements +the [Language Server +Protocol](https://microsoft.github.io/language-server-protocol/) (LSP). +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. + +This manual is written in [Markdown](https://commonmark.org/help/) and created using +[mdbook](https://github.com/rust-lang/mdBook). Some content is generated +from source. Please see the [Documentation](contributing/documentation.md) +section of the [Contributing](contributing/README.md) guide for more information. + +If you have questions about using rust-analyzer, please ask them in the +[“IDEs and Editors”](https://users.rust-lang.org/c/ide/14) topic of Rust +users forum. diff --git a/docs/manual/src/SUMMARY.md b/docs/manual/src/SUMMARY.md new file mode 100644 index 000000000000..2e58d2431e9d --- /dev/null +++ b/docs/manual/src/SUMMARY.md @@ -0,0 +1,24 @@ +# Summary + +# rust-analyzer + +- [Introduction](README.md) +- [Installation](installation.md) +- [Troubleshooting](troubleshooting.md) +- [Configuration](configuration.md) +- [Non-Cargo Based Projects](non_cargo_based_projects.md) +- [Security](security.md) +- [Privacy](privacy.md) +- [Features](features.md) +- [Assists](assists.md) +- [Diagnostics](diagnostics.md) +- [Editor Features](editor_features.md) +- [Contributing](contributing/README.md) + - [Guide](contributing/guide.md) + - [Architecture](contributing/architecture.md) + - [Debugging](contributing/debugging.md) + - [LSP Extensions](contributing/lsp-extensions.md) + - [Syntax](contributing/syntax.md) + - [Style](contributing/style.md) + - [Documentation](contributing/documentation.md) + \ No newline at end of file diff --git a/docs/manual/src/assists.md b/docs/manual/src/assists.md new file mode 100644 index 000000000000..16a6c8e2b41b --- /dev/null +++ b/docs/manual/src/assists.md @@ -0,0 +1,10 @@ +# Assists (Code Actions) + +Assists, or code actions, are small local refactorings, available in a +particular context. They are usually triggered by a shortcut or by +clicking a light bulb icon in the editor. Cursor position or selection +is signified by `┃` character. + + + +{{#include generated_assists.md:2:}} diff --git a/docs/manual/src/configuration.md b/docs/manual/src/configuration.md new file mode 100644 index 000000000000..554e2ac3bbe4 --- /dev/null +++ b/docs/manual/src/configuration.md @@ -0,0 +1,55 @@ +# Configuration + +**Source:** +[config.rs](https://github.com/rust-lang/rust-analyzer/blob/master/crates/rust-analyzer/src/config.rs) + +The [Installation](#_installation) section contains details on +configuration for some of the editors. 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. + +Some clients, such as [VS Code](#vs-code) or [COC plugin in +Vim](#coc-rust-analyzer) provide `rust-analyzer` specific configuration +UIs. Others may require you to know a bit more about the interaction +with `rust-analyzer`. + +For the later category, it might help to know that the initial +configuration is specified as a value of the `initializationOptions` +field of the [`InitializeParams` message, in the LSP +protocol](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#initialize). +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. Name of the setting, ignoring the `rust-analyzer.` prefix, +is used as a path, and value of the setting becomes the JSON property +value. + +For example, a very common configuration is to enable proc-macro +support, can be achieved by sending this JSON: + +``` json +{ + "cargo": { + "buildScripts": { + "enable": true, + }, + }, + "procMacro": { + "enable": true, + } +} +``` + +Please consult your editor’s documentation to learn more about how to +configure [LSP +servers](https://microsoft.github.io/language-server-protocol/). + +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. Logs should show both the JSON that +`rust-analyzer` sees as well as the updated config. + +This is the list of config options `rust-analyzer` supports: + + + +{{#include generated_config.md}} \ No newline at end of file diff --git a/docs/dev/README.md b/docs/manual/src/contributing/README.md similarity index 99% rename from docs/dev/README.md rename to docs/manual/src/contributing/README.md index c7f152acc266..4ac75b4bbfd9 100644 --- a/docs/dev/README.md +++ b/docs/manual/src/contributing/README.md @@ -98,7 +98,7 @@ After I am done with the fix, I use `cargo xtask install --client` to try the ne If I need to fix something in the `rust-analyzer` crate, I feel sad because it's on the boundary between the two processes, and working there is slow. I usually just `cargo xtask install --server` and poke changes from my live environment. Note that this uses `--release`, which is usually faster overall, because loading stdlib into debug version of rust-analyzer takes a lot of time. -To speed things up, sometimes I open a temporary hello-world project which has `"rust-analyzer.cargo.noSysroot": true` in `.code/settings.json`. +To speed things up, sometimes I open a temporary hello-world project which has `"rust-analyzer.cargo.sysroot": null` in `.code/settings.json`. This flag causes rust-analyzer to skip loading the sysroot, which greatly reduces the amount of things rust-analyzer needs to do, and makes printf's more useful. Note that you should only use the `eprint!` family of macros for debugging: stdout is used for LSP communication, and `print!` would break it. diff --git a/docs/dev/architecture.md b/docs/manual/src/contributing/architecture.md similarity index 95% rename from docs/dev/architecture.md rename to docs/manual/src/contributing/architecture.md index c173a239feab..3a52d72bddf2 100644 --- a/docs/dev/architecture.md +++ b/docs/manual/src/contributing/architecture.md @@ -8,18 +8,19 @@ It goes deeper than what is covered in this document, but will take some time to See also these implementation-related blog posts: -* https://rust-analyzer.github.io/blog/2019/11/13/find-usages.html -* https://rust-analyzer.github.io/blog/2020/07/20/three-architectures-for-responsive-ide.html -* https://rust-analyzer.github.io/blog/2020/09/16/challeging-LR-parsing.html -* https://rust-analyzer.github.io/blog/2020/09/28/how-to-make-a-light-bulb.html -* https://rust-analyzer.github.io/blog/2020/10/24/introducing-ungrammar.html +* +* +* +* +* For older, by now mostly outdated stuff, see the [guide](./guide.md) and [another playlist](https://www.youtube.com/playlist?list=PL85XCvVPmGQho7MZkdW-wtPtuJcFpzycE). + ## Bird's Eye View -![](https://user-images.githubusercontent.com/4789492/107129398-0ab70f00-687a-11eb-9bfc-d4eb023aec06.png) +![Bird's Eye View](https://user-images.githubusercontent.com/4789492/107129398-0ab70f00-687a-11eb-9bfc-d4eb023aec06.png) On the highest level, rust-analyzer is a thing which accepts input source code from the client and produces a structured semantic model of the code. @@ -93,9 +94,9 @@ For example, you can extract the set of names defined in a file (for typo correc Rust syntax tree structure and parser. See [RFC](https://github.com/rust-lang/rfcs/pull/2256) and [./syntax.md](./syntax.md) for some design notes. -- [rowan](https://github.com/rust-analyzer/rowan) library is used for constructing syntax trees. -- `ast` provides a type safe API on top of the raw `rowan` tree. -- `ungrammar` description of the grammar, which is used to generate `syntax_kinds` and `ast` modules, using `cargo test -p xtask` command. +* [rowan](https://github.com/rust-analyzer/rowan) library is used for constructing syntax trees. +* `ast` provides a type safe API on top of the raw `rowan` tree. +* `ungrammar` description of the grammar, which is used to generate `syntax_kinds` and `ast` modules, using `cargo test -p xtask` command. Tests for ra_syntax are mostly data-driven. `test_data/parser` contains subdirectories with a bunch of `.rs` (test vectors) and `.txt` files with corresponding syntax trees. @@ -118,8 +119,8 @@ See [#93](https://github.com/rust-lang/rust-analyzer/pull/93) for an example PR **Architecture Invariant:** `syntax` crate is completely independent from the rest of rust-analyzer. It knows nothing about salsa or LSP. This is important because it is possible to make useful tooling using only the syntax tree. -Without semantic information, you don't need to be able to _build_ code, which makes the tooling more robust. -See also https://web.stanford.edu/~mlfbrown/paper.pdf. +Without semantic information, you don't need to be able to *build* code, which makes the tooling more robust. +See also . You can view the `syntax` crate as an entry point to rust-analyzer. `syntax` crate is an **API Boundary**. @@ -186,15 +187,15 @@ If you think about "using rust-analyzer as a library", `hir` crate is most likel It wraps ECS-style internal API into a more OO-flavored API (with an extra `db` argument for each call). **Architecture Invariant:** `hir` provides a static, fully resolved view of the code. -While internal `hir_*` crates _compute_ things, `hir`, from the outside, looks like an inert data structure. +While internal `hir_*` crates *compute* things, `hir`, from the outside, looks like an inert data structure. `hir` also handles the delicate task of going from syntax to the corresponding `hir`. Remember that the mapping here is one-to-many. See `Semantics` type and `source_to_def` module. Note in particular a curious recursive structure in `source_to_def`. -We first resolve the parent _syntax_ node to the parent _hir_ element. -Then we ask the _hir_ parent what _syntax_ children does it have. +We first resolve the parent *syntax* node to the parent *hir* element. +Then we ask the *hir* parent what *syntax* children does it have. Then we look for our node in the set of children. This is the heart of many IDE features, like goto definition, which start with figuring out the hir node at the cursor. @@ -221,9 +222,9 @@ Internally, `ide` is split across several crates. `ide_assists`, `ide_completion `ide_db` implements common IDE functionality (notably, reference search is implemented here). The `ide` contains a public API/façade, as well as implementation for a plethora of smaller features. -**Architecture Invariant:** `ide` crate strives to provide a _perfect_ API. +**Architecture Invariant:** `ide` crate strives to provide a *perfect* API. Although at the moment it has only one consumer, the LSP server, LSP *does not* influence its API design. -Instead, we keep in mind a hypothetical _ideal_ client -- an IDE tailored specifically for rust, every nook and cranny of which is packed with Rust-specific goodies. +Instead, we keep in mind a hypothetical *ideal* client -- an IDE tailored specifically for rust, every nook and cranny of which is packed with Rust-specific goodies. ### `crates/rust-analyzer` @@ -425,7 +426,6 @@ There's no additional checks in CI, formatting and tidy tests are run with `carg **Architecture Invariant:** tests do not depend on any kind of external resources, they are perfectly reproducible. - ### Performance Testing TBA, take a look at the `metrics` xtask and `#[test] fn benchmark_xxx()` functions. @@ -472,7 +472,6 @@ It is enabled with `RA_PROFILE='*>50'` env var (log all (`*`) actions which take This is cheap enough to enable in production. - Similarly, we save live object counting (`RA_COUNT=1`). It is not cheap enough to enable in prod, and this is a bug which should be fixed. diff --git a/docs/dev/debugging.md b/docs/manual/src/contributing/debugging.md similarity index 75% rename from docs/dev/debugging.md rename to docs/manual/src/contributing/debugging.md index 48caec1d8fa6..be682e6d2463 100644 --- a/docs/dev/debugging.md +++ b/docs/manual/src/contributing/debugging.md @@ -2,12 +2,13 @@ ## Prerequisites -- Install [LLDB](https://lldb.llvm.org/) and the [LLDB Extension](https://marketplace.visualstudio.com/items?itemName=vadimcn.vscode-lldb). -- Open the root folder in VSCode. Here you can access the preconfigured debug setups. +* Install [LLDB](https://lldb.llvm.org/) and the [LLDB Extension](https://marketplace.visualstudio.com/items?itemName=vadimcn.vscode-lldb). +* Open the root folder in VSCode. Here you can access the preconfigured debug setups. Debug options view -- Install all TypeScript dependencies +* Install all TypeScript dependencies + ```bash cd editors/code npm ci @@ -19,11 +20,10 @@ where **only** the `rust-analyzer` extension being debugged is enabled. * To activate the extension you need to open any Rust project folder in `[Extension Development Host]`. - ## Debug TypeScript VSCode extension -- `Run Installed Extension` - runs the extension with the globally installed `rust-analyzer` binary. -- `Run Extension (Debug Build)` - runs extension with the locally built LSP server (`target/debug/rust-analyzer`). +* `Run Installed Extension` - runs the extension with the globally installed `rust-analyzer` binary. +* `Run Extension (Debug Build)` - runs extension with the locally built LSP server (`target/debug/rust-analyzer`). TypeScript debugging is configured to watch your source edits and recompile. To apply changes to an already running debug process, press Ctrl+Shift+P and run the following command in your `[Extension Development Host]` @@ -34,30 +34,31 @@ To apply changes to an already running debug process, press Ctrl+Shift+P + +## The rust-analyzer Manual + +The rust-analyzer Manual is written with Markdown and generated with [mdBook](https://github.com/rust-lang/mdBook). +just markdown, See the mdBook [documentation](https://rust-lang.github.io/mdBook/) for more information. + +## Generated Content + +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. diff --git a/docs/dev/guide.md b/docs/manual/src/contributing/guide.md similarity index 99% rename from docs/dev/guide.md rename to docs/manual/src/contributing/guide.md index 808eb5d10bf4..52ddc8cb40f2 100644 --- a/docs/dev/guide.md +++ b/docs/manual/src/contributing/guide.md @@ -1,5 +1,6 @@ # Guide to rust-analyzer + ## About the guide This guide describes the current state of rust-analyzer as of 2019-01-20 (git @@ -10,6 +11,8 @@ https://youtu.be/ANKBNiSWyfc. [guide-2019-01]: https://github.com/rust-lang/rust-analyzer/tree/guide-2019-01 + + ## The big picture On the highest possible level, rust-analyzer is a stateful component. A client may @@ -40,8 +43,8 @@ terms of files and offsets, and **not** in terms of Rust concepts like structs, traits, etc. The "typed" API with Rust specific types is slightly lower in the stack, we'll talk about it later. -[`AnalysisHost`]: https://github.com/rust-lang/rust-analyzer/blob/guide-2019-01/crates/ide_api/src/lib.rs#L265-L284 -[`Analysis`]: https://github.com/rust-lang/rust-analyzer/blob/guide-2019-01/crates/ide_api/src/lib.rs#L291-L478 +[`AnalysisHost`]: https://github.com/rust-lang/rust-analyzer/blob/guide-2019-01/crates/ra_ide_api/src/lib.rs#L265-L284 +[`Analysis`]: https://github.com/rust-lang/rust-analyzer/blob/guide-2019-01/crates/ra_ide_api/src/lib.rs#L291-L478 The reason for this separation of `Analysis` and `AnalysisHost` is that we want to apply changes "uniquely", but we might also want to fork an `Analysis` and send it to diff --git a/docs/dev/lsp-extensions.md b/docs/manual/src/contributing/lsp-extensions.md similarity index 99% rename from docs/dev/lsp-extensions.md rename to docs/manual/src/contributing/lsp-extensions.md index 6d2c7d7b0634..b52fe1473514 100644 --- a/docs/dev/lsp-extensions.md +++ b/docs/manual/src/contributing/lsp-extensions.md @@ -19,6 +19,8 @@ Requests, which are likely to always remain specific to `rust-analyzer` are unde If you want to be notified about the changes to this document, subscribe to [#4604](https://github.com/rust-lang/rust-analyzer/issues/4604). + + ## UTF-8 offsets rust-analyzer supports clangd's extension for opting into UTF-8 as the coordinate space for offsets (by default, LSP uses UTF-16 offsets). diff --git a/docs/dev/style.md b/docs/manual/src/contributing/style.md similarity index 99% rename from docs/dev/style.md rename to docs/manual/src/contributing/style.md index a80eebd63296..aeaef3c1923c 100644 --- a/docs/dev/style.md +++ b/docs/manual/src/contributing/style.md @@ -1,3 +1,5 @@ +# Style + Our approach to "clean code" is two-fold: * We generally don't block PRs on style changes. @@ -9,7 +11,7 @@ Sending small cleanup PRs (like renaming a single local variable) is encouraged. When reviewing pull requests prefer extending this document to leaving non-reusable comments on the pull request itself. -# General + ## Scale of Changes diff --git a/docs/dev/syntax.md b/docs/manual/src/contributing/syntax.md similarity index 99% rename from docs/dev/syntax.md rename to docs/manual/src/contributing/syntax.md index 30e13701383a..3c46487e5bda 100644 --- a/docs/dev/syntax.md +++ b/docs/manual/src/contributing/syntax.md @@ -4,6 +4,8 @@ This guide describes the current state of syntax trees and parsing in rust-analyzer as of 2020-01-09 ([link to commit](https://github.com/rust-lang/rust-analyzer/tree/cf5bdf464cad7ceb9a67e07985a3f4d3799ec0b6)). + + ## Source Code The things described are implemented in three places diff --git a/docs/manual/src/diagnostics.md b/docs/manual/src/diagnostics.md new file mode 100644 index 000000000000..f34b92afa89b --- /dev/null +++ b/docs/manual/src/diagnostics.md @@ -0,0 +1,13 @@ +# Diagnostics + +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. 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.experimental.enable` or +`rust-analyzer.diagnostics.disabled` settings. + + + +{{#include generated_diagnostics.md:2:}} diff --git a/docs/manual/src/editor_features.md b/docs/manual/src/editor_features.md new file mode 100644 index 000000000000..bbdecaf01256 --- /dev/null +++ b/docs/manual/src/editor_features.md @@ -0,0 +1,179 @@ +# Editor Features + +## VS Code + +### Color configurations + +It is possible to change the foreground/background color and font +family/size of inlay hints. Just add this to your `settings.json`: + +``` jsonc +{ + "editor.inlayHints.fontFamily": "Courier New", + "editor.inlayHints.fontSize": 11, + + "workbench.colorCustomizations": { + // Name of the theme you are currently using + "[Default Dark+]": { + "editorInlayHint.foreground": "#868686f0", + "editorInlayHint.background": "#3d3d3d48", + + // Overrides for specific kinds of inlay hints + "editorInlayHint.typeForeground": "#fdb6fdf0", + "editorInlayHint.parameterForeground": "#fdb6fdf0", + } + } +} +``` + +### Semantic style customizations + +You can customize the look of different semantic elements in the source +code. For example, mutable bindings are underlined by default and you +can override this behavior by adding the following section to your +`settings.json`: + +``` jsonc +{ + "editor.semanticTokenColorCustomizations": { + "rules": { + "*.mutable": { + "fontStyle": "", // underline is the default + }, + } + }, +} +``` + +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`: + +``` jsonc +{ + "editor.semanticTokenColorCustomizations": { + "rules": { + "operator.unsafe": "#ff6600", + "function.unsafe": "#ff6600", + "method.unsafe": "#ff6600" + } + }, +} +``` + +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: + +``` jsonc +{ + "editor.semanticTokenColorCustomizations": { + "rules": { + "operator.unsafe": "#ff6600" + }, + "[Ayu Light]": { + "rules": { + "operator.unsafe": "#572300" + } + } + }, +} +``` + +Make sure you include the brackets around the theme name. For example, +use `"[Ayu Light]"` to customize the theme Ayu Light. + +### Special `when` clause context for keybindings. + +You may use `inRustProject` context to configure keybindings for rust +projects only. For example: + +``` json +{ + "key": "ctrl+alt+d", + "command": "rust-analyzer.openDocs", + "when": "inRustProject" +} +``` + +More about `when` clause contexts +[here](https://code.visualstudio.com/docs/getstarted/keybindings#_when-clause-contexts). + +### Setting runnable environment variables + +You can use "rust-analyzer.runnableEnv" setting to define runnable +environment-specific substitution variables. The simplest way for all +runnables in a bunch: + +``` jsonc +"rust-analyzer.runnableEnv": { + "RUN_SLOW_TESTS": "1" +} +``` + +Or it is possible to specify vars more granularly: + +``` jsonc +"rust-analyzer.runnableEnv": [ + { + // "mask": null, // null mask means that this rule will be applied for all runnables + env: { + "APP_ID": "1", + "APP_DATA": "asdf" + } + }, + { + "mask": "test_name", + "env": { + "APP_ID": "2", // overwrites only APP_ID + } + } +] +``` + +You can use any valid regular expression as a mask. 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. + +### Compiler feedback from external commands + +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. + +To do this you need to create a new [VS Code +Task](https://code.visualstudio.com/docs/editor/tasks) and set +`rust-analyzer.checkOnSave.enable: false` in preferences. + +For example, if you want to run +[`cargo watch`](https://crates.io/crates/cargo-watch) instead, you might +add the following to `.vscode/tasks.json`: + +``` json +{ + "label": "Watch", + "group": "build", + "type": "shell", + "command": "cargo watch", + "problemMatcher": "$rustc-watch", + "isBackground": true +} +``` + +### Live Share + +VS Code Live Share has partial support for rust-analyzer. + +Live Share *requires* the official Microsoft build of VS Code, OSS +builds will not work correctly. + +The host’s rust-analyzer instance will be shared with all guests joining +the session. The guests do not have to have the rust-analyzer extension +installed for this to work. + +If you are joining a Live Share session and *do* have rust-analyzer +installed locally, commands from the command palette will not work +correctly since they will attempt to communicate with the local server. diff --git a/docs/manual/src/features.md b/docs/manual/src/features.md new file mode 100644 index 000000000000..b4d2ce86261c --- /dev/null +++ b/docs/manual/src/features.md @@ -0,0 +1,5 @@ +# Features + + + +{{#include generated_features.md}} \ No newline at end of file diff --git a/docs/manual/src/generated_diagnostics.md b/docs/manual/src/generated_diagnostics.md new file mode 100644 index 000000000000..68c24e4ef25b --- /dev/null +++ b/docs/manual/src/generated_diagnostics.md @@ -0,0 +1,145 @@ +//! Generated by `sourcegen_diagnostic_docs`, do not edit by hand. + +## break-outside-of-loop +**Source:** [break_outside_of_loop.rs](https://github.com/rust-lang/rust-analyzer/blob/master/crates/ide-diagnostics/src/handlers/break_outside_of_loop.rs#L3) + +This diagnostic is triggered if the `break` keyword is used outside of a loop. + + +## inactive-code +**Source:** [inactive_code.rs](https://github.com/rust-lang/rust-analyzer/blob/master/crates/ide-diagnostics/src/handlers/inactive_code.rs#L6) + +This diagnostic is shown for code with inactive `#[cfg]` attributes. + + +## incorrect-ident-case +**Source:** [incorrect_case.rs](https://github.com/rust-lang/rust-analyzer/blob/master/crates/ide-diagnostics/src/handlers/incorrect_case.rs#L13) + +This diagnostic is triggered if an item name doesn't follow https://doc.rust-lang.org/1.0.0/style/style/naming/README.html[Rust naming convention]. + + +## invalid-derive-target +**Source:** [invalid_derive_target.rs](https://github.com/rust-lang/rust-analyzer/blob/master/crates/ide-diagnostics/src/handlers/invalid_derive_target.rs#L3) + +This diagnostic is shown when the derive attribute is used on an item other than a `struct`, +`enum` or `union`. + + +## macro-error +**Source:** [macro_error.rs](https://github.com/rust-lang/rust-analyzer/blob/master/crates/ide-diagnostics/src/handlers/macro_error.rs#L3) + +This diagnostic is shown for macro expansion errors. + + +## malformed-derive +**Source:** [malformed_derive.rs](https://github.com/rust-lang/rust-analyzer/blob/master/crates/ide-diagnostics/src/handlers/malformed_derive.rs#L3) + +This diagnostic is shown when the derive attribute has invalid input. + + +## mismatched-arg-count +**Source:** [mismatched_arg_count.rs](https://github.com/rust-lang/rust-analyzer/blob/master/crates/ide-diagnostics/src/handlers/mismatched_arg_count.rs#L8) + +This diagnostic is triggered if a function is invoked with an incorrect amount of arguments. + + +## missing-fields +**Source:** [missing_fields.rs](https://github.com/rust-lang/rust-analyzer/blob/master/crates/ide-diagnostics/src/handlers/missing_fields.rs#L20) + +This diagnostic is triggered if record lacks some fields that exist in the corresponding structure. + +Example: + +```rust +struct A { a: u8, b: u8 } + +let a = A { a: 10 }; +``` + + +## missing-match-arm +**Source:** [missing_match_arms.rs](https://github.com/rust-lang/rust-analyzer/blob/master/crates/ide-diagnostics/src/handlers/missing_match_arms.rs#L5) + +This diagnostic is triggered if `match` block is missing one or more match arms. + + +## missing-unsafe +**Source:** [missing_unsafe.rs](https://github.com/rust-lang/rust-analyzer/blob/master/crates/ide-diagnostics/src/handlers/missing_unsafe.rs#L3) + +This diagnostic is triggered if an operation marked as `unsafe` is used outside of an `unsafe` function or block. + + +## no-such-field +**Source:** [no_such_field.rs](https://github.com/rust-lang/rust-analyzer/blob/master/crates/ide-diagnostics/src/handlers/no_such_field.rs#L11) + +This diagnostic is triggered if created structure does not have field provided in record. + + +## replace-filter-map-next-with-find-map +**Source:** [replace_filter_map_next_with_find_map.rs](https://github.com/rust-lang/rust-analyzer/blob/master/crates/ide-diagnostics/src/handlers/replace_filter_map_next_with_find_map.rs#L11) + +This diagnostic is triggered when `.filter_map(..).next()` is used, rather than the more concise `.find_map(..)`. + + +## type-mismatch +**Source:** [type_mismatch.rs](https://github.com/rust-lang/rust-analyzer/blob/master/crates/ide-diagnostics/src/handlers/type_mismatch.rs#L11) + +This diagnostic is triggered when the type of an expression does not match +the expected type. + + +## unimplemented-builtin-macro +**Source:** [unimplemented_builtin_macro.rs](https://github.com/rust-lang/rust-analyzer/blob/master/crates/ide-diagnostics/src/handlers/unimplemented_builtin_macro.rs#L3) + +This diagnostic is shown for builtin macros which are not yet implemented by rust-analyzer + + +## unlinked-file +**Source:** [unlinked_file.rs](https://github.com/rust-lang/rust-analyzer/blob/master/crates/ide-diagnostics/src/handlers/unlinked_file.rs#L17) + +This diagnostic is shown for files that are not included in any crate, or files that are part of +crates rust-analyzer failed to discover. The file will not have IDE features available. + + +## unnecessary-braces +**Source:** [useless_braces.rs](https://github.com/rust-lang/rust-analyzer/blob/master/crates/ide-diagnostics/src/handlers/useless_braces.rs#L8) + +Diagnostic for unnecessary braces in `use` items. + + +## unresolved-extern-crate +**Source:** [unresolved_extern_crate.rs](https://github.com/rust-lang/rust-analyzer/blob/master/crates/ide-diagnostics/src/handlers/unresolved_extern_crate.rs#L3) + +This diagnostic is triggered if rust-analyzer is unable to discover referred extern crate. + + +## unresolved-import +**Source:** [unresolved_import.rs](https://github.com/rust-lang/rust-analyzer/blob/master/crates/ide-diagnostics/src/handlers/unresolved_import.rs#L3) + +This diagnostic is triggered if rust-analyzer is unable to resolve a path in +a `use` declaration. + + +## unresolved-macro-call +**Source:** [unresolved_macro_call.rs](https://github.com/rust-lang/rust-analyzer/blob/master/crates/ide-diagnostics/src/handlers/unresolved_macro_call.rs#L3) + +This diagnostic is triggered if rust-analyzer is unable to resolve the path +to a macro in a macro invocation. + + +## unresolved-module +**Source:** [unresolved_module.rs](https://github.com/rust-lang/rust-analyzer/blob/master/crates/ide-diagnostics/src/handlers/unresolved_module.rs#L8) + +This diagnostic is triggered if rust-analyzer is unable to discover referred module. + + +## unresolved-proc-macro +**Source:** [unresolved_proc_macro.rs](https://github.com/rust-lang/rust-analyzer/blob/master/crates/ide-diagnostics/src/handlers/unresolved_proc_macro.rs#L6) + +This diagnostic is shown when a procedural macro can not be found. This usually means that +procedural macro support is simply disabled (and hence is only a weak hint instead of an error), +but can also indicate project setup problems. + +If you are seeing a lot of "proc macro not expanded" warnings, you can add this option to the +`rust-analyzer.diagnostics.disabled` list to prevent them from showing. Alternatively you can +enable support for procedural macros (see `rust-analyzer.procMacro.attributes.enable`). diff --git a/docs/manual/src/installation.md b/docs/manual/src/installation.md new file mode 100644 index 000000000000..77a61e52014c --- /dev/null +++ b/docs/manual/src/installation.md @@ -0,0 +1,543 @@ +# Installation + +In theory, one should be able to just install the [`rust-analyzer` +binary](#rust-analyzer-language-server-binary) and have it automatically +work with any editor. We are not there yet, so some editor specific +setup is required. + +Additionally, rust-analyzer needs the sources of the standard library. +If the source code is not present, rust-analyzer will attempt to install +it automatically. + +To add the sources manually, run the following command: + +```bash +$ rustup component add rust-src +``` + + + +## Toolchain + +Only the latest stable standard library source is officially supported +for use with rust-analyzer. If you are using an older toolchain or have +an override set, rust-analyzer may fail to understand the Rust source. +You will either need to update your toolchain or use an older version of +rust-analyzer that is compatible with your toolchain. + +If you are using an override in your project, you can still force +rust-analyzer to use the stable toolchain via the environment variable +`RUSTUP_TOOLCHAIN`. For example, with VS Code or coc-rust-analyzer: + +``` json +{ "rust-analyzer.server.extraEnv": { "RUSTUP_TOOLCHAIN": "stable" } } +``` + +## VS Code + +This is the best supported editor at the moment. The rust-analyzer +plugin for VS Code is maintained [in +tree](https://github.com/rust-lang/rust-analyzer/tree/master/editors/code). + +You can install the latest release of the plugin from [the +marketplace](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer). + +Note that the plugin may cause conflicts with the [official Rust +plugin](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust). +It is recommended to disable the Rust plugin when using the +rust-analyzer extension. + +By default, the plugin will prompt you to download the matching version +of the server as well: + +![75067008 17502500 54ba 11ea 835a +f92aac50e866](https://user-images.githubusercontent.com/9021944/75067008-17502500-54ba-11ea-835a-f92aac50e866.png) + +
+ +To disable this notification put the following to `settings.json` + +``` json +{ "rust-analyzer.updates.askBeforeDownload": false } +``` + +
+ +The server binary is stored in the extension install directory, which +starts with `rust-lang.rust-analyzer-` and is located under: + +- Linux: `~/.vscode/extensions` + +- Linux (Remote, such as WSL): `~/.vscode-server/extensions` + +- macOS: `~/.vscode/extensions` + +- Windows: `%USERPROFILE%\.vscode\extensions` + +As an exception, on NixOS, the extension makes a copy of the server and +stores it under +`~/.config/Code/User/globalStorage/rust-lang.rust-analyzer`. + +Note that we only support the two most recent versions of VS Code. + +### Updates + +The extension will be updated automatically as new versions become +available. It will ask your permission to download the matching language +server version binary if needed. + +#### Nightly + +We ship nightly releases for VS Code. To help us out by testing the +newest code, you can enable pre-release versions in the Code extension +page. + +### Manual installation + +Alternatively, download a VSIX corresponding to your platform from the +[releases](https://github.com/rust-lang/rust-analyzer/releases) page. + +Install the extension with the `Extensions: Install from VSIX` command +within VS Code, or from the command line via: + + $ code --install-extension /path/to/rust-analyzer.vsix + +If you are running an unsupported platform, you can install +`rust-analyzer-no-server.vsix` and compile or obtain a server binary. +Copy the server anywhere, then add the path to your settings.json, for +example: + +``` json +{ "rust-analyzer.server.path": "~/.local/bin/rust-analyzer-linux" } +``` + +### Building From Source + +Both the server and the Code plugin can be installed from source: + + $ git clone https://github.com/rust-lang/rust-analyzer.git && cd rust-analyzer + $ cargo xtask install + +You’ll need Cargo, nodejs (matching a supported version of VS Code) and +npm for this. + +Note that installing via `xtask install` does not work for VS Code +Remote, instead you’ll need to install the `.vsix` manually. + +If you’re not using Code, you can compile and install only the LSP +server: + + $ cargo xtask install --server + +## rust-analyzer Language Server Binary + +Other editors generally require the `rust-analyzer` binary to be in +`$PATH`. You can download pre-built binaries from the +[releases](https://github.com/rust-lang/rust-analyzer/releases) page. +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`. + +On Linux to install the `rust-analyzer` binary into `~/.local/bin`, +these commands should work: + +``` bash +$ mkdir -p ~/.local/bin +$ curl -L https://github.com/rust-lang/rust-analyzer/releases/latest/download/rust-analyzer-x86_64-unknown-linux-gnu.gz | gunzip -c - > ~/.local/bin/rust-analyzer +$ chmod +x ~/.local/bin/rust-analyzer +``` + +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. + +You don’t have to use `~/.local/bin`, any other path like `~/.cargo/bin` +or `/usr/local/bin` will work just as well. + +Alternatively, you can install it from source using the command below. +You’ll need the latest stable version of the Rust toolchain. + +``` bash +$ git clone https://github.com/rust-lang/rust-analyzer.git && cd rust-analyzer +$ cargo xtask install --server +``` + +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 [this +issue](https://github.com/rust-lang/rust-analyzer/issues/1811). On Unix, +running the editor from a shell or changing the `.desktop` file to set +the environment should help. + +### `rustup` + +`rust-analyzer` is available in `rustup`, but only in the nightly +toolchain: + +``` bash +$ rustup +nightly component add rust-analyzer-preview +``` + +However, in contrast to `component add clippy` or +`component add rustfmt`, this does not actually place a `rust-analyzer` +binary in `~/.cargo/bin`, see [this +issue](https://github.com/rust-lang/rustup/issues/2411). + +### Arch Linux + +The `rust-analyzer` binary can be installed from the repos or AUR (Arch +User Repository): + +- [`rust-analyzer`](https://www.archlinux.org/packages/community/x86_64/rust-analyzer/) + (built from latest tagged source) + +- [`rust-analyzer-git`](https://aur.archlinux.org/packages/rust-analyzer-git) + (latest Git version) + +Install it with pacman, for example: + +``` bash +$ pacman -S rust-analyzer +``` + +### Gentoo Linux + +`rust-analyzer` is available in the GURU repository: + +- [`dev-util/rust-analyzer`](https://gitweb.gentoo.org/repo/proj/guru.git/tree/dev-util/rust-analyzer?id=9895cea62602cfe599bd48e0fb02127411ca6e81) + builds from source + +- [`dev-util/rust-analyzer-bin`](https://gitweb.gentoo.org/repo/proj/guru.git/tree/dev-util/rust-analyzer-bin?id=9895cea62602cfe599bd48e0fb02127411ca6e81) + installs an official binary release + +If not already, GURU must be enabled (e.g. using +`app-eselect/eselect-repository`) and sync’d before running `emerge`: + +``` bash +$ eselect repository enable guru && emaint sync -r guru +$ emerge rust-analyzer-bin +``` + +### macOS + +The `rust-analyzer` binary can be installed via +[Homebrew](https://brew.sh/). + +``` bash +$ brew install rust-analyzer +``` + +## Emacs + +Note this excellent +[guide](https://robert.kra.hn/posts/2021-02-07_rust-with-emacs/) from +[@rksm](https://github.com/rksm). + +Prerequisites: You have installed the [`rust-analyzer` +binary](#rust-analyzer-language-server-binary). + +Emacs support is maintained as part of the +[Emacs-LSP](https://github.com/emacs-lsp/lsp-mode) package in +[lsp-rust.el](https://github.com/emacs-lsp/lsp-mode/blob/master/lsp-rust.el). + +1. Install the most recent version of `emacs-lsp` package by following + the [Emacs-LSP instructions](https://github.com/emacs-lsp/lsp-mode). + +2. Set `lsp-rust-server` to `'rust-analyzer`. + +3. Run `lsp` in a Rust buffer. + +4. (Optionally) bind commands like `lsp-rust-analyzer-join-lines`, + `lsp-extend-selection` and `lsp-rust-analyzer-expand-macro` to keys. + +## Vim/NeoVim + +Prerequisites: You have installed the [`rust-analyzer` +binary](#rust-analyzer-language-server-binary). Not needed if the +extension can install/update it on its own, coc-rust-analyzer is one +example. + +There are several LSP client implementations for vim or neovim: + +### coc-rust-analyzer + +1. Install coc.nvim by following the instructions at + [coc.nvim](https://github.com/neoclide/coc.nvim) (Node.js required) + +2. Run `:CocInstall coc-rust-analyzer` to install + [coc-rust-analyzer](https://github.com/fannheyward/coc-rust-analyzer), + this extension implements *most* of the features supported in the + VSCode extension: + + - automatically install and upgrade stable/nightly releases + + - same configurations as VSCode extension, + `rust-analyzer.server.path`, `rust-analyzer.cargo.features` etc. + + - same commands too, `rust-analyzer.analyzerStatus`, + `rust-analyzer.ssr` etc. + + - inlay hints for variables and method chaining, *Neovim Only* + +Note: for code actions, use `coc-codeaction-cursor` and +`coc-codeaction-selected`; `coc-codeaction` and `coc-codeaction-line` +are unlikely to be useful. + +### LanguageClient-neovim + +1. Install LanguageClient-neovim by following the instructions + [here](https://github.com/autozimu/LanguageClient-neovim) + + - The GitHub project wiki has extra tips on configuration + +2. Configure by adding this to your vim/neovim config file (replacing + the existing Rust-specific line if it exists): + + ``` vim + let g:LanguageClient_serverCommands = { + \ 'rust': ['rust-analyzer'], + \ } + ``` + +### YouCompleteMe + +Install YouCompleteMe by following the instructions +[here](https://github.com/ycm-core/YouCompleteMe#installation). + +rust-analyzer is the default in ycm, it should work out of the box. + +### ALE + +To use the LSP server in [ale](https://github.com/dense-analysis/ale): + +``` vim +let g:ale_linters = {'rust': ['analyzer']} +``` + +### nvim-lsp + +NeoVim 0.5 has built-in language server support. For a quick start +configuration of rust-analyzer, use +[neovim/nvim-lspconfig](https://github.com/neovim/nvim-lspconfig#rust_analyzer). +Once `neovim/nvim-lspconfig` is installed, use +`lua require'lspconfig'.rust_analyzer.setup({})` in your `init.vim`. + +You can also pass LSP settings to the server: + +``` vim +lua << EOF +local nvim_lsp = require'lspconfig' + +local on_attach = function(client) + require'completion'.on_attach(client) +end + +nvim_lsp.rust_analyzer.setup({ + on_attach=on_attach, + settings = { + ["rust-analyzer"] = { + imports = { + granularity = { + group = "module", + }, + prefix = "self", + }, + cargo = { + buildScripts = { + enable = true, + }, + }, + procMacro = { + enable = true + }, + } + } +}) +EOF +``` + +See for more tips on +getting started. + +Check out for a batteries +included rust-analyzer setup for neovim. + +### vim-lsp + +vim-lsp is installed by following [the plugin +instructions](https://github.com/prabirshrestha/vim-lsp). It can be as +simple as adding this line to your `.vimrc`: + +``` vim +Plug 'prabirshrestha/vim-lsp' +``` + +Next you need to register the `rust-analyzer` binary. If it is available +in `$PATH`, you may want to add this to your `.vimrc`: + +``` vim +if executable('rust-analyzer') + au User lsp_setup call lsp#register_server({ + \ 'name': 'Rust Language Server', + \ 'cmd': {server_info->['rust-analyzer']}, + \ 'whitelist': ['rust'], + \ }) +endif +``` + +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. Here is an +example of how to enable the proc-macro support: + +``` vim +if executable('rust-analyzer') + au User lsp_setup call lsp#register_server({ + \ 'name': 'Rust Language Server', + \ 'cmd': {server_info->['rust-analyzer']}, + \ 'whitelist': ['rust'], + \ 'initialization_options': { + \ 'cargo': { + \ 'buildScripts': { + \ 'enable': v:true, + \ }, + \ }, + \ 'procMacro': { + \ 'enable': v:true, + \ }, + \ }, + \ }) +endif +``` + +## Sublime Text + +### Sublime Text 4: + +- Follow the instructions in + [LSP-rust-analyzer](https://github.com/sublimelsp/LSP-rust-analyzer). + +
+ +Install +[LSP-file-watcher-chokidar](https://packagecontrol.io/packages/LSP-file-watcher-chokidar) +to enable file watching (`workspace/didChangeWatchedFiles`). + +
+ +### Sublime Text 3: + +- Install the [`rust-analyzer` + binary](#rust-analyzer-language-server-binary). + +- Install the [LSP package](https://packagecontrol.io/packages/LSP). + +- From the command palette, run `LSP: Enable Language Server Globally` + and select `rust-analyzer`. + +If it worked, you should see "rust-analyzer, Line X, Column Y" on the +left side of the status bar, and after waiting a bit, functionalities +like tooltips on hovering over variables should become available. + +If you get an error saying `No such file or directory: 'rust-analyzer'`, +see the [`rust-analyzer` binary](#rust-analyzer-language-server-binary) +section on installing the language server binary. + +## GNOME Builder + +GNOME Builder 3.37.1 and newer has native `rust-analyzer` support. If +the LSP binary is not available, GNOME Builder can install it when +opening a Rust file. + +## Eclipse IDE + +Support for Rust development in the Eclipse IDE is provided by [Eclipse +Corrosion](https://github.com/eclipse/corrosion). If available in PATH +or in some standard location, `rust-analyzer` is detected and powers +editing of Rust files without further configuration. 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. You’ll need to close and reopen all .rs and Cargo +files, or to restart the IDE, for this change to take effect. + +## Kate Text Editor + +Support for the language server protocol is built into Kate through the +LSP plugin, which is included by default. It is preconfigured to use +rust-analyzer for Rust sources since Kate 21.12. + +Earlier versions allow you to use rust-analyzer through a simple +settings change. In the LSP Client settings of Kate, copy the content of +the third tab "default parameters" to the second tab "server +configuration". Then in the configuration replace: + +``` json + "rust": { + "command": ["rls"], + "rootIndicationFileNames": ["Cargo.lock", "Cargo.toml"], + "url": "https://github.com/rust-lang/rls", + "highlightingModeRegex": "^Rust$" + }, +``` + +With + +``` json + "rust": { + "command": ["rust-analyzer"], + "rootIndicationFileNames": ["Cargo.lock", "Cargo.toml"], + "url": "https://github.com/rust-lang/rust-analyzer", + "highlightingModeRegex": "^Rust$" + }, +``` + +Then click on apply, and restart the LSP server for your rust project. + +## juCi++ + +[juCi++](https://gitlab.com/cppit/jucipp) has built-in support for the +language server protocol, and since version 1.7.0 offers installation of +both Rust and rust-analyzer when opening a Rust file. + +## Kakoune + +[Kakoune](https://kakoune.org/) supports LSP with the help of +[`kak-lsp`](https://github.com/kak-lsp/kak-lsp). Follow the +[instructions](https://github.com/kak-lsp/kak-lsp#installation) to +install `kak-lsp`. To configure `kak-lsp`, refer to the [configuration +section](https://github.com/kak-lsp/kak-lsp#configuring-kak-lsp) which +is basically about copying the [configuration +file](https://github.com/kak-lsp/kak-lsp/blob/master/kak-lsp.toml) in +the right place (latest versions should use `rust-analyzer` by default). + +Finally, you need to configure Kakoune to talk to `kak-lsp` (see [Usage +section](https://github.com/kak-lsp/kak-lsp#usage)). A basic +configuration will only get you LSP but you can also activate inlay +diagnostics and auto-formatting on save. The following might help you +get all of this. + +``` txt +eval %sh{kak-lsp --kakoune -s $kak_session} # Not needed if you load it with plug.kak. +hook global WinSetOption filetype=rust %{ + # Enable LSP + lsp-enable-window + + # Auto-formatting on save + hook window BufWritePre .* lsp-formatting-sync + + # Configure inlay hints (only on save) + hook window -group rust-inlay-hints BufWritePost .* rust-analyzer-inlay-hints + hook -once -always window WinSetOption filetype=.* %{ + remove-hooks window rust-inlay-hints + } +} +``` + +## Helix + +[Helix](https://docs.helix-editor.com/) supports LSP by default. +However, it won’t install `rust-analyzer` automatically. You can follow +instructions for installing [`rust-analyzer` +binary](#rust-analyzer-language-server-binary). \ No newline at end of file diff --git a/docs/manual/src/non_cargo_based_projects.md b/docs/manual/src/non_cargo_based_projects.md new file mode 100644 index 000000000000..0bbde31dd56d --- /dev/null +++ b/docs/manual/src/non_cargo_based_projects.md @@ -0,0 +1,143 @@ +# Non-Cargo Based Projects + +rust-analyzer does not require Cargo. 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: + +``` TypeScript +interface JsonProject { + /// Path to the directory with *source code* of + /// sysroot crates. + /// + /// It should point to the directory where std, + /// core, and friends can be found: + /// + /// https://github.com/rust-lang/rust/tree/master/library. + /// + /// If provided, rust-analyzer automatically adds + /// dependencies on sysroot crates. Conversely, + /// if you omit this path, you can specify sysroot + /// dependencies yourself and, for example, have + /// several different "sysroots" in one graph of + /// crates. + sysroot_src?: string; + /// The set of crates comprising the current + /// project. Must include all transitive + /// dependencies as well as sysroot crate (libstd, + /// libcore and such). + crates: Crate[]; +} + +interface Crate { + /// Optional crate name used for display purposes, + /// without affecting semantics. See the `deps` + /// key for semantically-significant crate names. + display_name?: string; + /// Path to the root module of the crate. + root_module: string; + /// Edition of the crate. + edition: "2015" | "2018" | "2021"; + /// Dependencies + deps: Dep[]; + /// Should this crate be treated as a member of + /// current "workspace". + /// + /// By default, inferred from the `root_module` + /// (members are the crates which reside inside + /// the directory opened in the editor). + /// + /// Set this to `false` for things like standard + /// library and 3rd party crates to enable + /// performance optimizations (rust-analyzer + /// assumes that non-member crates don't change). + is_workspace_member?: boolean; + /// Optionally specify the (super)set of `.rs` + /// files comprising this crate. + /// + /// By default, rust-analyzer assumes that only + /// files under `root_module.parent` can belong + /// to a crate. `include_dirs` are included + /// recursively, unless a subdirectory is in + /// `exclude_dirs`. + /// + /// Different crates can share the same `source`. + /// + /// If two crates share an `.rs` file in common, + /// they *must* have the same `source`. + /// rust-analyzer assumes that files from one + /// source can't refer to files in another source. + source?: { + include_dirs: string[], + exclude_dirs: string[], + }, + /// The set of cfgs activated for a given crate, like + /// `["unix", "feature=\"foo\"", "feature=\"bar\""]`. + cfg: string[]; + /// Target triple for this Crate. + /// + /// Used when running `rustc --print cfg` + /// to get target-specific cfgs. + target?: string; + /// Environment variables, used for + /// the `env!` macro + env: { [key: string]: string; }, + + /// Whether the crate is a proc-macro crate. + is_proc_macro: boolean; + /// For proc-macro crates, path to compiled + /// proc-macro (.so file). + proc_macro_dylib_path?: string; +} + +interface Dep { + /// Index of a crate in the `crates` array. + crate: number, + /// Name as should appear in the (implicit) + /// `extern crate name` declaration. + name: string, +} +``` + +This format is provisional and subject to change. Specifically, the +`roots` setup will be different eventually. + +There are three ways to feed `rust-project.json` to rust-analyzer: + +- Place `rust-project.json` file at the root of the project, and + rust-analyzer will discover it. + +- 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). + +- Specify + `"rust-analyzer.linkedProjects": [ { "roots": […​], "crates": […​] }]` + inline. + +Relative paths are interpreted relative to `rust-project.json` file +location or (for inline JSON) relative to `rootUri`. + +See for a +small example. + +You can set the `RA_LOG` environment variable to `rust_analyzer=info` to +inspect how rust-analyzer handles config and project loading. + +Note that calls to `cargo check` are disabled when using +`rust-project.json` by default, so compilation errors and warnings will +no longer be sent to your LSP client. To enable these compilation errors +you will need to specify explicitly what command rust-analyzer should +run to perform the checks using the `checkOnSave.overrideCommand` +configuration. As an example, the following configuration explicitly +sets `cargo check` as the `checkOnSave` command. + +``` json +{ "rust-analyzer.checkOnSave.overrideCommand": ["cargo", "check", "--message-format=json"] } +``` + +The `checkOnSave.overrideCommand` requires the command specified to +output json error messages for rust-analyzer to consume. The +`--message-format=json` flag does this for `cargo check` so whichever +command you use must also output errors in this format. See the +[Configuration](configuration.md) section for more information. diff --git a/docs/manual/src/privacy.md b/docs/manual/src/privacy.md new file mode 100644 index 000000000000..602c68d6f67d --- /dev/null +++ b/docs/manual/src/privacy.md @@ -0,0 +1,15 @@ +# Privacy + +The LSP server performs no network access in itself, but runs +`cargo metadata` which will update or download the crate registry and +the source code of the project dependencies. If enabled (the default), +build scripts and procedural macros can do anything. + +The Code extension does not access the network. + +Any other editor plugins are not under the control of the +`rust-analyzer` developers. For any privacy concerns, you should check +with their respective developers. + +For `rust-analyzer` developers, `cargo xtask release` uses the GitHub +API to put together the release notes. diff --git a/docs/manual/src/security.md b/docs/manual/src/security.md new file mode 100644 index 000000000000..18a3643a7be9 --- /dev/null +++ b/docs/manual/src/security.md @@ -0,0 +1,19 @@ +# Security + +At the moment, rust-analyzer assumes that all code is trusted. Here is a +**non-exhaustive** list of ways to make rust-analyzer execute arbitrary +code: + +- proc macros and build scripts are executed by default + +- `.cargo/config` can override `rustc` with an arbitrary executable + +- `rust-toolchain.toml` can override `rustc` with an arbitrary + executable + +- 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. + +- rust-analyzer’s syntax trees library uses a lot of `unsafe` and hasn’t + been properly audited for memory safety. \ No newline at end of file diff --git a/docs/manual/src/troubleshooting.md b/docs/manual/src/troubleshooting.md new file mode 100644 index 000000000000..d5d920e86ab7 --- /dev/null +++ b/docs/manual/src/troubleshooting.md @@ -0,0 +1,50 @@ +# Troubleshooting + +Start with looking at the rust-analyzer version. Try **rust-analyzer: +Show RA Version** in VS Code (using **Command Palette** feature +typically activated by Ctrl+Shift+P) or `rust-analyzer --version` in the +command line. If the date is more than a week ago, it’s better to update +rust-analyzer version. + +The next thing to check would be panic messages in rust-analyzer’s log. +Log messages are printed to stderr, in VS Code you can see then in the +`Output > Rust Analyzer Language Server` tab of the panel. To see more +logs, set the `RA_LOG=info` environment variable, this can be done +either by setting the environment variable manually or by using +`rust-analyzer.server.extraEnv`, note that both of these approaches +require the server to be restarted. + +To fully capture LSP messages between the editor and the server, set +`"rust-analyzer.trace.server": "verbose"` config and check +`Output > Rust Analyzer Language Server Trace`. + +The root cause for many “nothing works” problems is that rust-analyzer +fails to understand the project structure. To debug that, first note the +`rust-analyzer` section in the status bar. If it has an error icon and +red, that’s the problem (hover will have somewhat helpful error +message). **rust-analyzer: Status** prints dependency information for +the current file. Finally, `RA_LOG=project_model=debug` enables verbose +logs during project loading. + +If rust-analyzer outright crashes, try running +`rust-analyzer analysis-stats /path/to/project/directory/` on the +command line. This command type checks the whole project in batch mode +bypassing LSP machinery. + +When filing issues, it is useful (but not necessary) to try to minimize +examples. An ideal bug reproduction looks like this: + +``` bash +$ git clone https://github.com/username/repo.git && cd repo && git switch --detach commit-hash +$ rust-analyzer --version +rust-analyzer dd12184e4 2021-05-08 dev +$ rust-analyzer analysis-stats . +💀 💀 💀 +``` + +It is especially useful when the `repo` doesn’t use external crates or +the standard library. + +If you want to go as far as to modify the source code to debug the +problem, be sure to take a look at the [dev +docs](https://github.com/rust-lang/rust-analyzer/tree/master/docs/dev)! diff --git a/docs/user/.gitignore b/docs/user/.gitignore deleted file mode 100644 index c32b1bcec2ee..000000000000 --- a/docs/user/.gitignore +++ /dev/null @@ -1 +0,0 @@ -manual.html diff --git a/docs/user/generated_config.adoc b/docs/user/generated_config.adoc deleted file mode 100644 index a34f4d5093e3..000000000000 --- a/docs/user/generated_config.adoc +++ /dev/null @@ -1,703 +0,0 @@ -[[rust-analyzer.assist.expressionFillDefault]]rust-analyzer.assist.expressionFillDefault (default: `"todo"`):: -+ --- -Placeholder expression to use for missing expressions in assists. --- -[[rust-analyzer.cachePriming.enable]]rust-analyzer.cachePriming.enable (default: `true`):: -+ --- -Warm up caches on project load. --- -[[rust-analyzer.cachePriming.numThreads]]rust-analyzer.cachePriming.numThreads (default: `0`):: -+ --- -How many worker threads to handle priming caches. The default `0` means to pick automatically. --- -[[rust-analyzer.cargo.autoreload]]rust-analyzer.cargo.autoreload (default: `true`):: -+ --- -Automatically refresh project info via `cargo metadata` on -`Cargo.toml` or `.cargo/config.toml` changes. --- -[[rust-analyzer.cargo.buildScripts.enable]]rust-analyzer.cargo.buildScripts.enable (default: `true`):: -+ --- -Run build scripts (`build.rs`) for more precise code analysis. --- -[[rust-analyzer.cargo.buildScripts.overrideCommand]]rust-analyzer.cargo.buildScripts.overrideCommand (default: `null`):: -+ --- -Override the command rust-analyzer uses to run build scripts and -build procedural macros. The command is required to output json -and should therefore include `--message-format=json` or a similar -option. - -By default, a cargo invocation will be constructed for the configured -targets and features, with the following base command line: - -```bash -cargo check --quiet --workspace --message-format=json --all-targets -``` -. --- -[[rust-analyzer.cargo.buildScripts.useRustcWrapper]]rust-analyzer.cargo.buildScripts.useRustcWrapper (default: `true`):: -+ --- -Use `RUSTC_WRAPPER=rust-analyzer` when running build scripts to -avoid checking unnecessary things. --- -[[rust-analyzer.cargo.extraEnv]]rust-analyzer.cargo.extraEnv (default: `{}`):: -+ --- -Extra environment variables that will be set when running cargo, rustc -or other commands within the workspace. Useful for setting RUSTFLAGS. --- -[[rust-analyzer.cargo.features]]rust-analyzer.cargo.features (default: `[]`):: -+ --- -List of features to activate. - -Set this to `"all"` to pass `--all-features` to cargo. --- -[[rust-analyzer.cargo.noDefaultFeatures]]rust-analyzer.cargo.noDefaultFeatures (default: `false`):: -+ --- -Whether to pass `--no-default-features` to cargo. --- -[[rust-analyzer.cargo.noSysroot]]rust-analyzer.cargo.noSysroot (default: `false`):: -+ --- -Internal config for debugging, disables loading of sysroot crates. --- -[[rust-analyzer.cargo.target]]rust-analyzer.cargo.target (default: `null`):: -+ --- -Compilation target override (target triple). --- -[[rust-analyzer.cargo.unsetTest]]rust-analyzer.cargo.unsetTest (default: `["core"]`):: -+ --- -Unsets `#[cfg(test)]` for the specified crates. --- -[[rust-analyzer.checkOnSave.allTargets]]rust-analyzer.checkOnSave.allTargets (default: `true`):: -+ --- -Check all targets and tests (`--all-targets`). --- -[[rust-analyzer.checkOnSave.command]]rust-analyzer.checkOnSave.command (default: `"check"`):: -+ --- -Cargo command to use for `cargo check`. --- -[[rust-analyzer.checkOnSave.enable]]rust-analyzer.checkOnSave.enable (default: `true`):: -+ --- -Run specified `cargo check` command for diagnostics on save. --- -[[rust-analyzer.checkOnSave.extraArgs]]rust-analyzer.checkOnSave.extraArgs (default: `[]`):: -+ --- -Extra arguments for `cargo check`. --- -[[rust-analyzer.checkOnSave.extraEnv]]rust-analyzer.checkOnSave.extraEnv (default: `{}`):: -+ --- -Extra environment variables that will be set when running `cargo check`. -Extends `#rust-analyzer.cargo.extraEnv#`. --- -[[rust-analyzer.checkOnSave.features]]rust-analyzer.checkOnSave.features (default: `null`):: -+ --- -List of features to activate. Defaults to -`#rust-analyzer.cargo.features#`. - -Set to `"all"` to pass `--all-features` to Cargo. --- -[[rust-analyzer.checkOnSave.noDefaultFeatures]]rust-analyzer.checkOnSave.noDefaultFeatures (default: `null`):: -+ --- -Whether to pass `--no-default-features` to Cargo. Defaults to -`#rust-analyzer.cargo.noDefaultFeatures#`. --- -[[rust-analyzer.checkOnSave.overrideCommand]]rust-analyzer.checkOnSave.overrideCommand (default: `null`):: -+ --- -Override the command rust-analyzer uses instead of `cargo check` for -diagnostics on save. The command is required to output json and -should therefor include `--message-format=json` or a similar option. - -If you're changing this because you're using some tool wrapping -Cargo, you might also want to change -`#rust-analyzer.cargo.buildScripts.overrideCommand#`. - -If there are multiple linked projects, this command is invoked for -each of them, with the working directory being the project root -(i.e., the folder containing the `Cargo.toml`). - -An example command would be: - -```bash -cargo check --workspace --message-format=json --all-targets -``` -. --- -[[rust-analyzer.checkOnSave.target]]rust-analyzer.checkOnSave.target (default: `null`):: -+ --- -Check for a specific target. Defaults to -`#rust-analyzer.cargo.target#`. --- -[[rust-analyzer.completion.autoimport.enable]]rust-analyzer.completion.autoimport.enable (default: `true`):: -+ --- -Toggles the additional completions that automatically add imports when completed. -Note that your client must specify the `additionalTextEdits` LSP client capability to truly have this feature enabled. --- -[[rust-analyzer.completion.autoself.enable]]rust-analyzer.completion.autoself.enable (default: `true`):: -+ --- -Toggles the additional completions that automatically show method calls and field accesses -with `self` prefixed to them when inside a method. --- -[[rust-analyzer.completion.callable.snippets]]rust-analyzer.completion.callable.snippets (default: `"fill_arguments"`):: -+ --- -Whether to add parenthesis and argument snippets when completing function. --- -[[rust-analyzer.completion.postfix.enable]]rust-analyzer.completion.postfix.enable (default: `true`):: -+ --- -Whether to show postfix snippets like `dbg`, `if`, `not`, etc. --- -[[rust-analyzer.completion.privateEditable.enable]]rust-analyzer.completion.privateEditable.enable (default: `false`):: -+ --- -Enables completions of private items and fields that are defined in the current workspace even if they are not visible at the current position. --- -[[rust-analyzer.completion.snippets.custom]]rust-analyzer.completion.snippets.custom:: -+ --- -Default: ----- -{ - "Arc::new": { - "postfix": "arc", - "body": "Arc::new(${receiver})", - "requires": "std::sync::Arc", - "description": "Put the expression into an `Arc`", - "scope": "expr" - }, - "Rc::new": { - "postfix": "rc", - "body": "Rc::new(${receiver})", - "requires": "std::rc::Rc", - "description": "Put the expression into an `Rc`", - "scope": "expr" - }, - "Box::pin": { - "postfix": "pinbox", - "body": "Box::pin(${receiver})", - "requires": "std::boxed::Box", - "description": "Put the expression into a pinned `Box`", - "scope": "expr" - }, - "Ok": { - "postfix": "ok", - "body": "Ok(${receiver})", - "description": "Wrap the expression in a `Result::Ok`", - "scope": "expr" - }, - "Err": { - "postfix": "err", - "body": "Err(${receiver})", - "description": "Wrap the expression in a `Result::Err`", - "scope": "expr" - }, - "Some": { - "postfix": "some", - "body": "Some(${receiver})", - "description": "Wrap the expression in an `Option::Some`", - "scope": "expr" - } - } ----- -Custom completion snippets. - --- -[[rust-analyzer.diagnostics.disabled]]rust-analyzer.diagnostics.disabled (default: `[]`):: -+ --- -List of rust-analyzer diagnostics to disable. --- -[[rust-analyzer.diagnostics.enable]]rust-analyzer.diagnostics.enable (default: `true`):: -+ --- -Whether to show native rust-analyzer diagnostics. --- -[[rust-analyzer.diagnostics.experimental.enable]]rust-analyzer.diagnostics.experimental.enable (default: `false`):: -+ --- -Whether to show experimental rust-analyzer diagnostics that might -have more false positives than usual. --- -[[rust-analyzer.diagnostics.remapPrefix]]rust-analyzer.diagnostics.remapPrefix (default: `{}`):: -+ --- -Map of prefixes to be substituted when parsing diagnostic file paths. -This should be the reverse mapping of what is passed to `rustc` as `--remap-path-prefix`. --- -[[rust-analyzer.diagnostics.warningsAsHint]]rust-analyzer.diagnostics.warningsAsHint (default: `[]`):: -+ --- -List of warnings that should be displayed with hint severity. - -The warnings will be indicated by faded text or three dots in code -and will not show up in the `Problems Panel`. --- -[[rust-analyzer.diagnostics.warningsAsInfo]]rust-analyzer.diagnostics.warningsAsInfo (default: `[]`):: -+ --- -List of warnings that should be displayed with info severity. - -The warnings will be indicated by a blue squiggly underline in code -and a blue icon in the `Problems Panel`. --- -[[rust-analyzer.files.excludeDirs]]rust-analyzer.files.excludeDirs (default: `[]`):: -+ --- -These directories will be ignored by rust-analyzer. They are -relative to the workspace root, and globs are not supported. You may -also need to add the folders to Code's `files.watcherExclude`. --- -[[rust-analyzer.files.watcher]]rust-analyzer.files.watcher (default: `"client"`):: -+ --- -Controls file watching implementation. --- -[[rust-analyzer.highlightRelated.breakPoints.enable]]rust-analyzer.highlightRelated.breakPoints.enable (default: `true`):: -+ --- -Enables highlighting of related references while the cursor is on `break`, `loop`, `while`, or `for` keywords. --- -[[rust-analyzer.highlightRelated.exitPoints.enable]]rust-analyzer.highlightRelated.exitPoints.enable (default: `true`):: -+ --- -Enables highlighting of all exit points while the cursor is on any `return`, `?`, `fn`, or return type arrow (`->`). --- -[[rust-analyzer.highlightRelated.references.enable]]rust-analyzer.highlightRelated.references.enable (default: `true`):: -+ --- -Enables highlighting of related references while the cursor is on any identifier. --- -[[rust-analyzer.highlightRelated.yieldPoints.enable]]rust-analyzer.highlightRelated.yieldPoints.enable (default: `true`):: -+ --- -Enables highlighting of all break points for a loop or block context while the cursor is on any `async` or `await` keywords. --- -[[rust-analyzer.hover.actions.debug.enable]]rust-analyzer.hover.actions.debug.enable (default: `true`):: -+ --- -Whether to show `Debug` action. Only applies when -`#rust-analyzer.hover.actions.enable#` is set. --- -[[rust-analyzer.hover.actions.enable]]rust-analyzer.hover.actions.enable (default: `true`):: -+ --- -Whether to show HoverActions in Rust files. --- -[[rust-analyzer.hover.actions.gotoTypeDef.enable]]rust-analyzer.hover.actions.gotoTypeDef.enable (default: `true`):: -+ --- -Whether to show `Go to Type Definition` action. Only applies when -`#rust-analyzer.hover.actions.enable#` is set. --- -[[rust-analyzer.hover.actions.implementations.enable]]rust-analyzer.hover.actions.implementations.enable (default: `true`):: -+ --- -Whether to show `Implementations` action. Only applies when -`#rust-analyzer.hover.actions.enable#` is set. --- -[[rust-analyzer.hover.actions.references.enable]]rust-analyzer.hover.actions.references.enable (default: `false`):: -+ --- -Whether to show `References` action. Only applies when -`#rust-analyzer.hover.actions.enable#` is set. --- -[[rust-analyzer.hover.actions.run.enable]]rust-analyzer.hover.actions.run.enable (default: `true`):: -+ --- -Whether to show `Run` action. Only applies when -`#rust-analyzer.hover.actions.enable#` is set. --- -[[rust-analyzer.hover.documentation.enable]]rust-analyzer.hover.documentation.enable (default: `true`):: -+ --- -Whether to show documentation on hover. --- -[[rust-analyzer.hover.documentation.keywords.enable]]rust-analyzer.hover.documentation.keywords.enable (default: `true`):: -+ --- -Whether to show keyword hover popups. Only applies when -`#rust-analyzer.hover.documentation.enable#` is set. --- -[[rust-analyzer.hover.links.enable]]rust-analyzer.hover.links.enable (default: `true`):: -+ --- -Use markdown syntax for links in hover. --- -[[rust-analyzer.imports.granularity.enforce]]rust-analyzer.imports.granularity.enforce (default: `false`):: -+ --- -Whether to enforce the import granularity setting for all files. If set to false rust-analyzer will try to keep import styles consistent per file. --- -[[rust-analyzer.imports.granularity.group]]rust-analyzer.imports.granularity.group (default: `"crate"`):: -+ --- -How imports should be grouped into use statements. --- -[[rust-analyzer.imports.group.enable]]rust-analyzer.imports.group.enable (default: `true`):: -+ --- -Group inserted imports by the https://rust-analyzer.github.io/manual.html#auto-import[following order]. Groups are separated by newlines. --- -[[rust-analyzer.imports.merge.glob]]rust-analyzer.imports.merge.glob (default: `true`):: -+ --- -Whether to allow import insertion to merge new imports into single path glob imports like `use std::fmt::*;`. --- -[[rust-analyzer.imports.prefer.no.std]]rust-analyzer.imports.prefer.no.std (default: `false`):: -+ --- -Prefer to unconditionally use imports of the core and alloc crate, over the std crate. --- -[[rust-analyzer.imports.prefix]]rust-analyzer.imports.prefix (default: `"plain"`):: -+ --- -The path structure for newly inserted paths to use. --- -[[rust-analyzer.inlayHints.bindingModeHints.enable]]rust-analyzer.inlayHints.bindingModeHints.enable (default: `false`):: -+ --- -Whether to show inlay type hints for binding modes. --- -[[rust-analyzer.inlayHints.chainingHints.enable]]rust-analyzer.inlayHints.chainingHints.enable (default: `true`):: -+ --- -Whether to show inlay type hints for method chains. --- -[[rust-analyzer.inlayHints.closingBraceHints.enable]]rust-analyzer.inlayHints.closingBraceHints.enable (default: `true`):: -+ --- -Whether to show inlay hints after a closing `}` to indicate what item it belongs to. --- -[[rust-analyzer.inlayHints.closingBraceHints.minLines]]rust-analyzer.inlayHints.closingBraceHints.minLines (default: `25`):: -+ --- -Minimum number of lines required before the `}` until the hint is shown (set to 0 or 1 -to always show them). --- -[[rust-analyzer.inlayHints.closureReturnTypeHints.enable]]rust-analyzer.inlayHints.closureReturnTypeHints.enable (default: `"never"`):: -+ --- -Whether to show inlay type hints for return types of closures. --- -[[rust-analyzer.inlayHints.lifetimeElisionHints.enable]]rust-analyzer.inlayHints.lifetimeElisionHints.enable (default: `"never"`):: -+ --- -Whether to show inlay type hints for elided lifetimes in function signatures. --- -[[rust-analyzer.inlayHints.lifetimeElisionHints.useParameterNames]]rust-analyzer.inlayHints.lifetimeElisionHints.useParameterNames (default: `false`):: -+ --- -Whether to prefer using parameter names as the name for elided lifetime hints if possible. --- -[[rust-analyzer.inlayHints.maxLength]]rust-analyzer.inlayHints.maxLength (default: `25`):: -+ --- -Maximum length for inlay hints. Set to null to have an unlimited length. --- -[[rust-analyzer.inlayHints.parameterHints.enable]]rust-analyzer.inlayHints.parameterHints.enable (default: `true`):: -+ --- -Whether to show function parameter name inlay hints at the call -site. --- -[[rust-analyzer.inlayHints.reborrowHints.enable]]rust-analyzer.inlayHints.reborrowHints.enable (default: `"never"`):: -+ --- -Whether to show inlay type hints for compiler inserted reborrows. --- -[[rust-analyzer.inlayHints.renderColons]]rust-analyzer.inlayHints.renderColons (default: `true`):: -+ --- -Whether to render leading colons for type hints, and trailing colons for parameter hints. --- -[[rust-analyzer.inlayHints.typeHints.enable]]rust-analyzer.inlayHints.typeHints.enable (default: `true`):: -+ --- -Whether to show inlay type hints for variables. --- -[[rust-analyzer.inlayHints.typeHints.hideClosureInitialization]]rust-analyzer.inlayHints.typeHints.hideClosureInitialization (default: `false`):: -+ --- -Whether to hide inlay type hints for `let` statements that initialize to a closure. -Only applies to closures with blocks, same as `#rust-analyzer.inlayHints.closureReturnTypeHints.enable#`. --- -[[rust-analyzer.inlayHints.typeHints.hideNamedConstructor]]rust-analyzer.inlayHints.typeHints.hideNamedConstructor (default: `false`):: -+ --- -Whether to hide inlay type hints for constructors. --- -[[rust-analyzer.joinLines.joinAssignments]]rust-analyzer.joinLines.joinAssignments (default: `true`):: -+ --- -Join lines merges consecutive declaration and initialization of an assignment. --- -[[rust-analyzer.joinLines.joinElseIf]]rust-analyzer.joinLines.joinElseIf (default: `true`):: -+ --- -Join lines inserts else between consecutive ifs. --- -[[rust-analyzer.joinLines.removeTrailingComma]]rust-analyzer.joinLines.removeTrailingComma (default: `true`):: -+ --- -Join lines removes trailing commas. --- -[[rust-analyzer.joinLines.unwrapTrivialBlock]]rust-analyzer.joinLines.unwrapTrivialBlock (default: `true`):: -+ --- -Join lines unwraps trivial blocks. --- -[[rust-analyzer.lens.debug.enable]]rust-analyzer.lens.debug.enable (default: `true`):: -+ --- -Whether to show `Debug` lens. Only applies when -`#rust-analyzer.lens.enable#` is set. --- -[[rust-analyzer.lens.enable]]rust-analyzer.lens.enable (default: `true`):: -+ --- -Whether to show CodeLens in Rust files. --- -[[rust-analyzer.lens.forceCustomCommands]]rust-analyzer.lens.forceCustomCommands (default: `true`):: -+ --- -Internal config: use custom client-side commands even when the -client doesn't set the corresponding capability. --- -[[rust-analyzer.lens.implementations.enable]]rust-analyzer.lens.implementations.enable (default: `true`):: -+ --- -Whether to show `Implementations` lens. Only applies when -`#rust-analyzer.lens.enable#` is set. --- -[[rust-analyzer.lens.location]]rust-analyzer.lens.location (default: `"above_name"`):: -+ --- -Where to render annotations. --- -[[rust-analyzer.lens.references.adt.enable]]rust-analyzer.lens.references.adt.enable (default: `false`):: -+ --- -Whether to show `References` lens for Struct, Enum, and Union. -Only applies when `#rust-analyzer.lens.enable#` is set. --- -[[rust-analyzer.lens.references.enumVariant.enable]]rust-analyzer.lens.references.enumVariant.enable (default: `false`):: -+ --- -Whether to show `References` lens for Enum Variants. -Only applies when `#rust-analyzer.lens.enable#` is set. --- -[[rust-analyzer.lens.references.method.enable]]rust-analyzer.lens.references.method.enable (default: `false`):: -+ --- -Whether to show `Method References` lens. Only applies when -`#rust-analyzer.lens.enable#` is set. --- -[[rust-analyzer.lens.references.trait.enable]]rust-analyzer.lens.references.trait.enable (default: `false`):: -+ --- -Whether to show `References` lens for Trait. -Only applies when `#rust-analyzer.lens.enable#` is set. --- -[[rust-analyzer.lens.run.enable]]rust-analyzer.lens.run.enable (default: `true`):: -+ --- -Whether to show `Run` lens. Only applies when -`#rust-analyzer.lens.enable#` is set. --- -[[rust-analyzer.linkedProjects]]rust-analyzer.linkedProjects (default: `[]`):: -+ --- -Disable project auto-discovery in favor of explicitly specified set -of projects. - -Elements must be paths pointing to `Cargo.toml`, -`rust-project.json`, or JSON objects in `rust-project.json` format. --- -[[rust-analyzer.lru.capacity]]rust-analyzer.lru.capacity (default: `null`):: -+ --- -Number of syntax trees rust-analyzer keeps in memory. Defaults to 128. --- -[[rust-analyzer.notifications.cargoTomlNotFound]]rust-analyzer.notifications.cargoTomlNotFound (default: `true`):: -+ --- -Whether to show `can't find Cargo.toml` error message. --- -[[rust-analyzer.procMacro.attributes.enable]]rust-analyzer.procMacro.attributes.enable (default: `true`):: -+ --- -Expand attribute macros. Requires `#rust-analyzer.procMacro.enable#` to be set. --- -[[rust-analyzer.procMacro.enable]]rust-analyzer.procMacro.enable (default: `true`):: -+ --- -Enable support for procedural macros, implies `#rust-analyzer.cargo.buildScripts.enable#`. --- -[[rust-analyzer.procMacro.ignored]]rust-analyzer.procMacro.ignored (default: `{}`):: -+ --- -These proc-macros will be ignored when trying to expand them. - -This config takes a map of crate names with the exported proc-macro names to ignore as values. --- -[[rust-analyzer.procMacro.server]]rust-analyzer.procMacro.server (default: `null`):: -+ --- -Internal config, path to proc-macro server executable (typically, -this is rust-analyzer itself, but we override this in tests). --- -[[rust-analyzer.references.excludeImports]]rust-analyzer.references.excludeImports (default: `false`):: -+ --- -Exclude imports from find-all-references. --- -[[rust-analyzer.runnables.command]]rust-analyzer.runnables.command (default: `null`):: -+ --- -Command to be executed instead of 'cargo' for runnables. --- -[[rust-analyzer.runnables.extraArgs]]rust-analyzer.runnables.extraArgs (default: `[]`):: -+ --- -Additional arguments to be passed to cargo for runnables such as -tests or binaries. For example, it may be `--release`. --- -[[rust-analyzer.rustc.source]]rust-analyzer.rustc.source (default: `null`):: -+ --- -Path to the Cargo.toml of the rust compiler workspace, for usage in rustc_private -projects, or "discover" to try to automatically find it if the `rustc-dev` component -is installed. - -Any project which uses rust-analyzer with the rustcPrivate -crates must set `[package.metadata.rust-analyzer] rustc_private=true` to use it. - -This option does not take effect until rust-analyzer is restarted. --- -[[rust-analyzer.rustfmt.extraArgs]]rust-analyzer.rustfmt.extraArgs (default: `[]`):: -+ --- -Additional arguments to `rustfmt`. --- -[[rust-analyzer.rustfmt.overrideCommand]]rust-analyzer.rustfmt.overrideCommand (default: `null`):: -+ --- -Advanced option, fully override the command rust-analyzer uses for -formatting. --- -[[rust-analyzer.rustfmt.rangeFormatting.enable]]rust-analyzer.rustfmt.rangeFormatting.enable (default: `false`):: -+ --- -Enables the use of rustfmt's unstable range formatting command for the -`textDocument/rangeFormatting` request. The rustfmt option is unstable and only -available on a nightly build. --- -[[rust-analyzer.semanticHighlighting.doc.comment.inject.enable]]rust-analyzer.semanticHighlighting.doc.comment.inject.enable (default: `true`):: -+ --- -Inject additional highlighting into doc comments. - -When enabled, rust-analyzer will highlight rust source in doc comments as well as intra -doc links. --- -[[rust-analyzer.semanticHighlighting.operator.enable]]rust-analyzer.semanticHighlighting.operator.enable (default: `true`):: -+ --- -Use semantic tokens for operators. - -When disabled, rust-analyzer will emit semantic tokens only for operator tokens when -they are tagged with modifiers. --- -[[rust-analyzer.semanticHighlighting.operator.specialization.enable]]rust-analyzer.semanticHighlighting.operator.specialization.enable (default: `false`):: -+ --- -Use specialized semantic tokens for operators. - -When enabled, rust-analyzer will emit special token types for operator tokens instead -of the generic `operator` token type. --- -[[rust-analyzer.semanticHighlighting.punctuation.enable]]rust-analyzer.semanticHighlighting.punctuation.enable (default: `false`):: -+ --- -Use semantic tokens for punctuations. - -When disabled, rust-analyzer will emit semantic tokens only for punctuation tokens when -they are tagged with modifiers or have a special role. --- -[[rust-analyzer.semanticHighlighting.punctuation.separate.macro.bang]]rust-analyzer.semanticHighlighting.punctuation.separate.macro.bang (default: `false`):: -+ --- -When enabled, rust-analyzer will emit a punctuation semantic token for the `!` of macro -calls. --- -[[rust-analyzer.semanticHighlighting.punctuation.specialization.enable]]rust-analyzer.semanticHighlighting.punctuation.specialization.enable (default: `false`):: -+ --- -Use specialized semantic tokens for punctuations. - -When enabled, rust-analyzer will emit special token types for punctuation tokens instead -of the generic `punctuation` token type. --- -[[rust-analyzer.semanticHighlighting.strings.enable]]rust-analyzer.semanticHighlighting.strings.enable (default: `true`):: -+ --- -Use semantic tokens for strings. - -In some editors (e.g. vscode) semantic tokens override other highlighting grammars. -By disabling semantic tokens for strings, other grammars can be used to highlight -their contents. --- -[[rust-analyzer.signatureInfo.detail]]rust-analyzer.signatureInfo.detail (default: `"full"`):: -+ --- -Show full signature of the callable. Only shows parameters if disabled. --- -[[rust-analyzer.signatureInfo.documentation.enable]]rust-analyzer.signatureInfo.documentation.enable (default: `true`):: -+ --- -Show documentation. --- -[[rust-analyzer.typing.autoClosingAngleBrackets.enable]]rust-analyzer.typing.autoClosingAngleBrackets.enable (default: `false`):: -+ --- -Whether to insert closing angle brackets when typing an opening angle bracket of a generic argument list. --- -[[rust-analyzer.workspace.symbol.search.kind]]rust-analyzer.workspace.symbol.search.kind (default: `"only_types"`):: -+ --- -Workspace symbol search kind. --- -[[rust-analyzer.workspace.symbol.search.limit]]rust-analyzer.workspace.symbol.search.limit (default: `128`):: -+ --- -Limits the number of items returned from a workspace symbol search (Defaults to 128). -Some clients like vs-code issue new searches on result filtering and don't require all results to be returned in the initial search. -Other clients requires all results upfront and might require a higher limit. --- -[[rust-analyzer.workspace.symbol.search.scope]]rust-analyzer.workspace.symbol.search.scope (default: `"workspace"`):: -+ --- -Workspace symbol search scope. --- diff --git a/docs/user/manual.adoc b/docs/user/manual.adoc deleted file mode 100644 index 9bd3b6a692b1..000000000000 --- a/docs/user/manual.adoc +++ /dev/null @@ -1,874 +0,0 @@ -= User Manual -:toc: preamble -:sectanchors: -:page-layout: post -:icons: font -:source-highlighter: rouge -:experimental: - -//// -IMPORTANT: the master copy of this document lives in the https://github.com/rust-lang/rust-analyzer repository -//// - -At its core, rust-analyzer is a *library* for semantic analysis of Rust code as it changes over time. -This manual focuses on a specific usage of the library -- running it as part of a server that implements the -https://microsoft.github.io/language-server-protocol/[Language Server Protocol] (LSP). -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. - -[TIP] -==== -[.lead] -To improve this document, send a pull request: + -https://github.com/rust-lang/rust-analyzer/blob/master/docs/user/manual.adoc[https://github.com/rust-analyzer/.../manual.adoc] - -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. -==== - -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. - -== Installation - -In theory, one should be able to just install the <> and have it automatically work with any editor. -We are not there yet, so some editor specific setup is required. - -Additionally, rust-analyzer needs the sources of the standard library. -If the source code is not present, rust-analyzer will attempt to install it automatically. - -To add the sources manually, run the following command: - -```bash -$ rustup component add rust-src -``` - -=== Toolchain - -Only the latest stable standard library source is officially supported for use with rust-analyzer. -If you are using an older toolchain or have an override set, rust-analyzer may fail to understand the Rust source. -You will either need to update your toolchain or use an older version of rust-analyzer that is compatible with your toolchain. - -If you are using an override in your project, you can still force rust-analyzer to use the stable toolchain via the environment variable `RUSTUP_TOOLCHAIN`. -For example, with VS Code or coc-rust-analyzer: - -[source,json] ----- -{ "rust-analyzer.server.extraEnv": { "RUSTUP_TOOLCHAIN": "stable" } } ----- - -=== VS Code - -This is the best supported editor at the moment. -The rust-analyzer plugin for VS Code is maintained -https://github.com/rust-lang/rust-analyzer/tree/master/editors/code[in tree]. - -You can install the latest release of the plugin from -https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer[the marketplace]. - -Note that the plugin may cause conflicts with the -https://marketplace.visualstudio.com/items?itemName=rust-lang.rust[official Rust plugin]. -It is recommended to disable the Rust plugin when using the rust-analyzer extension. - -By default, the plugin will prompt you to download the matching version of the server as well: - -image::https://user-images.githubusercontent.com/9021944/75067008-17502500-54ba-11ea-835a-f92aac50e866.png[] - -[NOTE] -==== -To disable this notification put the following to `settings.json` - -[source,json] ----- -{ "rust-analyzer.updates.askBeforeDownload": false } ----- -==== - -The server binary is stored in the extension install directory, which starts with `rust-lang.rust-analyzer-` and is located under: - -* Linux: `~/.vscode/extensions` -* Linux (Remote, such as WSL): `~/.vscode-server/extensions` -* macOS: `~/.vscode/extensions` -* Windows: `%USERPROFILE%\.vscode\extensions` - -As an exception, on NixOS, the extension makes a copy of the server and stores it under `~/.config/Code/User/globalStorage/rust-lang.rust-analyzer`. - -Note that we only support the two most recent versions of VS Code. - -==== Updates - -The extension will be updated automatically as new versions become available. -It will ask your permission to download the matching language server version binary if needed. - -===== Nightly - -We ship nightly releases for VS Code. -To help us out by testing the newest code, you can enable pre-release versions in the Code extension page. - -==== Manual installation - -Alternatively, download a VSIX corresponding to your platform from the -https://github.com/rust-lang/rust-analyzer/releases[releases] page. - -Install the extension with the `Extensions: Install from VSIX` command within VS Code, or from the command line via: -[source] ----- -$ code --install-extension /path/to/rust-analyzer.vsix ----- - -If you are running an unsupported platform, you can install `rust-analyzer-no-server.vsix` and compile or obtain a server binary. -Copy the server anywhere, then add the path to your settings.json, for example: -[source,json] ----- -{ "rust-analyzer.server.path": "~/.local/bin/rust-analyzer-linux" } ----- - -==== Building From Source - -Both the server and the Code plugin can be installed from source: - -[source] ----- -$ git clone https://github.com/rust-lang/rust-analyzer.git && cd rust-analyzer -$ cargo xtask install ----- - -You'll need Cargo, nodejs (matching a supported version of VS Code) and npm for this. - -Note that installing via `xtask install` does not work for VS Code Remote, instead you'll need to install the `.vsix` manually. - -If you're not using Code, you can compile and install only the LSP server: - -[source] ----- -$ cargo xtask install --server ----- - -=== rust-analyzer Language Server Binary - -Other editors generally require the `rust-analyzer` binary to be in `$PATH`. -You can download pre-built binaries from the https://github.com/rust-lang/rust-analyzer/releases[releases] page. -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`. - -On Linux to install the `rust-analyzer` binary into `~/.local/bin`, these commands should work: - -[source,bash] ----- -$ mkdir -p ~/.local/bin -$ curl -L https://github.com/rust-lang/rust-analyzer/releases/latest/download/rust-analyzer-x86_64-unknown-linux-gnu.gz | gunzip -c - > ~/.local/bin/rust-analyzer -$ chmod +x ~/.local/bin/rust-analyzer ----- - -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. - -You don't have to use `~/.local/bin`, any other path like `~/.cargo/bin` or `/usr/local/bin` will work just as well. - -Alternatively, you can install it from source using the command below. -You'll need the latest stable version of the Rust toolchain. - -[source,bash] ----- -$ git clone https://github.com/rust-lang/rust-analyzer.git && cd rust-analyzer -$ cargo xtask install --server ----- - -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-lang/rust-analyzer/issues/1811[this issue]. -On Unix, running the editor from a shell or changing the `.desktop` file to set the environment should help. - -==== `rustup` - -`rust-analyzer` is available in `rustup`, but only in the nightly toolchain: - -[source,bash] ----- -$ rustup +nightly component add rust-analyzer-preview ----- - -However, in contrast to `component add clippy` or `component add rustfmt`, this does not actually place a `rust-analyzer` binary in `~/.cargo/bin`, see https://github.com/rust-lang/rustup/issues/2411[this issue]. - -==== Arch Linux - -The `rust-analyzer` binary can be installed from the repos or AUR (Arch User Repository): - -- https://www.archlinux.org/packages/community/x86_64/rust-analyzer/[`rust-analyzer`] (built from latest tagged source) -- https://aur.archlinux.org/packages/rust-analyzer-git[`rust-analyzer-git`] (latest Git version) - -Install it with pacman, for example: - -[source,bash] ----- -$ pacman -S rust-analyzer ----- - -==== Gentoo Linux - -`rust-analyzer` is available in the GURU repository: - -- https://gitweb.gentoo.org/repo/proj/guru.git/tree/dev-util/rust-analyzer?id=9895cea62602cfe599bd48e0fb02127411ca6e81[`dev-util/rust-analyzer`] builds from source -- https://gitweb.gentoo.org/repo/proj/guru.git/tree/dev-util/rust-analyzer-bin?id=9895cea62602cfe599bd48e0fb02127411ca6e81[`dev-util/rust-analyzer-bin`] installs an official binary release - -If not already, GURU must be enabled (e.g. using `app-eselect/eselect-repository`) and sync'd before running `emerge`: - -[source,bash] ----- -$ eselect repository enable guru && emaint sync -r guru -$ emerge rust-analyzer-bin ----- - -==== macOS - -The `rust-analyzer` binary can be installed via https://brew.sh/[Homebrew]. - -[source,bash] ----- -$ brew install rust-analyzer ----- - -=== Emacs - -Note this excellent https://robert.kra.hn/posts/2021-02-07_rust-with-emacs/[guide] from https://github.com/rksm[@rksm]. - -Prerequisites: You have installed the <>. - -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]. - -1. Install the most recent version of `emacs-lsp` package by following the https://github.com/emacs-lsp/lsp-mode[Emacs-LSP instructions]. -2. Set `lsp-rust-server` to `'rust-analyzer`. -3. Run `lsp` in a Rust buffer. -4. (Optionally) bind commands like `lsp-rust-analyzer-join-lines`, `lsp-extend-selection` and `lsp-rust-analyzer-expand-macro` to keys. - -=== Vim/NeoVim - -Prerequisites: You have installed the <>. -Not needed if the extension can install/update it on its own, coc-rust-analyzer is one example. - -There are several LSP client implementations for vim or neovim: - -==== coc-rust-analyzer - -1. Install coc.nvim by following the instructions at - https://github.com/neoclide/coc.nvim[coc.nvim] - (Node.js required) -2. Run `:CocInstall coc-rust-analyzer` to install - https://github.com/fannheyward/coc-rust-analyzer[coc-rust-analyzer], - this extension implements _most_ of the features supported in the VSCode extension: - * automatically install and upgrade stable/nightly releases - * same configurations as VSCode extension, `rust-analyzer.server.path`, `rust-analyzer.cargo.features` etc. - * same commands too, `rust-analyzer.analyzerStatus`, `rust-analyzer.ssr` etc. - * inlay hints for variables and method chaining, _Neovim Only_ - -Note: for code actions, use `coc-codeaction-cursor` and `coc-codeaction-selected`; `coc-codeaction` and `coc-codeaction-line` are unlikely to be useful. - -==== LanguageClient-neovim - -1. Install LanguageClient-neovim by following the instructions - https://github.com/autozimu/LanguageClient-neovim[here] - * The GitHub project wiki has extra tips on configuration - -2. Configure by adding this to your vim/neovim config file (replacing the existing Rust-specific line if it exists): -+ -[source,vim] ----- -let g:LanguageClient_serverCommands = { -\ 'rust': ['rust-analyzer'], -\ } ----- - -==== YouCompleteMe - -Install YouCompleteMe by following the instructions - https://github.com/ycm-core/YouCompleteMe#installation[here]. - -rust-analyzer is the default in ycm, it should work out of the box. - -==== ALE - -To use the LSP server in https://github.com/dense-analysis/ale[ale]: - -[source,vim] ----- -let g:ale_linters = {'rust': ['analyzer']} ----- - -==== nvim-lsp - -NeoVim 0.5 has built-in language server support. -For a quick start configuration of rust-analyzer, use https://github.com/neovim/nvim-lspconfig#rust_analyzer[neovim/nvim-lspconfig]. -Once `neovim/nvim-lspconfig` is installed, use `+lua require'lspconfig'.rust_analyzer.setup({})+` in your `init.vim`. - -You can also pass LSP settings to the server: - -[source,vim] ----- -lua << EOF -local nvim_lsp = require'lspconfig' - -local on_attach = function(client) - require'completion'.on_attach(client) -end - -nvim_lsp.rust_analyzer.setup({ - on_attach=on_attach, - settings = { - ["rust-analyzer"] = { - imports = { - granularity = { - group = "module", - }, - prefix = "self", - }, - cargo = { - buildScripts = { - enable = true, - }, - }, - procMacro = { - enable = true - }, - } - } -}) -EOF ----- - -See https://sharksforarms.dev/posts/neovim-rust/ for more tips on getting started. - -Check out https://github.com/simrat39/rust-tools.nvim for a batteries included rust-analyzer setup for neovim. - -==== vim-lsp - -vim-lsp is installed by following https://github.com/prabirshrestha/vim-lsp[the plugin instructions]. -It can be as simple as adding this line to your `.vimrc`: - -[source,vim] ----- -Plug 'prabirshrestha/vim-lsp' ----- - -Next you need to register the `rust-analyzer` binary. -If it is available in `$PATH`, you may want to add this to your `.vimrc`: - -[source,vim] ----- -if executable('rust-analyzer') - au User lsp_setup call lsp#register_server({ - \ 'name': 'Rust Language Server', - \ 'cmd': {server_info->['rust-analyzer']}, - \ 'whitelist': ['rust'], - \ }) -endif ----- - -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. -Here is an example of how to enable the proc-macro support: - -[source,vim] ----- -if executable('rust-analyzer') - au User lsp_setup call lsp#register_server({ - \ 'name': 'Rust Language Server', - \ 'cmd': {server_info->['rust-analyzer']}, - \ 'whitelist': ['rust'], - \ 'initialization_options': { - \ 'cargo': { - \ 'buildScripts': { - \ 'enable': v:true, - \ }, - \ }, - \ 'procMacro': { - \ 'enable': v:true, - \ }, - \ }, - \ }) -endif ----- - -=== Sublime Text - -==== Sublime Text 4: -* Follow the instructions in link:https://github.com/sublimelsp/LSP-rust-analyzer[LSP-rust-analyzer]. - -NOTE: Install link:https://packagecontrol.io/packages/LSP-file-watcher-chokidar[LSP-file-watcher-chokidar] to enable file watching (`workspace/didChangeWatchedFiles`). - -==== Sublime Text 3: -* Install the <>. -* Install the link:https://packagecontrol.io/packages/LSP[LSP package]. -* From the command palette, run `LSP: Enable Language Server Globally` and select `rust-analyzer`. - -If it worked, you should see "rust-analyzer, Line X, Column Y" on the left side of the status bar, and after waiting a bit, functionalities like tooltips on hovering over variables should become available. - -If you get an error saying `No such file or directory: 'rust-analyzer'`, see the <> section on installing the language server binary. - -=== GNOME Builder - -GNOME Builder 3.37.1 and newer has native `rust-analyzer` support. -If the LSP binary is not available, GNOME Builder can install it when opening a Rust file. - - -=== Eclipse IDE - -Support for Rust development in the Eclipse IDE is provided by link:https://github.com/eclipse/corrosion[Eclipse Corrosion]. -If available in PATH or in some standard location, `rust-analyzer` is detected and powers editing of Rust files without further configuration. -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. -You'll need to close and reopen all .rs and Cargo files, or to restart the IDE, for this change to take effect. - -=== Kate Text Editor - -Support for the language server protocol is built into Kate through the LSP plugin, which is included by default. -It is preconfigured to use rust-analyzer for Rust sources since Kate 21.12. - -Earlier versions allow you to use rust-analyzer through a simple settings change. -In the LSP Client settings of Kate, copy the content of the third tab "default parameters" to the second tab "server configuration". -Then in the configuration replace: -[source,json] ----- - "rust": { - "command": ["rls"], - "rootIndicationFileNames": ["Cargo.lock", "Cargo.toml"], - "url": "https://github.com/rust-lang/rls", - "highlightingModeRegex": "^Rust$" - }, ----- -With -[source,json] ----- - "rust": { - "command": ["rust-analyzer"], - "rootIndicationFileNames": ["Cargo.lock", "Cargo.toml"], - "url": "https://github.com/rust-lang/rust-analyzer", - "highlightingModeRegex": "^Rust$" - }, ----- -Then click on apply, and restart the LSP server for your rust project. - -=== juCi++ - -https://gitlab.com/cppit/jucipp[juCi++] has built-in support for the language server protocol, and since version 1.7.0 offers installation of both Rust and rust-analyzer when opening a Rust file. - -=== Kakoune - -https://kakoune.org/[Kakoune] supports LSP with the help of https://github.com/kak-lsp/kak-lsp[`kak-lsp`]. -Follow the https://github.com/kak-lsp/kak-lsp#installation[instructions] to install `kak-lsp`. -To configure `kak-lsp`, refer to the https://github.com/kak-lsp/kak-lsp#configuring-kak-lsp[configuration section] which is basically about copying the https://github.com/kak-lsp/kak-lsp/blob/master/kak-lsp.toml[configuration file] in the right place (latest versions should use `rust-analyzer` by default). - -Finally, you need to configure Kakoune to talk to `kak-lsp` (see https://github.com/kak-lsp/kak-lsp#usage[Usage section]). -A basic configuration will only get you LSP but you can also activate inlay diagnostics and auto-formatting on save. -The following might help you get all of this. - -[source,txt] ----- -eval %sh{kak-lsp --kakoune -s $kak_session} # Not needed if you load it with plug.kak. -hook global WinSetOption filetype=rust %{ - # Enable LSP - lsp-enable-window - - # Auto-formatting on save - hook window BufWritePre .* lsp-formatting-sync - - # Configure inlay hints (only on save) - hook window -group rust-inlay-hints BufWritePost .* rust-analyzer-inlay-hints - hook -once -always window WinSetOption filetype=.* %{ - remove-hooks window rust-inlay-hints - } -} ----- - -=== Helix - -https://docs.helix-editor.com/[Helix] supports LSP by default. -However, it won't install `rust-analyzer` automatically. -You can follow instructions for installing <>. - -== Troubleshooting - -Start with looking at the rust-analyzer version. -Try **rust-analyzer: Show RA Version** in VS Code (using **Command Palette** feature typically activated by Ctrl+Shift+P) or `rust-analyzer --version` in the command line. -If the date is more than a week ago, it's better to update rust-analyzer version. - -The next thing to check would be panic messages in rust-analyzer's log. -Log messages are printed to stderr, in VS Code you can see then in the `Output > Rust Analyzer Language Server` tab of the panel. -To see more logs, set the `RA_LOG=info` environment variable, this can be done either by setting the environment variable manually or by using `rust-analyzer.server.extraEnv`, note that both of these approaches require the server to be restarted. - -To fully capture LSP messages between the editor and the server, set `"rust-analyzer.trace.server": "verbose"` config and check -`Output > Rust Analyzer Language Server Trace`. - -The root cause for many "`nothing works`" problems is that rust-analyzer fails to understand the project structure. -To debug that, first note the `rust-analyzer` section in the status bar. -If it has an error icon and red, that's the problem (hover will have somewhat helpful error message). -**rust-analyzer: Status** prints dependency information for the current file. -Finally, `RA_LOG=project_model=debug` enables verbose logs during project loading. - -If rust-analyzer outright crashes, try running `rust-analyzer analysis-stats /path/to/project/directory/` on the command line. -This command type checks the whole project in batch mode bypassing LSP machinery. - -When filing issues, it is useful (but not necessary) to try to minimize examples. -An ideal bug reproduction looks like this: - -```bash -$ git clone https://github.com/username/repo.git && cd repo && git switch --detach commit-hash -$ rust-analyzer --version -rust-analyzer dd12184e4 2021-05-08 dev -$ rust-analyzer analysis-stats . -💀 💀 💀 -``` - -It is especially useful when the `repo` doesn't use external crates or the standard library. - -If you want to go as far as to modify the source code to debug the problem, be sure to take a look at the -https://github.com/rust-lang/rust-analyzer/tree/master/docs/dev[dev docs]! - -== Configuration - -**Source:** https://github.com/rust-lang/rust-analyzer/blob/master/crates/rust-analyzer/src/config.rs[config.rs] - -The <<_installation,Installation>> section contains details on configuration for some of the editors. -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. - -Some clients, such as <> or <> provide `rust-analyzer` specific configuration UIs. Others may require you to know a bit more about the interaction with `rust-analyzer`. - -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]. -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. -Name of the setting, ignoring the `rust-analyzer.` prefix, is used as a path, and value of the setting becomes the JSON property value. - -For example, a very common configuration is to enable proc-macro support, can be achieved by sending this JSON: - -[source,json] ----- -{ - "cargo": { - "buildScripts": { - "enable": true, - }, - }, - "procMacro": { - "enable": true, - } -} ----- - -Please consult your editor's documentation to learn more about how to configure https://microsoft.github.io/language-server-protocol/[LSP servers]. - -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. -Logs should show both the JSON that `rust-analyzer` sees as well as the updated config. - -This is the list of config options `rust-analyzer` supports: - -include::./generated_config.adoc[] - -== Non-Cargo Based Projects - -rust-analyzer does not require Cargo. -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: - -[source,TypeScript] ----- -interface JsonProject { - /// Path to the directory with *source code* of - /// sysroot crates. - /// - /// It should point to the directory where std, - /// core, and friends can be found: - /// - /// https://github.com/rust-lang/rust/tree/master/library. - /// - /// If provided, rust-analyzer automatically adds - /// dependencies on sysroot crates. Conversely, - /// if you omit this path, you can specify sysroot - /// dependencies yourself and, for example, have - /// several different "sysroots" in one graph of - /// crates. - sysroot_src?: string; - /// The set of crates comprising the current - /// project. Must include all transitive - /// dependencies as well as sysroot crate (libstd, - /// libcore and such). - crates: Crate[]; -} - -interface Crate { - /// Optional crate name used for display purposes, - /// without affecting semantics. See the `deps` - /// key for semantically-significant crate names. - display_name?: string; - /// Path to the root module of the crate. - root_module: string; - /// Edition of the crate. - edition: "2015" | "2018" | "2021"; - /// Dependencies - deps: Dep[]; - /// Should this crate be treated as a member of - /// current "workspace". - /// - /// By default, inferred from the `root_module` - /// (members are the crates which reside inside - /// the directory opened in the editor). - /// - /// Set this to `false` for things like standard - /// library and 3rd party crates to enable - /// performance optimizations (rust-analyzer - /// assumes that non-member crates don't change). - is_workspace_member?: boolean; - /// Optionally specify the (super)set of `.rs` - /// files comprising this crate. - /// - /// By default, rust-analyzer assumes that only - /// files under `root_module.parent` can belong - /// to a crate. `include_dirs` are included - /// recursively, unless a subdirectory is in - /// `exclude_dirs`. - /// - /// Different crates can share the same `source`. - /// - /// If two crates share an `.rs` file in common, - /// they *must* have the same `source`. - /// rust-analyzer assumes that files from one - /// source can't refer to files in another source. - source?: { - include_dirs: string[], - exclude_dirs: string[], - }, - /// The set of cfgs activated for a given crate, like - /// `["unix", "feature=\"foo\"", "feature=\"bar\""]`. - cfg: string[]; - /// Target triple for this Crate. - /// - /// Used when running `rustc --print cfg` - /// to get target-specific cfgs. - target?: string; - /// Environment variables, used for - /// the `env!` macro - env: { [key: string]: string; }, - - /// Whether the crate is a proc-macro crate. - is_proc_macro: boolean; - /// For proc-macro crates, path to compiled - /// proc-macro (.so file). - proc_macro_dylib_path?: string; -} - -interface Dep { - /// Index of a crate in the `crates` array. - crate: number, - /// Name as should appear in the (implicit) - /// `extern crate name` declaration. - name: string, -} ----- - -This format is provisional and subject to change. -Specifically, the `roots` setup will be different eventually. - -There are three ways to feed `rust-project.json` to rust-analyzer: - -* Place `rust-project.json` file at the root of the project, and rust-analyzer will discover it. -* 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). -* Specify `"rust-analyzer.linkedProjects": [ { "roots": [...], "crates": [...] }]` inline. - -Relative paths are interpreted relative to `rust-project.json` file location or (for inline JSON) relative to `rootUri`. - -See https://github.com/rust-analyzer/rust-project.json-example for a small example. - -You can set the `RA_LOG` environment variable to `rust_analyzer=info` to inspect how rust-analyzer handles config and project loading. - -Note that calls to `cargo check` are disabled when using `rust-project.json` by default, so compilation errors and warnings will no longer be sent to your LSP client. To enable these compilation errors you will need to specify explicitly what command rust-analyzer should run to perform the checks using the `checkOnSave.overrideCommand` configuration. As an example, the following configuration explicitly sets `cargo check` as the `checkOnSave` command. - -[source,json] ----- -{ "rust-analyzer.checkOnSave.overrideCommand": ["cargo", "check", "--message-format=json"] } ----- - -The `checkOnSave.overrideCommand` requires the command specified to output json error messages for rust-analyzer to consume. The `--message-format=json` flag does this for `cargo check` so whichever command you use must also output errors in this format. See the <> section for more information. - -== Security - -At the moment, rust-analyzer assumes that all code is trusted. -Here is a **non-exhaustive** list of ways to make rust-analyzer execute arbitrary code: - -* proc macros and build scripts are executed by default -* `.cargo/config` can override `rustc` with an arbitrary executable -* `rust-toolchain.toml` can override `rustc` with an arbitrary executable -* 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. -* rust-analyzer's syntax trees library uses a lot of `unsafe` and hasn't been properly audited for memory safety. - -== Privacy - -The LSP server performs no network access in itself, but runs `cargo metadata` which will update or download the crate registry and the source code of the project dependencies. -If enabled (the default), build scripts and procedural macros can do anything. - -The Code extension does not access the network. - -Any other editor plugins are not under the control of the `rust-analyzer` developers. For any privacy concerns, you should check with their respective developers. - -For `rust-analyzer` developers, `cargo xtask release` uses the GitHub API to put together the release notes. - -== Features - -include::./generated_features.adoc[] - -== Assists (Code Actions) - -Assists, or code actions, are small local refactorings, available in a particular context. -They are usually triggered by a shortcut or by clicking a light bulb icon in the editor. -Cursor position or selection is signified by `┃` character. - -include::./generated_assists.adoc[] - -== Diagnostics - -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. -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.experimental.enable` or `rust-analyzer.diagnostics.disabled` settings. - -include::./generated_diagnostic.adoc[] - -== Editor Features -=== VS Code - -==== Color configurations - -It is possible to change the foreground/background color and font family/size of inlay hints. -Just add this to your `settings.json`: - -[source,jsonc] ----- -{ - "editor.inlayHints.fontFamily": "Courier New", - "editor.inlayHints.fontSize": 11, - - "workbench.colorCustomizations": { - // Name of the theme you are currently using - "[Default Dark+]": { - "editorInlayHint.foreground": "#868686f0", - "editorInlayHint.background": "#3d3d3d48", - - // Overrides for specific kinds of inlay hints - "editorInlayHint.typeForeground": "#fdb6fdf0", - "editorInlayHint.parameterForeground": "#fdb6fdf0", - } - } -} ----- - -==== Semantic style customizations - -You can customize the look of different semantic elements in the source code. -For example, mutable bindings are underlined by default and you can override this behavior by adding the following section to your `settings.json`: - -[source,jsonc] ----- -{ - "editor.semanticTokenColorCustomizations": { - "rules": { - "*.mutable": { - "fontStyle": "", // underline is the default - }, - } - }, -} ----- - -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`: - -[source,jsonc] ----- -{ - "editor.semanticTokenColorCustomizations": { - "rules": { - "operator.unsafe": "#ff6600", - "function.unsafe": "#ff6600", - "method.unsafe": "#ff6600" - } - }, -} ----- - -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: - -[source,jsonc] ----- -{ - "editor.semanticTokenColorCustomizations": { - "rules": { - "operator.unsafe": "#ff6600" - }, - "[Ayu Light]": { - "rules": { - "operator.unsafe": "#572300" - } - } - }, -} ----- - -Make sure you include the brackets around the theme name. For example, use `"[Ayu Light]"` to customize the theme Ayu Light. - -==== Special `when` clause context for keybindings. -You may use `inRustProject` context to configure keybindings for rust projects only. -For example: - -[source,json] ----- -{ - "key": "ctrl+alt+d", - "command": "rust-analyzer.openDocs", - "when": "inRustProject" -} ----- -More about `when` clause contexts https://code.visualstudio.com/docs/getstarted/keybindings#_when-clause-contexts[here]. - -==== Setting runnable environment variables -You can use "rust-analyzer.runnableEnv" setting to define runnable environment-specific substitution variables. -The simplest way for all runnables in a bunch: -```jsonc -"rust-analyzer.runnableEnv": { - "RUN_SLOW_TESTS": "1" -} -``` - -Or it is possible to specify vars more granularly: -```jsonc -"rust-analyzer.runnableEnv": [ - { - // "mask": null, // null mask means that this rule will be applied for all runnables - env: { - "APP_ID": "1", - "APP_DATA": "asdf" - } - }, - { - "mask": "test_name", - "env": { - "APP_ID": "2", // overwrites only APP_ID - } - } -] -``` - -You can use any valid regular expression as a mask. -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. - -==== Compiler feedback from external commands - -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. - -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. - -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`: - -```json -{ - "label": "Watch", - "group": "build", - "type": "shell", - "command": "cargo watch", - "problemMatcher": "$rustc-watch", - "isBackground": true -} -``` - -==== Live Share - -VS Code Live Share has partial support for rust-analyzer. - -Live Share _requires_ the official Microsoft build of VS Code, OSS builds will not work correctly. - -The host's rust-analyzer instance will be shared with all guests joining the session. -The guests do not have to have the rust-analyzer extension installed for this to work. - -If you are joining a Live Share session and _do_ have rust-analyzer installed locally, commands from the command palette will not work correctly since they will attempt to communicate with the local server.