LaTeX collapses spaces in normal text, so pasted code loses its indentation. Code environments switch that off and print every space and line break as typed.
Methods covered:
- verbatim: no packages, no colour.
- listings: built-in highlighting, no external tools.
- minted: Pygments-quality highlighting.
- Inline code and code from files.
Plain code with verbatim
Use this for short snippets where colour and line numbers don’t matter. verbatim is built into LaTeX and needs no package.
\begin{verbatim}def example(): print("Hello, World!")\end{verbatim}Result: the code prints in a monospace font with indentation and special characters exactly as typed.

For line numbers or a frame without full highlighting, the fancyvrb package’s Verbatim environment adds options such as numbers=left and frame=single.
Highlighted code with listings
Use this when you want keyword highlighting, line numbers and indentation control without installing anything outside LaTeX. The listings package is in every TeX distribution and on Overleaf.
- Load listings and xcolor in the preamble. xcolor is needed for any colour option.
- Set a style once with
\lstset. - Put each code block in an
lstlistingenvironment and name the language.
\documentclass{article}\usepackage{xcolor}\usepackage{listings}
\lstset{ basicstyle=\ttfamily\small, keywordstyle=\color{blue}\bfseries, commentstyle=\color{gray}\itshape, stringstyle=\color{red}, backgroundcolor=\color{gray!10}, numbers=left, numberstyle=\tiny\color{gray}, frame=single, tabsize=4, showstringspaces=false}
\begin{document}
\begin{lstlisting}[language=Python]def example(): print("Hello, World!")\end{lstlisting}
\end{document}Result: keywords are blue and bold, strings red, and the block has line numbers, a frame and a light grey background.

Without keywordstyle, commentstyle and stringstyle, listings only makes keywords bold; colours have to be set. Supported languages include Python, Java, C, C++, HTML, SQL, R, Matlab and many more; change language= per block.
Control indentation in listings
listings preserves indentation; it doesn’t create it. These options control how that indentation looks:
| Option | What it does |
|---|---|
tabsize=4 | Width of a tab character, in spaces |
gobble=4 | Removes the first 4 characters of every line (for code indented in your .tex file) |
xleftmargin=2em | Indents the whole block from the left margin |
columns=fullflexible | Uses natural character widths, so copied code pastes cleanly |
keepspaces=true | Keeps runs of spaces when columns is flexible |
breaklines=true | Wraps lines longer than the text width |
showspaces=true | Shows every space as a visible ␣ mark |
showtabs=true | Shows tab characters visibly |
Example: a block indented in the source, with the extra spaces removed:
\begin{lstlisting}[language=Python, gobble=4] def indented(): return 1\end{lstlisting}Here is a styled block with line numbers, background colour and tabsize=4 together:

Long lstlisting blocks break across pages automatically, as long as you don’t put them inside a floating environment. To number listings and give them captions, add caption={…} and label={lst:name}.
The listings documentation on CTAN has every option. To change the monospace font used by basicstyle, see how to change the monospace font in LaTeX.
Better highlighting with minted
Use this when highlighting quality matters, or for languages listings doesn’t know well. minted uses the Pygments highlighter.
\usepackage{minted} % in the preamble
\begin{minted}{python}def example(): print("Hello, World!")\end{minted}Setting up minted today
minted 3 changed the setup that older tutorials describe:
- No separate Pygments install. minted 3 ships its own
latexmintedhelper, which brings Pygments with it. It needs Python 3.8 or later on your system. - No
-shell-escapeon current TeX Live. Since minted 3.3,latexmintedis on TeX Live’s list of trusted programs, so a plainpdflatex file.texworks. Source: the minted changelog. - Overleaf runs minted with no setup.
- Older installs (minted 2, or minted 3 before version 3.3) still need
pdflatex -shell-escape file.tex. Updating TeX Live is the cleaner fix.
Customise minted output
Options go in square brackets before the language:
\begin{minted}[linenos, autogobble, bgcolor=gray!10, fontsize=\small, breaklines, tabsize=4]{python} def example(): print("Hello, World!")\end{minted}linenosadds line numbers.autogobblestrips the common leading indentation automatically.bgcolorsets a background colour.fontsizeandbreaklinescontrol size and wrapping.
To change the colour scheme, put \usemintedstyle{friendly} in the preamble. Other built-in styles include monokai, colorful and default. Overleaf’s minted guide shows the style gallery.
Inline code
Use this for a variable or command name inside a sentence:
| Package | Command |
|---|---|
| None | \verb|x = 1| |
| listings | \lstinline[language=Python]|print(x)| |
| minted | \mintinline{python}{x = 1} |
The character after \verb or \lstinline is the delimiter; pick one that isn’t in the code. \verb can’t be used inside another command’s argument, such as a footnote or section title.
Include code from a file
Use this for long programs, so the code and the document stay in sync:
\lstinputlisting[language=Python]{script.py} % listings\lstinputlisting[language=Python, firstline=2, lastline=10]{script.py} % lines 2 to 10\inputminted{python}{script.py} % mintedWhich package should you use?
| Package | Highlighting | External tools | Indentation control | Overleaf |
|---|---|---|---|---|
| verbatim | None | None | Keeps spaces only | Yes |
| fancyvrb | None | None | Margins, line numbers, frames | Yes |
| listings | Keywords, comments, strings (you set colours) | None | tabsize, gobble, xleftmargin | Yes |
| minted | Full Pygments highlighting | Python 3.8+ (via latexminted) | autogobble, tabsize | Yes, no setup |
For most papers, listings is enough. Choose minted when you want highlighting close to a code editor’s.
Common errors
- “Undefined control sequence” at
\color: you used a colour option without\usepackage{xcolor}. - “Invalid UTF-8 byte sequence” in a listing: listings doesn’t handle accented or other non-ASCII characters by default. Map them with the
literateoption, for exampleliterate={é}{{\'e}}1, or switch to minted. - minted asks for
-shell-escape: you’re on an older minted or TeX Live. Update the distribution, or add-shell-escapefor that project only. - minted stops with a Python traceback from latexminted: the bundled helper may not support a very new Python release. Update minted (for example with
tlmgr update minted). - Indentation is too wide or misaligned: the code mixes tabs and spaces. Set
tabsizeto your editor’s tab width, or convert tabs to spaces. - Code runs off the right margin: add
breaklines=true(listings) orbreaklines(minted). - A listing won’t break across pages: it’s inside a
figureor other float. Take it out, and keep listings’ ownfloatoption for short listings only.
Related guides
Running code and maths in notebooks instead? See how to write LaTeX in Jupyter notebooks. For URLs inside code comments or documentation, see how to write URLs in LaTeX.
When the document needs to go to colleagues who use Word, check what happens to your code blocks when you convert your LaTeX document to Word. More tutorials are collected in the LaTeX guides.