# Unwanted spaces in aux file

Suppose I want to write the following to the .aux-file

\gdef\hello{\world\foobar}

And I do it this way:

\documentclass{article}
\makeatletter
\def\auxdef#1#2{
\immediate\write\@auxout{\string\gdef\string#1{\unexpanded{#2}}}
}
\makeatother
\begin{document}
\def\world{world}
\def\foobar{foo bar}
\auxdef\hello{\world\foobar}
\ifcsname hello\endcsname%
\hello
\else%
not set yet
\fi
\end{document}


Then running pdflatex once and checking the .aux-file, it shows:

\relax
\gdef\hello{\world \foobar }


There are now two spaces that I didn't explicitly insert anywhere: one between \world and \foobar and another one betwenn \foobar and }.

The questions are: where does the spaces come from? How can they be removed?

The spaces are added by \write: TeX always adds a space after a control word during \write; such spaces are harmless when reading but are essential in case you have

\write\file{\relax x}


because the space after \relax (or any other control word that's unexpandable or made such, in your case by \unexpanded) would not even be seen and, if TeX didn't add the space you'd end up with \relaxx.

Note that \detokenize does the same, because it is implemented with the same code that's used for \write.

Those spaces do nothing bad, unless you happen to read a file when the space has a different category code than 10.

• As I wrote below @Jhor's answer: a problem could arise with the space between \world and }: \def\name{andreas }\name~strauman is not the same as \def\name{andreas}\name~strauman. When \name is intended to be an end-user command, it could definitely matter! Jun 24 '18 at 14:18
• @AndreasStorvikStrauman I can't understand what you're saying: \name~strauman and \name<space>~strauman are perfectly equivalent. Jun 24 '18 at 14:20
• Notice the difference in \def\name! There is a space at the end of the definition. Jun 24 '18 at 14:21
• @AndreasStorvikStrauman “TeX always adds a space after a control word”. Is andreas a control word? Jun 24 '18 at 14:21
• Oh, never mind. I thought that \name ~strauman and \name~strauman would produce different results! Jun 24 '18 at 14:25

I don't know how the \immediate\write\@auxout does that.

But there is absolutely no need to remove them as a LaTeX command (like your \world) always gobbles the (regular) space that follows it. Hence the result of \hello{\world\foobar} and \hello{\world \foobar } is expected to be exactly the same.