3

I am trying to typeset an inline C# code listing using the listings package. However, the chunk of inline code spans a few lines, so listings has to insert a coupe of line breaks into my code. So far, all goes according to plan.

However, listings seems to get the \textwidth wrong, or at least it inserts line breaks too late. In my opinion, it is better to sacrifice the justified alignment of paragraphs such that some lines are too short, than it is to have some lines spill out into the right margin.

In the example below, I'd rather see the line be broken between <in and TArgument. How can I do that?

bad listings linebreak

\documentclass[a4paper]{article}
\usepackage{color,listings}

\setlength{\textwidth}{120mm}

\lstset{language=[Sharp]C,
    showspaces=false,
    showtabs=false,
    linewidth=\textwidth{},
    breaklines=true,
    showstringspaces=false,
    breakatwhitespace=false,
    escapeinside={(*@}{@*)},
    commentstyle=\color{green},
    keywordstyle=\color{blue},
    stringstyle=\color{red},
    basicstyle=\ttfamily
}

\begin{document}

By writing this sentence, we will get a feeling for the textwidth of this document.
Then we will talk about some type definition:
\lstinline$delegate TResult here.we.have.a.looooong.typename.containing.some.Calcualtion<in TArgument, out TResult>(TArgument argument)$.
Now that that's out of the way, we can continue writing about other nonsensical subjects which helps reveal the textwidth once again.

\end{document}
  • If the code spans more than one line, you should consider using an lstlisting environment instead. IMO, inline code is best reserved for short stuff. – jub0bs Feb 25 '14 at 11:27
4

use

\begin{sloppypar}
By writing this sentence, we will get a feeling for the textwidth of this document.
Then we will talk about some type definition:
\lstinline$delegate TResult here.we.have.a.looooong.typename.containing.some.Calcualtion<in TArgument, out TResult>(TArgument argument)$.
Now that that's out of the way, we can continue writing about other nonsensical subjects which helps reveal the textwidth once again.
\end{sloppypar}

However, I would prefer to use the option breakatwhitespace

  • Why would you prefer breakatwhitespace=true? Is there an inline flavor of sloppypar as well, i.e. one that does not start a new paragraph, and keeps my regular text nicely spaced? – derabbink Feb 25 '14 at 11:23
  • 1
    It makes sense for your code to break at whitespace. And sloppypar can only be used for paragraphs. – user2478 Feb 25 '14 at 12:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.