diff --git a/crates/ruff_python_formatter/src/comments/format.rs b/crates/ruff_python_formatter/src/comments/format.rs index e682924284..6a6cb33768 100644 --- a/crates/ruff_python_formatter/src/comments/format.rs +++ b/crates/ruff_python_formatter/src/comments/format.rs @@ -474,18 +474,19 @@ fn normalize_comment<'a>( if content.starts_with('\u{A0}') { let trimmed = content.trim_start_matches('\u{A0}'); - // Black adds a space before the non-breaking space if part of a type pragma. if trimmed.trim_start().starts_with("type:") { - return Ok(Cow::Owned(std::format!("# \u{A0}{trimmed}"))); - } - - // Black replaces the non-breaking space with a space if followed by a space. - if trimmed.starts_with(' ') { - return Ok(Cow::Owned(std::format!("# {trimmed}"))); + // Black adds a space before the non-breaking space if part of a type pragma. + Ok(Cow::Owned(std::format!("# {content}"))) + } else if trimmed.starts_with(' ') { + // Black replaces the non-breaking space with a space if followed by a space. + Ok(Cow::Owned(std::format!("# {trimmed}"))) + } else { + // Otherwise we replace the first non-breaking space with a regular space. + Ok(Cow::Owned(std::format!("# {}", &content["\u{A0}".len()..]))) } + } else { + Ok(Cow::Owned(std::format!("# {}", content.trim_start()))) } - - Ok(Cow::Owned(std::format!("# {}", content.trim_start()))) } /// A helper for stripping '#' from comments. diff --git a/crates/ruff_python_formatter/tests/snapshots/format@trailing_comments.py.snap b/crates/ruff_python_formatter/tests/snapshots/format@trailing_comments.py.snap index 982bb00711..7e6a4bdc16 100644 --- a/crates/ruff_python_formatter/tests/snapshots/format@trailing_comments.py.snap +++ b/crates/ruff_python_formatter/tests/snapshots/format@trailing_comments.py.snap @@ -65,11 +65,11 @@ i = "" #   type: Add space before leading NBSP followed by spaces i = "" # type: A space is added i = "" #   type: Add space before leading NBSP followed by a space i = "" #  type: Add space before leading NBSP -i = "" #  type: Add space before two leading NBSP +i = "" #   type: Add space before two leading NBSP # A noqa as `#\u{A0}\u{A0}noqa` becomes `# \u{A0}noqa` -i = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" # noqa +i = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" #  noqa ```