0

With the listings package, for some listings I would like to have line numbers using numbers=left as in the following example:

\begin{lstlisting}[
      numbers=left,framexleftmargin=5mm,frame=single]
   foo(); // arbitrary code lines
\end{lstlisting}

But, I also want the listing (including the frame and the line numbers) to keep its alignment with the surrounding text. What happens, however, that the line numbers extend to the left. (In fact, this already happens with the frame itself when there are no line numbers, but with the line numbers it gets worse.)

You can easily see the effect with the following, slightly extended example:

\documentclass{article}
\usepackage{listings,lstautogobble}
\begin{document}

\begin{quote}
   Surrounding text
\begin{lstlisting}[
      autogobble,
      numbers=left,framexleftmargin=5mm,
      frame=single]
   foo(); // arbitrary code lines
\end{lstlisting}
   Surrounding text
\end{quote}

\end{document}

enter image description here

The surrounding text is aligned with the code, but neither with the line numbers nor the frame. Ideally, I would like the surrounding text to be aligned with the frame, but I can also accept if the surrounding text is aligned with the line numbers.

In the listings documentation I was not able to figure out how to achieve this.

1

by looking into the documentation I found the option xleftmargin which sets the left margin. By setting it to 18 pt it aligns the frame with the surrounding text

\documentclass{article}
\usepackage{listings,lstautogobble}
\begin{document}

\begin{quote}
   Surrounding text
\begin{lstlisting}[
      autogobble,
      numbers=left,framexleftmargin=5mm,
      frame=single,
      xleftmargin=18pt]
   foo(); // arbitrary code lines
\end{lstlisting}
   Surrounding text
\end{quote}

\end{document}

example's result I hope it helped

1
  • 1
    Yes, that helped, thanks a lot for pointing me to the right option. For completeness: I also found the information about the default widths in the documentation: framesep is 3pt and framerule = 0.4pt. Therefore, in my example, the 'perfect' value for xleftmargin would be \dimexpr5mm+3.4pt. – Dirk Herrmann Mar 24 '20 at 0:00

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.