ide_completion/snippet.rs
1//! User (postfix)-snippet definitions.
2//!
3//! Actual logic is implemented in [`crate::completions::postfix`] and [`crate::completions::snippet`] respectively.
4
5// Feature: User Snippet Completions
6//
7// 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.
8//
9// A custom snippet can be defined by adding it to the `rust-analyzer.completion.snippets.custom` object respectively.
10//
11// ```json
12// {
13// "rust-analyzer.completion.snippets.custom": {
14// "thread spawn": {
15// "prefix": ["spawn", "tspawn"],
16// "body": [
17// "thread::spawn(move || {",
18// "\t$0",
19// "});",
20// ],
21// "description": "Insert a thread::spawn call",
22// "requires": "std::thread",
23// "scope": "expr",
24// }
25// }
26// }
27// ```
28//
29// In the example above:
30//
31// * `"thread spawn"` is the name of the snippet.
32//
33// * `prefix` defines one or more trigger words that will trigger the snippets completion.
34// Using `postfix` will instead create a postfix snippet.
35//
36// * `body` is one or more lines of content joined via newlines for the final output.
37//
38// * `description` is an optional description of the snippet, if unset the snippet name will be used.
39//
40// * `requires` is an optional list of item paths that have to be resolvable in the current crate where the completion is rendered.
41// On failure of resolution the snippet won't be applicable, otherwise the snippet will insert an import for the items on insertion if
42// the items aren't yet in scope.
43//
44// * `scope` is an optional filter for when the snippet should be applicable. Possible values are:
45// * for Snippet-Scopes: `expr`, `item` (default: `item`)
46// * for Postfix-Snippet-Scopes: `expr`, `type` (default: `expr`)
47//
48// The `body` field also has access to placeholders as visible in the example as `$0`.
49// These placeholders take the form of `$number` or `${number:placeholder_text}` which can be traversed as tabstop in ascending order starting from 1,
50// with `$0` being a special case that always comes last.
51//
52// 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.
53// This replacement for normal snippets allows you to reuse a snippet for both post- and prefix in a single definition.
54//
55// For the VSCode editor, rust-analyzer also ships with a small set of defaults which can be removed
56// by overwriting the settings object mentioned above, the defaults are:
57//
58// ```json
59// {
60// "Arc::new": {
61// "postfix": "arc",
62// "body": "Arc::new(${receiver})",
63// "requires": "std::sync::Arc",
64// "description": "Put the expression into an `Arc`",
65// "scope": "expr"
66// },
67// "Rc::new": {
68// "postfix": "rc",
69// "body": "Rc::new(${receiver})",
70// "requires": "std::rc::Rc",
71// "description": "Put the expression into an `Rc`",
72// "scope": "expr"
73// },
74// "Box::pin": {
75// "postfix": "pinbox",
76// "body": "Box::pin(${receiver})",
77// "requires": "std::boxed::Box",
78// "description": "Put the expression into a pinned `Box`",
79// "scope": "expr"
80// },
81// "Ok": {
82// "postfix": "ok",
83// "body": "Ok(${receiver})",
84// "description": "Wrap the expression in a `Result::Ok`",
85// "scope": "expr"
86// },
87// "Err": {
88// "postfix": "err",
89// "body": "Err(${receiver})",
90// "description": "Wrap the expression in a `Result::Err`",
91// "scope": "expr"
92// },
93// "Some": {
94// "postfix": "some",
95// "body": "Some(${receiver})",
96// "description": "Wrap the expression in an `Option::Some`",
97// "scope": "expr"
98// }
99// }
100// ```
101
102use hir::{ModPath, Name, Symbol};
103use ide_db::imports::import_assets::LocatedImport;
104use itertools::Itertools;
105
106use crate::context::CompletionContext;
107
108/// A snippet scope describing where a snippet may apply to.
109/// These may differ slightly in meaning depending on the snippet trigger.
110#[derive(Clone, Debug, PartialEq, Eq)]
111pub enum SnippetScope {
112 Item,
113 Expr,
114 Type,
115}
116
117/// A user supplied snippet.
118#[derive(Clone, Debug, PartialEq, Eq)]
119pub struct Snippet {
120 pub postfix_triggers: Box<[Box<str>]>,
121 pub prefix_triggers: Box<[Box<str>]>,
122 pub scope: SnippetScope,
123 pub description: Option<Box<str>>,
124 snippet: String,
125 requires: Box<[ModPath]>,
126}
127
128impl Snippet {
129 pub fn new(
130 prefix_triggers: &[String],
131 postfix_triggers: &[String],
132 snippet: &[String],
133 description: &str,
134 requires: &[String],
135 scope: SnippetScope,
136 ) -> Option<Self> {
137 if prefix_triggers.is_empty() && postfix_triggers.is_empty() {
138 return None;
139 }
140 let (requires, snippet, description) = validate_snippet(snippet, description, requires)?;
141 Some(Snippet {
142 postfix_triggers: postfix_triggers.iter().map(String::as_str).map(Into::into).collect(),
143 prefix_triggers: prefix_triggers.iter().map(String::as_str).map(Into::into).collect(),
144 scope,
145 snippet,
146 description,
147 requires,
148 })
149 }
150
151 /// Returns [`None`] if the required items do not resolve.
152 pub(crate) fn imports(&self, ctx: &CompletionContext<'_, '_>) -> Option<Vec<LocatedImport>> {
153 import_edits(ctx, &self.requires)
154 }
155
156 pub fn snippet(&self) -> String {
157 self.snippet.replace("${receiver}", "$0")
158 }
159
160 pub fn postfix_snippet(&self, receiver: &str) -> String {
161 self.snippet.replace("${receiver}", receiver)
162 }
163}
164
165fn import_edits(
166 ctx: &CompletionContext<'_, '_>,
167 requires: &[ModPath],
168) -> Option<Vec<LocatedImport>> {
169 let import_cfg = ctx.config.find_path_config(ctx.is_nightly);
170
171 let resolve = |import| {
172 let item = ctx.scope.resolve_mod_path(import).next()?;
173 let path = ctx.module.find_use_path(
174 ctx.db,
175 item,
176 ctx.config.insert_use.prefix_kind,
177 import_cfg,
178 )?;
179 Some((path.len() > 1).then(|| LocatedImport::new_no_completion(path.clone(), item, item)))
180 };
181 let mut res = Vec::with_capacity(requires.len());
182 for import in requires {
183 res.extend(resolve(import)?)
184 }
185 Some(res)
186}
187
188fn validate_snippet(
189 snippet: &[String],
190 description: &str,
191 requires: &[String],
192) -> Option<(Box<[ModPath]>, String, Option<Box<str>>)> {
193 let mut imports = Vec::with_capacity(requires.len());
194 for path in requires.iter() {
195 let use_path = ModPath::from_segments(
196 hir::PathKind::Plain,
197 path.split("::").map(Symbol::intern).map(Name::new_symbol_root),
198 );
199 imports.push(use_path);
200 }
201 let snippet = snippet.iter().join("\n");
202 let description = (!description.is_empty())
203 .then(|| description.split_once('\n').map_or(description, |(it, _)| it))
204 .map(ToOwned::to_owned)
205 .map(Into::into);
206 Some((imports.into_boxed_slice(), snippet, description))
207}