3
3
from functools import lru_cache
4
4
from typing import Collection , Final , Iterator , List , Optional , Tuple , Union
5
5
6
- from black .mode import Mode
6
+ from black .mode import Mode , Preview
7
7
from black .nodes import (
8
8
CLOSING_BRACKETS ,
9
9
STANDALONE_COMMENT ,
@@ -46,6 +46,7 @@ class ProtoComment:
46
46
newlines : int # how many newlines before the comment
47
47
consumed : int # how many characters of the original leaf's prefix did we consume
48
48
form_feed : bool # is there a form feed before the comment
49
+ leading_whitespace : str # leading whitespace before the comment, if any
49
50
50
51
51
52
def generate_comments (leaf : LN ) -> Iterator [Leaf ]:
@@ -88,7 +89,9 @@ def list_comments(prefix: str, *, is_endmarker: bool) -> List[ProtoComment]:
88
89
form_feed = False
89
90
for index , full_line in enumerate (re .split ("\r ?\n " , prefix )):
90
91
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 ()
92
95
if not line :
93
96
nlines += 1
94
97
if "\f " in full_line :
@@ -113,6 +116,7 @@ def list_comments(prefix: str, *, is_endmarker: bool) -> List[ProtoComment]:
113
116
newlines = nlines ,
114
117
consumed = consumed ,
115
118
form_feed = form_feed ,
119
+ leading_whitespace = whitespace ,
116
120
)
117
121
)
118
122
form_feed = False
@@ -230,7 +234,11 @@ def convert_one_fmt_off_pair(
230
234
standalone_comment_prefix += fmt_off_prefix
231
235
hidden_value = comment .value + "\n " + hidden_value
232
236
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
234
242
if hidden_value .endswith ("\n " ):
235
243
# That happens when one of the `ignored_nodes` ended with a NEWLINE
236
244
# leaf (possibly followed by a DEDENT).
0 commit comments