aboutsummaryrefslogtreecommitdiff
path: root/crates/ide_completion/src/completions/snippet.rs
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ide_completion/src/completions/snippet.rs')
-rw-r--r--crates/ide_completion/src/completions/snippet.rs116
1 files changed, 116 insertions, 0 deletions
diff --git a/crates/ide_completion/src/completions/snippet.rs b/crates/ide_completion/src/completions/snippet.rs
new file mode 100644
index 000000000..df17a15c5
--- /dev/null
+++ b/crates/ide_completion/src/completions/snippet.rs
@@ -0,0 +1,116 @@
1//! This file provides snippet completions, like `pd` => `eprintln!(...)`.
2
3use ide_db::helpers::SnippetCap;
4
5use crate::{
6 item::Builder, CompletionContext, CompletionItem, CompletionItemKind, CompletionKind,
7 Completions,
8};
9
10fn snippet(ctx: &CompletionContext, cap: SnippetCap, label: &str, snippet: &str) -> Builder {
11 CompletionItem::new(CompletionKind::Snippet, ctx.source_range(), label)
12 .insert_snippet(cap, snippet)
13 .kind(CompletionItemKind::Snippet)
14}
15
16pub(crate) fn complete_expr_snippet(acc: &mut Completions, ctx: &CompletionContext) {
17 if !(ctx.is_trivial_path && ctx.function_syntax.is_some()) {
18 return;
19 }
20 let cap = match ctx.config.snippet_cap {
21 Some(it) => it,
22 None => return,
23 };
24
25 snippet(ctx, cap, "pd", "eprintln!(\"$0 = {:?}\", $0);").add_to(acc);
26 snippet(ctx, cap, "ppd", "eprintln!(\"$0 = {:#?}\", $0);").add_to(acc);
27}
28
29pub(crate) fn complete_item_snippet(acc: &mut Completions, ctx: &CompletionContext) {
30 if !ctx.is_new_item {
31 return;
32 }
33 let cap = match ctx.config.snippet_cap {
34 Some(it) => it,
35 None => return,
36 };
37
38 snippet(
39 ctx,
40 cap,
41 "tmod (Test module)",
42 "\
43#[cfg(test)]
44mod tests {
45 use super::*;
46
47 #[test]
48 fn ${1:test_name}() {
49 $0
50 }
51}",
52 )
53 .lookup_by("tmod")
54 .add_to(acc);
55
56 snippet(
57 ctx,
58 cap,
59 "tfn (Test function)",
60 "\
61#[test]
62fn ${1:feature}() {
63 $0
64}",
65 )
66 .lookup_by("tfn")
67 .add_to(acc);
68
69 snippet(ctx, cap, "macro_rules", "macro_rules! $1 {\n\t($2) => {\n\t\t$0\n\t};\n}").add_to(acc);
70}
71
72#[cfg(test)]
73mod tests {
74 use expect_test::{expect, Expect};
75
76 use crate::{test_utils::completion_list, CompletionKind};
77
78 fn check(ra_fixture: &str, expect: Expect) {
79 let actual = completion_list(ra_fixture, CompletionKind::Snippet);
80 expect.assert_eq(&actual)
81 }
82
83 #[test]
84 fn completes_snippets_in_expressions() {
85 check(
86 r#"fn foo(x: i32) { $0 }"#,
87 expect![[r#"
88 sn pd
89 sn ppd
90 "#]],
91 );
92 }
93
94 #[test]
95 fn should_not_complete_snippets_in_path() {
96 check(r#"fn foo(x: i32) { ::foo$0 }"#, expect![[""]]);
97 check(r#"fn foo(x: i32) { ::$0 }"#, expect![[""]]);
98 }
99
100 #[test]
101 fn completes_snippets_in_items() {
102 check(
103 r#"
104#[cfg(test)]
105mod tests {
106 $0
107}
108"#,
109 expect![[r#"
110 sn tmod (Test module)
111 sn tfn (Test function)
112 sn macro_rules
113 "#]],
114 )
115 }
116}