@@ -989,6 +989,9 @@ def format(
989989 Use 'latex' to replace the characters ``&``, ``%``, ``$``, ``#``, ``_``,
990990 ``{``, ``}``, ``~``, ``^``, and ``\`` in the cell display string with
991991 LaTeX-safe sequences.
992+ Use 'latex-math' to replace the characters ``&``, ``%``, ``#``, ``_``,
993+ ``{``, ``}``, ``~``, ``^``, and ``\``
994+ in the cell display string with LaTeX-safe sequences.
992995 Escaping is done before ``formatter``.
993996
994997 .. versionadded:: 1.3.0
@@ -1743,9 +1746,12 @@ def _str_escape(x, escape):
17431746 return escape_html (x )
17441747 elif escape == "latex" :
17451748 return _escape_latex (x )
1749+ elif escape == "latex-math" :
1750+ return _escape_latex_math (x )
17461751 else :
17471752 raise ValueError (
1748- f"`escape` only permitted in {{'html', 'latex'}}, got { escape } "
1753+ f"`escape` only permitted in {{'html', 'latex', 'latex-math'}}, \
1754+ got { escape } "
17491755 )
17501756 return x
17511757
@@ -2344,3 +2350,35 @@ def _escape_latex(s):
23442350 .replace ("^" , "\\ textasciicircum " )
23452351 .replace ("ab2§=§8yz" , "\\ textbackslash " )
23462352 )
2353+
2354+
2355+ def _escape_latex_math (s ):
2356+ r"""
2357+ Replace the characters ``&``, ``%``, ``#``, ``_``, ``{``, ``}``,
2358+ ``~``, ``^``, and ``\`` in the string with LaTeX-safe sequences.
2359+
2360+ Parameters
2361+ ----------
2362+ s : str
2363+ Input to be escaped
2364+
2365+ Return
2366+ ------
2367+ str :
2368+ Escaped string
2369+ """
2370+ return (
2371+ s .replace ("\\ " , "ab2§=§8yz" ) # rare string for final conversion: avoid \\ clash
2372+ .replace ("ab2§=§8yz " , "ab2§=§8yz\\ space " ) # since \backslash gobbles spaces
2373+ .replace ("&" , "\\ &" )
2374+ .replace ("%" , "\\ %" )
2375+ .replace ("#" , "\\ #" )
2376+ .replace ("_" , "\\ _" )
2377+ .replace ("{" , "\\ {" )
2378+ .replace ("}" , "\\ }" )
2379+ .replace ("~ " , "~\\ space " ) # since \textasciitilde gobbles spaces
2380+ .replace ("~" , "\\ textasciitilde " )
2381+ .replace ("^ " , "^\\ space " ) # since \textasciicircum gobbles spaces
2382+ .replace ("^" , "\\ textasciicircum " )
2383+ .replace ("ab2§=§8yz" , "\\ textbackslash " )
2384+ )
0 commit comments