Repository: hhatto/autopep8

Issue:
Applying W504 may cause syntax error if there are comments
Hi, I just noticed that the following code:
```
x = (1 |
     2) # test
```
was being formatted as
```
x = (1|
     | 2) # test
```
causing a syntax error. It seems to be related to the presence of the comment.

I'll push a PR shortly

Discussion:

Patch:
diff --git a/autopep8.py b/autopep8.py
index d07f74c..258f30c 100755
--- a/autopep8.py
+++ b/autopep8.py
@@ -1313,14 +1313,15 @@ class FixPEP8(object):
             old = []
             for t in tts:
                 if tokenize.COMMENT == t[0] and old:
-                    comment_index = old[3][1]
+                    comment_row, comment_index = old[3]
                     break
                 old = t
             break
         if not operator_position:
             return
         target_operator = target[operator_position[0]:operator_position[1]]
-        if comment_index:
+
+        if comment_index and comment_row == 1:
             self.source[line_index] = '{}{}'.format(
                 target[:operator_position[0]].rstrip(),
                 target[comment_index:])
@@ -1329,6 +1330,7 @@ class FixPEP8(object):
                 target[:operator_position[0]].rstrip(),
                 target[operator_position[1]:].lstrip(),
                 target[operator_position[1]:])
+
         next_line = self.source[line_index + 1]
         next_line_indent = 0
         m = re.match(r'\s*', next_line)


Test patch:
diff --git a/test/test_autopep8.py b/test/test_autopep8.py
index d1c6e3a..aa502d1 100755
--- a/test/test_autopep8.py
+++ b/test/test_autopep8.py
@@ -4425,6 +4425,24 @@ b = (1 +
         with autopep8_context(line, options=['--select=W504', '--ignore=E']) as result:
             self.assertEqual(fixed, result)
 
+    def test_w504_comment_on_first_line(self):
+        line = 'x = (1 | # test\n2)\n'
+        fixed = 'x = (1 # test\n| 2)\n'
+        with autopep8_context(line, options=['--select=W504', '--ignore=E']) as result:
+            self.assertEqual(fixed, result)
+
+    def test_w504_comment_on_second_line(self):
+        line = 'x = (1 |\n2) # test\n'
+        fixed = 'x = (1\n| 2) # test\n'
+        with autopep8_context(line, options=['--select=W504', '--ignore=E']) as result:
+            self.assertEqual(fixed, result)
+
+    def test_w504_comment_on_each_lines(self):
+        line = 'x = (1 |# test\n2 |# test\n3) # test\n'
+        fixed = 'x = (1# test\n| 2# test\n| 3) # test\n'
+        with autopep8_context(line, options=['--select=W504', '--ignore=E']) as result:
+            self.assertEqual(fixed, result)
+
     def test_w504_with_e265_ignore_option(self):
         line = '(width == 0 +\n height == 0)\n'
         with autopep8_context(line, options=['--ignore=E265']) as result: