[Tex/LaTex] Right-align the prebreak symbol in a listings environment

alignline-breakinglistings

I’m using the breaklines and prebreak option with listings, but I find it visually not very pleasing that the prebreak-symbols are not vertically aligned. I’d prefer if they were all on the very right of the listing.

Here is example code.

\documentclass{standalone}
\usepackage{listings}
\begin{document}
\begin{lstlisting}[breaklines,breakatwhitespace,prebreak=!,basicstyle=\ttfamily]
This is a long line This is a long line This is a long line This is a long line This is a long line
This is another long line This is another long line This is another long line This is another long line
\end{lstlisting}
\end{document}

Which yields:

enter image description here

while I want something like

enter image description here

Best Answer

A more or less ugly hack is the following. Instead of putting the prebreak symbol in the current line you can put the symbol inside the margin. The distance between the margin and the text body is given by marginparsep. So you can simple adjust it. The example needs two compilation steps.

\documentclass{article}
\usepackage{listings}

\usepackage{marginnote}
\begin{document}
\begin{lstlisting}[breaklines,breakatwhitespace,prebreak={\def\marginnotevadjust{-\baselineskip}\marginnote{\llap{!\hspace*{\marginparsep}}}},basicstyle=\ttfamily]
This is a long line This is a long line This is a long line This is a long line This is a long line
This is another long line This is another long line This is another long line This is another long line
\end{lstlisting}
\end{document}

enter image description here

Related Question