Skip to content

Commit 7b9aefc

Browse files
committed
Fix introduce var duplicating newlines
This fixes #713. If the block before the statement we want to use introduce var on, had empty lines these empty lines would also be added between the let-statement and the current line where the new variable is used. This fixes that by trimming excess newlines from the start of the indent chunk and simply adding a single newline (when the chunk had newlines) between the let-statement and the current statement. If there were no newlines this matches the previous behaviour.
1 parent d0a3262 commit 7b9aefc

File tree

1 file changed

+80
-1
lines changed

1 file changed

+80
-1
lines changed

crates/ra_assists/src/introduce_variable.rs

Lines changed: 80 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,22 @@ pub(crate) fn introduce_variable(ctx: AssistCtx<impl HirDatabase>) -> Option<Ass
4444
edit.replace(expr.syntax().range(), buf);
4545
} else {
4646
buf.push_str(";");
47-
indent.text().push_to(&mut buf);
47+
48+
// We want to maintain the indent level,
49+
// but we do not want to duplicate possible
50+
// extra newlines in the indent block
51+
for chunk in indent.text().chunks() {
52+
if chunk.starts_with("\r\n") {
53+
buf.push_str("\r\n");
54+
buf.push_str(chunk.trim_start_matches("\r\n"));
55+
} else if chunk.starts_with("\n") {
56+
buf.push_str("\n");
57+
buf.push_str(chunk.trim_start_matches("\n"));
58+
} else {
59+
buf.push_str(chunk);
60+
}
61+
}
62+
4863
edit.target(expr.syntax().range());
4964
edit.replace(expr.syntax().range(), "var_name".to_string());
5065
edit.insert(anchor_stmt.range().start(), buf);
@@ -337,6 +352,70 @@ fn foo() -> u32 {
337352
",
338353
"
339354
fn foo() -> u32 {
355+
let <|>var_name = 2 + 2;
356+
return var_name;
357+
}
358+
",
359+
);
360+
}
361+
362+
#[test]
363+
fn test_introduce_var_does_not_add_extra_whitespace() {
364+
check_assist(
365+
introduce_variable,
366+
"
367+
fn foo() -> u32 {
368+
369+
370+
r<|>eturn 2 + 2;
371+
}
372+
",
373+
"
374+
fn foo() -> u32 {
375+
376+
377+
let <|>var_name = 2 + 2;
378+
return var_name;
379+
}
380+
",
381+
);
382+
383+
check_assist(
384+
introduce_variable,
385+
"
386+
fn foo() -> u32 {
387+
388+
r<|>eturn 2 + 2;
389+
}
390+
",
391+
"
392+
fn foo() -> u32 {
393+
394+
let <|>var_name = 2 + 2;
395+
return var_name;
396+
}
397+
",
398+
);
399+
400+
check_assist(
401+
introduce_variable,
402+
"
403+
fn foo() -> u32 {
404+
let foo = 1;
405+
406+
// bar
407+
408+
409+
r<|>eturn 2 + 2;
410+
}
411+
",
412+
"
413+
fn foo() -> u32 {
414+
let foo = 1;
415+
416+
// bar
417+
418+
340419
let <|>var_name = 2 + 2;
341420
return var_name;
342421
}

0 commit comments

Comments
 (0)