[Tex/LaTex] the necessary places to be appended with % to remove unwanted spaces

commentsmacros

I have experience where empty spaces cause unwanted effects. It is not easy to trace the cause of these unwanted effects. In order to eliminate any doubt, I often overuse % as follows.

\usepackage%
[%
left=3cm,
right=3cm%
]%
{geometry}

or

\newcommand{\mycommand}%
{%
This is my command.%
}

I got an extreme example that will break what Leo Liu said

In fact, only spaces which would be
output have to be removed by comment.

The following code does not produce output, but we cannot remove the % and leave a blank line between two elements of a list below.

\newpsstyle{gridstyle}
{
gridwidth=0.4pt,
%
griddots=0
}

Shortly speaking, where are the necessary places to be appended with % to remove unwanted spaces?

Best Answer

In fact, only spaces which would be output have to be removed by comment. And remember, spaces after a all-letter control sequence (also known as a control word as opposed to a control symbol) are ignored.

You can use:

\usepackage
[
  left  = 3cm,
  right = 3cm
]
{geometry}

It's Okey, no spaces will be output.

But you have to use:

\newcommand\foo
{% the space in \foo will be output when you use it in the text
  foo.%
}

That's why in TeX, package writers often use:

\newcommand\foo{%
  foo.}

In LaTeX3 macro syntax, all spaces (even between words) are ignored to ease macro writers. For example,

\RequirePackage{expl3,xparse}
\ExplSyntaxOn
\DeclareDocumentCommand \hello { m }
{
  hello~#1.
}
\ExplSyntaxOff

The tilde ~ here is a normal space char.


In some packages, like CJK, writers use

\endlinechar \m@ne

to ignore the extra spaces introduced by newlines. Then you can use:

\newcommand\foo{
  foo.
}

and after all macros,

\endlinechar `\^^M
Related Question