10000 Merge pull request #15696 from anntzer/mathmpl-fontset · matplotlib/matplotlib@7ea91b6 · GitHub
[go: up one dir, main page]

Skip to content

Commit 7ea91b6

Browse files
authored
Merge pull request #15696 from anntzer/mathmpl-fontset
Improve mathtext.fontset docs and fix :mathmpl: cache bug.
2 parents 98f04ea + b4faa55 commit 7ea91b6

File tree

6 files changed

+59
-36
lines changed

6 files changed

+59
-36
lines changed

doc/_static/cm_fontset.png

-3.17 KB
Binary file not shown.

doc/_static/stix_fontset.png

-2.94 KB
Binary file not shown.

doc/_static/stixsans_fontset.png

-2.92 KB
Binary file not shown.

lib/matplotlib/mathtext.py

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3320,27 +3320,31 @@ def __init__(self, output):
33203320
"""
33213321
self._output = output.lower()
33223322

3323-
@functools.lru_cache(50)
3324-
def parse(self, s, dpi = 72, prop = None):
3323+
def parse(self, s, dpi=72, prop=None):
33253324
"""
3326-
Parse the given math expression *s* at the given *dpi*. If
3327-
*prop* is provided, it is a
3328-
:class:`~matplotlib.font_manager.FontProperties` object
3329-
specifying the "default" font to use in the math expression,
3330-
used for all non-math text.
3325+
Parse the given math expression *s* at the given *dpi*. If *prop* is
3326+
provided, it is a `.FontProperties` object specifying the "default"
3327+
font to use in the math expression, used for all non-math text.
33313328
33323329
The results are cached, so multiple calls to :meth:`parse`
33333330
with the same expression should be fast.
33343331
"""
3332+
# lru_cache can't decorate parse() directly because the ps.useafm and
3333+
# mathtext.fontset rcParams also affect the parse (e.g. by affecting
3334+
# the glyph metrics).
3335+
return self._parse_cached(
3336+
s, dpi, prop, rcParams['ps.useafm'], rcParams['mathtext.fontset'])
3337+
3338+
@functools.lru_cache(50)
3339+
def _parse_cached(self, s, dpi, prop, ps_useafm, fontset):
33353340

33363341
if prop is None:
33373342
prop = FontProperties()
33383343

3339-
if self._output == 'ps' and rcParams['ps.useafm']:
3344+
if self._output == 'ps' and ps_useafm:
33403345
font_output = StandardPsFonts(prop)
33413346
else:
33423347
backend = self._backend_mapping[self._output]()
3343-
fontset = rcParams['mathtext.fontset'].lower()
33443348
fontset_class = cbook._check_getitem(
33453349
self._font_type_mapping, fontset=fontset)
33463350
font_output = fontset_class(prop, backend)

lib/matplotlib/sphinxext/mathmpl.py

Lines changed: 16 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,13 @@
11
import hashlib
22
import os
3-
import sys
43

54
from docutils import nodes
65
from docutils.parsers.rst import Directive, directives
76
import sphinx
87

9-
from matplotlib import rcParams
8+
import matplotlib as mpl
109
from matplotlib import cbook
1110
from matplotlib.mathtext import MathTextParser
12-
rcParams['mathtext.fontset'] = 'cm'
1311
mathtext_parser = MathTextParser("Bitmap")
1412

1513

@@ -19,7 +17,7 @@ class latex_math(nodes.General, nodes.Element):
1917

2018

2119
def fontset_choice(arg):
22-
return directives.choice(arg, ['cm', 'stix', 'stixsans'])
20+
return directives.choice(arg, MathTextParser._font_type_mapping)
2321

2422

2523
def math_role(role, rawtext, text, lineno, inliner,
@@ -61,36 +59,34 @@ def run(self):
6159
# This uses mathtext to render the expression
6260
def latex2png(latex, filename, fontset='cm'):
6361
latex = "$%s$" % latex
64-
orig_fontset = rcParams['mathtext.fontset']
65-
rcParams['mathtext.fontset'] = fontset
66-
if os.path.exists(filename):
67-
depth = mathtext_parser.get_depth(latex, dpi=100)
68-
else:
69-
try:
70-
depth = mathtext_parser.to_png(filename, latex, dpi=100)
71-
except Exception:
72-
cbook._warn_external("Could not render math expression %s" % latex,
73-
Warning)
74-
depth = 0
75-
rcParams['mathtext.fontset'] = orig_fontset
76-
sys.stdout.write("#")
77-
sys.stdout.flush()
62+
with mpl.rc_context({'mathtext.fontset': fontset}):
63+
if os.path.exists(filename):
64+
depth = mathtext_parser.get_depth(latex, dpi=100)
65+
else:
66 B41A +
try:
67+
depth = mathtext_parser.to_png(filename, latex, dpi=100)
68+
except Exception:
69+
cbook._warn_external(
70+
f"Could not render math expression {latex}")
71+
depth = 0
7872
return depth
7973

8074

8175
# LaTeX to HTML translation stuff:
8276
def latex2html(node, source):
8377
inline = isinstance(node.parent, nodes.TextElement)
8478
latex = node['latex']
85-
name = 'math-%s' % hashlib.md5(latex.encode()).hexdigest()[-10:]
79+
fontset = node['fontset']
80+
name = 'math-{}'.format(
81+
hashlib.md5((latex + fontset).encode()).hexdigest()[-10:])
8682

8783
destdir = os.path.join(setup.app.builder.outdir, '_images', 'mathmpl')
8884
if not os.path.exists(destdir):
8985
os.makedirs(destdir)
9086
dest = os.path.join(destdir, '%s.png' % name)
9187
path = '/'.join((setup.app.builder.imgpath, 'mathmpl'))
9288

93-
depth = latex2png(latex, dest, node['fontset'])
89+
depth = latex2png(latex, dest, fontset)
9490

9591
if inline:
9692
cls = ''

tutorials/text/mathtext.py

Lines changed: 30 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -224,21 +224,44 @@
224224
``\mathrm{\mathsf{sansserif}}`` :math-stix:`\mathrm{\mathsf{sansserif}}`
225225
================================ =========================================
226226
227-
There are also three global "font sets" to choose from, which are
227+
There are also five global "font sets" to choose from, which are
228228
selected using the ``mathtext.fontset`` parameter in :ref:`matplotlibrc
229229
<matplotlibrc-sample>`.
230230
231-
``cm``: **Computer Modern (TeX)**
231+
``dejavusans``: DejaVu Sans
232232
233-
.. image:: ../../_static/cm_fontset.png
233+
.. mathmpl::
234+
:fontset: dejavusans
234235
235-
``stix``: **STIX** (designed to blend well with Times)
236+
\mathcal{R} \prod_{i=\alpha}^{\infty} a_i \sin\left(2\pi fx_i\right)
236237
237-
.. image:: ../../_static/stix_fontset.png
238+
``dejavuserif``: DejaVu Serif
238239
239-
``stixsans``: **STIX sans-serif**
240+
.. mathmpl::
241+
:fontset: dejavuserif
240242
241-
.. image:: ../../_static/stixsans_fontset.png
243+
\mathcal{R} \prod_{i=\alpha}^{\infty} a_i \sin\left(2\pi fx_i\right)
244+
245+
``cm``: Computer Modern (TeX)
246+
247+
.. mathmpl::
248+
:fontset: cm
249+
250+
\mathcal{R} \prod_{i=\alpha}^{\infty} a_i \sin\left(2\pi fx_i\right)
251+
252+
``stix``: STIX (designed to blend well with Times)
253+
254+
.. mathmpl::
255+
:fontset: stix
256+
257+
\mathcal{R} \prod_{i=\alpha}^{\infty} a_i \sin\left(2\pi fx_i\right)
258+
259+
``stixsans``: STIX sans-serif
260+
261+
.. mathmpl::
262+
:fontset: stixsans
263+
264+
\mathcal{R} \prod_{i=\alpha}^{\infty} a_i \sin\left(2\pi fx_i\right)
242265
243266
Additionally, you can use ``\mathdefault{...}`` or its alias
244267
``\mathregular{...}`` to use the font used for regular text outside of

0 commit comments

Comments
 (0)
0