# How to re-define \space using \space in its definition

I am trying to implement a counter that counts the white spaces in order to give a rough estimate of the number of words contained in a paragraph.

In order to do so, I set a new counter

\newcounter{spacenumber}


and I would like for it to step forward every time a \space command is invoked.

Looking at @egreg's answer in this post: Can I redefine a command to contain itself?, I wrote

\LetLtxMacro{\oldspace}{\space}
\renewcommand{\space}{\oldspace%
\stepcounter{spacenumber}
}


but it doesn't work so far.

Here is the complete code:

\documentclass{article}% it does NOT work

\usepackage{letltxmacro}
\newcounter{spacenumber}
\LetLtxMacro{\oldspace}{\space}
\renewcommand{\space}{\oldspace%
\stepcounter{spacenumber}%
}

\begin{document}
\setcounter{spacenumber}{0}
This is an example. \thespacenumber
\end{document}


I took a look at the etoolbox package, but I still didn't find an answer because I don't know how \space is defined. In fact, I get

> \space=macro:
-> .


The question is: Am I wrong about the whole counter setup or am I wrong about how \space has to be re-defined?

• Just note that you don't need \space, just don't comment the end of line after \def\space{. You are calling \space zero times. If you want to call \space on each space, you need something like \obeyspaces. – Manuel Aug 15 '14 at 14:58
• @Manuel: Could you please be a little more clear? I don't understand the \def\space{ part... – Pier Paolo Aug 15 '14 at 15:04
• A space in input does not execute \space. – egreg Aug 15 '14 at 15:05

\documentclass{article}

\newcounter{spacenumber}
{\catcode\ =\active\relax\gdef {\space\stepcounter{spacenumber}}}

\begin{document}
\begingroup
\setcounter{spacenumber}{0}
\obeyspaces%
This is an example. \thespacenumber
\endgroup
\end{document}


As egreg says, a space doesn't call \space command, so in your example the number of spacenumber is obviously zero. If you want the spaces to call \space you need \obeyspaces (to be used carefully).

• Redefining \space is useless, since \obeyspaces uses the old definition of \space (it's done via a \let =\space). So you need to redefine the space itself rather than \space. By the way, this should be used carefully, so the best would be to make it only work inside an environment. – Manuel Aug 15 '14 at 15:15
• Thanks! Works like a charm. I have a question, though: in the first version of the answer you didn't use \begingroup, \obeyspaces and \endgroup but it still worked. Why the change? – Pier Paolo Aug 15 '14 at 15:18
• @PierPaolo I forgot a closing brace. If I added the missing closing brace, you need \obeyspaces. However, since I think it's not “safe” to use \obeyspaces` freely, I used it inside a group, so outside that group, spaces work as usual. – Manuel Aug 15 '14 at 15:20