The listings package

Typesets source code with syntax highlighting, line numbers and captions, without an external program: the lstlisting environment, \lstinline and \lstinputlisting, configured with \lstset.

Loading the package

\usepackage{listings}

verbatim prints code as typed and nothing more. listings recognises keywords, comments and strings of the chosen language and formats them. It can number the lines, break lines that are too long, draw a frame and give the listing a caption with a label. All of this happens inside TeX, so it works where shell escape is switched off, unlike minted.

Without settings the output is plain: the text font instead of a monospaced one, and no colours. A \lstset{...} in the preamble defines the look once for all listings; colours need xcolor.

The package knows several dozen languages, among them C, C++, Java, Python, SQL, HTML, bash, Matlab, R and TeX. Others, such as JavaScript and Rust, are missing in the version of TeX Live 2023 and have to be defined with \lstdefinelanguage.

Main commands

\begin{lstlisting}[language=Python] ... \end{lstlisting}A block of code in the given language.
\lstinline|x = 1|Code inside a line of text; the two delimiters are any character that does not occur in the code.
\lstinputlisting[language=C, firstline=10, lastline=25]{main.c}Reads the code from a file, here only lines 10 to 25.
\lstset{basicstyle=\ttfamily\small, numbers=left, breaklines=true}Settings for all following listings: font, line numbers, automatic line breaks.
keywordstyle=\color{blue}, commentstyle=\color{gray}, stringstyle=\color{teal}Formatting of keywords, comments and strings.
caption={Sum of a list}, label={lst:sum}Caption and label of one listing; refer to it with \ref{lst:sum}.
frame=singleA frame around the listing; frame=lines draws only a rule above and below.
\lstlistoflistingsA list of all listings that have a caption.

Complete example

\documentclass{article}
\usepackage{xcolor}
\usepackage{listings}
\lstset{
  basicstyle=\ttfamily\small,
  keywordstyle=\color{blue},
  commentstyle=\color{gray},
  numbers=left, numberstyle=\tiny,
  frame=single, breaklines=true
}
\begin{document}
\begin{lstlisting}[language=Python, caption={Sum of a list}, label={lst:sum}]
def total(values):
    # add all values
    return sum(values)
\end{lstlisting}
Listing~\ref{lst:sum} is called as \lstinline|total([1, 2, 3])|.
\end{document}
Result
The compiled example

Open in the editor

Compiled with pdfLaTeX from TeX Live 2023. Tools run in this order: pdflatex → pdflatex.

Pitfalls

Related pages