# How to influence line breaks in lstlistings?

Latex breaks lines at odd positions in code listings, for example, before a comma or after opening quotation marks. Is there any way to influence the line breaking strategy or to suggest where a line should be split?

I am aware of the workaround to escape within the code and to surround parts with an mbox (e.g., print(~\mbox{"ggggg"}~);), however, this has the side effect that the formatting (e.g., string higlighting) is no longer applied. Therefore, I am wondering whether a better way exists.

\documentclass{article}
\usepackage{listings}
\usepackage{xcolor}

\lstset{
breaklines=true,
escapechar=~
}

\newcommand{\highlightInListing}[1]{\textbf{\textcolor[rgb]{1,0.41,0.13}{#1}}}

\begin{document}
\begin{lstlisting}
public static void x() {
System.out.println(ffffffffffffffffffffffffffffffffff, "ggggggggggggg");
System.out.println("ffffffffffffffffffff", "ggggggggggggg");
}
\end{lstlisting}
\end{document}


Resulting in:

One can influence the line breaks with \nolinebreak and \linebreak - escaping these won't affect the coloring

\documentclass{article}
\usepackage{listings}
\usepackage{xcolor}

\lstset{
breaklines=true,
escapechar=~,
stringstyle=\color{purple},
}

\newcommand{\highlightInListing}[1]{\textbf{\textcolor[rgb]{1,0.41,0.13}{#1}}}

\begin{document}
\begin{lstlisting}[language=java]
public static void x() {
System.out.println("ffffffffffffffffffffffffffffffffff"~\nolinebreak~, ~\linebreak~"ggggggggggggg");
System.out.println("ffffffffffffffffffff", ~\linebreak~"ggggggggggggg");
}
\end{lstlisting}
\end{document}


• Is there a reason why \nolinebreak does not work in the second case (and I would need to use \linebreak instead? (linebreak messes with the listings background) May 3 '19 at 10:56
• @nrainer What do you mean with "does not work"?
– user188004
May 3 '19 at 10:57
• Using a \nolinebreak after " does not have any effect (i.e., if I replace linebreak with nolinebreak in the second printline and move it after the " character). May 3 '19 at 11:00

An alternative is to use the lstlisting with the option breakatwhitespace=true.