1 //! User (postfix)-snippet definitions.
3 //! Actual logic is implemented in [`crate::completions::postfix`] and [`crate::completions::snippet`] respectively.
7 // Feature: User Snippet Completions
9 // rust-analyzer allows the user to define custom (postfix)-snippets that may depend on items to be accessible for the current scope to be applicable.
11 // A custom snippet can be defined by adding it to the `rust-analyzer.completion.snippets` object respectively.
16 // "rust-analyzer.completion.snippets": {
18 // "prefix": ["spawn", "tspawn"],
20 // "thread::spawn(move || {",
24 // "description": "Insert a thread::spawn call",
25 // "requires": "std::thread",
32 // In the example above:
34 // * `"thread spawn"` is the name of the snippet.
36 // * `prefix` defines one or more trigger words that will trigger the snippets completion.
37 // Using `postfix` will instead create a postfix snippet.
39 // * `body` is one or more lines of content joined via newlines for the final output.
41 // * `description` is an optional description of the snippet, if unset the snippet name will be used.
43 // * `requires` is an optional list of item paths that have to be resolvable in the current crate where the completion is rendered.
44 // On failure of resolution the snippet won't be applicable, otherwise the snippet will insert an import for the items on insertion if
45 // the items aren't yet in scope.
47 // * `scope` is an optional filter for when the snippet should be applicable. Possible values are:
48 // ** for Snippet-Scopes: `expr`, `item` (default: `item`)
49 // ** for Postfix-Snippet-Scopes: `expr`, `type` (default: `expr`)
51 // The `body` field also has access to placeholders as visible in the example as `$0`.
52 // These placeholders take the form of `$number` or `${number:placeholder_text}` which can be traversed as tabstop in ascending order starting from 1,
53 // with `$0` being a special case that always comes last.
55 // There is also a special placeholder, `${receiver}`, which will be replaced by the receiver expression for postfix snippets, or a `$0` tabstop in case of normal snippets.
56 // This replacement for normal snippets allows you to reuse a snippet for both post- and prefix in a single definition.
58 // For the VSCode editor, rust-analyzer also ships with a small set of defaults which can be removed
59 // by overwriting the settings object mentioned above, the defaults are:
65 // "body": "Arc::new(${receiver})",
66 // "requires": "std::sync::Arc",
67 // "description": "Put the expression into an `Arc`",
72 // "body": "Rc::new(${receiver})",
73 // "requires": "std::rc::Rc",
74 // "description": "Put the expression into an `Rc`",
78 // "postfix": "pinbox",
79 // "body": "Box::pin(${receiver})",
80 // "requires": "std::boxed::Box",
81 // "description": "Put the expression into a pinned `Box`",
86 // "body": "Ok(${receiver})",
87 // "description": "Wrap the expression in a `Result::Ok`",
92 // "body": "Err(${receiver})",
93 // "description": "Wrap the expression in a `Result::Err`",
98 // "body": "Some(${receiver})",
99 // "description": "Wrap the expression in an `Option::Some`",
105 use ide_db::helpers::{import_assets::LocatedImport, insert_use::ImportScope};
106 use itertools::Itertools;
107 use syntax::{ast, AstNode, GreenNode, SyntaxNode};
109 use crate::{context::CompletionContext, ImportEdit};
111 /// A snippet scope describing where a snippet may apply to.
112 /// These may differ slightly in meaning depending on the snippet trigger.
113 #[derive(Clone, Debug, PartialEq, Eq)]
114 pub enum SnippetScope {
120 /// A user supplied snippet.
121 #[derive(Clone, Debug, PartialEq, Eq)]
123 pub postfix_triggers: Box<[Box<str>]>,
124 pub prefix_triggers: Box<[Box<str>]>,
125 pub scope: SnippetScope,
126 pub description: Option<Box<str>>,
128 // These are `ast::Path`'s but due to SyntaxNodes not being Send we store these
129 // and reconstruct them on demand instead. This is cheaper than reparsing them
131 requires: Box<[GreenNode]>,
136 prefix_triggers: &[String],
137 postfix_triggers: &[String],
143 if prefix_triggers.is_empty() && postfix_triggers.is_empty() {
146 let (requires, snippet, description) = validate_snippet(snippet, description, requires)?;
148 // Box::into doesn't work as that has a Copy bound 😒
149 postfix_triggers: postfix_triggers.iter().map(Deref::deref).map(Into::into).collect(),
150 prefix_triggers: prefix_triggers.iter().map(Deref::deref).map(Into::into).collect(),
158 /// Returns [`None`] if the required items do not resolve.
159 pub(crate) fn imports(
161 ctx: &CompletionContext,
162 import_scope: &ImportScope,
163 ) -> Option<Vec<ImportEdit>> {
164 import_edits(ctx, import_scope, &self.requires)
167 pub fn snippet(&self) -> String {
168 self.snippet.replace("${receiver}", "$0")
171 pub fn postfix_snippet(&self, receiver: &str) -> String {
172 self.snippet.replace("${receiver}", receiver)
177 ctx: &CompletionContext,
178 import_scope: &ImportScope,
179 requires: &[GreenNode],
180 ) -> Option<Vec<ImportEdit>> {
181 let resolve = |import: &GreenNode| {
182 let path = ast::Path::cast(SyntaxNode::new_root(import.clone()))?;
183 let item = match ctx.scope.speculative_resolve(&path)? {
184 hir::PathResolution::Macro(mac) => mac.into(),
185 hir::PathResolution::Def(def) => def.into(),
188 let path = ctx.scope.module()?.find_use_path_prefixed(
191 ctx.config.insert_use.prefix_kind,
193 Some((path.len() > 1).then(|| ImportEdit {
194 import: LocatedImport::new(path.clone(), item, item, None),
195 scope: import_scope.clone(),
198 let mut res = Vec::with_capacity(requires.len());
199 for import in requires {
200 match resolve(import) {
201 Some(first) => res.extend(first),
212 ) -> Option<(Box<[GreenNode]>, String, Option<Box<str>>)> {
213 let mut imports = Vec::with_capacity(requires.len());
214 for path in requires.iter() {
215 let path = ast::Path::parse(path).ok()?;
216 let valid_use_path = path.segments().all(|seg| {
217 matches!(seg.kind(), Some(ast::PathSegmentKind::Name(_)))
218 || seg.generic_arg_list().is_none()
223 let green = path.syntax().green().into_owned();
226 let snippet = snippet.iter().join("\n");
227 let description = (!description.is_empty())
228 .then(|| description.split_once('\n').map_or(description, |(it, _)| it))
229 .map(ToOwned::to_owned)
231 Some((imports.into_boxed_slice(), snippet, description))