Skip to content

Commit 0489bbc

Browse files
authored
Match Black's formatting of trailing comments containing NBSP (#7030)
1 parent 60132da commit 0489bbc

File tree

2 files changed

+12
-11
lines changed

2 files changed

+12
-11
lines changed

crates/ruff_python_formatter/src/comments/format.rs

+10-9
Original file line numberDiff line numberDiff line change
@@ -474,18 +474,19 @@ fn normalize_comment<'a>(
474474
if content.starts_with('\u{A0}') {
475475
let trimmed = content.trim_start_matches('\u{A0}');
476476

477-
// Black adds a space before the non-breaking space if part of a type pragma.
478477
if trimmed.trim_start().starts_with("type:") {
479-
return Ok(Cow::Owned(std::format!("# \u{A0}{trimmed}")));
480-
}
481-
482-
// Black replaces the non-breaking space with a space if followed by a space.
483-
if trimmed.starts_with(' ') {
484-
return Ok(Cow::Owned(std::format!("# {trimmed}")));
478+
// Black adds a space before the non-breaking space if part of a type pragma.
479+
Ok(Cow::Owned(std::format!("# {content}")))
480+
} else if trimmed.starts_with(' ') {
481+
// Black replaces the non-breaking space with a space if followed by a space.
482+
Ok(Cow::Owned(std::format!("# {trimmed}")))
483+
} else {
484+
// Otherwise we replace the first non-breaking space with a regular space.
485+
Ok(Cow::Owned(std::format!("# {}", &content["\u{A0}".len()..])))
485486
}
487+
} else {
488+
Ok(Cow::Owned(std::format!("# {}", content.trim_start())))
486489
}
487-
488-
Ok(Cow::Owned(std::format!("# {}", content.trim_start())))
489490
}
490491

491492
/// A helper for stripping '#' from comments.

crates/ruff_python_formatter/tests/snapshots/format@trailing_comments.py.snap

+2-2
Original file line numberDiff line numberDiff line change
@@ -65,11 +65,11 @@ i = "" #   type: Add space before leading NBSP followed by spaces
6565
i = "" # type: A space is added
6666
i = "" #   type: Add space before leading NBSP followed by a space
6767
i = "" #  type: Add space before leading NBSP
68-
i = "" #  type: Add space before two leading NBSP
68+
i = "" #   type: Add space before two leading NBSP
6969
7070
7171
# A noqa as `#\u{A0}\u{A0}noqa` becomes `# \u{A0}noqa`
72-
i = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" # noqa
72+
i = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" #  noqa
7373
```
7474

7575

0 commit comments

Comments
 (0)