Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@

<!-- Changes that affect Black's stable style -->

- Preserve blank lines that come immediately before a `# fmt: on` comment. They are
inside the opted-out region, but they live in the prefix of the `# fmt: on` comment
rather than in the verbatim block, so they were being capped like any ordinary blank
run (#5300)
- Stop treating a t-string in docstring position as a docstring (for example
`t" spam "` as the first statement of a module, class or function). t-strings
evaluate to `Template`, never `str`, so stripping and reindenting one changed the
Expand Down
12 changes: 11 additions & 1 deletion src/black/lines.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from typing import NamedTuple, Optional, TypeVar, Union, cast

from black.brackets import COMMA_PRIORITY, DOT_PRIORITY, BracketTracker
from black.comments import FMT_ON, contains_fmt_directive
from black.mode import Mode, Preview
from black.nodes import (
BRACKETS,
Expand Down Expand Up @@ -1009,7 +1010,16 @@ def _maybe_empty_lines(self, current_line: Line) -> tuple[int, int]:
# Consume the first leaf's extra newlines.
first_leaf = current_line.leaves[0]
before = first_leaf.prefix.count("\n")
before = min(before, max_allowed)
# The blank lines that terminate a `# fmt: off` region live in the
# prefix of the `# fmt: on` comment, not in the verbatim block, so
# capping them here would edit formatting that was opted out of.
if not (
first_leaf.type == STANDALONE_COMMENT
and contains_fmt_directive(first_leaf.value, FMT_ON)
and self.previous_line is not None
and self.previous_line.is_fmt_pass_converted()
):
before = min(before, max_allowed)
first_leaf.prefix = ""
else:
before = 0
Expand Down
40 changes: 40 additions & 0 deletions tests/data/cases/fmtonoff9.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# Regression test for https://github.com/psf/black/issues/2877.
# Blank lines that terminate a `# fmt: off` region are inside the region, so
# they must be preserved rather than collapsed to the usual maximum.
x = 1
# fmt: off
a = 1



# fmt: on
y = 2


def f():
x = 1
# fmt: off
a = 1




# fmt: on
y = 2


# yapf: disable
b = 1



# yapf: enable
z = 2


# fmt:off
c = 1


# fmt:on
w = 2