]> git.lizzy.rs Git - rust.git/commitdiff
Preserve trailing two whitespace in comments
authorSeiichi Uchida <seuchida@gmail.com>
Tue, 13 Feb 2018 09:27:54 +0000 (18:27 +0900)
committerSeiichi Uchida <seuchida@gmail.com>
Tue, 13 Feb 2018 10:39:37 +0000 (19:39 +0900)
Closes #2434.

rustfmt-core/src/comment.rs
rustfmt-core/tests/source/markdown-comment.rs [new file with mode: 0644]
rustfmt-core/tests/target/markdown-comment.rs [new file with mode: 0644]

index 9c0322bcaeb194cd040cf94069e996210ae21f60..ccb69442ff7d830189111959be836f85bf303a7a 100644 (file)
@@ -494,6 +494,15 @@ pub fn recover_missing_comment_in_span(
     }
 }
 
+/// Trim trailing whitespaces unless they consist of two whitespaces.
+fn trim_right_unless_two_whitespaces(s: &str) -> &str {
+    if s.ends_with("  ") && !s.chars().rev().nth(2).map_or(true, char::is_whitespace) {
+        s
+    } else {
+        s.trim_right()
+    }
+}
+
 /// Trims whitespace and aligns to indent, but otherwise does not change comments.
 fn light_rewrite_comment(orig: &str, offset: Indent, config: &Config) -> Option<String> {
     let lines: Vec<&str> = orig.lines()
@@ -502,7 +511,7 @@ fn light_rewrite_comment(orig: &str, offset: Indent, config: &Config) -> Option<
             // with `*` we want to leave one space before it, so it aligns with the
             // `*` in `/*`.
             let first_non_whitespace = l.find(|c| !char::is_whitespace(c));
-            if let Some(fnw) = first_non_whitespace {
+            let left_trimmed = if let Some(fnw) = first_non_whitespace {
                 if l.as_bytes()[fnw] == b'*' && fnw > 0 {
                     &l[fnw - 1..]
                 } else {
@@ -510,7 +519,9 @@ fn light_rewrite_comment(orig: &str, offset: Indent, config: &Config) -> Option<
                 }
             } else {
                 ""
-            }.trim_right()
+            };
+            // Preserve markdown's double-space line break syntax.
+            trim_right_unless_two_whitespaces(left_trimmed)
         })
         .collect();
     Some(lines.join(&format!("\n{}", offset.to_string(config))))
diff --git a/rustfmt-core/tests/source/markdown-comment.rs b/rustfmt-core/tests/source/markdown-comment.rs
new file mode 100644 (file)
index 0000000..265f97f
--- /dev/null
@@ -0,0 +1,11 @@
+//! hello world  
+//! hello world 
+
+/// hello world  
+/// hello world 
+fn foo() {
+    // hello world  
+    // hello world 
+    let x = 3;
+    println!("x = {}", x);
+}
diff --git a/rustfmt-core/tests/target/markdown-comment.rs b/rustfmt-core/tests/target/markdown-comment.rs
new file mode 100644 (file)
index 0000000..20dc726
--- /dev/null
@@ -0,0 +1,11 @@
+//! hello world  
+//! hello world
+
+/// hello world  
+/// hello world
+fn foo() {
+    // hello world  
+    // hello world
+    let x = 3;
+    println!("x = {}", x);
+}