[Tex/LaTex] the difference between \nobreak and \nolinebreak

comparisonline-breaking

What is the difference between \nobreak and \nolinebreak?

I noticed that a lot of solutions in TeX.SE use the former, but I thought the latter is LaTeX while the former is plain TeX. And LaTeX macros are often more fleshed-out versions of the more rudimentary TeX equivalents. Which is better for which situations?

Best Answer

\nobreak is defined in plain TeX (and given the same definition in LaTeX) as

\penalty \@M

which is \penalty 10000 which is an infinitely bad place to break (a line if in horizontal mode or a page if in vertical mode).

\nolinebreak Is a LaTeX command that tests that it is in horizontal mode, and gives an error message if not, and then can give one of 5 different penalty values giving different strengths of hint \nolinebreak[0] to ... \nolinebreak[4] 4 is the default and gives \@M the same as \nobreak. The actual penalties inserted for values 0–4 are set by the class file.

The values are [0] is penalty 0, 4 is penalty 10000 and 1–3 are set (in article class) by

\@lowpenalty   51
\@medpenalty  151
\@highpenalty 301

There is also some code to fix white space so that

a \nolinebreak[0] b
a\nolinebreak[0] b
a \nolinebreak[0]b

each get exactly one word space between a and b if no break happens.

So in the usual case the two commands do the same thing. The LaTeX one takes more time and because of the optional argument testing it used to be fragile (it is robust in LaTeX releases since 2019). So since most LaTeX2e class files use quite low level code you usually see \nobreak or even just \penalty\@M in class files but in documents it is better to use the LaTeX form usually for the extra error checking and the interface to standard levels of penalty hint set by the class.