Skip to content

Commit 2df1d5a

Browse files
committed
Inline definition of _common_texification
Work around matplotlib/matplotlib@1936c94 Fixes nschloe#559 Closes nschloe#602 Closes nschloe#597 Overalps a bit with nschloe#540
1 parent 450712b commit 2df1d5a

File tree

2 files changed

+35
-8
lines changed

2 files changed

+35
-8
lines changed

src/tikzplotlib/_axes.py

+1-8
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,8 @@
11
import matplotlib as mpl
22
import numpy as np
3-
from matplotlib.backends.backend_pgf import (
4-
common_texification as mpl_common_texification,
5-
)
63

74
from . import _color
8-
9-
10-
def _common_texification(string):
11-
# Work around <https://github.com/matplotlib/matplotlib/issues/15493>
12-
return mpl_common_texification(string).replace("&", "\\&")
5+
from ._util import _common_texification
136

147

158
class Axes:

src/tikzplotlib/_util.py

+34
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import functools
2+
import re
13
import matplotlib.transforms
24
import numpy as np
35

@@ -39,3 +41,35 @@ def transform_to_data_coordinates(obj, xdata, ydata):
3941
)
4042
return transform.transform(points).T
4143
return xdata, ydata
44+
45+
46+
_NO_ESCAPE = r"(?<!\\)(?:\\\\)*"
47+
_split_math = re.compile(_NO_ESCAPE + r"\$").split
48+
_replace_mathdefault = functools.partial(
49+
# Replace \mathdefault (when not preceded by an escape) by empty string.
50+
re.compile(_NO_ESCAPE + r"(\\mathdefault)").sub, "")
51+
52+
def _common_texification(text):
53+
return _tex_escape(text)
54+
55+
def _tex_escape(text):
56+
r"""
57+
Do some necessary and/or useful substitutions for texts to be included in
58+
LaTeX documents.
59+
This distinguishes text-mode and math-mode by replacing the math separator
60+
``$`` with ``\(\displaystyle %s\)``. Escaped math separators (``\$``)
61+
are ignored.
62+
"""
63+
# Sometimes, matplotlib adds the unknown command \mathdefault.
64+
# Not using \mathnormal instead since this looks odd for the latex cm font.
65+
text = _replace_mathdefault(text)
66+
text = text.replace("\N{MINUS SIGN}", r"\ensuremath{-}")
67+
# Work around <https://github.com/matplotlib/matplotlib/issues/15493>
68+
text = text.replace("&", r"\&")
69+
# split text into normaltext and inline math parts
70+
parts = _split_math(text)
71+
for i, s in enumerate(parts):
72+
if i % 2: # mathmode replacements
73+
s = r"\(\displaystyle %s\)" % s
74+
parts[i] = s
75+
return "".join(parts)

0 commit comments

Comments
 (0)