tags:

views:

30

answers:

1

This is driving me crazy.

I want to center a lstlisting in LaTeX.

After 3 hours attempting here's some code:

\lstset{ %
    caption=Descriptive Caption Text,
    label=lst:descr_capti_text,
    basicstyle=\ttfamily\footnotesize\bfseries,
    frame=tb,
    linewidth=0.6\textwidth
 }
\centering\begin{tabular}{c}
\begin{lstlisting}
printf("this should be centered!");
\end{lstlisting}
\end{tabular}

This is putting the lstlisting on the center but not its caption, that goes to the right. If I take out the tabular, then caption gets centered but the code goes to the left! :(

Thank you.

+2  A: 

Your caption is actually centered over the listing. You are just making the lines that run along the top and bottom of your listing only 0.6\textwidth long. This makes it appear as if the caption was off-center. Also, your \centering doesn't center the listing (visible if you don't shorten the lines below and above).

This should work:

\begin{center}
  \lstset{%
    caption=Descriptive Caption Text,
    basicstyle=\ttfamily\footnotesize\bfseries,
    frame=tb
  }
  \begin{lstlisting}
    printf("this should be centered!");
  \end{lstlisting}
\end{center}

You don't explain why you want the delimiting lines to be 0.6\textwidth long. If you actually wanted to set the width of your listing to be that value, your approach doesn't do what you want. Use something like a minipage to set a width for the whole listing.

begin{minipage}{0.6\textwidth}
  \begin{center}
    \lstset{%
      caption=Descriptive Caption Text,
      basicstyle=\ttfamily\footnotesize\bfseries,
      frame=tb,
    }
    \begin{lstlisting}
      printf("this should be centered!");
    \end{lstlisting}
  \end{center}
\end{minipage}
honk