1

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}
3

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

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.