Verbatim text in LaTeX (verbatim, Verbatim)

The verbatim environment prints everything between \begin{verbatim} and \end{verbatim} exactly as typed, in typewriter font. For a frame, line numbers or a smaller font, use the Verbatim environment from the fancyvrb package.

Preamble

The snippets on this page need these lines before \begin{document}:

\usepackage{fancyvrb}

Print a block of text as typed

Spaces, line breaks and all special characters appear as they are, and no command is executed. The environment needs no package. Its variant verbatim* prints a visible mark for every space.

\begin{verbatim}
$ pdflatex main.tex
Output written on main.pdf (1 page).
100% done & no_errors {yet} \o/
\end{verbatim}
Result
The compiled example

Open in the editor

Print a few characters inside a sentence

\verb|...| is the inline form. The content stands between two equal characters that do not occur in it.

Every document ends with \verb|\end{document}|, and \verb|%| starts a comment.
Result
The compiled example

Open in the editor

Add a frame, line numbers and a font size

The Verbatim environment from fancyvrb, with a capital V, takes options: frame=single draws a border, numbers=left numbers the lines, fontsize=\small sets the size and xleftmargin indents the block.

\begin{Verbatim}[frame=single, numbers=left, fontsize=\small, xleftmargin=5mm]
$ pdflatex main.tex
Output written on main.pdf (1 page).
\end{Verbatim}
Result
The compiled example

Open in the editor

Format a part of the verbatim text

commandchars=\\\{\} makes the backslash and the braces work as usual inside this Verbatim environment, so commands such as \textit are executed. All other characters are still printed as typed. The default typewriter font has no bold variant, so \textbf shows no effect here.

\begin{Verbatim}[commandchars=\\\{\}]
$ pdflatex \textit{main.tex}
100% done & no_errors
\end{Verbatim}
Result
The compiled example

Open in the editor

Print a whole file

\VerbatimInput{output.txt} from fancyvrb reads a text file and prints it with the same options as Verbatim. The verbatim package offers \verbatiminput{output.txt} without options.

\VerbatimInput[frame=single, fontsize=\small]{output.txt}
Result
The compiled example

Open in the editor

File output.txt:

This is pdfTeX, Version 3.141592653
Output written on main.pdf (1 page).
Transcript written on main.log.

Pitfalls

Compiled with pdfLaTeX from TeX Live 2023.

Related pages