Source code in LaTeX

Listings package

The listings package allows to include source code for a number of programming languages within a LaTeX document and features syntax highlighting adapted to the respective language.

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage[scaled]{beramono}
\usepackage{listings}
\usepackage{color}

\definecolor{mygray}{rgb}{0.6,0.6,0.6}
\definecolor{mygreen}{rgb}{0,0.5,0.2}
\definecolor{myorange}{rgb}{1.0,0.4,0}

\lstdefinestyle{colorful}{
basicstyle=\footnotesize\ttfamily\color{black},
commentstyle=\color{mygray},
numbers=left,
numbersep=5pt,
numberstyle=\tiny\color{mygray},
keywordstyle=\color{mygreen},
showspaces=false,
showstringspaces=false,
stringstyle=\color{myorange},
tabsize=2
}

\begin{document}
\section{some example}
more text to come here

\begin{lstlisting}[language=Python,style=colorful]
import re
for test_string in ['555-1212', 'ILL-EGAL']: # a comment
if re.match(r'^\d{3}-\d{4}$', test_string):
print test_string, 'is a valid US local phone number'
else:
print test_string, 'rejected'
\end{lstlisting}
\end{document}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s