# How to achieve that when adding line numbers to listings the indentation still matches the surrounding text?

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}


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.

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}


I hope it helped

• 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