Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

I want to include some Mathematica code in a LaTeX document.

It's along the lines of f[a_,b_]:=a^2+b^2+4b^3+25a*b*c ;

However, when I build my PDF, the _ and ^ always render. Is there a way to get it to just show up as it shows above?

share|improve this question
add comment

3 Answers

As rdhs mentionned, you can use the listings package. A sample example is:




f[a_,b_]:=a^2+b^2+4b^3+25a*b*c ;

For inline stuff you can use \lstinline$f[a_,b_]:=a^2+b^2+4b^3+25a*b*c ;$
 instead of the lstlisting environment. 

Note the verb like delimiters for lstinline. One thing however, the listings manual indicates verb like delimiters, but in all of my work I use the usual { and } and it works fine (maybe a quirk, but I find it easier to read and will continue using it as long as possible)

enter image description here

There are other ways also. For example the minted package does what you what, but it requires that you install Pygments, which is a Python library.

share|improve this answer
\lstinline has \verb-style delimiters: \lstinline$f[a_,b_]:=a^2+b^2+4b^3+25a*b*c ;$. The big difference is that it also has an optional keyval argument. –  rdhs Jan 26 '12 at 16:42
@rdhs: thanks for the correction. I edited the code. However, when I use { and } it works fine. –  Frédéric Jan 26 '12 at 16:56
Why is there no syntax highlighting in the Mathematica code? I also see this for Mathematica, but not for other languages? Is it because the most recent version of Mathematica included in the listings package is 5.2, whereas Mathematica is currently at version 8? –  user001 Feb 25 '12 at 4:23
add comment

Use \verb, as in \verb|f[a_,b_]:=a^2+b^2+4b^3+25a*b*c ;|. For longer programs, use the listings package. Or use Mathematica's Save selection as PDF feature and include the PDF as an image.

share|improve this answer
add comment

To include an image of your Mathematica code, you can evaluate the cell

Function in Mathematica 8

and then select it (by clicking on the right square bracket ]). Then, following the menu's File>Save Selection As... and saving as a PDF produces the PDF output:

enter image description here

One advantage of this approach is that it will include the embedded Mathematica font, as well as the same spacing and layout as in the actual Mathematica display. If you which to get rid of the input/output indicators, you can either clip the image using graphicx's trim=lx ly ux uy,clip key-value, or extract the image before it is evaluated.

share|improve this answer
add comment

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.