11

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.

11

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).

8

For writing spaces in output files you need the explicit \space. Therefore you just do:

\writefile{\Insert\space stuff.}
  • That's strange, but ok, thanks :) – Didii Jul 17 '12 at 9:59
7
\writefile{\noexpand\Insert stuff.}

Or if you don't need the write to be immediate:

\protected@write\file{}{\protect\Insert stuff.}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.