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 have a problem putting a listing (using lstlisting package) within a table. The problem is that I want to put a multiline listing in a row taking 2 columns.

The following minimal example shows what I want to achieve. However, multicolumn wraps the listing on a single line.

\documentclass{article}
\usepackage{listings}
\lstset{basicstyle=\ttfamily}
\begin{document}

\begin{table}[h]
\begin{center}
\begin{tabular}{ |l|l| }
\hline
\multicolumn{2}{|l|}{
  \begin{lstlisting}^^J
    1st line
    2nd line
  ^^J\end{lstlisting}
} \\ \hline
some text & some text \\ \hline
\end{tabular}
\end{center}
\end{table}

\end{document}

I've tried to wrap the listing in a vbox or minipage, but that didn't help.

Any alternatives to multicolumn, or other ways to get a multiline listing in a table like this?

share|improve this question

2 Answers 2

up vote 2 down vote accepted

an l column is like \mbox and is for single line material normally you would just need to change l to p{5cm} in your \multicolumn, however listings like most verbatim things can not be in the argument of another command so a sleight of hand is needed to avoid putting it in the argument of \multicolumn.

I also change begin{center} to \centering to avoid extra white space, and changed [h] as [h] means "please take all floats to end of document, which isn't normally the desired behaviour.

enter image description here

\documentclass{article}
\usepackage{listings}
\lstset{basicstyle=\ttfamily}
\begin{document}

\begin{table}[htbp]
\centering
\begin{tabular}{ |l|l| }
\hline
\multicolumn{2}{|}{}
  \begin{minipage}{5cm}
  \begin{lstlisting}
    1st line
    2nd line
  \end{lstlisting}
  \end{minipage}\hfill\vline\kern-\arrayrulewidth
 \\ \hline
some text & some text \\ \hline
\end{tabular}

\end{table}

\end{document}
share|improve this answer
    
You've made my day, this indeed solves my problem! –  Elmervc Feb 19 '13 at 12:17
\documentclass{article}
\usepackage{listings,array,varwidth}
\lstset{basicstyle=\ttfamily}
\begin{document}

\begin{table}[htbp]
\centering
\begin{tabular}{ |l|l| } \hline
\multicolumn{2}{|}{}
  \varwidth{\linewidth}
  \begin{lstlisting}
    1st line
    2nd line
  \end{lstlisting}
  \endvarwidth\hfill\vline
 \\ \hline
some text & some text \\ \hline
\end{tabular}

\end{table}

\end{document}

enter image description here

share|improve this answer
    
+1 yes I wondered about varwidth but thought I'd keep it simple, –  David Carlisle Feb 19 '13 at 12:20

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.