@@ -989,6 +989,9 @@ def format(
989
989
Use 'latex' to replace the characters ``&``, ``%``, ``$``, ``#``, ``_``,
990
990
``{``, ``}``, ``~``, ``^``, and ``\`` in the cell display string with
991
991
LaTeX-safe sequences.
992
+ Use 'latex-math' to replace the characters ``&``, ``%``, ``#``, ``_``,
993
+ ``{``, ``}``, ``~``, ``^``, and ``\``
994
+ in the cell display string with LaTeX-safe sequences.
992
995
Escaping is done before ``formatter``.
993
996
994
997
.. versionadded:: 1.3.0
@@ -1742,9 +1745,12 @@ def _str_escape(x, escape):
1742
1745
return escape_html (x )
1743
1746
elif escape == "latex" :
1744
1747
return _escape_latex (x )
1748
+ elif escape == "latex-math" :
1749
+ return _escape_latex_math (x )
1745
1750
else :
1746
1751
raise ValueError (
1747
- f"`escape` only permitted in {{'html', 'latex'}}, got { escape } "
1752
+ f"`escape` only permitted in {{'html', 'latex', 'latex-math'}}, \
1753
+ got { escape } "
1748
1754
)
1749
1755
return x
1750
1756
@@ -2343,3 +2349,35 @@ def _escape_latex(s):
2343
2349
.replace ("^" , "\\ textasciicircum " )
2344
2350
.replace ("ab2§=§8yz" , "\\ textbackslash " )
2345
2351
)
2352
+
2353
+
2354
+ def _escape_latex_math (s ):
2355
+ r"""
2356
+ Replace the characters ``&``, ``%``, ``#``, ``_``, ``{``, ``}``,
2357
+ ``~``, ``^``, and ``\`` in the string with LaTeX-safe sequences.
2358
+
2359
+ Parameters
2360
+ ----------
2361
+ s : str
2362
+ Input to be escaped
2363
+
2364
+ Return
2365
+ ------
2366
+ str :
2367
+ Escaped string
2368
+ """
2369
+ return (
2370
+ s .replace ("\\ " , "ab2§=§8yz" ) # rare string for final conversion: avoid \\ clash
2371
+ .replace ("ab2§=§8yz " , "ab2§=§8yz\\ space " ) # since \backslash gobbles spaces
2372
+ .replace ("&" , "\\ &" )
2373
+ .replace ("%" , "\\ %" )
2374
+ .replace ("#" , "\\ #" )
2375
+ .replace ("_" , "\\ _" )
2376
+ .replace ("{" , "\\ {" )
2377
+ .replace ("}" , "\\ }" )
2378
+ .replace ("~ " , "~\\ space " ) # since \textasciitilde gobbles spaces
2379
+ .replace ("~" , "\\ textasciitilde " )
2380
+ .replace ("^ " , "^\\ space " ) # since \textasciicircum gobbles spaces
2381
+ .replace ("^" , "\\ textasciicircum " )
2382
+ .replace ("ab2§=§8yz" , "\\ textbackslash " )
2383
+ )
0 commit comments