33from functools import lru_cache
44from typing import Collection , Final , Iterator , List , Optional , Tuple , Union
55
6- from black .mode import Mode
6+ from black .mode import Mode , Preview
77from black .nodes import (
88 CLOSING_BRACKETS ,
99 STANDALONE_COMMENT ,
@@ -46,6 +46,7 @@ class ProtoComment:
4646 newlines : int # how many newlines before the comment
4747 consumed : int # how many characters of the original leaf's prefix did we consume
4848 form_feed : bool # is there a form feed before the comment
49+ leading_whitespace : str # leading whitespace before the comment, if any
4950
5051
5152def generate_comments (leaf : LN ) -> Iterator [Leaf ]:
@@ -88,7 +89,9 @@ def list_comments(prefix: str, *, is_endmarker: bool) -> List[ProtoComment]:
8889 form_feed = False
8990 for index , full_line in enumerate (re .split ("\r ?\n " , prefix )):
9091 consumed += len (full_line ) + 1 # adding the length of the split '\n'
91- line = full_line .lstrip ()
92+ match = re .match (r"^(\s*)(\S.*|)$" , full_line )
93+ assert match
94+ whitespace , line = match .groups ()
9295 if not line :
9396 nlines += 1
9497 if "\f " in full_line :
@@ -113,6 +116,7 @@ def list_comments(prefix: str, *, is_endmarker: bool) -> List[ProtoComment]:
113116 newlines = nlines ,
114117 consumed = consumed ,
115118 form_feed = form_feed ,
119+ leading_whitespace = whitespace ,
116120 )
117121 )
118122 form_feed = False
@@ -230,7 +234,11 @@ def convert_one_fmt_off_pair(
230234 standalone_comment_prefix += fmt_off_prefix
231235 hidden_value = comment .value + "\n " + hidden_value
232236 if _contains_fmt_skip_comment (comment .value , mode ):
233- hidden_value += " " + comment .value
237+ hidden_value += (
238+ comment .leading_whitespace
239+ if Preview .no_normalize_fmt_skip_whitespace in mode
240+ else " "
241+ ) + comment .value
234242 if hidden_value .endswith ("\n " ):
235243 # That happens when one of the `ignored_nodes` ended with a NEWLINE
236244 # leaf (possibly followed by a DEDENT).
0 commit comments