Avoiding linebreaks before citations and things
When using a numerical bibliography style, it’s considered bad form (at least by me) to have a linebreak before the citation. You might see suggestions in LaTeX guides to write
... something profound~\cite{robertson2013}.
to avoid the citation number (‘[72]’, or whatever) ending up on its own at the beginning of a line.
This idea departs slightly from LaTeX’s philosophy of separating form and content, since you have to explicitly remember to insert the non-breaking space before each citation. I prefer to do this sort of thing automatically, so that I can write
... something profound \cite{robertson2013}.
and rest assured in the knowledge that I’ll have no lonely citations. Donald Arseneau’s cite
package will do exactly that if you ask it to, although these days it’s unlikely you’re not using biblatex
or similar which precludes the use of cite
.
The method used by cite
is nice and general:
\def\cite@adjust{\begingroup%
\@tempskipa\lastskip \edef\@tempa{\the\@tempskipa}\unskip
\ifnum\lastpenalty=\z@ \penalty\citeprepenalty \fi
\ifx\@tempa\@zero@skip \spacefactor1001 \fi % if no space before, set flag
\ifnum\spacefactor>\@m \ \else \hskip\@tempskipa \fi
\endgroup}
(in inimitable Arseneau style). If you can follow this code then feel free to use it for your own documents. Were I writing a package to automatically insert nonbreaking spaces, I’d use something very similar.
But for me in my own documents, things are a little more simple. The easiest solution is
\let\oldcite\cite
\renewcommand\cite{\unskip~\cite}
which I can write without even thinking and sometimes do. To be slightly more general, it would be nice if this code didn’t add a space if one wasn’t already there to begin with.
So here’s a command \nobreakbefore
that examines whether there’s any previous space, and if there is some removes it and re-adds a nonbreaking space. It suits basically all of my needs, which is enough when I’m running against a deadline on my thesis:
\def\nobreakbefore{\relax
\ifvmode\else
\ifhmode
\ifdim\lastskip > 0pt\relax
\unskip\nobreakspace
\fi
\fi
\fi
}
\let\oldcite\cite
\renewcommand\cite{\nobreakbefore\oldcite}
Being able to automate this sort of thing is one of the reasons that I like LaTeX.