# How to indent code in \begin{verbatim}

I have code. I used \begin{verbatim} \end{verbatim}. My code contains indentation to organize the code. But the verbatim does not add spaces. When I try to add vertical spaces using \quad, the command \quad appears as it is. How can I indent my code inside verbatim?

• Add spaces (blank characters) – user94293 Feb 3 '17 at 22:15
• most likely you have tabs which by default don't work, convert them to spaces or the verbatim package has an option to handle tab – David Carlisle Feb 3 '17 at 22:16
• Try with \usepackage{fancyvrb} an the Verbatim environment (note the upper case initial). – egreg Feb 3 '17 at 22:20

You can use fancyvrb (this is the CTAN repository); its Verbatim environment respects tabs.

\documentclass{article}
\usepackage{fancyvrb}

\begin{document}

\begin{Verbatim}
1234567890
12345678901234567890
1234567890
12345678901234567890
1234567890
\end{Verbatim}

\begin{Verbatim}[tabsize=4]
1234567890
12345678901234567890
1234567890
12345678901234567890
1234567890
\end{Verbatim}

\end{document}


The default value of tabsize is 8; you can set it once for all with \fvset{tabsize=4} (or whatever value you want) in the document preamble.

Technical note Pasting on the site changes tabs to spaces. The second and fourth lines have one tab, the third line has two.

• It works nicely for me. It doesn't like in-line comments though. For example, \begin{Verbatim}[tabsize=4] % comment throws an error that disappears when the comment is on a new line. – XavierStuvw Sep 21 '17 at 15:29
• @XavierStuvw It's not possible; anything after \begin{Verbatim} is typeset verbatim, including comments; for implementation reasons, tokens after the options are discarded (with error) – egreg Sep 21 '17 at 15:32

The verbatim environment ignores tabs but not white space characters. If your code is just a short snippet and you want to avoid excess packages you could just use the space bar. It's perhaps less elegant but since it will be displayed in a monospace typeface it's not all that bad in my opinion.

Here are two ways with the verbatimbox package. The first way will pagebreak, but adds space above/below the environment. The second way does not page break, but is flexibly manipulated in the manner of a LaTeX box (i.e., one can apply \centering, etc. to the box or, as here, frame it)

\documentclass{article}
\usepackage{verbatimbox,lipsum}
\begin{document}
\lipsum[1]

\begin{verbnobox}[\small\slshape\hspace{1in}]
Lorem ipsum
do\or $it amet%, consectetuer \end{verbnobox} \lipsum[4] \begin{verbbox}[\small\slshape] Lorem ipsum do\or$it amet%,
consectetuer
\end{verbbox}
\noindent\hspace{1in}\fbox{\theverbbox}

\lipsum[4]
\end{document}