1
$\begingroup$

I would like to display some formulae in a Mathematica notebook. For this I would like to have a function like

DisplayLaTeX[latex_String] := Module[{modlatex}, modlatex:=StringReplace[latex,"\\"->"\\\\"]; CellPrint@Cell[BoxData[ToBoxes[DisplayForm@ToExpression[modlatex, TeXForm, HoldForm]]], "Text"] ]; 

taking regular LaTeX syntax (with only single backslashes) as an input.

With the above approach, Mathematica already evaluates escape sequences like \f, \s, ... before doing the StringReplace and thus renders expressions like

DisplayLaTeX["\zeta(n_1,\ldots,n_r)=\sum_{0<k_1<\cdots<k_r}\frac{1}{k_1^{n_1}\cdots k_r^{n_r}}"] 

incorrectly. What would be the correct way to achieve a proper rendering?

$\endgroup$
1
  • 3
    $\begingroup$ Does this answer your question? How do I make a string literal without having to escape backslashes? Long story short: Backslashes work as escape characters in Mathematica (and many other languages. That is why you have to properly escape them with another backslash. If you want to bypass this, you can use a solution from the answer mentioned above. $\endgroup$ Commented Jan 8, 2024 at 18:44

1 Answer 1

2
$\begingroup$

Thanks to Domen's recommendation, I could indeed create the expected behaviour by using the common variable $PreRead in Mathematica. Here is the function rendering simple LaTeX commands:

$PreRead = ( # /. RowBox@{"DisplayLaTeX", "[", str_String, "]"} | RowBox@{"DisplayLaTeX", "@", str_String} | RowBox@{str_String, "//", "DisplayLaTeX"} :> RowBox@{"DisplayLaTeXHelper", "[","StringTrim", "[", ToString@InputForm@str, ",", "\"\\\"\"", "]","]"} )&; DisplayLaTeXHelper[latex_String] := Module[{}, CellPrint@Cell[BoxData[ToBoxes[DisplayForm@ToExpression[latex, TeXForm, HoldForm]]], "Text"] ]; 

Using the following command one can now display the definition of multiple zeta values:

DisplayLaTeX["\zeta(n_1,\ldots,n_r)=\sum_{0<k_1<\cdots<k_r}\frac{1}{k_1^{n_1}\cdots k_r^{n_r}}"] 

The only downside of this method is that autocompletion for DisplayLaTeX won't work.

$\endgroup$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.