Function and usage of \leavevmode

The \leavevmode is defined by LaTeX and plainTeX and ensures that the vertical mode is ended and horizontal mode is entered. In vertical mode, TeX stacks horizontal boxes vertically, whereas in horizontal mode, they are taken as part of the text line.

For example \mbox{..} is defined as \leavevmode\hbox{..} to ensure that horizontal mode is entered if it is used at the beginning of a paragraph. If you only use \hbox{ } it is stacked above the following paragraph instead.

Compare:

Text\par\hbox{Hello} World

Result:

  Text
Hello
  World

with:

Text\par\mbox{Hello} World

Result:

  Text
  Hello World

You see that in the first case the \hbox is stacked with the two paragraphs vertically (but without paragraph indention) because it is processed in vertical mode. In the second case horizontal mode is entered first and so Hello is processed as part of the second paragraph.

Use \leavevmode for all macros which could be used at the begin of the paragraph and add horizontal boxes by themselves (e.g. in form of text).


For further reading about \leavevmode please see "The TeXBook" by Donald E. Knuth, Appendix A, section 13.1, page 313 as well Appendix B, page 356.


With the 2018/12/01 release of LaTeX something has changed about \leavevmode.

The command didn't change, but a few others were modified. In particular

  • \thinspace
  • \negthinspace
  • \enspace
  • \finph@nt (used by \phantom, \hphantom and \vphantom)
  • \finsm@sh (used by \smash)
  • \big, \Big, \bigg, \Bigg

were modified to add \leavevmode@ifvmode, which is a sort of “implicit \leavevmode.

The problem with these commands was that if issued in vertical mode they wouldn't initiate a new paragraph. For instance, \thinspace, \negthinspace and \enspace would add vertical spacing and

... end of a paragraph.

\phantom{X}Other text

would produce an empty line, with “Other” at the normal indentation.

With the new release, all the above mentioned commands will properly start a new paragraph, if necessary (that is, if found after the end of a paragraph like in the previous example). The definition of \leavevmode@ifvmode is

% latex.ltx, line 1633:
\protected\def\leavevmode@ifvmode{\ifvmode\expandafter\indent\fi}

This makes some previous usages of \leavevmode redundant. Typical code where \leavevmode is no longer necessary is something like

\newcommand{\foo}[1]{\leavevmode\smash{#1}...}

Code that relied on the feature of \smash or \phantom to not initiate vertical mode would no longer work as expected, though. The cases are rare, as far as we know. This can be solved by adding a further level of boxing. So code such as

\newcommand{\foo}[1]{\vadjust{\smash{#1}}}

(that I saw a couple of days ago) should become

\newcommand{\foo}[1]{\vadjust{\hbox{\smash{#1}}}}

because \hbox still doesn't initiate horizontal mode.

Tags:

Boxes