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=1cm | Font 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. |
\VerbatimFootnotes | After 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}File hello.py:
def greet(name):
return "Hello, " + name
print(greet("world"))Compiled with pdfLaTeX from TeX Live 2023.
Pitfalls
- The environment is
Verbatimwith a capital V. The lower-caseverbatimremains the one of LaTeX and takes no options. - Like every verbatim environment,
Verbatimcannot stand inside the argument of another command. Store the text with\SaveVerbor theSaveVerbatimenvironment and insert it with\UseVerbor\UseVerbatim. - With
commandchars=\\\{\}, a backslash or a brace that belongs to the code itself has to be written as\textbackslash,\{and\}.
Related pages
- How-to Verbatim text in LaTeX
- How-to Include source code from a file in LaTeX
- Package
verbatim - Package
listings