[Tex/LaTex] How to make inline listings wrap nicely


Does anyone know how to make inline listings wrap nicely? Take a look at the screenshot that I attached below. The code example in the second line goes outside the text margin.

Also, any ideas why inline listing \lstinline|{ print "" }| on the 3rd line of text removes the space after the quotes? It shows as { print ""} in the book, even though my listing is { print "" }.

enter image description here

Here is the whole LaTeX for the document you see in the screenshot,







\lstset{emph={awk}, emphstyle=\textbf}

\chapter{Line Spacing}
\label{linespacing}    % So I can \ref{filespacing} later.

\section{Double-space a file}

awk '1; { print "" }'

So how does this one-liner work? A one-liner is an Awk program and every Awk program consists of a sequence of pattern-action statements \lstinline|pattern { action statements }|. In this case there are two statements \lstinline|1| and \lstinline|{ print "" }|. In a pattern-action statement either the pattern or the action may be missing. If the pattern is missing, the action is applied to every single line of input. A missing action is equivalent to \lstinline|{ print }|. Thus, this one-liner translates to:

awk '1 { print }; { print "" }'

An action is applied only if the pattern matches, i.e., pattern is true. Since \code1 is always true, this one-liner translates further into two print statements:

awk '{ print }; { print "" }'

Every print statement in Awk is silently followed by the \code{ORS} - Output Record Separator variable, which is a newline by default. The first print statement with no arguments is equivalent to \lstinline{print \$0}, where \code{\$0} is the variable holding the entire line (including the newline at the end). The second print statement seemingly prints nothing, but knowing that each print statement is followed by \code{ORS}, it actually prints a newline. So there we have it, each line gets double-spaced.

We can also drop the semicolon and write it as:


Best Answer

You can enable line breaking with the option breaklines, but I doubt that you will like the result (e.g. there will be line breaks after the braces) as listings can't know what you find "nice looking". I would probably split the code in two or more \lstinline commands.

The missing space is at my opinion a bug. The parsing for string delimiters loose the space (but only for fixed-width fonts). You can either use two spaces after a ", or remove the quote as string delimiter with \lstset{deletestring=[b]{"}}

Related Question