Skip to content

Commit 75ddcc7

Browse files
committed
fix: do not treat blank lines with trailing whitespace as line continuations
A blank line that contains trailing whitespace (e.g. " \n") produces an NL token whose `.line` is not exactly "\n" or "\r\n". The guard in `is_newline_continuation` only excluded the exact-blank forms, so such a line was misclassified as a continuation of the preceding line. This caused `_do_update_token_indices` to rewrite the token's start row back to the previous token's end row, yielding a start position that precedes the previous token's end. `tokenize.untokenize` then raised `ValueError: start (r,c) precedes previous end (r,c)` and docformatter crashed (regression from the stdlib tokenize migration in #325, v1.7.8). Classify any whitespace-only line as blank by testing `token.line.strip()` instead of comparing the raw line against {"\n", "\r\n"}. Genuine continuations (whose stripped line is non-empty) are unaffected. Fixes #355.
1 parent ead6248 commit 75ddcc7

3 files changed

Lines changed: 9 additions & 1 deletion

File tree

src/docformatter/classify.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -439,8 +439,8 @@ def is_newline_continuation(
439439
"""
440440
if (
441441
token.type in (tokenize.NEWLINE, tokenize.NL)
442+
and token.line.strip()
442443
and token.line.strip() in prev_token.line.strip()
443-
and token.line not in {"\n", "\r\n"}
444444
):
445445
return True
446446

tests/_data/string_files/do_format_code.toml

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1244,3 +1244,10 @@ expected='''"""A."""
12441244
12451245
pass
12461246
'''
1247+
1248+
# A blank line with trailing whitespace must not crash the tokenizer round-trip.
1249+
# The "\n" escapes are used so the four trailing spaces on the blank line are
1250+
# explicit and cannot be stripped by editors or formatters.
1251+
[issue_355]
1252+
source="def foo():\n \"\"\"Summary.\"\"\"\n x = 1\n # next line has 4 spaces of trailing whitespace\n \n return x\n"
1253+
expected="def foo():\n \"\"\"Summary.\"\"\"\n x = 1\n # next line has 4 spaces of trailing whitespace\n \n return x\n"

tests/formatter/test_do_format_code.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,7 @@
141141
("do_not_break_f_string_double_quotes", NO_ARGS),
142142
("do_not_break_f_string_single_quotes", NO_ARGS),
143143
("issue_331_black_module_docstring", ["--black", ""]),
144+
("issue_355", NO_ARGS),
144145
],
145146
)
146147
def test_do_format_code(test_key, test_args, args):

0 commit comments

Comments
 (0)