Skip to content

Commit

Permalink
Rearrange code
Browse files Browse the repository at this point in the history
  • Loading branch information
Khoa Duong committed Jul 30, 2019
1 parent aca3cbf commit f5f57f9
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 143 deletions.
94 changes: 42 additions & 52 deletions lab_black.py
Original file line number Diff line number Diff line change
@@ -1,88 +1,78 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import, division, print_function, unicode_literals

import json
import logging
import re
import sys
from distutils.version import LooseVersion

import IPython
from IPython.display import Javascript, display

if sys.version_info >= (3, 6, 0):
from black import format_str, FileMode


def _format_code(code):
return format_str(src_contents=code, mode=FileMode())


else:
from yapf.yapflib.yapf_api import FormatCode


def _format_code(code):
return FormatCode(code, style_config="facebook")[0]


class BlackFormatter(object):
def __init__(self, ip):
def __init__(self, ip, is_lab):
self.shell = ip

if LooseVersion(IPython.__version__) < LooseVersion("6.5"):

def format(self):
try:
inp_id = len(self.shell.user_ns["In"]) - 1
if inp_id > 0:
cell = self.shell.user_ns["_i%d" % inp_id]

# Skip if exists magic command `load`
if re.search(r"^[ \t]*%load +", cell, flags=re.M) or \
re.search(r"(?<! )(\?)$", cell, flags=re.M):
return

cell = re.sub(r"^(\s*[!%?])", "# :@BF@: \g<1>", cell, flags=re.M)
cell = _format_code(cell)
cell = re.sub(r"^\s*# :@BF@: (\s*[!%?])", "\g<1>", cell, flags=re.M)
self.shell.set_next_input(cell.rstrip(), replace=True)
except (ValueError, TypeError) as e:
logging.exception(e)

else:

def format(self, result):
try:
cell = result.info.raw_cell

# Skip if exists magic command `load`
if re.search(r"^[ \t]*%load +", cell, flags=re.M) or \
re.search(r"(?<! )(\?)$", cell, flags=re.M):
return

cell = re.sub(r"^(\s*[!%?])", "# :@BF@: \g<1>", cell, flags=re.M)
cell = _format_code(cell)
cell = re.sub(r"^\s*# :@BF@: (\s*[!%?])", "\g<1>", cell, flags=re.M)
self.shell.set_next_input(cell.rstrip(), replace=True)
except (ValueError, TypeError) as e:
logging.exception(e)
self.is_lab = is_lab

def __set_cell(self, cell, cell_id=None):
if self.is_lab:
self.shell.set_next_input(cell, replace=True)
else:
js_code = """
setTimeout(function() {
var nbb_cell_id = {};
var nbb_formatted_code = {};
var nbb_cells = Jupyter.notebook.get_cells();
for (var i = 0; i < nbb_cells.length; ++i) {
if (nbb_cells[i].input_prompt_number == nbb_cell_id) {
nbb_cells[i].set_text(nbb_formatted_code);
break;
}
}
}, 500);
"""
display(Javascript(js_code.format(cell_id, json.dumps(cell))))

def format_cell(self, *args, **kwargs):
try:
cell_id = len(self.shell.user_ns["In"]) - 1
if cell_id > 0:
transformed_cell = self.shell.user_ns["In"][cell_id]

formatted_code = _format_code(transformed_cell)

# Reverse magic functions

self.__set_cell(formatted_code.strip(), cell_id)
except (ValueError, TypeError, AssertionError) as err:
logging.exception(err)


black_formatter = None


def load_ipython_extension(ip):
global black_formatter
if not black_formatter:
black_formatter = BlackFormatter(ip)
ip.events.register("post_run_cell", black_formatter.format)
if black_formatter is None:
black_formatter = BlackFormatter(ip, is_lab=True)
ip.events.register("post_run_cell", black_formatter.format_cell)


def unload_ipython_extension(ip):
global black_formatter
if black_formatter:
ip.events.unregister("post_run_cell", black_formatter.format)
ip.events.unregister("post_run_cell", black_formatter.format_cell)
black_formatter = None
93 changes: 5 additions & 88 deletions nb_black.py
Original file line number Diff line number Diff line change
@@ -1,94 +1,11 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import, division, print_function, unicode_literals

import json
import logging
import re
import sys
from distutils.version import LooseVersion

import IPython
from IPython.display import display, Javascript

if sys.version_info >= (3, 6, 0):
from black import format_str, FileMode


def _format_code(code):
return format_str(src_contents=code, mode=FileMode())


else:
from yapf.yapflib.yapf_api import FormatCode


def _format_code(code):
return FormatCode(code, style_config="facebook")[0]


class BlackFormatter(object):
def __init__(self, ip):
self.shell = ip
self.js_code = """
setTimeout(function() {
var nbb_cell_id = %d;
var nbb_formatted_code = %s;
var nbb_cells = Jupyter.notebook.get_cells();
for (var i = 0; i < nbb_cells.length; ++i) {
if (nbb_cells[i].input_prompt_number == nbb_cell_id) {
nbb_cells[i].set_text(nbb_formatted_code);
break;
}
}
}, 500);
"""

def __format(self):
try:
inp_id = len(self.shell.user_ns["In"]) - 1
if inp_id > 0:
cell = self.shell.user_ns["_i%d" % inp_id]

# Skip if exists magic command `load`
if re.search(r"^[ \t]*%load +", cell, flags=re.M) or \
re.search(r"(?<! )(\?)$", cell, flags=re.M):
return

cell = re.sub(r"^(\s*[!%?])", "# :@BF@: \g<1>", cell, flags=re.M)
cell = _format_code(cell)
cell = re.sub(r"^\s*# :@BF@: (\s*[!%?])", "\g<1>", cell, flags=re.M)
# noinspection PyTypeChecker
display(Javascript(self.js_code % (inp_id, json.dumps(cell.rstrip()))))
except (ValueError, TypeError) as e:
logging.exception(e)

if LooseVersion(IPython.__version__) < LooseVersion("6.5"):

def format(self):
self.__format()

else:

def format(self, _):
self.__format()


black_formatter = None
from lab_black import BlackFormatter, black_formatter, unload_ipython_extension


def load_ipython_extension(ip):
global black_formatter
if not black_formatter:
black_formatter = BlackFormatter(ip)
ip.events.register("post_run_cell", black_formatter.format)


def unload_ipython_extension(ip):
global black_formatter
if black_formatter:
ip.events.unregister("post_run_cell", black_formatter.format)
black_formatter = None
if black_formatter is None:
black_formatter = BlackFormatter(ip, is_lab=False)
ip.events.register("post_run_cell", black_formatter.format_cell)
5 changes: 2 additions & 3 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,8 @@ def readme(file_name):

setup(
name="nb_black",
version="1.0.5",
description="A simple extension for Jupyter Notebook and Jupyter Lab to beautify Python code automatically using "
"Black.",
version="1.0.6",
description="A simple extension for Jupyter Notebook and Jupyter Lab to beautify Python code automatically using Black.",
long_description=readme(file_name="README.md"),
keywords="black-formatter black-beautifier black jupyterlab-extension jupyter-notebook-extension",
url="https://github.com/dnanhkhoa/nb_black",
Expand Down

0 comments on commit f5f57f9

Please sign in to comment.