diff --git a/yapf/yapflib/reformatter.py b/yapf/yapflib/reformatter.py index 14e0bde70..634041619 100644 --- a/yapf/yapflib/reformatter.py +++ b/yapf/yapflib/reformatter.py @@ -62,6 +62,17 @@ def Reformat(llines, verify=False, lines=None): if not lline.disable: if lline.first.is_comment: + for character in lline.first.value: + if character == '#': + comment_before_tab = True + elif character == '\t': + break + + if comment_before_tab: + non_comment_text_index = (len(lline.first.value[1:]) - len(lline.first.value[1:].lstrip())) + 1 + new_string = '# ' + lline.first.value[non_comment_text_index:] + + lline.first.value = new_string lline.first.value = lline.first.value.rstrip() elif lline.last.is_comment: lline.last.value = lline.last.value.rstrip() diff --git a/yapftests/reformatter_basic_test.py b/yapftests/reformatter_basic_test.py index 657d1e246..c612b805a 100644 --- a/yapftests/reformatter_basic_test.py +++ b/yapftests/reformatter_basic_test.py @@ -3165,6 +3165,64 @@ def testWalrus(self): llines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected, reformatter.Reformat(llines)) + def testIndentBlockComments(self): + unformatted_code = textwrap.dedent("""\ + class Foo(object): + def __init__(self): + # pass + pass + """) + + expected = textwrap.dedent("""\ + class Foo(object): + + def __init__(self): + # pass + pass + """) + + llines = yapf_test_helper.ParseAndUnwrap(unformatted_code) + self.assertCodeEqual(expected, reformatter.Reformat(llines)) + + def testIndentBlockCommentsMultipleTabs(self): + unformatted_code = textwrap.dedent("""\ + class Foo(object): + def __init__(self): + # pass + pass + """) + + expected = textwrap.dedent("""\ + class Foo(object): + + def __init__(self): + # pass + pass + """) + + llines = yapf_test_helper.ParseAndUnwrap(unformatted_code) + self.assertCodeEqual(expected, reformatter.Reformat(llines)) + + def testIndentBlockCommentsRepeats(self): + unformatted_code = textwrap.dedent("""\ + class Foo(object): + def __init__(self): + # pass + # pass + pass + """) + + expected = textwrap.dedent("""\ + class Foo(object): + + def __init__(self): + # pass + # pass + pass + """) + + llines = yapf_test_helper.ParseAndUnwrap(unformatted_code) + self.assertCodeEqual(expected, reformatter.Reformat(llines)) if __name__ == '__main__': unittest.main()