Writing verbatim inside verbatim

More strange problems, still teaching LaTeX. So I wanted to teach people how to get text or code formatted exactly as they type it with the verbatim environment. This is the part of code I wanted to use as an example:

\begin{verbatim}
text inside a      verbatim environment
is printed \emph{exactly} as     you\\
type      it ! % no comment!
\end{verbatim}


What I usually do is I have a block that shows the code they have to write and then the result. And of course for showing the code they need to write, I use verbatim. So can you include verbatim inside verbatim?

Well, yes you can, but of course you cannot include \end{verbatim}, as this would be interpreted as ending the verbatim environment. So I had to add this separately afterwards, using \verb (inline verbatim). Voila:

\begin{block}{What you write}
\begin{verbatim}
\begin{verbatim}
text inside a      verbatim environment
is printed \emph{exactly} as     you\\
type      it ! % no comment!
\end{verbatim}
\verb|\end{verbatim}|
\end{block}


Now there’s only a small problem, namely that there is some spacing after the environment, so it seems like there is an empty line between the end of the verbatim text and the \end{verbatim}. For this example it doesn’t matter, I use it to show them that empty lines are also printed exactly as they are given.

But next example is how to include verbatim inside a beamer frame. The example code I wanted to show inside the usual verbatim environment:

\begin{frame}[fragile]
\begin{verbatim}
test
\end{verbatim}
\end{frame}


So you see that here I don’t really want an empty line between \end{verbatim} and \end{frame}. So my final hacky solution jumped back up over that space after the environment:

\begin{block}{What you write}
\begin{verbatim}
\begin{frame}[fragile]
\begin{verbatim}
test
\end{verbatim}
\vspace{-0.9\baselineskip}
\verb|   \end{verbatim}|\\
\verb|\end{frame}|
\end{block}


Which works fine, but the more easy solution is probably this one (or use lstlisting or any other code-environment):

\begin{block}{What you write}
\verb|\begin{frame}[fragile]|\\
\verb|   \begin{verbatim}|\\
\verb|      test|\\
\verb|   \end{verbatim}|\\
\verb|\end{frame}|
\end{block}

This entry was posted in LaTeX and tagged , , , by swk. Bookmark the permalink.