Skip to content

Inline definition of _common_texification (fixes #559 for matplotlib >= 3.8) #603

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 1 addition & 8 deletions src/tikzplotlib/_axes.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,8 @@
import matplotlib as mpl
import numpy as np
from matplotlib.backends.backend_pgf import (
common_texification as mpl_common_texification,
)

from . import _color


def _common_texification(string):
# Work around <https://github.com/matplotlib/matplotlib/issues/15493>
return mpl_common_texification(string).replace("&", "\\&")
from ._util import _common_texification


class Axes:
Expand Down
34 changes: 34 additions & 0 deletions src/tikzplotlib/_util.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import functools
import re
import matplotlib.transforms
import numpy as np

Expand Down Expand Up @@ -39,3 +41,35 @@ def transform_to_data_coordinates(obj, xdata, ydata):
)
return transform.transform(points).T
return xdata, ydata


_NO_ESCAPE = r"(?<!\\)(?:\\\\)*"
_split_math = re.compile(_NO_ESCAPE + r"\$").split
_replace_mathdefault = functools.partial(
# Replace \mathdefault (when not preceded by an escape) by empty string.
re.compile(_NO_ESCAPE + r"(\\mathdefault)").sub, "")

def _common_texification(text):
return _tex_escape(text)

def _tex_escape(text):
r"""
Do some necessary and/or useful substitutions for texts to be included in
LaTeX documents.
This distinguishes text-mode and math-mode by replacing the math separator
``$`` with ``\(\displaystyle %s\)``. Escaped math separators (``\$``)
are ignored.
"""
# Sometimes, matplotlib adds the unknown command \mathdefault.
# Not using \mathnormal instead since this looks odd for the latex cm font.
text = _replace_mathdefault(text)
text = text.replace("\N{MINUS SIGN}", r"\ensuremath{-}")
# Work around <https://github.com/matplotlib/matplotlib/issues/15493>
text = text.replace("&", r"\&")
# split text into normaltext and inline math parts
parts = _split_math(text)
for i, s in enumerate(parts):
if i % 2: # mathmode replacements
s = r"\(\displaystyle %s\)" % s
parts[i] = s
return "".join(parts)