@@ -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
@@ -1743,9 +1746,12 @@ def _str_escape(x, escape):
1743
1746
return escape_html (x )
1744
1747
elif escape == "latex" :
1745
1748
return _escape_latex (x )
1749
+ elif escape == "latex-math" :
1750
+ return _escape_latex_math (x )
1746
1751
else :
1747
1752
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 } "
1749
1755
)
1750
1756
return x
1751
1757
@@ -2344,3 +2350,35 @@ def _escape_latex(s):
2344
2350
.replace ("^" , "\\ textasciicircum " )
2345
2351
.replace ("ab2§=§8yz" , "\\ textbackslash " )
2346
2352
)
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