diff --git a/src/docformatter/format.py b/src/docformatter/format.py index 584ff6a..21d8e62 100644 --- a/src/docformatter/format.py +++ b/src/docformatter/format.py @@ -196,8 +196,14 @@ def _do_update_token_indices( is_multiline = _is_multiline_parameter(tokens, i - 1) is_same_line = tokens[i].line == tokens[i - 1].line is_same_position = tokens[i].start[0] == tokens[i - 1].end[0] - - if ( + # A backslash continuation joins two physical lines without an NL + # token between them, so the current token always starts on the row + # after the previous one, even though the rows may look the same once + # the previous token has been shifted. + prev_line = tokens[i - 1].line.rstrip("\r\n") + is_backslash_continuation = not is_same_line and prev_line.endswith("\\") + + if not is_backslash_continuation and ( is_multiline or (is_same_line or is_same_position) and tokens[i - 1].type diff --git a/tests/_data/string_files/do_format_code.toml b/tests/_data/string_files/do_format_code.toml index 65282a8..4ca0541 100644 --- a/tests/_data/string_files/do_format_code.toml +++ b/tests/_data/string_files/do_format_code.toml @@ -1273,6 +1273,16 @@ expected="def foo():\n \"\"\"Summary.\"\"\"\n x = 1\n # next line has 4 source="def foo():\n \"\"\"\n Hello foo.\n \"\"\"\n x = 1" expected="def foo():\n \"\"\"Hello foo.\"\"\"\n x = 1" +# A backslash continuation after a docstring that gets a blank line inserted +# must not crash the tokenizer round-trip: the continuation line has no NL +# token in front of it, so its row must be derived from the previous token. +[issue_377_backslash_continuation] +source="class A:\n \"\"\"Doc.\"\"\"\n x = 1 \\\n + 2\n" +expected="class A:\n \"\"\"Doc.\"\"\"\n\n x = 1 \\\n + 2\n" + +[issue_377_module_docstring] +source="\"\"\"Doc.\"\"\"\nx = 1 \\\n + 2\n" +expected="\"\"\"Doc.\"\"\"\n\nx = 1 \\\n + 2\n" [issue_367] source='''def build(x): return ( diff --git a/tests/formatter/test_do_format_code.py b/tests/formatter/test_do_format_code.py index 9d8a1b4..0880a60 100644 --- a/tests/formatter/test_do_format_code.py +++ b/tests/formatter/test_do_format_code.py @@ -144,6 +144,8 @@ ("issue_351", NO_ARGS), ("issue_355", NO_ARGS), ("issue_360_no_trailing_newline", NO_ARGS), + ("issue_377_backslash_continuation", NO_ARGS), + ("issue_377_module_docstring", NO_ARGS), ("issue_367", NO_ARGS), ("issue_366_triple_quote_in_parens_not_docstring", NO_ARGS), ],