[Tex/LaTex] avoid linebreak in \lstinline if possible

inline()line-breakinglistings

By using \lstinline{mysourcecode} I put some code within my document.

I would like to avoid that this code is broken to a new line, if possible.
so, if the codeline itself is less long than a full textline, then I would like LaTeX to make no linebreak if the code is somewhere in the middle of the textline, but make the linebreak before \lstline if not doing so would cause the code onto two lines.

How to do that?

Best Answer

The following MWE provides \lstInline[<options>]{<code snippet>} as a complement to \lstinline that tests whether the in-line code will fit within the remainder of the line, otherwise it issues a line break.

enter image description here

\documentclass{article}
\usepackage{linegoal,listings}
\newsavebox{\mylisting}
\makeatletter
\newcommand{\lstInline}[2][,]{%
  \begingroup%
  \lstset{#1}% Set any keys locally
  \begin{lrbox}{\mylisting}\lstinline!#2!\end{lrbox}% Store listing in \mylisting
  \setlength{\@tempdima}{\linegoal}% Space left on line.
  \ifdim\wd\mylisting>\@tempdima\hfill\\\fi% Insert line break
  \lstinline!#2!% Reset listing
  \endgroup%
}
\makeatother
\setlength{\parindent}{0pt}% Just for this example
\begin{document}
\lstset{basicstyle=\ttfamily,breaklines=true}
Here is some text and \lstinline!some code segment! as well. \par
Here is some text and \lstInline{some code segment} as well. \par
Here is some text, then a little more text, 
  and finally there is also \lstinline!some code segment! as well. \par
Here is some text, then a little more text, 
  and finally there is also \lstInline{some code segment} as well. \par
\end{document}

The driver behind the line break conditioning comes from the linegoal package the relies on zref's savepos module. \lstinline is first set within a box \mylisting inside \lstInline, to establish its width. If it exceeds \linegoal (the remaining space available on the line), a line break in the form \hfill\\ is issued, after which \lstinline is called again.

Resetting \lstinline (rather than just using the boxed value \usebox{\mylisting}) allows for the code segment to wrap around multiple lines and also properly stretch/shrink, if needed, within the regular text.

Any changes in the start position of the code segment will require a recompile to properly work - a requirement when working with the \label-\ref system provided by linegoal.

Note that \lstInline uses \lstinline!...! with ! as the character delimiter. As such there will be problems when actually using ! in the inline listing. If this is a problem, just use an alternate character inside the definition.