16

If I try

\mbox{
  \begin{verbatim}
    Some looooong text...
  \end{verbatim}
}

Then some compilation errors occur.

16

There are several packages on ctan that offer enhanced verbatim features. In particular, fancyvrb provides a simple mechanism to prevent page breaks.

\documentclass{minimal}
\usepackage{fancyvrb}
\begin{document}
\begin{Verbatim}[samepage=true]
Some looooong text...
\end{Verbatim}
\end{document}

fancyvrb also provides the BVerbatim environment which puts verbatim material into a box.

13

Ian Thompson shows how to use fancyvrb to prevent page breaking. If you still want to know how to put verbatim in a box, see below:

1) You can put it in a minipage environment:

\documentclass{minimal}

\begin{document}
\begin{minipage}{\linewidth}
\begin{verbatim}
blah blah
\end{verbatim}
\end{minipage}

\end{document}

It is enough if you just want to prevent page breaks.

2) You cannot put verbatim in the argument of \parbox, \mbox, \makebox, or \fbox. That's because verbatim is vertical material (that only minipage and \parbox can be used), and it changes category codes heavily (that you can't use it in a argument). You can, when necessary, use lrbox environment to save the box, for future use:

\documentclass{minimal}

\newsavebox{\verbbox}
\begin{document}
\begin{lrbox}{\verbbox}
\begin{minipage}{0.5\linewidth}
\begin{verbatim}
blah blah
blah blah
\end{verbatim}
\end{minipage}
\end{lrbox}

\fbox{\usebox{\verbbox}}

\end{document}

BTW, it is also easier to use fancyvrb to save the verbatim environment.

1

TH posted at http://texhacks.blogspot.com/2011/01/better-mbox-and-fbox.html about the reason for \verb not being available in \mbox (its "argument[...] cannot change category codes") and how to cure that: be redefining \mbox:

\def\bettermbox{\leavevmode\hbox}

[I'm not sure whether it would be OK to cite the whole post, thus please follow the link yourself. @TH: Could you either add an own answer or grant the right for citing your whole post here?]

That said, I would not recommend using an \mbox to solve your page-break-problem. The answer of Ian Thompson is better suited for that purpose.

  • Yes, TH is that TH – Leo Liu Nov 25 '11 at 19:15
  • @LeoLiu: Thanks, changed the answer accordingly. Now we only need to get TH's attention. – Stephen Nov 25 '11 at 19:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.