Debian Codegraph @

IPython/lib/latextools.py

raw
1 # -*- coding: utf-8 -*-
2 """Tools for handling LaTeX."""
3
4 # Copyright (c) IPython Development Team.
5 # Distributed under the terms of the Modified BSD License.
6
7 from io import BytesIO
8 import os
9 import tempfile
10 import shutil
11 import subprocess
12 from base64 import encodebytes
13 import textwrap
14
15 from pathlib import Path
16
17 from IPython.utils.process import find_cmd, FindCmdError
18 from traitlets.config import get_config
19 from traitlets.config.configurable import SingletonConfigurable
20 from traitlets import List, Bool, Unicode
21
22
23 class LaTeXTool(SingletonConfigurable):
24 """An object to store configuration of the LaTeX tool."""
25 def _config_default(self):
26 return get_config()
27
28 backends = List(
29 Unicode(), ["matplotlib", "dvipng"],
30 help="Preferred backend to draw LaTeX math equations. "
31 "Backends in the list are checked one by one and the first "
32 "usable one is used. Note that `matplotlib` backend "
33 "is usable only for inline style equations. To draw "
34 "display style equations, `dvipng` backend must be specified. ",
35 # It is a List instead of Enum, to make configuration more
36 # flexible. For example, to use matplotlib mainly but dvipng
37 # for display style, the default ["matplotlib", "dvipng"] can
38 # be used. To NOT use dvipng so that other repr such as
39 # unicode pretty printing is used, you can use ["matplotlib"].
40 ).tag(config=True)
41
42 use_breqn = Bool(
43 True,
44 help="Use breqn.sty to automatically break long equations. "
45 "This configuration takes effect only for dvipng backend.",
46 ).tag(config=True)
47
48 packages = List(
49 ['amsmath', 'amsthm', 'amssymb', 'bm'],
50 help="A list of packages to use for dvipng backend. "
51 "'breqn' will be automatically appended when use_breqn=True.",
52 ).tag(config=True)
53
54 preamble = Unicode(
55 help="Additional preamble to use when generating LaTeX source "
56 "for dvipng backend.",
57 ).tag(config=True)
58
59
60 def latex_to_png(
61 s: str, encode=False, backend=None, wrap=False, color="Black", scale=1.0
62 ):
63 """Render a LaTeX string to PNG.
64
65 Parameters
66 ----------
67 s : str
68 The raw string containing valid inline LaTeX.
69 encode : bool, optional
70 Should the PNG data base64 encoded to make it JSON'able.
71 backend : {matplotlib, dvipng}
72 Backend for producing PNG data.
73 wrap : bool
74 If true, Automatically wrap `s` as a LaTeX equation.
75 color : string
76 Foreground color name among dvipsnames, e.g. 'Maroon' or on hex RGB
77 format, e.g. '#AA20FA'.
78 scale : float
79 Scale factor for the resulting PNG.
80 None is returned when the backend cannot be used.
81
82 """
83 assert isinstance(s, str)
84 allowed_backends = LaTeXTool.instance().backends
85 if backend is None:
86 backend = allowed_backends[0]
87 if backend not in allowed_backends:
88 return None
89 if backend == 'matplotlib':
90 f = latex_to_png_mpl
91 elif backend == 'dvipng':
92 f = latex_to_png_dvipng
93 if color.startswith('#'):
94 # Convert hex RGB color to LaTeX RGB color.
95 if len(color) == 7:
96 try:
97 color = "RGB {}".format(" ".join([str(int(x, 16)) for x in
98 textwrap.wrap(color[1:], 2)]))
99 except ValueError as e:
100 raise ValueError('Invalid color specification {}.'.format(color)) from e
101 else:
102 raise ValueError('Invalid color specification {}.'.format(color))
103 else:
104 raise ValueError('No such backend {0}'.format(backend))
105 bin_data = f(s, wrap, color, scale)
106 if encode and bin_data:
107 bin_data = encodebytes(bin_data)
108 return bin_data
109
110
111 def latex_to_png_mpl(s, wrap, color='Black', scale=1.0):
112 try:
113 from matplotlib import figure, font_manager, mathtext
114 from matplotlib.backends import backend_agg
115 from pyparsing import ParseFatalException
116 except ImportError:
117 return None
118
119 # mpl mathtext doesn't support display math, force inline
120 s = s.replace('$$', '$')
121 if wrap:
122 s = u'${0}$'.format(s)
123
124 try:
125 prop = font_manager.FontProperties(size=12)
126 dpi = 120 * scale
127 buffer = BytesIO()
128
129 # Adapted from mathtext.math_to_image
130 parser = mathtext.MathTextParser("path")
131 width, height, depth, _, _ = parser.parse(s, dpi=72, prop=prop)
132 fig = figure.Figure(figsize=(width / 72, height / 72))
133 fig.text(0, depth / height, s, fontproperties=prop, color=color)
134 backend_agg.FigureCanvasAgg(fig)
135 fig.savefig(buffer, dpi=dpi, format="png", transparent=True)
136 return buffer.getvalue()
137 except (ValueError, RuntimeError, ParseFatalException):
138 return None
139
140
141 def latex_to_png_dvipng(s, wrap, color='Black', scale=1.0):
142 try:
143 find_cmd('latex')
144 find_cmd('dvipng')
145 except FindCmdError:
146 return None
147
148 startupinfo = None
149 if os.name == "nt":
150 # prevent popup-windows
151 startupinfo = subprocess.STARTUPINFO()
152 startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
153
154 try:
155 workdir = Path(tempfile.mkdtemp())
156 tmpfile = "tmp.tex"
157 dvifile = "tmp.dvi"
158 outfile = "tmp.png"
159
160 with workdir.joinpath(tmpfile).open("w", encoding="utf8") as f:
161 f.writelines(genelatex(s, wrap))
162
163 subprocess.check_call(
164 ["latex", "-halt-on-error", "-interaction", "batchmode", tmpfile],
165 cwd=workdir,
166 stdout=subprocess.DEVNULL,
167 stderr=subprocess.DEVNULL,
168 startupinfo=startupinfo,
169 )
170
171 resolution = round(150 * scale)
172 subprocess.check_call(
173 [
174 "dvipng",
175 "-T",
176 "tight",
177 "-D",
178 str(resolution),
179 "-z",
180 "9",
181 "-bg",
182 "Transparent",
183 "-o",
184 outfile,
185 dvifile,
186 "-fg",
187 color,
188 ],
189 cwd=workdir,
190 stdout=subprocess.DEVNULL,
191 stderr=subprocess.DEVNULL,
192 startupinfo=startupinfo,
193 )
194
195 with workdir.joinpath(outfile).open("rb") as f:
196 return f.read()
197 except subprocess.CalledProcessError:
198 return None
199 finally:
200 shutil.rmtree(workdir)
201
202
203 def kpsewhich(filename):
204 """Invoke kpsewhich command with an argument `filename`."""
205 try:
206 find_cmd("kpsewhich")
207 proc = subprocess.Popen(
208 ["kpsewhich", filename],
209 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
210 (stdout, stderr) = proc.communicate()
211 return stdout.strip().decode('utf8', 'replace')
212 except FindCmdError:
213 pass
214
215
216 def genelatex(body, wrap):
217 """Generate LaTeX document for dvipng backend."""
218 lt = LaTeXTool.instance()
219 breqn = wrap and lt.use_breqn and kpsewhich("breqn.sty")
220 yield r'\documentclass{article}'
221 packages = lt.packages
222 if breqn:
223 packages = packages + ['breqn']
224 for pack in packages:
225 yield r'\usepackage{{{0}}}'.format(pack)
226 yield r'\pagestyle{empty}'
227 if lt.preamble:
228 yield lt.preamble
229 yield r'\begin{document}'
230 if breqn:
231 yield r'\begin{dmath*}'
232 yield body
233 yield r'\end{dmath*}'
234 elif wrap:
235 yield u'$${0}$$'.format(body)
236 else:
237 yield body
238 yield u'\\end{document}'
239
240
241 _data_uri_template_png = u"""<img src="data:image/png;base64,%s" alt=%s />"""
242
243 def latex_to_html(s, alt='image'):
244 """Render LaTeX to HTML with embedded PNG data using data URIs.
245
246 Parameters
247 ----------
248 s : str
249 The raw string containing valid inline LateX.
250 alt : str
251 The alt text to use for the HTML.
252 """
253 base64_data = latex_to_png(s, encode=True).decode('ascii')
254 if base64_data:
255 return _data_uri_template_png % (base64_data, alt)
256
257