Skip to content

Commit b06c5fa

Browse files
author
Geobert Quach
committed
feat(assists): Be smart about hashes
Add max_hashes_streak + 1 hashes to the raw string
1 parent e293c34 commit b06c5fa

File tree

1 file changed

+36
-1
lines changed

1 file changed

+36
-1
lines changed

crates/ra_assists/src/assists/raw_string.rs

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,25 @@ pub(crate) fn make_raw_string(mut ctx: AssistCtx<impl HirDatabase>) -> Option<As
2828
if error.is_err() {
2929
eprintln!("Error unescaping string");
3030
} else {
31-
edit.replace(literal.syntax().text_range(), format!("r#\"{}\"#", unescaped));
31+
let mut max_hash_streak = 0;
32+
unescaped.chars().fold(0, |acc, c| {
33+
if c == '#' {
34+
acc + 1
35+
} else {
36+
if acc > max_hash_streak {
37+
max_hash_streak = acc;
38+
}
39+
0
40+
}
41+
});
42+
let mut hashes = String::with_capacity(max_hash_streak + 1);
43+
for _ in 0..hashes.capacity() {
44+
hashes.push('#');
45+
}
46+
edit.replace(
47+
literal.syntax().text_range(),
48+
format!("r{}\"{}\"{}", hashes, unescaped, hashes),
49+
);
3250
}
3351
});
3452
ctx.build()
@@ -136,6 +154,23 @@ string"#;
136154
)
137155
}
138156

157+
#[test]
158+
fn make_raw_string_hashes_inside_works() {
159+
check_assist(
160+
make_raw_string,
161+
r###"
162+
fn f() {
163+
let s = <|>"#random##\nstring";
164+
}
165+
"###,
166+
r####"
167+
fn f() {
168+
let s = <|>r###"#random##
169+
string"###;
170+
}
171+
"####,
172+
)
173+
}
139174
#[test]
140175
fn make_raw_string_nothing_to_unescape_works() {
141176
check_assist(

0 commit comments

Comments
 (0)