How to Insert Code in LaTeX with Indentation (listings, minted)

Updated Tested on TeX Live 2025 with minted 3, Oct 2026 5 min read

Quick answer

To insert code with its indentation preserved, load the listings package and put the code in an lstlisting environment, for example \begin{lstlisting}[language=Python, tabsize=4]. Spaces and tabs are kept as typed. For richer highlighting use minted with \begin{minted}{python}, and for plain unformatted text the built-in verbatim environment is enough.

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:

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.

Python function shown in monospace with its indentation kept, using the verbatim environment

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.

  1. Load listings and xcolor in the preamble. xcolor is needed for any colour option.
  2. Set a style once with \lstset.
  3. Put each code block in an lstlisting environment 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.

Python code in a framed lstlisting block with line numbers, blue keywords, red strings and a 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:

OptionWhat it does
tabsize=4Width of a tab character, in spaces
gobble=4Removes the first 4 characters of every line (for code indented in your .tex file)
xleftmargin=2emIndents the whole block from the left margin
columns=fullflexibleUses natural character widths, so copied code pastes cleanly
keepspaces=trueKeeps runs of spaces when columns is flexible
breaklines=trueWraps lines longer than the text width
showspaces=trueShows every space as a visible ␣ mark
showtabs=trueShows 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:

Seven-line Python listing with line numbers, a grey background, coloured comments and a nested for loop indented by four spaces

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 latexminted helper, which brings Pygments with it. It needs Python 3.8 or later on your system.
  • No -shell-escape on current TeX Live. Since minted 3.3, latexminted is on TeX Live’s list of trusted programs, so a plain pdflatex file.tex works. 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}
  • linenos adds line numbers.
  • autogobble strips the common leading indentation automatically.
  • bgcolor sets a background colour.
  • fontsize and breaklines control 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:

PackageCommand
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} % minted

Which package should you use?

PackageHighlightingExternal toolsIndentation controlOverleaf
verbatimNoneNoneKeeps spaces onlyYes
fancyvrbNoneNoneMargins, line numbers, framesYes
listingsKeywords, comments, strings (you set colours)Nonetabsize, gobble, xleftmarginYes
mintedFull Pygments highlightingPython 3.8+ (via latexminted)autogobble, tabsizeYes, 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 literate option, for example literate={é}{{\'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-escape for 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 tabsize to your editor’s tab width, or convert tabs to spaces.
  • Code runs off the right margin: add breaklines=true (listings) or breaklines (minted).
  • A listing won’t break across pages: it’s inside a figure or other float. Take it out, and keep listings’ own float option for short listings only.

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.

Frequently asked questions

How do I keep code indentation in LaTeX?

Put the code in a verbatim, lstlisting or minted environment; all three keep spaces exactly as typed. If the code contains tab characters, set tabsize=4 (or your editor's tab width) so tabs line up.

How do I remove the leading indentation from indented source code?

In listings, add gobble=4 to drop the first four characters of every line. In minted, add autogobble, which detects and removes the common leading whitespace for you.

Does minted still need -shell-escape?

Not on current TeX Live. Since minted 3.3, its latexminted helper is on TeX Live's list of trusted programs, so pdflatex runs it without -shell-escape. Older minted versions and some other setups still need the flag.

How do I add inline code in LaTeX?

Use \verb|x = 1| for plain text, \lstinline|x = 1| with listings, or \mintinline{python}{x = 1} with minted. The delimiter after \verb and \lstinline can be any character not used in the code.

How do I include code from a file in LaTeX?

With listings, use \lstinputlisting[language=Python]{script.py}. With minted, use \inputminted{python}{script.py}. Add firstline and lastline to listings to include only part of the file.