11

This happens when I use programming code and enumeration, how can I add a gap between the numbering and the line numbers of the code. enter image description here

I'm using this in LaTeX Preamble:

\usepackage{listings}
\lstset{language=java,numbers=left,tabsize=2,showstringspaces=false,showspaces=false}
  • 3
    Add an appropriate value for xleftmargin in your key-value settings. For example, xleftmargin=2em. The default is 0pt, putting the numbers flush against the left margin (and overlaying with your enumeration). – Werner Feb 23 '12 at 21:17
  • I tried \lstset{language=java,numbers=left,tabsize=2,showstringspaces=false,showspaces=false,xleftmargin=2em} it moves the numbered bullet as well. – orange Feb 23 '12 at 21:27
  • I'll have to get back to you on that, since it seems like you're using LyX, and therefore things may be different (more difficult) compared to regular LaTeX - not all LyX users enjoy using ERTs. – Werner Feb 23 '12 at 21:30
  • A not-optimal fix is to change the paragraph setting of the list as well as setting the xleftmargin. Right-click the number and choose Paragraph settings, uncheck the "Indent paragraph" box. You won't get the overlap, but the program listing starts below the list number. – Torbjørn T. Feb 24 '12 at 0:43
  • @TorbjørnT.: Perhaps you can use a combination of your suggestion with the vertical correction suggested in Vertical alignment of tables when using numbered list in LyX? – Werner Feb 24 '12 at 2:12
7

Besides addin xleftmargin=<size> to shift the listings over, you also need resetmargins=true which resets the indention from list environments like enumerate or itemize.

The frame here is from the geometry package to show the alignment with the margins.

enter image description here

Code:

Commenting out the resetmargins=true below will illustrate the problem.

\documentclass{article}
\usepackage[showframe]{geometry}
\usepackage{listings}

\lstset{
    language=java,
    numbers=left,
    tabsize=2,
    showstringspaces=false,
    showspaces=false,
    numberstyle=\tiny,
    xleftmargin=4em,
    resetmargins=true,
}


\begin{document}
\begin{enumerate}
\item
\begin{lstlisting}
 public int nextInt(int n) {
     if (n<=0)
     return val;
 }
\end{lstlisting}
%
\item abcd
%
\item
\begin{lstlisting}
 public int nextInt(int n) {
     if (n<=0)
     return val;
 }
\end{lstlisting}
\end{enumerate}
\end{document}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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