Skip to content

Commit

Permalink
Fix formatting cells with magic methods and starting or trailing empt…
Browse files Browse the repository at this point in the history
…y lines (#4484)
  • Loading branch information
AleksMat authored Oct 14, 2024
1 parent 9995bff commit fff747d
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 2 deletions.
3 changes: 3 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@

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

- Fix formatting cells in IPython notebooks with magic methods and starting or trailing
empty lines (#4484)

### Preview style

<!-- Changes that affect Black's preview style -->
Expand Down
6 changes: 4 additions & 2 deletions src/black/handle_ipynb_magics.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,12 +178,14 @@ def mask_cell(src: str) -> tuple[str, list[Replacement]]:
from IPython.core.inputtransformer2 import TransformerManager

transformer_manager = TransformerManager()
# A side effect of the following transformation is that it also removes any
# empty lines at the beginning of the cell.
transformed = transformer_manager.transform_cell(src)
transformed, cell_magic_replacements = replace_cell_magics(transformed)
replacements += cell_magic_replacements
transformed = transformer_manager.transform_cell(transformed)
transformed, magic_replacements = replace_magics(transformed)
if len(transformed.splitlines()) != len(src.splitlines()):
if len(transformed.strip().splitlines()) != len(src.strip().splitlines()):
# Multi-line magic, not supported.
raise NothingChanged
replacements += magic_replacements
Expand Down Expand Up @@ -269,7 +271,7 @@ def replace_magics(src: str) -> tuple[str, list[Replacement]]:
magic_finder = MagicFinder()
magic_finder.visit(ast.parse(src))
new_srcs = []
for i, line in enumerate(src.splitlines(), start=1):
for i, line in enumerate(src.split("\n"), start=1):
if i in magic_finder.magics:
offsets_and_magics = magic_finder.magics[i]
if len(offsets_and_magics) != 1: # pragma: nocover
Expand Down
16 changes: 16 additions & 0 deletions tests/test_ipynb.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,22 @@ def test_cell_magic_with_magic() -> None:
assert result == expected


@pytest.mark.parametrize(
"src, expected",
(
("\n\n\n%time \n\n", "%time"),
(" \n\t\n%%timeit -n4 \t \nx=2 \n\r\n", "%%timeit -n4\nx = 2"),
(
" \t\n\n%%capture \nx=2 \n%config \n\n%env\n\t \n \n\n",
"%%capture\nx = 2\n%config\n\n%env",
),
),
)
def test_cell_magic_with_empty_lines(src: str, expected: str) -> None:
result = format_cell(src, fast=True, mode=JUPYTER_MODE)
assert result == expected


@pytest.mark.parametrize(
"mode, expected_output, expectation",
[
Expand Down

0 comments on commit fff747d

Please sign in to comment.