aboutsummaryrefslogtreecommitdiff
path: root/crates/ide_assists/src/handlers/replace_string_with_char.rs
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ide_assists/src/handlers/replace_string_with_char.rs')
-rw-r--r--crates/ide_assists/src/handlers/replace_string_with_char.rs137
1 files changed, 137 insertions, 0 deletions
diff --git a/crates/ide_assists/src/handlers/replace_string_with_char.rs b/crates/ide_assists/src/handlers/replace_string_with_char.rs
new file mode 100644
index 000000000..317318c24
--- /dev/null
+++ b/crates/ide_assists/src/handlers/replace_string_with_char.rs
@@ -0,0 +1,137 @@
1use syntax::{ast, AstToken, SyntaxKind::STRING};
2
3use crate::{AssistContext, AssistId, AssistKind, Assists};
4
5// Assist: replace_string_with_char
6//
7// Replace string with char.
8//
9// ```
10// fn main() {
11// find("{$0");
12// }
13// ```
14// ->
15// ```
16// fn main() {
17// find('{');
18// }
19// ```
20pub(crate) fn replace_string_with_char(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
21 let token = ctx.find_token_syntax_at_offset(STRING).and_then(ast::String::cast)?;
22 let value = token.value()?;
23 let target = token.syntax().text_range();
24
25 if value.chars().take(2).count() != 1 {
26 return None;
27 }
28
29 acc.add(
30 AssistId("replace_string_with_char", AssistKind::RefactorRewrite),
31 "Replace string with char",
32 target,
33 |edit| {
34 edit.replace(token.syntax().text_range(), format!("'{}'", value));
35 },
36 )
37}
38
39#[cfg(test)]
40mod tests {
41 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
42
43 use super::*;
44
45 #[test]
46 fn replace_string_with_char_target() {
47 check_assist_target(
48 replace_string_with_char,
49 r#"
50 fn f() {
51 let s = "$0c";
52 }
53 "#,
54 r#""c""#,
55 );
56 }
57
58 #[test]
59 fn replace_string_with_char_assist() {
60 check_assist(
61 replace_string_with_char,
62 r#"
63 fn f() {
64 let s = "$0c";
65 }
66 "#,
67 r##"
68 fn f() {
69 let s = 'c';
70 }
71 "##,
72 )
73 }
74
75 #[test]
76 fn replace_string_with_char_assist_with_emoji() {
77 check_assist(
78 replace_string_with_char,
79 r#"
80 fn f() {
81 let s = "$0😀";
82 }
83 "#,
84 r##"
85 fn f() {
86 let s = '😀';
87 }
88 "##,
89 )
90 }
91
92 #[test]
93 fn replace_string_with_char_assist_not_applicable() {
94 check_assist_not_applicable(
95 replace_string_with_char,
96 r#"
97 fn f() {
98 let s = "$0test";
99 }
100 "#,
101 )
102 }
103
104 #[test]
105 fn replace_string_with_char_works_inside_macros() {
106 check_assist(
107 replace_string_with_char,
108 r#"
109 fn f() {
110 format!($0"x", 92)
111 }
112 "#,
113 r##"
114 fn f() {
115 format!('x', 92)
116 }
117 "##,
118 )
119 }
120
121 #[test]
122 fn replace_string_with_char_works_func_args() {
123 check_assist(
124 replace_string_with_char,
125 r#"
126 fn f() {
127 find($0"x");
128 }
129 "#,
130 r##"
131 fn f() {
132 find('x');
133 }
134 "##,
135 )
136 }
137}