[Tex/LaTex] Parse comma-separated list of command names with spaces

comma-separated listmacrosparsing

Problem

This question is related to How can I specify a long list of math operators? – but with a twist: I want to allow spaces in in the comma-separated list, like so:

\newacronyms{acm, ams, cpu, nih}

For each of these, the macro \newacronym (note missing suffix “s”) should be invoked, which is defined as follows:

\newcommand*\newacronym[1]{
  \expandafter\newcommand\csname#1\endcsname[1][]{{\acronymstyle#1}##1\xspace}}

Then I can use the acronyms in a text as follows:

The \nih is the National Institute of Health.
Modern computers have several \cpu[s].

– But how does the \newacronyms macro look like?

Partial solution

I got it working without spaces – that is, it only works as \newacronyms{foo,bar}:

\newcommand*\newacronyms[1]{
  \@for\@i:=#1\do{\expandafter\newacronym\expandafter{\@i}}}

My approach (not working …)

Now I need a way to gobble the leading spaces inside the \@i macro but I’ve come up dry. My initial thought was that something along the following lines should work, but to no avail.

\def\gobble@spaces{\@ifnextchar\space{\@gobble\gobble@spaces}{}}

\newcommand*\newacronyms[1]{
  \@for\@i:=#1\do{%
    \edef\@ii{\expandafter\gobble@spaces\@i}%
    \expandafter\newacronym\expandafter{\@ii}}}

It should be noted that \gobble@spaces works in similar circumstances (although I’m not sure why … shouldn’t there be an \expandafter before the \@gobble?), just not in the above:

% This WORKS:
\def\mylst{1, 2, 3, 4}
\@for\i:=\mylst\do{print ``\expandafter\gobble@spaces\i''\\}

Incidentally, does an equivalent command already exist somewhere in the kernel? I can’t imagine that I’m the first to need it.

Best Answer

Here a solution that uses the etoolbox package:

\usepackage{etoolbox}
\newcommand*{\newacronym}[1]{\typeout{New acronym: [#1]}}
\newcommand*{\newacronyms}{%
  \let\do\newacronym
  \docsvlist
}
\newacronyms{acm, ams, cpu, nih}