Skip to content

Commit c7504a2

Browse files
committed
Remove multiple trailing lines in comments
Previously, rustfmt would remove one blank, trailing line in a comment every time it ran, so formatting was not idempotent if a comment had multiple trailing lines. Comments are only reformatted in this way if `comment::rewrite_comment_inner` is called, which is enabled by any of the config options `normalize_comments`, `wrap_comments`, or `format_code_in_doc_comments` (for doc comments only). Absent those config options, no trailing line reformatting occurs at all. In this commit, when the existing condition that detects a blank, trailing line is true, any preceding blank lines are removed from the reformatted comment. A source/target "system test" was added to prevent regression. Signed-off-by: Ross Williams <ross@ross-williams.net>
1 parent cf352a7 commit c7504a2

File tree

3 files changed

+42
-1
lines changed

3 files changed

+42
-1
lines changed

src/comment.rs

+7-1
Original file line numberDiff line numberDiff line change
@@ -811,7 +811,13 @@ impl<'a> CommentRewrite<'a> {
811811
} else if self.is_prev_line_multi_line && !line.is_empty() {
812812
self.result.push(' ')
813813
} else if is_last && line.is_empty() {
814-
// trailing blank lines are unwanted
814+
// Trailing blank lines are unwanted; if the last line is blank, look for additional,
815+
// preceding blank lines to remove, also.
816+
let trailing_line = self.comment_line_separator.trim_end_matches(' ');
817+
while self.result.ends_with(trailing_line) {
818+
self.result
819+
.truncate(self.result.len() - trailing_line.len());
820+
}
815821
if !self.closer.is_empty() {
816822
self.result.push_str(&self.indent_str);
817823
}
+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// rustfmt-wrap_comments: true
2+
3+
//! Module comment with multiple trailing lines
4+
//!
5+
//!
6+
7+
/// Doc comment with multiple trailing lines
8+
///
9+
///
10+
pub mod foo {}
11+
12+
/// Doc comment with one trailing line
13+
///
14+
pub mod bar {}
15+
16+
/*
17+
* Block comment with multiple trailing lines
18+
*
19+
*
20+
*/
21+
pub mod block {}
+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
// rustfmt-wrap_comments: true
2+
3+
//! Module comment with multiple trailing lines
4+
5+
/// Doc comment with multiple trailing lines
6+
pub mod foo {}
7+
8+
/// Doc comment with one trailing line
9+
pub mod bar {}
10+
11+
/*
12+
* Block comment with multiple trailing lines
13+
*/
14+
pub mod block {}

0 commit comments

Comments
 (0)