I am typesetting inline code listings using the listings package. Since I'm using C# syntax, oftentimes listings contain long words (type names/variable names). Since words in listings won't be hyphenated & broken over multiple lines, I end up with overfull lines whenever such an inline listing happens to start at the end of a line.
When I use sloppypar
(as suggested here), the entire paragraph looks terrible, as no word will be hyphenated & broken over two lines, and spaces may become very wide. When I don't use sloppypar
, individual lines may run into the page's right margin and stand out; Not pretty either.
What I'd like to achieve is one of the following two, but maybe you have better suggestions:
- Hyphenate & break words in inlinelistings using a hyphen in an entirely different font. This way the inserted hyphenation will become apparent to the reader and will not interfere with the listing's syntax.
- Let only those lines that an inline listing is involved in be sloppy, but not the entire paragraph. I am prepared to sacrifice the neat appearance of a few lines in order to make the greater part of a paragraph look nice and tidy.
See my MWE below:
\documentclass[a4paper]{article}
\usepackage{color,listings}
\setlength{\textwidth}{120mm}
\lstset{language=[Sharp]C,
showspaces=false,
showtabs=false,
linewidth=\textwidth{},
breaklines=true,
showstringspaces=false,
breakatwhitespace=true,
escapeinside={(*@}{@*)},
basicstyle=\ttfamily
}
\begin{document}
\section{Tidy, But Overfull}
By writing this sentence, we will get a feeling for the textwidth of this document.
Then we will talk about some variable:
\lstinline$CancellationToken cancellationToken$.
Now that that's out of the way, we can continue writing about other nonsensical subjects which helps reveal the textwidth once again.
\section{Sloppy, But Not Overfull}
\begin{sloppypar}
By writing this sentence, we will get a feeling for the textwidth of this document.
Then we will talk about some variable:
\lstinline$CancellationToken cancellationToken$.
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}
\end{document}