[Tex/LaTex] Getting verbatim with soft grey background, as in tex.stackexchange

backgroundscolorverbatim

Given a verbatim as on below,

\begin{verbatim}
This is an awesome verbatim
\end{verbatim}

which is displayed with no background on the compiled pdf page :

This is an awesome verbatim

I would like to have a soft grey background on this verbatim instead. The result on the compiled pdf page would be :

This is an awesome verbatim

Is there a simple way doing it, still using the verbatim (ie. not using listings)? Thank you in advance.

ADDITIONAL QUESTION :

Is this possible to do the same with \texttt{not usual verbatim but still code quote} and getting also a grey background for all \texttt{*} elements ?
It would also display :

not verbatim but still code quote

Best Answer

You can use fancyvrb; I present two solutions, one with the background only below the actual contents, the other one going all the way to the line width.

For the additional question you can use newverbs:

\documentclass{article}
\usepackage{fancyvrb,newverbs,xcolor}
\usepackage{lipsum}% just for this example

\definecolor{cverbbg}{gray}{0.93}

\newenvironment{cverbatim}
 {\SaveVerbatim{cverb}}
 {\endSaveVerbatim
  \flushleft\fboxrule=0pt\fboxsep=.5em
  \colorbox{cverbbg}{\BUseVerbatim{cverb}}%
  \endflushleft
}
\newenvironment{lcverbatim}
 {\SaveVerbatim{cverb}}
 {\endSaveVerbatim
  \flushleft\fboxrule=0pt\fboxsep=.5em
  \colorbox{cverbbg}{%
    \makebox[\dimexpr\linewidth-2\fboxsep][l]{\BUseVerbatim{cverb}}%
  }
  \endflushleft
}

\newcommand{\ctexttt}[1]{\colorbox{cverbbg}{\texttt{#1}}}
\newverbcommand{\cverb}
  {\setbox\verbbox\hbox\bgroup}
  {\egroup\colorbox{cverbbg}{\box\verbbox}}

\begin{document}
Some verbatim mid line \cverb|$a^{x+y}=a^xa^y$| and other words. Also
a simple \ctexttt{typewriter text} with its background.

\lipsum[1]
\begin{cverbatim}
Something 
verbatim
\foo
\end{cverbatim}
\lipsum[2]
\begin{lcverbatim}
Something 
verbatim
\foo
\end{lcverbatim}
\lipsum[3]
\end{document}