[Tex/LaTex] Listing inside tabularx

listingstabularx

I have a tabularx environment where I want to put an lstlisting into. But Latex fails to compile it. Testcase:

\documentclass[a4paper,12pt]{scrreprt}
\usepackage[utf8x]{inputenc}

\usepackage{tabularx}
\usepackage{listings}

\begin{document}
\begin{tabularx}{\textwidth}{lX}
 First column &
 \begin{lstlisting}
  Sample text
 \end{lstlisting} \\
\end{tabularx}

\end{document} 

I always get a ! Argument of \lst@next has an extra }. Two questions:

  1. What's causing it?
  2. How can I fix it?

Best Answer

You can use:

\begin{tabularx}{\textwidth}{lX}
 First column &
\begin{lstlisting}^^J
  Sample text^^J
\end{lstlisting} \\
\end{tabularx}

Generally speaking, all verbatim-like commands and environments cannot be directly used in parameters of other commands. In tabularx environments, X columntype works actually as macro arguments(it reads the cell contents into boxes first). listings package partially fixes it, but still has some limits. See "5.1 Listings inside arguments" of manual of listings for more information.