The fancyvrb package

Provides the Verbatim environment with options for line numbers, frames, font size and line ranges, and \VerbatimInput for files.

Loading the package

\usepackage{fancyvrb}

The verbatim environment of LaTeX has no settings. Verbatim, with a capital V, takes key=value options: numbered lines, a frame with a label, another font size, an indent, or only some lines of the content.

The package does not highlight syntax. It fits console output, configuration files and code in which you want to mark single places yourself: with commandchars, three characters keep their LaTeX meaning inside the block, so commands such as \textbf work there.

\DefineVerbatimEnvironment creates an environment of your own with fixed options.

Main commands

\begin{Verbatim}[numbers=left, frame=single] ... \end{Verbatim}Verbatim block with line numbers and a frame.
fontsize=\small, xleftmargin=1cmFont size and left indent of the block.
commandchars=\\\{\}Backslash and braces keep their meaning, so \textbf{...} inside the block is executed.
\VerbatimInput[firstline=2, lastline=5]{hello.py}Prints a file, here only lines 2 to 5.
\fvset{fontsize=\small, frame=lines}Default options for all following blocks.
\DefineVerbatimEnvironment{console}{Verbatim}{frame=single, label=Terminal}A new environment console with these options.
\VerbatimFootnotesAfter this command, \verb works inside footnotes.
\SaveVerb{name}|text|, \UseVerb{name}Stores verbatim text and prints it later, also in a heading.

Complete example

\documentclass{article}
\usepackage{fancyvrb}
\DefineVerbatimEnvironment{console}{Verbatim}{frame=single, label=Terminal}
\begin{document}
\begin{Verbatim}[numbers=left, fontsize=\small, commandchars=\\\{\}]
def total(values):
    return \textbf{sum}(values)
\end{Verbatim}

\begin{console}
$ python total.py
6
\end{console}

\VerbatimInput[frame=lines, firstline=1, lastline=2]{hello.py}
\end{document}
Result
The compiled example

Open in the editor

File hello.py:

def greet(name):
    return "Hello, " + name

print(greet("world"))

Compiled with pdfLaTeX from TeX Live 2023.

Pitfalls

Related pages