# lstlisting-environment not available within tabularx-environment

Please consider the following example. Does anyone has an idea why I cannot use the listings-environment within the tabularx-environment?

\documentclass{article}
\usepackage[ngerman]{babel}

\usepackage{tabularx}
\usepackage{listings}

\usepackage{lipsum}

\begin{document}

\newenvironment{foo}{\tabularx{\textwidth}{p{2cm}X}}{\endtabularx}
\newcommand{\M}{\textit{Mathematica }}
\newcommand{\C}[1]{\texttt{#1}}

\newcommand{\LongText}{This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text.}

\lipsum[1-3]

\begin{tabularx}{\textwidth}{p{2cm}X}
Whatever & \LongText \LongText \\
Something else & \LongText \LongText \\
Code & \begin{lstlisting} for i=0 do... \end{lstlisting}
\end{tabularx}

\end{document}

-
Since you have some responses below that seem to answer your question, please consider marking one of them as ‘Accepted’ by clicking on the tickmark below their vote count (see How do you accept an answer?). This shows which answer helped you most, and it assigns reputation points to the author of the answer (and to you!). It's part of this site's idea to identify good questions and answers through upvotes and acceptance of answers. – Jubobs Mar 2 '14 at 13:39

tabularx environment body is grabbed as a macro argument so it can do trial settings at different widths, listings is a verbatim-style thing, and verbatim-style things never work in macro arguments.

tabularx has some code so that \verb sort of works, but anything more complicated is doomed.

You can however do this

\setbox0\vbox{\hsize5cm
\begin{lstlisting}
for i=0 do...
\end{lstlisting}}

\noindent\begin{tabularx}{\textwidth}{p{2cm}X}
Whatever & \LongText \LongText \\
Something else & \LongText \LongText \\
Code & \usebox0
\end{tabularx}


But you have to know in advance the width you want (or do some more complicated thing that queries tabularx to get the width then sets the listings in a box then does tabularx again. Note I added \noindent in front of your table otherwise you get overfull box warnings in your MWE as full width table + paragraph indent comes to more than full width.

-
@MarcoDaniel thanks was just fixing it but egreg beat me to it:-) – David Carlisle Jun 22 '12 at 16:32