]> git.lizzy.rs Git - rust.git/commitdiff
Fix introduce var duplicating newlines
authorVille Penttinen <villem.penttinen@gmail.com>
Sat, 9 Feb 2019 11:41:03 +0000 (13:41 +0200)
committerVille Penttinen <villem.penttinen@gmail.com>
Sat, 9 Feb 2019 11:52:01 +0000 (13:52 +0200)
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.

crates/ra_assists/src/introduce_variable.rs

index 934d1d6b3ca2b5a5be12f768eae62ede6045d6ef..954b97b055db3e465bfa3a3db43ff95ab34e82a0 100644 (file)
@@ -44,7 +44,22 @@ pub(crate) fn introduce_variable(ctx: AssistCtx<impl HirDatabase>) -> Option<Ass
             edit.replace(expr.syntax().range(), buf);
         } else {
             buf.push_str(";");
-            indent.text().push_to(&mut buf);
+
+            // We want to maintain the indent level,
+            // but we do not want to duplicate possible
+            // extra newlines in the indent block
+            for chunk in indent.text().chunks() {
+                if chunk.starts_with("\r\n") {
+                    buf.push_str("\r\n");
+                    buf.push_str(chunk.trim_start_matches("\r\n"));
+                } else if chunk.starts_with("\n") {
+                    buf.push_str("\n");
+                    buf.push_str(chunk.trim_start_matches("\n"));
+                } else {
+                    buf.push_str(chunk);
+                }
+            }
+
             edit.target(expr.syntax().range());
             edit.replace(expr.syntax().range(), "var_name".to_string());
             edit.insert(anchor_stmt.range().start(), buf);
@@ -337,6 +352,70 @@ fn foo() -> u32 {
 ",
             "
 fn foo() -> u32 {
+    let <|>var_name = 2 + 2;
+    return var_name;
+}
+",
+        );
+    }
+
+    #[test]
+    fn test_introduce_var_does_not_add_extra_whitespace() {
+        check_assist(
+            introduce_variable,
+            "
+fn foo() -> u32 {
+
+
+    r<|>eturn 2 + 2;
+}
+",
+            "
+fn foo() -> u32 {
+
+
+    let <|>var_name = 2 + 2;
+    return var_name;
+}
+",
+        );
+
+        check_assist(
+            introduce_variable,
+            "
+fn foo() -> u32 {
+
+        r<|>eturn 2 + 2;
+}
+",
+            "
+fn foo() -> u32 {
+
+        let <|>var_name = 2 + 2;
+        return var_name;
+}
+",
+        );
+
+        check_assist(
+            introduce_variable,
+            "
+fn foo() -> u32 {
+    let foo = 1;
+
+    // bar
+
+
+    r<|>eturn 2 + 2;
+}
+",
+            "
+fn foo() -> u32 {
+    let foo = 1;
+
+    // bar
+
+
     let <|>var_name = 2 + 2;
     return var_name;
 }