Insert source code in LaTeX (listings)

Load the listings package and put the code into a lstlisting environment. The option language=Python selects the keywords to highlight, and \lstset sets font, colors, line numbers and frame for all listings.

Preamble

The snippets on this page need these lines before \begin{document}:

\usepackage{listings}
\usepackage{xcolor}

Print a block of code

The code appears as typed, with its line breaks and indentation, and no LaTeX command inside it is executed. With a language, listings prints keywords in bold and comments in italics.

\begin{lstlisting}[language=Python]
def area(radius):
    # area of a circle
    return 3.14159 * radius ** 2

print(area(2))
\end{lstlisting}
Result
The compiled example

Open in the editor

Set the style for all listings

\lstset in the preamble applies to every listing. basicstyle sets font and size, keywordstyle, commentstyle and stringstyle the look of the three kinds of text. numbers=left adds line numbers, frame=single a border, and breaklines=true wraps lines that are too long. showstringspaces=false turns off the marks that listings otherwise prints for spaces inside strings.

This goes into the preamble.

\lstset{
  basicstyle=\ttfamily\small,
  keywordstyle=\color{blue},
  commentstyle=\color{gray},
  stringstyle=\color{red!70!black},
  numbers=left,
  numberstyle=\tiny\color{gray},
  frame=single,
  breaklines=true,
  showstringspaces=false,
  tabsize=4
}

Open in the editor

Add a caption and refer to the listing

caption and label are options of the environment. The listing gets a number, \ref prints it, and \lstlistoflistings prints the list of all listings with a caption.

\begin{lstlisting}[language=Python, caption={Area of a circle}, label={lst:area}]
def area(radius):
    return 3.14159 * radius ** 2
\end{lstlisting}

Listing~\ref{lst:area} computes the area.
Result
The compiled example

Open in the editor

Use umlauts and other non-ASCII characters

With pdfLaTeX, a listing that contains characters such as ä or ß stops with the error "Invalid UTF-8 byte sequence". The key literate replaces each listed character with a LaTeX command; the 1 after each pair is the width in characters. With LuaLaTeX the characters work without this setting.

\lstset{literate=
  {ä}{{\"a}}1 {ö}{{\"o}}1 {ü}{{\"u}}1
  {Ä}{{\"A}}1 {Ö}{{\"O}}1 {Ü}{{\"U}}1 {ß}{{\ss}}1
}
\begin{lstlisting}[language=Python]
# Größe prüfen
print("Zähler")
\end{lstlisting}
Result
The compiled example

Open in the editor

Define a language that listings does not know

listings has no definition for JavaScript, among others. \lstdefinelanguage creates one: keywords lists the words to highlight, morecomment=[l] sets the start of a line comment, morecomment=[s] the two delimiters of a block comment, and morestring=[b] a string delimiter that a backslash escapes.

\lstdefinelanguage{JavaScript}{
  keywords={const, let, var, function, return, if, else, for, while, new, class},
  morecomment=[l]{//},
  morecomment=[s]{/*}{*/},
  morestring=[b]",
  morestring=[b]'
}
\begin{lstlisting}[language=JavaScript]
// greet the user
function greet(name) {
  return "Hello, " + name;
}
\end{lstlisting}
Result
The compiled example

Open in the editor

Pitfalls

Compiled with pdfLaTeX from TeX Live 2023.

Related pages