Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center Latex lstlisting

Tags:

latex

listings

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.

like image 364
BrunoB Avatar asked Jun 24 '10 00:06

BrunoB


People also ask

How do I center code in latex?

Centering. We center text or images using \begin{center} and \end{center}. Just put \begin{center} when you want to start centering, and \end{center} when you want to stop centering.

How do you reference a list in latex?

Referencing Code Listings\lstinputlisting[caption=Example C++, label={lst:listing-cpp}, language=C++]{code_sample. cpp} An example table can be seen in \ref{lst:listing-cpp}. Also note how the "Listing" prefix is automatically added within the document text whenever the reference is called.


1 Answers

Instead of using linewidth you should consider to use xleftmargin and xrightmargin (cf. texdoc listings, Chapter 4.10). The following code works without any center or minipage environment:

\lstset{   caption=Descriptive Caption Text,    basicstyle=\footnotesize, frame=tb,   xleftmargin=.2\textwidth, xrightmargin=.2\textwidth } \begin{lstlisting}     printf("this should be centered!"); \end{lstlisting} 
like image 51
user1460856 Avatar answered Sep 21 '22 17:09

user1460856