CTAN Comprehensive TeX Archive Network

Direc­tory macros/latex/contrib/loops

This is the README file for the 'loops' package.


Ahmed Musa


Version 1.3, 2013/05/15.



The package provides efficient looping macros for processing both
csv (separated-values) and nsv/tsv (non-separated values) lists.
Csv lists that have associated arbitrary list-separators may be
processed with the tools of the package.


Copyright (c) 2012-2013 Ahmed Musa

This software is author-maintained. Permission is granted to copy,
distribute and/or modify this software under the terms of the
LaTeX Project Public License, version 1.3 or higher. This software
is provided 'as it is', without warranty of any kind, either
expressed or implied, including, but not limited to, the implied
warranties of merchantability and fitness for any particular purpose.


Non-LaTeX users can use the \newforeach macro (and some other
looping macros) by loading the file skeyval-for.tex. These exclude
\foreachfox, which are available only in loops.sty.


The 'loops' package provides efficient looping macros for processing
both csv (separated-values) and nsv/tsv (non-separated values) lists.
csv lists having arbitrary parsers, and even active parsers, can
be processed with the tools of this package.

All our loops can be safely nested. Breaking the inner loop doesn't
affect the continuation of the outer loop.

The looping macros include:



    A variant of D.E. Knuth's \loop macro.

          \typeout{Doing \the\@tempcnta,\the\@tempcntb}



    A nesting version of D.E. Knuth's \loop macro,
    adapted from the original macros of David Carlisle.

    \maxrow4 \maxcol3\relax
    $$\vbox{\halign{&\ \hfil#\hfil\strut\cr\entries}}$$



    A generalized and naturally nesting version of D.E. Knuth's
    \loop macro. No nesting brace is required, unlike in \skvrecurse.
    No <id> is required, unlike in \carlisleloop.

    $$\vbox{\halign{&\ \hfil#\hfil\strut\cr\entries}}$$



    A variant of LaTeX kernel's \@tfor that has a different
    approach to breaking the loop prematurely.

    \skvtfor\x:=a \ifx {\def\x#1{#1}} \fi\do{%
        \typeout{Doing: \detokenize\expandafter{\x}--\y}%



    A variant of \skvtfor that uses parameter characters
    directly, instead of a holder macro.

    \ayeloop abcd\do{%
      \ayeloop 12345\do{%
        \typeout{Doing #1--##1}%



    \sifakaloop is as \ayeloop but will first normalize the list
    using \skvtsvnormalize before parsing. Unlike all the
    other nsv/tsv loops, it preserves outer braces in the
    arguments. Hence, it is costlier. You can insert \foreachlistbreaker
    as a token in <list> or <listcmd> to terminate the list prematurely.



    \skvfor is an expandable comma loop. The list is not
    normalized prior to parsing, and it is not possible to
    terminate the loop prematurely (ie, before exhausting
    the list).

    \show\x -> \let\cmda\cmda@ii \let\cmdb\cmdb@ii



    \skvgenloop is non-expandable but it takes any arbitrary
    list separator (parser). In the case of non-separated (nsv/tsv)
    lists, <parser> can be empty. The list is not normalized prior to
    parsing, and it is not possible to terminate the loop prematurely
    (ie, before exhausting the list).

    Here, <1.parameter.callback> is not a macro, unlike the
    <1.parameter.callback.macro> for \skvfor.


\skvcommaloop, \skvecommaloop, \skvcommaparse, \skvkvparse:


    All these have the same syntax. \skvecommaloop is as
    \skvcommaloop but will execute <callback> once when <list>
    is empty. This is needed for processing empty key families.

    \skvcommaparse is as \skvcommaloop but will first normalize
    <list> using \skvcsvnormalize. \skvkvparse is as \skvcommaloop
    but will first normalize <list> using \skvkvnormalize.
    \skvkvparse is meant for processing key-value lists.

\skvdolist and \skvparselist:


    These can process lists with arbitrary parsers/list
    separators, including non-separated lists. The only difference
    between \skvdolist and \skvparselist is that \skvparselist will
    first normalize the list before parsing.



    \cicadaloop will terminate prematurely on the current depth
    whenever the condition specified by <\if...> is true.
    <callback> is the regular code, to be executed
    for every item of the list before the loop is terminated.

    Some internal macros are accessible by the user: \iflastcicada,
    \currentcicada, \nextcicada, \lastcicada, \cicadacount.
    \cicadacount is depth-dependent.

    You can insert \foreachlistbreaker as an item in <list> or <listcmd>
    to terminate the list prematurely. Note: Unlike \newforeach and \foreachfox,
    \foreachlistpauser isn't recognized by \cicadaloop.

        \typeout{Doing \romn\@tempcnta,\romn\@tempcntb:



    The star (*) form of \newforeach is equivalent to declaring
    the option 'list is a macro' in <options>.

    \newforeach is a more versatile and robust version of the popular
    \foreach macro of the PGF bundle. The macro accepts arbitrary list
    parsers and sub-parsers, including active list separators.
    When needed, parameters corresponding to the holder macros can
    be used directly in the callback. \newforeach does everything
    that PGF's \foreach does. It doesn't automatically scope
    calculations as \foreach does. Automatically creating local
    groups for computations has been a problem for some users
    of \foreach. Instead, \newforeach uses stacks to save and
    restore the values of holder macros and some other internal

    There is a long list of options/keys in <options>, available for
    \newforeach and \foreachfox. For example, key 'reverse list'
    allows users to automatically reverse their lists prior to processing.

    Also, there are many internal macros that can be accessed by the user.
    A few of them are

    \breaknewforeach (=\skvbreakloop),
    \breakallforeachloops, \foreachcurrentitem,
    \foreachnextitem, \foreachitemcount, \foreachprevitem,
    \prependtobeginforeach, \appendtobeginforeach (=\atbeginforeach),
    \prependtoendforeach, \appendtoendforeach (=\atendforeach),
    \ifforeachlastitem, \foreachnestdepth, \foreachlistremainder,

    \foreachitemcount counts the items as the loop progresses.
    It is depth dependent, ie, it can be called to access the
    number of items processed on each depth of nesting of
    \newforeach. On any depth, the user can say, eg,




    You can insert \foreachlistbreaker as an item in <list> or <listcmd>
    to terminate the list prematurely. \foreachlistpauser will pause
    the processing for user action.

    \newforeach found a bug in PGF's \foreach, as reported at
    outcome-from-pgfs-foreach>. However, \newforeach itself
    can't be said to be bug free.

    Maybe you fancy the following syntactic sugar:

      \draw[step=.5cm,blue!65,very thin] (0,0) grid (13,6);
      \newforeach \x [
        expand list once,
        count in=\xc all \x satisfying \ifnum\x>5\fi
      ] in \alist {
        \newforeach [
          evaluate=\y as \ye using \numexpr\y*10
        \y:\z in {1:red; 2:green; 3:blue; 4:brown; 5:purple} do {
          \draw [fill=\z\ifnum\x>5!\ye\fi] (\x,\y) +(-.5,-.5)
            rectangle ++(.5,.5);
          \draw (\x,\y) node {\x,\y};

    \begin{tikzpicture}[every node/.style=draw]
    \node (A) at (0,0) {A};
    \node (B) at (1,0) {B};
    \node (C) at (2,0) {C};
    \node (D) at (3,0) {D};
    \newforeach \n [remember=\n as \lastn initially A] in {B,C,D}
      \draw [->] (\lastn) -- (\n);

    \foreachfox [remember=#1 as \x initially A] in {B,...,H} {%

    \foreachfox [list type=tsv,remember=#1 as \x initially A] {B(C1)DE[F1]GH} {%

    % Example credit: Tom Bombadil
      % You may fix \pgfmathsetseed to get a constant output:
      % \pgfmathsetseed{42}
      \newforeach \y [count=\yc] in {-0.5,-1,...,-2.5} {%
        \node[right] at (15.2,\y+0.1) {\scriptsize Subject \yc};
        \newforeach \x in {1,...,300}{%
          \pgfmathtruncatemacro{\drawbool}{rand-0.7 > 0 ? 1 : 0}%
            \fill (\x/20,\y) rectangle (\x/20+0.05,\y+0.3);
      \draw[-stealth] (0,0) -- (15.5,0);
      \node[right] at (15.5,0.2) {t in ms};
      \newforeach \x [
        pgf evaluate=\x as \xv using int(20*\x)
      ] in {0,...,15} {%
        \draw (\x,-0.05) -- (\x,0.05) node[above] {\xv};

    Here, it is possible to use #1, ##1, ##2 in the callback to
    refer to \x, y, \z, respectively. This relieves the user of the
    need to manually expand the holder macros \x,\y,\z in the callbacks,
    as I have seen some TikZ users do.

    Here is an example that uses parameters.

    \newforeach will not accept \skvifstreq or \skvifstrcmpTF because
    they don't start with '\if'. So skeyval package cast \skvifstreq to

    Normally, breaking an inner loop doesn't affect the continuation of
    outer loops, but \breakallforeachloops will break all current inner
    and outer loops.

    \newforeach \x [
      item counter = \xc,
      exit when =  \ifforeachstrcmp{#1}{b}\then\fi
    ] in {a,b,c} do {%
      \newforeach [
        count in = \yc all \y satisfying \ifnum\y>2\fi,
        loop stopper = \ifnum\y>3\fi
      ] \y in {1,2,3,4,5} {%
        \typeout{Doing items: #1, ##1}%
        %\ifnum\y=3 \breakallforeachloops\fi
    Numbers: {\tt\string\xc}: \xc, {\tt\string\yc}: \yc

    Because of 'continue={\ifnum\y=3\fi}' item number 3 will not appear
    in the log file from the following loop:

    \newforeach [
      item counter = \xc,
      exit when = \ifforeachstrcmp{#1}{c}\then\fi
    ] \x in {a,...,e} do {%
      \newforeach \y [
        count in = \yc all \y satisfying \ifnum\y>2\fi,
        continue = {\ifnum\y=3\fi}
      ] in {1,...,10} {%
        \typeout{Doing items: #1, ##1}%
        % \ifnum\y=5 \breakallforeachloops\fi

    \newforeach [count=\ic] \x/\y in {1/.5,1/1,0/1,0/0,1/0,1/-1,0/-1,0/-.5,0/0}
      \coordinate (p\ic) at (\x,\y);
    \draw[line width=1pt,blue] (p1) \newforeach \p in {2,...,8} {-- (p\p)};
    \newforeach \q in {1,...,7} {%
      \coordinate (n\ind) at (barycentric cs:p\q=0.5,p\qa=0.5);
      \coordinate (n\next) at (barycentric cs:p\q=0.125,p\qa=0.75,p\qb=0.125);
    \draw[line width=2pt,red] (n1)\newforeach \q in {2,...,13}{--(n\q)};

    % A complete graph.
    % Example credit:
    %     Quintin Jean-No´┐Żl
    %     <http://moais.imag.fr/membres/jean-noel.quintin/>
    \begin{tikzpicture}[transform shape]
    \newforeach \nr in {1,...,8}{
      \node[draw,circle,inner sep=0.25cm] (N-\nr) at
        (\the\mycount:5.4cm) {};
    \newforeach \nr in {9,...,16}{
      \node[draw,circle,inner sep=0.25cm] (N-\nr) at
       (\the\mycount:5.4cm) {};
    \newforeach \nr in {1,...,15}{
      \newforeach \nra in {\the\mycount,...,16}{
        \path (N-\nr) edge[->,bend right=3] (N-\nra)
          edge[<-,bend left=3](N-\nra);



    \foreachfox does everything that \newforeach does, but, in addition,
    it can process nsv/tsv (non-separated, tokenwise lists). It can
    auto-complete ellipsis lists (ie, lists with '...'), but this
    feature is available only for csv lists and not for tsv lists.

    1.  One important characteristic of \foreachfox is that it doesn't use
        holder macros (eg, \x/\y), but instead it uses parameter
        characters directly. So it doesn't accept/expect holder macros.
    2.  That means that if the argument isn't simple (ie, if it isn't #1),
        then it has to be specified as the value of the key/option 'arg'
        (eg, arg=#1/#2).
    3.  Note that \foreachfox doesn't expect any optional 'in' or 'do' in the
        argument list.
    4.  Unlike \newforeach, \foreachfox doesn't recognize the semicolon
        (;) as a callback terminator. In fact, the callback for \foreachfox
        should ideally be always enclosed in balanced braces. PGF
        often uses the semicolon as the callback terminator. \newforeach
        supports that feature.

    The following macros are available to the user:

    \breakforeachfox, \foreachnestdepth, \foreachitemcount, \foreachprevitem,
    \foreachcurrentitem, \foreachnextitem, \ifforeachlastitem, \foreachlistremainder,
    \prependtobeginforeach, \appendtobeginforeach (=\atbeginforeachfox),
    \prependtoendforeach, \appendtoendforeach (=\atendforeachfox).


    \foreachfox [
      remember=#1 as \x initially A
    ] {B,...,H} {%

    This is equivalent to:

    \foreachfox [
      list type=tsv,
      remember=#1 as \x initially A
    ] in {BCDEFGH} {%

    \foreachfox [count=\nchar] {a,...,f} {
      \foreachfox [
        evaluate=##1 as \xe using \numexpr##1*20,
        evaluate=##1 as \hx using \pgfmathparse{##1 mm*5},
        evaluate=##1 as \vx using \pgfmathparse{##1 mm*1.5},
        count in= \ci all ##1 satisfying \ifnum##1<4\fi initially 2,
        count in= \di all ##1 satisfying \ifnum##1>2\fi,
      ] {1,...,6} {
        Doing: #1, ##1, \nchar, \ci, \di
          \vskip-\vx pt\relax
        \hskip\hx pt\relax
        \tikz[rounded corners,ultra thick]{
          \shade[ball color=red!\xe!blue] (0,0) circle (.25cm);
          \node[white,font=\large] (0,0) {#1};

    % Example credit: Heiko Oberdiek.
      \node at (0,0) {%
        \foreachfox* [arg=##1/##2,parser={#1}] #2 {%
    \begin{tikzpicture}[scale=1.2,auto=left,every node/.style={circle,thick}]
    \foreachfox* [arg=#1/#2,parser={;},count=\xc] \yellowlist {
      \node (#1) at (#2) [fill=blue!20,draw=yellow] {\DimBox{#1}};
    \foreachfox* [arg=#1/#2] \bluelist {
      \draw [->] (#1) -- (#2)
        node [midway,fill=red!20,draw=blue]{\DimBox{#1--#2}};

    \foreachfox [
      item counter = \xc,
      exit when = \ifforeachstrcmp{#1}{c}\then\fi
    ] {a,b,c,d} {%
      \foreachfox [
        count in = \yc all ##1 satisfying \ifnum##1>2\fi,
        ignore callback = {\ifnum##1=3\fi}
      ] {1,...,10} {%
        \typeout{Doing items: #1, ##1}%
        \ifnum##1=8 \breakforeachfox\fi

*   Unfortunately, for drawing instructions like

      \draw[blue] (p) \newforeach \p in {1,...,8}{...};

    (ie, when \draw precedes \newforeach), both \newforeach and \foreachfox
    will not work, because of the way TikZ hardwires \foreach for this type
    of task. The tack that loops package resorts to in this situation is
    simply to replace \newforeach and \foreachfox with \foreach. The fact
    here is that in this case, both \newforeach and \foreachfox will not work
    but leave everything for \foreach. This can be a problem when \newforeach
    or \foreachfox is called to avoid a known bug in \foreach, such as at


% End of readme file of loops.sty

Down­load the con­tents of this pack­age in one zip archive (21.4k).

loops – Gen­eral loop­ing macros for use with

The pack­age pro­vides ef­fi­cient loop­ing macros for pro­cess­ing both csv (sep­a­rated-val­ues) and nsv/tsv (non-sep­a­rated val­ues) lists.

CSV lists which have as­so­ci­ated parsers may be pro­cessed with the tools of the pack­age.

Li­censesThe Project Public Li­cense 1.3
Copy­right2012 Ahmed Musa
Main­tainerAhmed Musa
Con­tained inTeX Live as loops
MiKTeX as loops
TopicsMacro sup­port
List sup­port
CSV sup­port
Guest Book Sitemap Contact Contact Author