diff --git a/yapf/__init__.py b/yapf/__init__.py index cf4be9379..088ee614d 100644 --- a/yapf/__init__.py +++ b/yapf/__init__.py @@ -54,6 +54,22 @@ def _removeBOM(source): return source +def filterEmptyTuples(source): + comment_start = False + quote_str = '\'\'\'' + reformatted_source = [] + for code_val in source: + if not comment_start and quote_str in code_val: + reformatted_source.append(code_val) + comment_start = True + elif comment_start and quote_str in code_val: + comment_start = False + reformatted_source.append(code_val) + elif code_val != '': + reformatted_source.append(code_val) + return reformatted_source + + def main(argv): """Main program. @@ -108,6 +124,8 @@ def main(argv): source = [line.rstrip() for line in original_source] source[0] = _removeBOM(source[0]) + # filter all the tuples with empty space + source = filterEmptyTuples(source) try: reformatted_source, _ = yapf_api.FormatCode( diff --git a/yapf/yapflib/reformatter.py b/yapf/yapflib/reformatter.py index ff0952543..62374283b 100644 --- a/yapf/yapflib/reformatter.py +++ b/yapf/yapflib/reformatter.py @@ -398,12 +398,19 @@ def _AlignTrailingComments(final_lines): def _FormatFinalLines(final_lines): """Compose the final output from the finalized lines.""" formatted_code = [] + comment_start = False + quote_str = '\'\'\'' for line in final_lines: formatted_line = [] for tok in line.tokens: if not tok.is_pseudo: - formatted_line.append(tok.formatted_whitespace_prefix) - formatted_line.append(tok.value) + if not comment_start and tok.value.startswith(quote_str): + comment_start = True + formatted_line.append(tok.formatted_whitespace_prefix) + formatted_line.append(tok.value) + else: + formatted_line.append(re.sub('\n+','\n',tok.formatted_whitespace_prefix)) + formatted_line.append(tok.value) elif (not tok.next_token.whitespace_prefix.startswith('\n') and not tok.next_token.whitespace_prefix.startswith(' ')): if (tok.previous_token.value == ':' or diff --git a/yapftests/reformatter_basic_test.py b/yapftests/reformatter_basic_test.py index 74b1ba405..b266dd44c 100644 --- a/yapftests/reformatter_basic_test.py +++ b/yapftests/reformatter_basic_test.py @@ -3339,6 +3339,27 @@ def testParenthesizedContextManagers(self): llines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected, reformatter.Reformat(llines)) + def testExtraBlankLine(self): + unformatted_code = textwrap.dedent("""\ + ''' + Comment section started + ''' + if True: + + + print(2) + """) + expected = textwrap.dedent("""\ + ''' + Comment section started + ''' + if True: + print(2) + """) + + llines = yapf_test_helper.ParseAndUnwrap(unformatted_code) + self.assertCodeEqual(expected, reformatter.Reformat(llines)) + if __name__ == '__main__': unittest.main()