Skip to content

Commit

Permalink
Run darker
Browse files Browse the repository at this point in the history
  • Loading branch information
romulofff committed Oct 8, 2020
1 parent 2bc1ebd commit b773816
Showing 1 changed file with 71 additions and 48 deletions.
119 changes: 71 additions & 48 deletions IPython/lib/latextools.py
Expand Up @@ -23,11 +23,13 @@

class LaTeXTool(SingletonConfigurable):
"""An object to store configuration of the LaTeX tool."""

def _config_default(self):
return get_config()

backends = List(
Unicode(), ["matplotlib", "dvipng"],
Unicode(),
["matplotlib", "dvipng"],
help="Preferred backend to draw LaTeX math equations. "
"Backends in the list are checked one by one and the first "
"usable one is used. Note that `matplotlib` backend "
Expand All @@ -38,28 +40,27 @@ def _config_default(self):
# for display style, the default ["matplotlib", "dvipng"] can
# be used. To NOT use dvipng so that other repr such as
# unicode pretty printing is used, you can use ["matplotlib"].
).tag(config=True)
).tag(config=True)

use_breqn = Bool(
True,
help="Use breqn.sty to automatically break long equations. "
"This configuration takes effect only for dvipng backend.",
).tag(config=True)
).tag(config=True)

packages = List(
['amsmath', 'amsthm', 'amssymb', 'bm'],
["amsmath", "amsthm", "amssymb", "bm"],
help="A list of packages to use for dvipng backend. "
"'breqn' will be automatically appended when use_breqn=True.",
).tag(config=True)
).tag(config=True)

preamble = Unicode(
help="Additional preamble to use when generating LaTeX source "
"for dvipng backend.",
).tag(config=True)
).tag(config=True)


def latex_to_png(s, encode=False, backend=None, wrap=False, color='Black',
scale=1.0):
def latex_to_png(s, encode=False, backend=None, wrap=False, color="Black", scale=1.0):
"""Render a LaTeX string to PNG.
Parameters
Expand Down Expand Up @@ -87,54 +88,57 @@ def latex_to_png(s, encode=False, backend=None, wrap=False, color='Black',
backend = allowed_backends[0]
if backend not in allowed_backends:
return None
if backend == 'matplotlib':
if backend == "matplotlib":
f = latex_to_png_mpl
elif backend == 'dvipng':
elif backend == "dvipng":
f = latex_to_png_dvipng
if color.startswith('#'):
if color.startswith("#"):
# Convert hex RGB color to LaTeX RGB color.
if len(color) == 7:
try:
color = "RGB {}".format(" ".join([str(int(x, 16)) for x in
textwrap.wrap(color[1:], 2)]))
color = "RGB {}".format(
" ".join([str(int(x, 16)) for x in textwrap.wrap(color[1:], 2)])
)
except ValueError as e:
raise ValueError('Invalid color specification {}.'.format(color)) from e
raise ValueError(
"Invalid color specification {}.".format(color)
) from e
else:
raise ValueError('Invalid color specification {}.'.format(color))
raise ValueError("Invalid color specification {}.".format(color))
else:
raise ValueError('No such backend {0}'.format(backend))
raise ValueError("No such backend {0}".format(backend))
bin_data = f(s, wrap, color, scale)
if encode and bin_data:
bin_data = encodebytes(bin_data)
return bin_data


def latex_to_png_mpl(s, wrap, color='Black', scale=1.0):
def latex_to_png_mpl(s, wrap, color="Black", scale=1.0):
try:
from matplotlib import mathtext
from pyparsing import ParseFatalException
except ImportError:
return None

# mpl mathtext doesn't support display math, force inline
s = s.replace('$$', '$')
s = s.replace("$$", "$")
if wrap:
s = u'${0}$'.format(s)
s = u"${0}$".format(s)

try:
mt = mathtext.MathTextParser('bitmap')
mt = mathtext.MathTextParser("bitmap")
f = BytesIO()
dpi = 120*scale
dpi = 120 * scale
mt.to_png(f, s, fontsize=12, dpi=dpi, color=color)
return f.getvalue()
except (ValueError, RuntimeError, ParseFatalException):
return None


def latex_to_png_dvipng(s, wrap, color='Black', scale=1.0):
def latex_to_png_dvipng(s, wrap, color="Black", scale=1.0):
try:
find_cmd('latex')
find_cmd('dvipng')
find_cmd("latex")
find_cmd("dvipng")
except FindCmdError:
return None
try:
Expand All @@ -143,19 +147,39 @@ def latex_to_png_dvipng(s, wrap, color='Black', scale=1.0):
dvifile = workdir.joinpath("tmp.dvi")
outfile = workdir.joinpath("tmp.png")

with tmpfile.open("w", encoding='utf8') as f:
with tmpfile.open("w", encoding="utf8") as f:
f.writelines(genelatex(s, wrap))

with open(os.devnull, 'wb') as devnull:
with open(os.devnull, "wb") as devnull:
subprocess.check_call(
["latex", "-halt-on-error", "-interaction", "batchmode", tmpfile],
cwd=workdir, stdout=devnull, stderr=devnull)
cwd=workdir,
stdout=devnull,
stderr=devnull,
)

resolution = round(150*scale)
resolution = round(150 * scale)
subprocess.check_call(
["dvipng", "-T", "tight", "-D", str(resolution), "-z", "9",
"-bg", "transparent", "-o", outfile, dvifile, "-fg", color],
cwd=workdir, stdout=devnull, stderr=devnull)
[
"dvipng",
"-T",
"tight",
"-D",
str(resolution),
"-z",
"9",
"-bg",
"transparent",
"-o",
outfile,
dvifile,
"-fg",
color,
],
cwd=workdir,
stdout=devnull,
stderr=devnull,
)

with outfile.open("rb") as f:
return f.read()
Expand All @@ -170,10 +194,10 @@ def kpsewhich(filename):
try:
find_cmd("kpsewhich")
proc = subprocess.Popen(
["kpsewhich", filename],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
["kpsewhich", filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
(stdout, stderr) = proc.communicate()
return stdout.strip().decode('utf8', 'replace')
return stdout.strip().decode("utf8", "replace")
except FindCmdError:
pass

Expand All @@ -182,30 +206,31 @@ def genelatex(body, wrap):
"""Generate LaTeX document for dvipng backend."""
lt = LaTeXTool.instance()
breqn = wrap and lt.use_breqn and kpsewhich("breqn.sty")
yield r'\documentclass{article}'
yield r"\documentclass{article}"
packages = lt.packages
if breqn:
packages = packages + ['breqn']
packages = packages + ["breqn"]
for pack in packages:
yield r'\usepackage{{{0}}}'.format(pack)
yield r'\pagestyle{empty}'
yield r"\usepackage{{{0}}}".format(pack)
yield r"\pagestyle{empty}"
if lt.preamble:
yield lt.preamble
yield r'\begin{document}'
yield r"\begin{document}"
if breqn:
yield r'\begin{dmath*}'
yield r"\begin{dmath*}"
yield body
yield r'\end{dmath*}'
yield r"\end{dmath*}"
elif wrap:
yield u'$${0}$$'.format(body)
yield u"$${0}$$".format(body)
else:
yield body
yield u'\\end{document}'
yield u"\\end{document}"


_data_uri_template_png = u"""<img src="data:image/png;base64,%s" alt=%s />"""

def latex_to_html(s, alt='image'):

def latex_to_html(s, alt="image"):
"""Render LaTeX to HTML with embedded PNG data using data URIs.
Parameters
Expand All @@ -215,8 +240,6 @@ def latex_to_html(s, alt='image'):
alt : str
The alt text to use for the HTML.
"""
base64_data = latex_to_png(s, encode=True).decode('ascii')
base64_data = latex_to_png(s, encode=True).decode("ascii")
if base64_data:
return _data_uri_template_png % (base64_data, alt)


return _data_uri_template_png % (base64_data, alt)

0 comments on commit b773816

Please sign in to comment.