Colored source code output with LaTeX and Pygments
Introduction
If you want to include source code in your LaTeX document, there are several ways.
One way is to use the listings
environment but the default output doesn’t look very nice.
\usepackage{listings}
...
\begin{lstlisting}[language=Python]
import tensorflow as tf
a = 1
b = 2
r = tf.add(a, b, name='Add')
print(r)
\end{lstlisting}
Another way is to use the minted
environment which uses the Python Pygments package which is a generic syntax highlighter supporting a variety of languages.
\usepackage{minted}
...
\begin{minted}{python}
import tensorflow as tf
a = 1
b = 2
r = tf.add(a, b, name='Add')
print(r)
\end{minted}
Installation steps (Linux)
- Install
minted
package:sudo apt-get install texlive-latex-extra
- Install the Pygments program:
sudo apt-get install python-pygments
- Append
-shell-escape
in the settings for PdfLaTeX in TeXstudio - Use the
minted
environment with your preferred source code style - Enjoy the nicely colored source code in your document!