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}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.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}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}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}File output.txt:
This is pdfTeX, Version 3.141592653
Output written on main.pdf (1 page).
Transcript written on main.log.Pitfalls
verbatim,Verbatimand\verbdo not work inside the argument of another command, for example in\footnote{...},\fbox{...}or the body of a\newcommand.- Lines are never wrapped. A line that is longer than the text block sticks out into the margin and produces Overfull \hbox (263.664pt too wide) in paragraph at lines 3--6. For automatic line breaks use Insert source code in LaTeX with
breaklines=true. verbatimprints a tab character as one space.Verbatimreplaces it with eight spaces; the optiontabsizechanges the number.
Compiled with pdfLaTeX from TeX Live 2023.
Related pages
- Package
verbatim - Package
fancyvrb - How-to Inline code in LaTeX
- How-to Insert source code in LaTeX
- How-to Special characters in LaTeX: percent, underscore, ampersand, backslash