[Tex/LaTex] Apply a macro to every word

macros

In order to improve the \sameword feature of reledmac, I would like to find a way to automatically apply a command to every word. For example, in plain TeX,

\def\foo#1{#1 (#1)}
foo bar foo bar foo bar foo, foo? foo. foo;
\end

should be automatically transformed to

\def\foo#1{#1 (#1)}
\foo{foo} \foo{bar} \foo{foo} \foo{bar} \foo{foo} \foo{bar} \foo{foo}, \foo{foo}? \foo{foo}. \foo{foo};
\end

My constraints are:

  • excluding the punctuation mark
  • excluding some commands (for example foo\footnote{bar} should become \foo{foo}\footnote{bar} and not \foo{foo\footnote{bar}})
  • if possible, working with pdfTeX, XeTeX and LuaTeX, but a LuaTeX-only solution would be nice.
  • using any already existing LaTeX package (but a pure plainTeX is also accepted)

Best Answer

It would be so easy to break this, but..

enter image description here

\def\foo#1{#1 (#1)}
\def\xfoo#1 {%
\def\tmp{#1}%
\ifx\tmp\endfoo
\let\next\relax
\else
\ftnfoo#1\footnote\empty\empty\empty\relax
\let\next\xfoo
\fi
\next}
\def\ftnfoo#1\footnote#2#3#4\relax{%
\ifx\footnote#4\foo{#1}\footnote{#2}{#3} \else\afoo#1?\relax\fi}
\def\afoo#1?#2\relax{\ifx?#2\foo{#1}? \else\bfoo#1,\relax\fi}
\def\bfoo#1,#2\relax{\ifx,#2\foo{#1}, \else\cfoo#1;\relax\fi}
\def\cfoo#1;#2\relax{\ifx;#2\foo{#1}; \else\dfoo#1.\relax\fi}
\def\dfoo#1.#2\relax{\ifx.#2\foo{#1}. \else\foo{#1} \relax\fi}


\vsize=5\baselineskip

% assumes a space before the par
\def\yfoo#1\par{\xfoo#1!@ \par}

\def\endfoo{!@}

\yfoo
foo bar foo bar foo\footnote{$^1$}{bar} bar foo, foo? foo. foo;

\bye
Related Question