Code in LaTeX: verbatim, listings and minted Explained
November 11, 2026 · 10 min read
Code in LaTeX: verbatim, listings and minted Blocks
To put code in LaTeX, wrap it in a block environment. Use verbatim for plain monospaced text, the listings package's lstlisting for keyword styling in pure LaTeX, or minted for Pygments highlighting through a Python helper. Pick by where the document gets built, then set the style once in your preamble.
How Do You Put Code in LaTeX?
The shortest working answer needs no package at all. The verbatim environment is built into LaTeX, and it prints every character between its begin and end lines exactly as you typed it.
\documentclass{article}
\begin{document}
The loop below adds up a list:
\begin{verbatim}
total = 0
for x in values:
total += x # 100% literal: \ { } and _ print as typed
\end{verbatim}
\end{document}
That typesets the three code lines in a typewriter font with the indentation kept. The backslash, braces, underscore and percent sign print as characters instead of being read as LaTeX. For a short snippet inside a sentence you'd reach for \texttt, \verb or \lstinline instead, which is a separate topic. Our LaTeX inline code guide compares all three.
From here you have three families of tools. Plain verbatim blocks never colour anything. The listings package styles keywords, comments and strings using LaTeX alone. The minted package hands each block to the Pygments highlighter and pastes the result back into your PDF.
verbatim*, \verbatiminput and fancyvrb
Plain blocks come in a few useful variants. The starred form, verbatim*, prints every space as a visible ␣ mark, which helps when whitespace matters, as in Makefiles or YAML. To pull code straight from a file, load the verbatim package and call \verbatiminput{script.py}, so the listing in your PDF always matches the file on disk.
The fancyvrb package adds a Verbatim environment that takes options.
\usepackage{fancyvrb}
...
\begin{Verbatim}[numbers=left, frame=single, fontsize=\small]
SELECT name, total
FROM orders
WHERE total > 100;
\end{Verbatim}
This draws a box around the query, numbers each line on the left and sets the text a size smaller. Neither package colours keywords, and neither wraps a long line, so a 120-character line runs straight past the right margin. The fvextra package adds a breaklines option to Verbatim if wrapping is all you need. For colour, move up to listings or minted.
The listings Package: lstlisting, Languages and \lstinputlisting
The listings package (version 1.11b on CTAN, November 2025) is written in LaTeX itself. It compiles with plain pdfLaTeX, XeLaTeX or LuaLaTeX and needs nothing beyond your TeX distribution.
\usepackage{listings}
...
\begin{lstlisting}[language=Python]
def mean(values):
m = sum(values) / len(values)
print("mean is", m)
return m
\end{lstlisting}
With no styling, def and return come out bold and any comment comes out italic. Two defaults surprise people. The code is set in your document's normal roman font, because basicstyle starts empty. The space inside "mean is" also prints as a ␣ mark, because showstringspaces is on by default.
To print a file, or part of one, use \lstinputlisting.
\lstinputlisting[language=C, firstline=5, lastline=20]{main.c}
That typesets lines 5 to 20 of main.c, so you can show one function without copying it into your .tex file. Language names are case-insensitive. A dialect goes in square brackets, and inside an optional argument it needs braces, as in language={[Sharp]C} for C#.
Styling Listings: Colours, Frames, Line Numbers and Long Lines
Define a named style once with \lstdefinestyle, then switch it on for every listing with \lstset. This block fixes both defaults above and adds colour, a frame, line numbers and line wrapping.
\usepackage{listings}
\usepackage{xcolor}
\lstdefinestyle{mycode}{
basicstyle=\ttfamily\small,
keywordstyle=\color{blue}\bfseries,
commentstyle=\color{gray}\itshape,
stringstyle=\color{teal},
backgroundcolor=\color{gray!8},
frame=single,
numbers=left,
numberstyle=\tiny\color{gray},
breaklines=true,
breakatwhitespace=true,
showstringspaces=false,
tabsize=4
}
\lstset{style=mycode}
Now every lstlisting uses a small typewriter font, blue bold keywords, grey italic comments and a light grey background inside a single-line box. breaklines=true wraps lines that are too long for the page, and breakatwhitespace=true keeps the break at a space instead of splitting a word.
The one real weakness of listings is non-ASCII text. Its manual says it only handles single-byte extended characters. UTF-8 letters like é or ü in a comment can therefore break a pdfLaTeX build or print the wrong glyph. The manual's advice is to escape such characters to LaTeX. The common shortcut is the literate key, which swaps each character for a LaTeX command.
\lstset{literate={é}{{\'e}}1 {ü}{{\"u}}1 {ß}{{\ss}}1}
Each entry reads: the character to find, its replacement, and how many columns it takes.
How Do You Use minted for Pygments Highlighting?
The minted package passes each block to Pygments, the Python highlighter, so you get the kind of colouring a code editor shows, for hundreds of languages.
\usepackage{minted}
\setminted{fontsize=\small, linenos, frame=lines}
\usemintedstyle{friendly}
...
\begin{minted}{python}
def mean(values):
return sum(values) / len(values)
\end{minted}
\inputminted[firstline=5, lastline=20]{c}{main.c}
\setminted applies options to every block, \usemintedstyle picks a Pygments colour scheme (default, friendly, borland and many more), and \inputminted reads a file. The result has numbered lines, a rule above and below, and the colours of the chosen style.
Setup is where minted differs. Version 3 (3.8.0 on CTAN, March 2026) runs a helper program called latexminted. Pygments ships inside the package when you install it with tlmgr or the MiKTeX package manager. You still need Python 3.8 or later on your PATH. Per the minted manual:
- Up-to-date TeX Live 2024 or newer:
latexmintedis on the trusted list, so a normalpdflatex file.texworks without-shell-escape. - Older TeX Live: compile with
pdflatex -shell-escape file.tex. - MiKTeX: compile with
-enable-write18, or addlatexmintedto the allowed commands.
Overleaf's own documentation says minted works there out of the box, with no setup or flags.
That's the trade-off: minted depends on an external process, and not every build service runs one. arXiv's help pages say shell escape is disabled there and point minted users to a pre-built frozen cache, which is an extra step that's easy to get wrong.
Captions, Labels and a List of Listings
Both packages number code blocks the way LaTeX numbers figures. In listings, the caption and label go in the optional argument.
\begin{lstlisting}[language=Python, caption={Mean of a list}, label={lst:mean}]
def mean(values):
return sum(values) / len(values)
\end{lstlisting}
Listing~\ref{lst:mean} divides by the length.
\lstlistoflistings
That prints "Listing 1: Mean of a list" above the code, since captions sit on top by default. The sentence after it reads "Listing 1 divides by the length". \ref supplies only the number, so type the word Listing yourself. \lstlistoflistings prints a list of listings, like a table of contents for code. To call them "Code 1" instead, put \renewcommand{\lstlistingname}{Code} in the preamble.
minted uses a floating listing environment instead.
\begin{listing}[H]
\begin{minted}{python}
print("hello")
\end{minted}
\caption{A first program}
\label{lst:hello}
\end{listing}
\caption and \label work just as they do in a figure, \ref gives you the listing's number, and \listoflistings prints the list. The [H] keeps the block exactly where you wrote it instead of letting it float to the next page.
Python, C, MATLAB and R Code in LaTeX: Language Settings
These are the values to type for the four languages people ask about most. listings names come from the predefined language table in its manual; minted names are Pygments lexer short names.
| Language | listings | minted | Notes |
|---|---|---|---|
| Python | language=Python | python or py | listings has dialects 2 and 3 |
| C | language=C | c | language={[ANSI]C} picks ANSI C |
| C++ | language=C++ | cpp | dialects include 11, ISO and Visual |
| MATLAB | language=Matlab | matlab | or the matlab-prettifier package |
| R | language=R | r | Pygments also accepts splus and s |
For MATLAB, the matlab-prettifier package builds on listings and gives you three ready styles: Matlab-editor, Matlab-bw and Matlab-Pyglike. Load it, then write \begin{lstlisting}[style=Matlab-editor] or \lstinputlisting[style=Matlab-editor]{sample.m}.
Check the listings table before you commit to it. It covers more than 90 languages, but JavaScript, Rust and Kotlin aren't among them, so you'd define those yourself with \lstdefinelanguage. minted covers all three out of the box.
listings vs minted vs verbatim: Which Should You Pick?
| verbatim / fancyvrb | listings | minted | |
|---|---|---|---|
| Extra software | None | None | Python 3.8+ |
| External program at build time | No | No | Yes, latexminted |
| Keyword colouring | No | Yes, LaTeX rules | Yes, Pygments lexers |
| Languages | Any, unstyled | 90+ predefined | Hundreds |
| UTF-8 inside code | Fine | Needs literate under pdfLaTeX | Fine, assumes UTF-8 |
| Wraps long lines | Only with fvextra | breaklines=true | breaklines |
| Builds on arXiv as-is | Yes | Yes | Only with a frozen cache |
We prefer listings for papers you submit to arXiv or a journal, because it compiles anywhere plain pdfLaTeX runs and nothing can fail outside TeX. For a thesis, a book or slides you build yourself, minted is worth the setup. Its colouring is closer to what readers see in their own editors, and it handles languages listings doesn't know. Plain verbatim is fine for short shell commands and output logs.
From Markdown Code Blocks to LaTeX Listings
If you draft in Markdown, your code already sits in fenced blocks with a language label, which is the information LaTeX needs.
```python
def mean(values):
return sum(values) / len(values)
```
The Markdown to LaTeX converter turns that fence into \begin{lstlisting}[language=Python], and you can switch its code block option to minted or verbatim. It runs in your browser and gives you a .tex file; it doesn't compile a PDF, so you still build that with your own TeX setup or Overleaf. For a Pandoc command line instead, see Markdown to LaTeX with Pandoc.
For the Markdown side itself, our guides cover fenced code block syntax and code block language identifiers. Our editor's preview shows code blocks as plain monospaced text without syntax highlighting, so judge colours in the compiled PDF.
Frequently Asked Questions
Putting code in LaTeX comes down to one decision: does your build allow an external program? If it doesn't, or you're not sure, use listings with a shared style block. If it does, minted gives you better highlighting for more languages. Drafting the text first? Write it in the editor, then run it through the Markdown to LaTeX converter and pick lstlisting, minted or verbatim for your code blocks.