W3cubDocs

/LaTeX

\ignorespaces & \ignorespacesafterend

Synopsis:

\ignorespaces

or

\ignorespacesafterend

Both commands cause LaTeX to ignore spaces after the end of the command up until the first non-space character. The first is a command from plain TeX, and the second is LaTeX-specific.

The ignorespaces is often used when defining commands via \newcommand, or \newenvironment, or \def. The example below illustrates. It allows a user to show the points values for quiz questions in the margin but it is inconvenient because, as shown in the enumerate list, users must not put any space between the command and the question text.

\newcommand{\points}[1]{\makebox[0pt]{\makebox[10em][l]{#1~pts}}
\begin{enumerate} 
  \item\points{10}no extra space output here
  \item\points{15} extra space between the number and the `extra'
\end{enumerate} 

The solution is to change to this.

\newcommand{\points}[1]{%
  \makebox[0pt]{\makebox[10em][l]{#1~pts}}\ignorespaces}

A second example shows spaces being removed from the front of text. The commands below allow a user to uniformly attach a title to names. But, as given, if a title accidentally starts with a space then \fullname will reproduce that.

\makeatletter
\newcommand{\honorific}[1]{\def\@honorific{#1}} % remember title
\newcommand{\fullname}[1]{\@honorific~#1}       % put title before name
\makeatother
\begin{tabular}{|l|}
\honorific{Mr/Ms}  \fullname{Jones} \\  % no extra space here
\honorific{ Mr/Ms} \fullname{Jones}     % extra space before title
\end{tabular}

To fix this, change to \newcommand{\fullname}[1]{\ignorespaces\@honorific~#1}.

The \ignorespaces is also often used in a \newenvironment at the end of the begin clause, that is, as part of the second argument, as in \begin{newenvironment}{env name}{... \ignorespaces}{...}.

To strip spaces off the end of an environment use \ignorespacesafterend. An example is that this will show a much larger vertical space between the first and second environments than between the second and third.

\newenvironment{eq}{\begin{equation}}{\end{equation}}
\begin{eq}
e=mc^2
\end{eq}
\begin{equation}
F=ma
\end{equation}
\begin{equation}
E=IR
\end{equation}

Putting a comment character % immediately after the \end{eq} will make the vertical space disappear, but that is inconvenient. The solution is to change to \newenvironment{eq}{\begin{equation}}{\end{equation}\ignorespacesafterend}.

© 2007–2018 Karl Berry
Public Domain Software
http://latexref.xyz/_005cignorespaces-_0026-_005cignorespacesafterend.html