Template for code highlighting with minted in LaTeX beamer

Syntax highlighting can be achieved in LaTeX via listings or more recently with minted. The latter package uses Pygments to create beautiful code highlighting and includes fantastic additional features such as line numbering.

Minted's compatibility with the Latex beamer class, however, is restricted and some workarounds (as laid out by Tristan Ravitch in his blog post are needed to assure full functionality of both the beamer class and minted.

Here's a template I made for anyone who wants to present code with the beamer class and the minted package, like in the image above:

\documentclass{beamer}
\usetheme{default}

\usepackage{minted}

\newminted{python}{fontsize=\scriptsize, 
                   linenos,
                   numbersep=8pt,
                   gobble=4,
                   frame=lines,
                   bgcolor=bg,
                   framesep=3mm} 


\begin{document}

\definecolor{bg}{rgb}{0.95,0.95,0.95}

\defverbatim[colored]\exampleCode{
\begin{pythoncode}


    import numpy as np
    import pylab as pl

    def f_x(x):
      return np.exp(x)+x**2-5*x

    def approx_f(x):
      return 1 -4*x +3./2*x**2

    xvals = np.arange(-4,4,0.1)
    fx_vals = [f_x(x) for x in xvals]
    approx_vals = [approx_f(x) for x in xvals]

    pl.plot(xvals,fx_vals)
    pl.plot(xvals,approx_vals)

    pl.show()


\end{pythoncode}
}

\begin{frame}
\frametitle{Code example}
\exampleCode
\pause
Overlays work!
\end{frame}

\end{document}