Skip to content

Commit 2df498f

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 d5f1200 commit 2df498f

File tree

3 files changed

+43
-1
lines changed

3 files changed

+43
-1
lines changed

src/comment.rs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -824,7 +824,14 @@ impl<'a> CommentRewrite<'a> {
824824
} else if self.is_prev_line_multi_line && !line.is_empty() {
825825
self.result.push(' ')
826826
} else if is_last && line.is_empty() {
827-
// trailing blank lines are unwanted
827+
// Trailing blank lines are unwanted; if the last line is blank, look for additional,
828+
// preceding blank lines to remove, also.
829+
let trailing_line = self.comment_line_separator.trim_end_matches(' ');
830+
while self.result
831+
.ends_with(trailing_line)
832+
{
833+
self.result.truncate(self.result.len() - trailing_line.len());
834+
}
828835
if !self.closer.is_empty() {
829836
self.result.push_str(&self.indent_str);
830837
}
Lines changed: 21 additions & 0 deletions
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 {}
Lines changed: 14 additions & 0 deletions
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)