[Tex/LaTex] Space after command with \write

spacingwrite file

I did not see this question yet, correct me if there is.

It's not the usual problem of adding a space after a command. It's more specifically when writing to a file. For some reason the same method does not apply when using the \write command.

Minimal working example:

\documentclass{article}

\newcommand\Insert{Insert}

\begin{document}

% write to pdf
\Insert stuff.\par % wrong method
\Insert\ stuff.\par   %
\Insert{} stuff.\par  % all valid methods
\Insert~stuff.\par    %

% open file to write to
\immediate\newwrite\file
\immediate\openout\file=filename.txt
\newcommand\writefile{\immediate\write\file}

% write the same to file
\writefile{\Insert stuff.}
\writefile{\Insert\ stuff.}
\writefile{\Insert{} stuff.}
\writefile{\Insert~stuff.}

% close file
\immediate\closeout\file


\end{document}

Output pdf:

Insertstuff.
Insert stuff.
Insert stuff.
Insert stuff.

Output filename.txt

Insertstuff.
Insert\ stuff.
Insert{} stuff.
Insert\protect \unhbox \voidb@x \penalty \@M \ {}stuff.

Which is not quite what I need or expected.

Best Answer

TeX ignores spaces after control sequences (formed by letters) and performs complete expansion when doing a \write.

The tokens it sees when you do \writefile{\Insert stuff.} are (separated by • just for clarity)

\Insert•s•t•u•f•f•.

and there's no space. The expansion gives

Insertstuff

When you put a pair of braces, the space after them is not ignored (it doesn't follow a control sequence):

\Insert•{•}• •s•t•u•f•f•.

With \Insert\ stuff it's the same: the token "control space" is unexpandable, so you get

Insert\ stuff.

With \Insert~stuff you lose: the complete expansion of ~ is not what you'd expect: it's the set of instructions necessary to "print a non breaking space". Indeed LaTeX has \protected@write to cope with this kind of commands that should not be expanded during a write.

As zeroth explained, the expansion of \space is a space; but it's not ignored after \Insert, because when TeX is reading tokens it doesn't yet see the expansion of \space, but that token (which undoubtedly isn't a space token).

Related Question