How can I indent verbatim blocks?

The package fancyvrb has the enhanced Verbatim environment, and the key xleftmargin:

\documentclass{article}
\usepackage{fancyvrb}

\begin{document}
\thispagestyle{empty}

\noindent A non-verbatim line
\begin{Verbatim}[xleftmargin=.5in]
Some verbatim
lines
\end{Verbatim}
\noindent Another line
\end{document}

enter image description here

Moreover, you can redefine the standard verbatim like this:

\documentclass{article}
\usepackage{fancyvrb}

\DefineVerbatimEnvironment{verbatim}{Verbatim}{xleftmargin=.5in}

\begin{document}
\thispagestyle{empty}
\noindent A non-verbatim line
\begin{verbatim}
Some verbatim
lines
\end{verbatim}
\noindent Another line
\end{document}

This gives the same result as above


The verbatim package has an internal interface that allows one to do this. One has to redefine \verbatim@processline, adding an \hspace command at its start:

\documentclass{article}
\usepackage{verbatim}
\newlength\myverbindent 
\setlength\myverbindent{1in} % change this to change indentation
\makeatletter
\def\verbatim@processline{%
  \hspace{\myverbindent}\the\verbatim@line\par}
\makeatother
\begin{document}

\noindent Unindented text followed by 1 inch indented verbatim:
\begin{verbatim}
verbatim \stuff
\and more stuff
\end{verbatim}

\setlength\myverbindent{.5in}
\noindent Unindented text followed by .5 inch indented verbatim:
\begin{verbatim}
verbatim \stuff
\and more stuff
\end{verbatim}

\end{document}

output


verbatim like most LaTeX display environments is a list environment, and one of the main reasons for that is so that they do the right thing when nested in other display environment such as quote (or a similar custom environment with different indentation).

enter image description here

\documentclass{article}

\begin{document}

X\dotfill X\\
X\dotfill X
\begin{verbatim}
%
 $$
  @@@
   ####
\end{verbatim}
X\dotfill X
\begin{quote}
\begin{verbatim}
%
 $$
  @@@
   ####
\end{verbatim}
\end{quote}
X\dotfill X


\end{document}

Tags:

Verbatim