1

Is it possible to configure lstlisting such that it doesn't break lines at certain characters? In this example, a line break is inserted after the opening parenthesis:

public void someMethod(
    String parameter)

Instead, I would like the opening parenthesis to appear in the second line:

public void someMethod
    (String parameter)

Edit (MWE added):

\documentclass{article}
\usepackage{listings}

\begin{document}

\begin{lstlisting}[breaklines=true, linewidth=5cm, frame=single]
public void someMethod(String parameter)
\end{lstlisting}

\end{document}
Zoidberg
  • 229
  • Please add a minimal working example (MWE) that illustrates your problem. It will be much easier for us to reproduce your situation and find out what the issue is when we see compilable code, starting with \documentclass{...} and ending with \end{document} – jub0bs Mar 03 '14 at 17:26
  • I'm not sure whether that's relevant (I would need to see a MWE), but the listings package can perform some automatic code formatting; however, that feature is relatively limited and only documented in the developer's guide, at the moment. – jub0bs Mar 03 '14 at 17:29
  • Ok, I've added an MWE. The output looks like the first example in the question. – Zoidberg Mar 03 '14 at 17:47
  • 1
    In this case the best solution is probably to add a space between the d and the (. – karlkoeller Mar 03 '14 at 18:39
  • If you only have short, embedded listings (i.e. listings inside lstlisting environments as opposed to listings inserted with \lstinputlisting), it's easier to simply follow karlkoeller's advice: introduce some spaces in order to allow for a line break where desired. – jub0bs Mar 03 '14 at 19:07
  • Thanks for this suggestion. I think, that might work, although I would prefer a solution that doesn't require changes in the code. – Zoidberg Mar 04 '14 at 20:00

1 Answers1

3

What follows is more an ugly hack than a proper solution, but it might just do the trick for you.

In a nutshell, the approach consists locally setting a very high line-breaking penalty right after any occurence of the ( character in listings; that way, no line break can occur after (, as desired.

enter image description here

\documentclass{article}
\usepackage{listings}

\lstset{
  breaklines=true,
  frame=single,
  literate=({{(\penalty10000\hspace{-.7em}}}2, % <--- ugly hack right there
}

\begin{document}

\begin{lstlisting}[linewidth=5cm]
public void someMethod(String parameter)
\end{lstlisting}

\begin{lstlisting}
public void someMethod(String parameter)
\end{lstlisting}

\end{document}
jub0bs
  • 58,916