Skip to content
Open
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
19 changes: 15 additions & 4 deletions blackcellmagic.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
from black import format_str
from IPython.core import magic_arguments
from IPython.core.magic import Magics, cell_magic, magics_class

import re

@magics_class
class FormattingMagic(Magics):
Expand All @@ -37,10 +37,21 @@ def black(self, line, cell):
args = magic_arguments.parse_argstring(self.black, line)
line_length = args.line_length
if cell:
formated = format_str(src_contents=cell, line_length=line_length)
if formated and formated[-1] == "\n":
# Comment magics
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shall we leave a detailed comment on:

  1. Pattern the regex replacing and what it is replacing it with.
  2. Give an example.

cell = re.sub(r"^%", r"##!%", cell)
cell = re.sub(r"\n\s*%", "\n##!%", cell)
try:
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a good logic! Can we abstract it out to a method and add tests for that method. It would be amazing if you can do that. Also, we should avoid exception based flow control.

formated = format_str(src_contents=cell, line_length=line_length)
if formated and formated[-1] == "\n":
formated = formated[:-1]
self.shell.set_next_input(formated, replace=True)
except ValueError as e:
formated = cell
print(e)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we should have logging.error() instead of printing the exception.

finally:
# Uncomment magics
formated = re.sub(r"##!%", "%", formated)
# No matter success or not, something will always be put back
self.shell.set_next_input(formated, replace=True)


def load_ipython_extension(ipython):
Expand Down