Highlighting Mathematica code in $\LaTeX$ document

I too had a need for a better syntax highlighting engine for Mathematica that can be used in different formats (so the javascript plugin is ruled out), so I wrote a better lexer and highlighter for Pygments than the one that ships with pygments. From the README:

It can currently lex and highlight:

  • All builtin functions in the System` context including unicode symbols like π except those that use characters from the private unicode space (e.g. \[FormalA])
  • User defined symbols, including those in a context.
  • Comments, including multi line and nested.
  • Strings, including multi line and escaped quotes.
  • Patterns, slots (including named slots #name introduced in version 10) and slot sequences.
  • Message names (e.g. the ivar in General::ivar)
  • Numbers including base notation (e.g. 8 ^^ 23 == 19) and scientific notation (e.g. 1 *^ 3 == 1000).
  • Local variables in Block, With and Module.

Installing it is as simple as executing pip install pygments-mathematica.

Here's an example of using it in a $\LaTeX$ document:

\documentclass{article}
\usepackage[english]{babel}
\usepackage{fontspec}
\setmonofont{Menlo}

\usepackage{minted}
\usemintedstyle{mathematica}

\begin{document}
\begin{minted}[linenos=true]{wolfram}
(* An example highlighting the features of
   this Pygments plugin for Mathematica *)
lissajous::usage = "An example Lissajous curve.\n" <>
                   "Definition: f(t) = (sin(3t + Pi/2), sin(t))"
lissajous = {Sin[2^^11 # + 0.005`10 * 1*^2 * Pi], Sin[#]} &;

ParametricPlot[lissajous[t], {t, 0, 2 Pi}] /. x_Line :> {Dashed, x}
\end{minted}
\end{document}

Assuming the file is called mma.tex, run xelatex --shell-escape mma.tex to generate a pdf that looks like this:

mma latex screenshot

The style mathematica is shipped with this plugin and if you'd like to change the colors, you can just update them in mathematica/style.py and then (re)install the plugin.

If you like the default notebook colors, you can use the style mathematicanotebook.


To get syntax highlighting for Mathematica in a latex code listing, try this:

\usepackage{listings}
\usepackage{color} 
\definecolor{listinggray}{gray}{0.9}
\definecolor{graphgray}{gray}{0.7}
\definecolor{blue}{rgb}{0,0,1}
\definecolor{mygreen}{rgb}{0,0.6,0}
\definecolor{mygray}{rgb}{0.5,0.5,0.5}
\definecolor{mymauve}{rgb}{0.58,0,0.82}

% define a custom mathematica language for syntax highlighting
\lstdefinelanguage{myMMA}{
keywords={SetDirectory, NotebookDirectory, Exp, IdentityMatrix, Eigenvalues, 
ListPlot, PlotRange, PlotStyle, Directive, PointSize, AspectRatio, Blue, Graphics, Line, 
Manipulate, Show, Sqrt, UniformDistribution, GammaDistribution, BetaDistribution, 
Nintegrate, For, DataRange, AxesLabel, PlotLabel, Transpose, Export, Plot, Append, Infinity},
keywordstyle=\color{black},
commentstyle=\color{gray}, 
stringstyle=\color{mymauve},
identifierstyle=\color{blue},
sensitive=false,
comment=[l]{(*},
morecomment=[s]{/*}{*/},
morestring=[b]',
morestring=[b]"
}

Keep in mind that the keywords I've listed here are far from exhaustive. I tried to find a list of Mathematica keywords but gave up. So I just used the keywords that I actually used in my code.

Edit

Here is a list of the keywords in a .txt file: https://www.dropbox.com/s/i3m8do7uof5uval/keywords.txt?dl=0

I found them by using

Names["System`*"]

The answer by @R.M. is what I would recommend to anyone who has the ability to install the required prerequisites. But as requested by @murray, here is an example of a complete $\LaTeX$ document that should have all the commands required for use with regular pdflatex (i.e., it doesn't require xelatex):

\documentclass[11pt,english]{scrartcl}
\usepackage{babel}
\usepackage{beramono}
\usepackage[T1]{fontenc}
\usepackage[latin9]{inputenc}
\usepackage{color}

\definecolor{identifiercolor}{rgb}{.4,.6,.56}
\definecolor{stringcolor}{gray}{0.5}
\definecolor{inactivecolor}{rgb}{0.15,0.15,0.5}
\usepackage{listings}
\lstset{basicstyle={\footnotesize\def\fvm@Scale{.85}\fontfamily{fvm}\selectfont},
  breaklines=true,
  escapeinside={\%*}{*)},
  keywordstyle={\bfseries\color{inactivecolor}},
  stringstyle={\bfseries\color{stringcolor}},
  identifierstyle={\bfseries\color{identifiercolor}},
  language=Mathematica,
  otherkeywords={DiscretizeRegion},
  showstringspaces=false}
\renewcommand{\lstlistingname}{Listing}

\begin{document}

Here I tell Mathematica to make a wave function plot:
\begin{lstlisting}[extendedchars=true,language=Mathematica]
Block[
 {region=DiscretizeRegion[Polygon[{{0,0},{-1/2,Sqrt[3]/2},{1/2,Sqrt[3]/2}}]]},
 ContourPlot[
  2 Cos[4 Pi x] Sin[(4 Pi y)/Sqrt[3]] - Sin[(8 Pi y)/Sqrt[3]],
  {x,y} %*$\in$*) region,
  PlotPoints ->70,
  Contours ->10,
  AspectRatio ->Automatic,
  FrameLabel ->{"x","y"},
  PlotLabel ->"Excited state of the equilateral triangle"
 ]
]
\end{lstlisting}

To get some characters such as \textbackslash{}[Element] in the output, 
I manually have to escpape from the listings environment and use the corresponding \LaTeX{} command.

\end{document}

Save this as listingsExample.tex and run pdflatex listingsExample. Make sure your editor doesn't automatically convert quotes " to $\LaTeX$ code (emacs does this by default). We want the code to be copied verbatim because it's supposed to be a source listing. The output should look like this:

PDF screen shot

I used the beramono font to get the arrows -> to come out in a form that allows the code to work directly when copied back to Mathematica. With the default font, the arrows look OK in the PDF but don't get translated back correctly inside Mathematica.

Also, I use the line basicstyle={\footnotesize\def\fvm@Scale{.85}\fontfamily{fvm}\selectfont}, to switch the font in the listing from serif to something closer to the Mathematica style. This font switching code comes from this answer on TeX.SE by Jubobs.

I also added a keyword not yet recognized by the package in its current version, using the line otherkeywords={DiscretizeRegion}.

For simplicity, the colors were chosen to look like the notebook display before any evaluation (i.e., keywords are blue). That way, I don't have to think about different colors for symbols that already have values.

The line escapeinside={\%*}{*)} defines two character sequences that are recognized as delimiters surrounding the escape to $\LaTeX$ code inside the listings environment.