##// END OF EJS Templates
Disable ipdoctest outside core...
Disable ipdoctest outside core Ultimately, we can get rid of ipdoctest, but we still have several doctests in core.

File last commit:

r19565:c68c6249
r21133:729e77b5
Show More
latextools.py
195 lines | 5.9 KiB | text/x-python | PythonLexer
Brian Granger
More improvements to the display system....
r3279 # -*- coding: utf-8 -*-
Min RK
make lib.latextools accept unicode...
r19562 """Tools for handling LaTeX."""
Brian Granger
More improvements to the display system....
r3279
Min RK
make lib.latextools accept unicode...
r19562 # Copyright (c) IPython Development Team.
Brian Granger
More improvements to the display system....
r3279 # Distributed under the terms of the Modified BSD License.
Min RK
make lib.latextools accept unicode...
r19562 from io import BytesIO, open
Brian Granger
More improvements to the display system....
r3279 from base64 import encodestring
Takafumi Arakaki
Add dvipng backend to latex_to_png
r7306 import os
import tempfile
import shutil
import subprocess
Brian Granger
More improvements to the display system....
r3279
Takafumi Arakaki
Check if latex/dvipng exist before calling them
r7330 from IPython.utils.process import find_cmd, FindCmdError
Min RK
hook up latex tools config to global instance...
r19565 from IPython.config import get_config
Takafumi Arakaki
Make lib.latextools configurable...
r7861 from IPython.config.configurable import SingletonConfigurable
Min RK
make lib.latextools accept unicode...
r19562 from IPython.utils.traitlets import List, Bool, Unicode
from IPython.utils.py3compat import cast_unicode, cast_unicode_py2 as u
Brian Granger
More improvements to the display system....
r3279
Takafumi Arakaki
Make lib.latextools configurable...
r7861 class LaTeXTool(SingletonConfigurable):
"""An object to store configuration of the LaTeX tool."""
Min RK
hook up latex tools config to global instance...
r19565 def _config_default(self):
return get_config()
Takafumi Arakaki
Make lib.latextools configurable...
r7861 backends = List(
Min RK
make lib.latextools accept unicode...
r19562 Unicode, ["matplotlib", "dvipng"],
Takafumi Arakaki
Make lib.latextools configurable...
r7861 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 "
"is usable only for inline style equations. To draw "
"display style equations, `dvipng` backend must be specified. ",
# It is a List instead of Enum, to make configuration more
# flexible. For example, to use matplotlib mainly but dvipng
# 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"].
config=True)
Min RK
make lib.latextools accept unicode...
r19562 use_breqn = Bool(
Takafumi Arakaki
Make lib.latextools configurable...
r7861 True,
help="Use breqn.sty to automatically break long equations. "
"This configuration takes effect only for dvipng backend.",
config=True)
packages = List(
['amsmath', 'amsthm', 'amssymb', 'bm'],
help="A list of packages to use for dvipng backend. "
"'breqn' will be automatically appended when use_breqn=True.",
config=True)
Min RK
make lib.latextools accept unicode...
r19562 preamble = Unicode(
Takafumi Arakaki
Make lib.latextools configurable...
r7861 help="Additional preamble to use when generating LaTeX source "
"for dvipng backend.",
config=True)
def latex_to_png(s, encode=False, backend=None, wrap=False):
Takafumi Arakaki
Add dvipng backend to latex_to_png
r7306 """Render a LaTeX string to PNG.
Brian Granger
More improvements to the display system....
r3279
Parameters
----------
Min RK
make lib.latextools accept unicode...
r19562 s : text
Brian Granger
More improvements to the display system....
r3279 The raw string containing valid inline LaTeX.
encode : bool, optional
Min RK
make lib.latextools accept unicode...
r19562 Should the PNG data base64 encoded to make it JSON'able.
Takafumi Arakaki
Make lib.latextools configurable...
r7861 backend : {matplotlib, dvipng}
Takafumi Arakaki
Add dvipng backend to latex_to_png
r7306 Backend for producing PNG data.
Takafumi Arakaki
Use breqn.sty in dvipng backend if possible
r7852 wrap : bool
If true, Automatically wrap `s` as a LaTeX equation.
Takafumi Arakaki
Add dvipng backend to latex_to_png
r7306
Takafumi Arakaki
latex_to_png returns None when the backend cannot be used...
r7309 None is returned when the backend cannot be used.
Brian Granger
More improvements to the display system....
r3279 """
Min RK
make lib.latextools accept unicode...
r19562 s = cast_unicode(s)
Takafumi Arakaki
Make lib.latextools configurable...
r7861 allowed_backends = LaTeXTool.instance().backends
if backend is None:
backend = allowed_backends[0]
if backend not in allowed_backends:
return None
if backend == 'matplotlib':
Takafumi Arakaki
Add dvipng backend to latex_to_png
r7306 f = latex_to_png_mpl
elif backend == 'dvipng':
f = latex_to_png_dvipng
else:
raise ValueError('No such backend {0}'.format(backend))
Takafumi Arakaki
Use breqn.sty in dvipng backend if possible
r7852 bin_data = f(s, wrap)
Takafumi Arakaki
latex_to_png returns None when the backend cannot be used...
r7309 if encode and bin_data:
Takafumi Arakaki
Add dvipng backend to latex_to_png
r7306 bin_data = encodestring(bin_data)
return bin_data
Takafumi Arakaki
Use breqn.sty in dvipng backend if possible
r7852 def latex_to_png_mpl(s, wrap):
Takafumi Arakaki
latex_to_png returns None when the backend cannot be used...
r7309 try:
from matplotlib import mathtext
except ImportError:
return None
Min RK
hook up latex tools config to global instance...
r19565
Min RK
mpl mathtext doesn't support display math...
r19564 # mpl mathtext doesn't support display math, force inline
s = s.replace('$$', '$')
Takafumi Arakaki
Use breqn.sty in dvipng backend if possible
r7852 if wrap:
Min RK
make lib.latextools accept unicode...
r19562 s = u'${0}$'.format(s)
Min RK
hook up latex tools config to global instance...
r19565
Brian Granger
More improvements to the display system....
r3279 mt = mathtext.MathTextParser('bitmap')
Thomas Kluyver
Fix IPython.lib.latextools for Python 3
r8013 f = BytesIO()
Brian Granger
More improvements to the display system....
r3279 mt.to_png(f, s, fontsize=12)
Takafumi Arakaki
Add dvipng backend to latex_to_png
r7306 return f.getvalue()
Takafumi Arakaki
Use breqn.sty in dvipng backend if possible
r7852 def latex_to_png_dvipng(s, wrap):
Takafumi Arakaki
Add dvipng backend to latex_to_png
r7306 try:
Takafumi Arakaki
Check if latex/dvipng exist before calling them
r7330 find_cmd('latex')
find_cmd('dvipng')
except FindCmdError:
return None
try:
Takafumi Arakaki
Add dvipng backend to latex_to_png
r7306 workdir = tempfile.mkdtemp()
tmpfile = os.path.join(workdir, "tmp.tex")
dvifile = os.path.join(workdir, "tmp.dvi")
outfile = os.path.join(workdir, "tmp.png")
Min RK
make lib.latextools accept unicode...
r19562 with open(tmpfile, "w", encoding='utf8') as f:
Takafumi Arakaki
Use breqn.sty in dvipng backend if possible
r7852 f.writelines(genelatex(s, wrap))
Takafumi Arakaki
Add dvipng backend to latex_to_png
r7306
Min RK
make lib.latextools accept unicode...
r19562 with open(os.devnull, 'wb') as devnull:
Jörgen Stenarson
Fix for latextools commandline arguments...
r8255 subprocess.check_call(
Thomas Kluyver
Use batchmode in latex_to_png_dvipng...
r17891 ["latex", "-halt-on-error", "-interaction", "batchmode", tmpfile],
cwd=workdir, stdout=devnull, stderr=devnull)
Jörgen Stenarson
Fix for latextools commandline arguments...
r8255
subprocess.check_call(
["dvipng", "-T", "tight", "-x", "1500", "-z", "9",
"-bg", "transparent", "-o", outfile, dvifile], cwd=workdir,
stdout=devnull, stderr=devnull)
Takafumi Arakaki
Add dvipng backend to latex_to_png
r7306
Thomas Kluyver
Fix IPython.lib.latextools for Python 3
r8013 with open(outfile, "rb") as f:
Abhinav Upadhyay
Avoid temprary variable assignment by returning value directly from try...
r12883 return f.read()
Takafumi Arakaki
Add dvipng backend to latex_to_png
r7306 finally:
shutil.rmtree(workdir)
Brian Granger
More improvements to the display system....
r3279
Brian Granger
Added mdboom's math_to_image from matplotlib.
r3881
Takafumi Arakaki
Use breqn.sty in dvipng backend if possible
r7852 def kpsewhich(filename):
"""Invoke kpsewhich command with an argument `filename`."""
try:
find_cmd("kpsewhich")
proc = subprocess.Popen(
["kpsewhich", filename],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stdout, stderr) = proc.communicate()
Min RK
make lib.latextools accept unicode...
r19562 return stdout.strip().decode('utf8', 'replace')
Takafumi Arakaki
Use breqn.sty in dvipng backend if possible
r7852 except FindCmdError:
pass
def genelatex(body, wrap):
"""Generate LaTeX document for dvipng backend."""
Takafumi Arakaki
Make lib.latextools configurable...
r7861 lt = LaTeXTool.instance()
breqn = wrap and lt.use_breqn and kpsewhich("breqn.sty")
Min RK
make lib.latextools accept unicode...
r19562 yield u(r'\documentclass{article}')
Takafumi Arakaki
Make lib.latextools configurable...
r7861 packages = lt.packages
Takafumi Arakaki
Use breqn.sty in dvipng backend if possible
r7852 if breqn:
Takafumi Arakaki
Make lib.latextools configurable...
r7861 packages = packages + ['breqn']
Takafumi Arakaki
Use breqn.sty in dvipng backend if possible
r7852 for pack in packages:
Min RK
make lib.latextools accept unicode...
r19562 yield u(r'\usepackage{{{0}}}'.format(pack))
yield u(r'\pagestyle{empty}')
Takafumi Arakaki
Make lib.latextools configurable...
r7861 if lt.preamble:
yield lt.preamble
Min RK
make lib.latextools accept unicode...
r19562 yield u(r'\begin{document}')
Takafumi Arakaki
Use breqn.sty in dvipng backend if possible
r7852 if breqn:
Min RK
make lib.latextools accept unicode...
r19562 yield u(r'\begin{dmath*}')
Takafumi Arakaki
Use breqn.sty in dvipng backend if possible
r7852 yield body
Min RK
make lib.latextools accept unicode...
r19562 yield u(r'\end{dmath*}')
Takafumi Arakaki
Use breqn.sty in dvipng backend if possible
r7852 elif wrap:
Min RK
make lib.latextools accept unicode...
r19562 yield u'$${0}$$'.format(body)
Takafumi Arakaki
Use breqn.sty in dvipng backend if possible
r7852 else:
yield body
Min RK
make lib.latextools accept unicode...
r19562 yield u'\end{document}'
Takafumi Arakaki
Add dvipng backend to latex_to_png
r7306
Min RK
make lib.latextools accept unicode...
r19562 _data_uri_template_png = u"""<img src="data:image/png;base64,%s" alt=%s />"""
Brian Granger
More improvements to the display system....
r3279
def latex_to_html(s, alt='image'):
"""Render LaTeX to HTML with embedded PNG data using data URIs.
Parameters
----------
s : str
The raw string containing valid inline LateX.
alt : str
The alt text to use for the HTML.
"""
Min RK
make lib.latextools accept unicode...
r19562 base64_data = latex_to_png(s, encode=True).decode('ascii')
Takafumi Arakaki
latex_to_png returns None when the backend cannot be used...
r7309 if base64_data:
return _data_uri_template_png % (base64_data, alt)
Brian Granger
More improvements to the display system....
r3279
Brian Granger
Added mdboom's math_to_image from matplotlib.
r3881