[Tex/LaTex] How to indent code in \begin{verbatim}

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?

Best Answer

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.

enter image description here