[Tex/LaTex] lstlisting line wrapping

listingssourcecode

How is it possible to let lstlisting wrap lines?

I've troubles with following block:

\begin{lstlisting}[language=java] 
public class MeasureStationControllerV0Test {   
MeasureStationControllerV0 controller;  
MeasureStation ms = new MeasureStation();   
MeasureStationConfiguration config = new MeasureStationConfiguration();     
DataServer dataserver = new DataServer();

In the PDF output there is an overflow:

overlapping code

Other code-snippets look horrible too.

  • So have I to manually wrap them or is listings able to handle that?
  • Why isn't syntax highlighting working?

Best Answer

Use the options breaklines=true and postbreak=\mbox{\textcolor{red}{$\hookrightarrow$}\space} for placing a red arrow at the beginning of the broken line to emphasize the line break.

\documentclass{article}
\usepackage{lmodern}  % for bold teletype font
\usepackage{amsmath}  % for \hookrightarrow
\usepackage{xcolor}   % for \textcolor
\usepackage{listings}
\lstset{
  basicstyle=\ttfamily,
  columns=fullflexible,
  frame=single,
  breaklines=true,
  postbreak=\mbox{\textcolor{red}{$\hookrightarrow$}\space},
}
\begin{document}
\begin{lstlisting}[language=java]
public class MeasureStationControllerV0Test {   
        MeasureStationControllerV0 controller;  
        MeasureStation ms = new MeasureStation();   
        MeasureStationConfiguration config = new MeasureStationConfiguration();     
        DataServer dataserver = new DataServer();
\end{lstlisting}
\end{document}

enter image description here


With the minted package you get nice line breaking and syntax highlighting out-of-the-box. Simply specify the breaklines option on your snippet. The downside is that you have to process the document with the --shell-escape option because the external program pygmentize is used to format the source code.

\documentclass{article}
\usepackage{lmodern} % for bold teletype font
\usepackage{minted}
\begin{document}
\begin{minted}[breaklines,frame=single]{java}
public class MeasureStationControllerV0Test {   
        MeasureStationControllerV0 controller;  
        MeasureStation ms = new MeasureStation();   
        MeasureStationConfiguration config = new MeasureStationConfiguration();     
        DataServer dataserver = new DataServer();
\end{minted}
\end{document}

enter image description here