5

I'm trying to add sample code to my document. It seems that the listing is left aligned with the margin, and the numbers go outside it. How should I align the number, instead of the code? Here is my latex code:

\documentclass[a4paper,10pt]{article}
\usepackage[utf8x]{inputenc}
\usepackage{listings}

%opening
\title{}
\author{}

\begin{document}
Some dummy text. Some dummy text. Some dummy text. Some dummy text.
\begin{figure}
\begin{minipage}[b]{0.4\linewidth}
\begin{lstlisting}[language=C, %frame=single,
basicstyle=\footnotesize\ttfamily,
numbers=left,stepnumber=1, morekeywords={assert} ]
void test(int x, int y){
  if(x > 5){
    x++;
    if (x < 3) 
      x--;
    else 
      y = x;
  }
  assert (x < 10 );
}
\end{lstlisting}
\caption{A simple example}
\end{minipage}

%another minipage goes here

\end{figure}

\end{document}

Thank you.

2
  • I don't understand what you are trying to achieve. Also, why the lstlisting is inside a minipage which is inside a figure? – karlkoeller Sep 30 '13 at 4:56
  • @karlkoeller: I have another figure that I do not include in here. I use minipages to arrange them side by side to save space. – qsp Sep 30 '13 at 5:28
8

You can control the left margin by xleftmargin=1cm, (similarly xrightmargin=3.5cm). Adjust the values accordingly. Further, listings offers a caption by itself hence you won't be needing the figure environment.

\documentclass[a4paper,10pt]{article}
\usepackage[utf8x]{inputenc}
\usepackage{listings,showframe}

%opening
\title{}
\author{}

\begin{document}
Some dummy text. Some dummy text. Some dummy text. Some dummy text.

%\begin{figure}
\begin{minipage}[b]{0.4\linewidth}
\begin{lstlisting}[language=C, % frame=single,
basicstyle=\footnotesize\ttfamily,
numbers=left,
stepnumber=1,
numbersep=5pt,                   
% numberstyle=\tiny,                %% adjust the size of numbers
morekeywords={assert},
caption={A simple example},
captionpos=b,                       %% sets the caption-position to bottom,
% xleftmargin=\parindent,
% xrightmargin=3.5cm
]
void test(int x, int y){
  if(x > 5){
    x++;
    if (x < 3)
      x--;
    else
      y = x;
  }
  assert (x < 10 );
}
\end{lstlisting}

\end{minipage}

%another minipage goes here

%\end{figure}

\end{document}

enter image description here

You can change the name of label (Listing 1.) by putting \renewcommand\lstlistingname{Program}.

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