From cf8e998f46e89da39fa64029cc4550e2862f7ec2 Mon Sep 17 00:00:00 2001 From: =?utf8?q?=C5=81ukasz=20Langa?= Date: Wed, 11 Apr 2018 16:25:47 -0700 Subject: [PATCH] Don't omit escaping the second consecutive quote This would produce invalid code for strings like `"x = ''; y = \"\""`. --- black.py | 3 +++ tests/string_quotes.py | 16 ++++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/black.py b/black.py index c7cfa2f..9581d63 100644 --- a/black.py +++ b/black.py @@ -1998,6 +1998,9 @@ def normalize_string_quotes(leaf: Leaf) -> None: else: new_body = escaped_orig_quote.sub(rf"\1{orig_quote}", body) new_body = unescaped_new_quote.sub(rf"\1\\{new_quote}", new_body) + # Add escapes again for consecutive occurences of new_quote (sub + # doesn't match overlapping substrings). + new_body = unescaped_new_quote.sub(rf"\1\\{new_quote}", new_body) if new_quote == '"""' and new_body[-1] == '"': # edge case: new_body = new_body[:-1] + '\\"' diff --git a/tests/string_quotes.py b/tests/string_quotes.py index 1532a7a..8ccd041 100644 --- a/tests/string_quotes.py +++ b/tests/string_quotes.py @@ -30,6 +30,14 @@ jumps over\n\ the \'lazy\' dog.\n\ ' re.compile(r'[\\"]') +"x = ''; y = \"\"" +"x = '''; y = \"\"" +"x = ''''; y = \"\"" +"x = '' ''; y = \"\"" +"x = ''; y = \"\"\"" +"x = '''; y = \"\"\"\"" +"x = ''''; y = \"\"\"\"\"" +"x = '' ''; y = \"\"\"\"\"" # output @@ -65,3 +73,11 @@ jumps over\n\ the 'lazy' dog.\n\ " re.compile(r'[\\"]') +"x = ''; y = \"\"" +"x = '''; y = \"\"" +"x = ''''; y = \"\"" +"x = '' ''; y = \"\"" +'x = \'\'; y = """' +'x = \'\'\'; y = """"' +'x = \'\'\'\'; y = """""' +'x = \'\' \'\'; y = """""' -- 2.39.5