Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

I typeset a lot of listings (using the listings package) inside (array-based) tabular environments. This works like a charm, however, breaks when I pass the numbers= option to the listing:

\documentclass{article}

\usepackage{listings}
\usepackage{array}

\begin{document}

\begin{tabular}{p{8cm}}
  % The following works if you remove the numbers=left option
  \begin{lstlisting}[language=C,basicstyle=\ttfamily, numbers=left, gobble=4]
    int main(){
      printf("Hello, Bug\n");
    }
  \end{lstlisting}
\end{tabular}

\end{document}

This fails with the error message:

Runaway definition?
#1\\left\unskip \relax \@endpbox \hskip \col@sep 
! Forbidden control sequence found while scanning definition of \lst@temp.
<inserted text> 
            }
l.9 ...sicstyle=\ttfamily, numbers=left, gobble=4]

Any idea, what causes this problem?

Is there a possible workaround (besides external boxing or falling back to \lstinputlisting)?

share|improve this question
    
I don't know if this has side effects, but putting the environment inside braces doesn't trigger the error. –  egreg Jun 26 '11 at 21:52
    
@egreg: That indeed seems to solve the problem. Did you somehow figure this by looking at the source or was it just "trial-and-error"? –  Daniel Jun 26 '11 at 22:01
    
Why are you putting a lstlisting in a tabular float? –  You Jun 26 '11 at 22:20
    
Side note: If you have many same styled listings, then create proper environment for them, e.g. \lstnewenvironment{c-numbers}{\lstset{language=C,basicstyle=\ttfamily,numbers=l‌​eft,gobble=4}}{} (so you can later just type \begin{c-numbers}...\end{c-numbers}). If all of your listings have same settings, then just use once \lstset{...} in preamble of your document. –  przemoc Jun 26 '11 at 22:31
    
@przemoc: Right, I am using this all the time. However, both do not actually contribute to a MWE. –  Daniel Jun 27 '11 at 7:49
show 2 more comments

1 Answer

up vote 5 down vote accepted

The problem seems to be solvable by putting the lstlisting environment in braces:

\begin{tabular}{p{8cm}}
  {\begin{lstlisting}[language=C,basicstyle=\ttfamily, numbers=left, gobble=4]
    int main(){
      printf("Hello, Bug\n");
    }
  \end{lstlisting}}
\end{tabular}

It seems that without braces the macros of listings go "too far" and try to look at the internal token that finishes table cells (the TeXbook calls it \endtemplate, but it cannot really be written in any way in a document). The clue was indeed the "Forbidden control sequence found" message.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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