[Tex/LaTex] Shrinking verbatim text

graphicsscalingverbatim

Heiko Oberdiek helped me a lot by finding a solution for shrinking text when needed. I want to apply this method to verbatim text as in the example below, but this is somehow forbidden (Something's wrong–perhaps a missing \item.). Is there another way to shrink verbatim text to fit the \linewidth?

\documentclass{article}
\usepackage{graphicx}

\newcommand*{\restrictlinewidthbox}[1]{%
  \begingroup
    \sbox0{#1}%
    \ifdim\wd0>\linewidth
      \resizebox{\linewidth}{!}{\copy0}%
    \else
      \copy0 %
    \fi
  \endgroup
}

\setlength{\parindent}{0pt}

\begin{document}

\restrictlinewidthbox{%
\begin{verbatim}
\begin{tabular}
       {|lc|c|c|c|}\hline   
      & \textbf{Input}  & Cnstrnt 1  &  Cnstrnt 2& Cnstrnt 3\\ \hline\hline
      & candidate 1     & *!         &           &          \\ \hline
      & candidate 2     &            &  *        &          \\ \hline
\hand & candidate 3     &            &           &  *       \\ \hline
\end{tabular}
\end{verbatim}
}


\end{document}

Best Answer

You have to use an environment for this. You can use fancyvrb and its facilities:

\documentclass{article}
\usepackage{graphicx,fancyvrb}

\newenvironment{restrictlinewidthverb}
 {\SaveVerbatim{rlwv}}
 {\endSaveVerbatim
  \sbox0{\BUseVerbatim{rlwv}}
  \begingroup\center % don't add indentation
  \ifdim\wd0>\linewidth
    \resizebox{\linewidth}{!}{\copy0}%
  \else
    \copy0
  \fi
  \endcenter\endgroup}

\begin{document}

\noindent X\dotfill X

\begin{restrictlinewidthverb}
\begin{tabular}
       {|lc|c|c|c|}\hline   
      & \textbf{Input}  & Cnstrnt 1  &  Cnstrnt 2& Cnstrnt 3\\ \hline\hline
      & candidate 1     & *!         &           &          \\ \hline
      & candidate 2     &            &  *        &          \\ \hline
\hand & candidate 3     &            &           &  *       \\ \hline
\end{tabular}
\end{restrictlinewidthverb}

\begin{restrictlinewidthverb}
Abc
def
\end{restrictlinewidthverb}

\end{document}

enter image description here

This is only an example, of course: double \hline commands and worksheet-like tables are evil: don't use vertical rules in your tables and your life will be better. ;-).