[Tex/LaTex] Indent content of verbatim / lstlisting environment relative to containing environment

indentationlistingsverbatim

I want the content of \verbatim to be indented relative to the actual indent of \verbatim, not the exact number of spaces.

For example, I like to indent at sections to make the LaTeX source more readable:

\section{a}
  Regular paragraph.
  \begin{verbatim}
  Gets indented by 2 spaces. Bad!
  \end{verbatim}

The problem is that the verbatim will also get an unwanted 2 space indent in that case.

I could solve it via:

\section{a}
  Regular paragraph.
  \begin{verbatim}
Not indented in output, GOOD. But LaTeX source is ugly. BAD!
  \end{verbatim}

or:

\section{a}
  Regular paragraph.
\begin{verbatim}
Not indented in output, GOOD. but LaTeX source is ugly.
\end{verbatim}

but then I'd lose all my LaTeX source indentation.

Is there a way to only count spaces relative to the indent of the verbatim environment?

If this were possible, I would expect:

\section{a}
  Regular paragraph.
  \begin{verbatim}
Gets indented. Bad!
  \end{verbatim}

to either render without indentation, or with negative indentation, but it does not matter since I don't intend to ever use it.

Best Answer

The verbatim environment is not sophisticated enough for what you're asking. What you can do instead is

  • use an lstlisting environment (from the listings package) in conjunction with the autogobble option (from the lstautogobble package),
  • set the basic style to typewriter font,
  • pass fullflexible to the columns key (more details in 2.10 in the listings manual),
  • set keepspaces to true, which tells the package not to drop spaces to fix column alignment and always converts tabulators to spaces (see subsection 4.13).

so as to mimick verbatim output but automatically remove the leading white space. For convenience, you can even define a custom environment with listings' \lstnewenvironment macro. See below.

Side note: if you really insist on using a verbatim environment, you probably shouldn't leave a newline character just before \end{verbatim}; otherwise, that newline char will be printed verbatim and you'll get an (undesirable?) linebreak. For instance, you should write

\begin{verbatim}
    Regular paragraph.\end{verbatim}

instead of

\begin{verbatim}
    Regular paragraph.
\end{verbatim}

enter image description here

\documentclass{article}

\usepackage{listings}
\usepackage{lstautogobble}

\lstnewenvironment{lstverbatim}[1][]{
  \lstset
  {
    autogobble,
    basicstyle=\ttfamily,
    columns=fullflexible,
    breaklines=true,
    keepspaces=true,
  }
}{}

\begin{document}
\section{a}
    \begin{verbatim}
        Regular paragraph\end{verbatim}
\section{b}
    \begin{lstverbatim}
        Regular paragraph
    \end{lstverbatim}
\end{document}
Related Question