black icon indicating copy to clipboard operation
black copied to clipboard

empty lines at end of file trimmed even with fmt: off

Open matejcik opened this issue 8 years ago • 5 comments

Operating system: Linux Mint Python version: 3.6.6 Black version: latest Does also happen on master: yes

The following file:

# fmt: off

print("hello")

gets trimmed to:

# fmt: off

print("hello")

IOW, if the file ends with empty lines, they are removed.

matejcik avatar Sep 03 '18 13:09 matejcik

Sounds like a bug. Want to take a look at fixing it?

zsol avatar Sep 07 '18 19:09 zsol

The problem here appears to happen in convert_one_fmt_off_pair, where the node enters as # fmt: off\n\nprint("hello")\n\n and exits as # fmt: off\n\nprint("hello")\n. I am continuing to investigate.

scolby33 avatar Dec 17 '18 14:12 scolby33

The function generate_ignored_nodes creates a list of nodes that is just # fmt: off\n\nprint("hello")\n. This is where the final newline is lost.

Unfortunately, I've reached the end of my experience/time to look at this today. I hope this has given someone more versed in the project a better starting place for fixing this bug.

EDIT: also, because of how test files are read in read_data in test_black.py, it will be difficult to write a test for this since the final \n will be removed.

scolby33 avatar Dec 17 '18 14:12 scolby33

At least our documentation states that fmt: off should be followed by a fmt: on, but supporting a single off switch is a reasonable request.

felix-hilden avatar Jan 29 '22 16:01 felix-hilden

I reproduced this on the current development branch (26.5.2.dev98+g8947c48ef, CPython 3.12.3).

Minimal input:

# fmt: off

print("hello")

Running black file.py removes the final blank line and produces:

# fmt: off

print("hello")

The issue is that the parser stores trailing blank lines after the final statement in the END marker prefix, while fmt-off conversion currently discards that prefix. I have a focused fix that preserves the END marker prefix for an unclosed # fmt: off block at EOF, together with a regression test through Black’s file-formatting path.

tagadearpit avatar Aug 21 '26 17:08 tagadearpit