avoid linebreak in \lstinline if possible

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?

-
Welcome to TeX.sx! Could you please rephrase your question and include proper punctuation. Having three if-clauses into one "sentence" is a little confusing. It would be even better if you actually add a minimal working example (MWE) that shows all cases. –  Martin Scharrer May 18 '12 at 9:23

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.

\documentclass{article}
\usepackage{showframe}% http://ctan.org/pkg/showframe
\usepackage{linegoal}% http://ctan.org/pkg/linegoal
\usepackage{listings}% http://ctan.org/pkg/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.

showframe was just used in this example to highlight the text block boundary, and is not needed in the usage of \lstInline.

-