14

In user700902's answer to this thread, a for-loop with the syntax \@for is used. How does this syntax work? I tried searching about for-loops on other websites, but I could only find something like this page, where the syntax is a different one.

  • It is part of latex "kernel" and poorly documented. Related question here – JLDiaz Mar 3 '13 at 0:51
19

The syntax for \@for is

\@for\cs:=<list>\do{<code>}

Here <list> is either a comma separated list of tokens or a macro expanding to such a list.

Thus, the calls

\@for\next:=abc, def, gh ,ij\do{<code>}

and

\def\mylist{abc, def, gh ,ij}
\@for\next:=\mylist\do{<code>}

are equivalent. Notice that LaTeX doesn't really distinguish the two cases: it just does an \expandafter, so the two cases are completely equivalent only if the explicit list (first case) starts with an unexpandable token. In case one can't be sure of this, it's better to follow the second path.

The macro will cycle through the list doing essentially

\def\next{abc}<code>
\def\next{def}<code>
\def\next{gh }<code>
\def\next{ij}<code>

where the <code> is supposed to do something with \next. It's customary to use \next or some other scratch control sequence: it's important to realize that it will be redefined at each step.

Notice also that \@for doesn't remove leading or trailing spaces; this is proved by using \show\next as the <code>, getting

> \next=macro:
->abc.

> \next=macro:
-> def.

> \next=macro:
-> gh .

> \next=macro:
->ij.

An example from the kernel:

\DeclareRobustCommand\cite{%
  \@ifnextchar [{\@tempswatrue\@citex}{\@tempswafalse\@citex[]}}

\def\@citex[#1]#2{\leavevmode
  \let\@citea\@empty
  \@cite{\@for\@citeb:=#2\do
    {\@citea\def\@citea{,\penalty\@m\ }%
     \edef\@citeb{\expandafter\@firstofone\@citeb\@empty}%
     \if@filesw\immediate\write\@auxout{\string\citation{\@citeb}}\fi
     \@ifundefined{b@\@citeb}{\hbox{\reset@font\bfseries ?}%
       \G@refundefinedtrue
       \@latex@warning
         {Citation `\@citeb' on page \thepage \space undefined}}%
       {\@cite@ofmt{\csname b@\@citeb\endcsname}}}}{#1}}

\def\@cite#1#2{[{#1\if@tempswa , #2\fi}]}

Here \cite passes control to \@citex; then the mandatory argument is passed through a \@for loop, for typesetting the list of citations.

3

The \@for command you mention is an internal LaTeX command. I don't know if there's any extensive documentation about it.

The Wikibooks page you link to is about typesetting algorithms, so not what you're looking for.

I'd recommend using package etoolbox. See section 3.7 (List Processing) of the manual for documentation.

  • 1
    \forcsvlist (etoolbox) works like a charm, plus, it trims white space. thanks! – phfaist Apr 25 '16 at 19:12

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.