Debian Codegraph @

texmf-dist/doc/generic/pgf/pgfmanual-en-pgffor.tex

raw
1 % Copyright 2019 by Till Tantau
2 %
3 % This file may be distributed and/or modified
4 %
5 % 1. under the LaTeX Project Public License and/or
6 % 2. under the GNU Free Documentation License.
7 %
8 % See the file doc/generic/pgf/licenses/LICENSE for more details.
9
10
11 \section{Repeating Things: The Foreach Statement}
12 \label{section-foreach}
13
14 This section describes the package |pgffor|, which is loaded automatically by
15 \tikzname, but not by \pgfname:
16
17 \begin{package}{pgffor}
18 This package can be used independently of \pgfname, but works particularly
19 well together with \pgfname\ and \tikzname. It defines two new commands:
20 |\foreach| and |\breakforeach|.
21 \end{package}
22
23 \begin{command}{\foreach| |\meta{variables}| |\opt{{\ttfamily[}\meta{options}{\ttfamily]}}| in |\meta{list} \meta{commands}}
24 The syntax of this command is a bit complicated, so let us go through it
25 step-by-step.
26
27 In the easiest case, \meta{variables} is a single \TeX-command like |\x| or
28 |\point|. (If you want to have some fun, you can also use active
29 characters. If you do not know what active characters are, you are
30 blessed.)
31
32 Still in the easiest case, \meta{options} will be omitted. The keys for
33 customizing this command will be discussed below.
34
35 Again, in the easiest case, \meta{list} is either a comma-separated list of
36 values surrounded by curly braces or it is the name of a macro that contain
37 such a list of values. Anything can be used as a value, but numbers are
38 most likely.
39
40 Finally, in the easiest case, \meta{commands} is some \TeX-text in curly
41 braces.
42
43 With all these assumptions, the |\foreach| statement will execute the
44 \meta{commands} repeatedly, once for every element of the \meta{list}. Each
45 time the \meta{commands} are executed, the \meta{variable} will be set to
46 the current value of the list item.
47 %
48 \begin{codeexample}[]
49 \foreach \x in {1,2,3,0} {[\x]}
50 \end{codeexample}
51
52 \begin{codeexample}[]
53 \def\mylist{1,2,3,0}
54 \foreach \x in \mylist {[\x]}
55 \end{codeexample}
56
57 Note that in each execution of \meta{commands} the \meta{commands} are put
58 in a \TeX\ group. This means that \emph{local changes to counters inside
59 \meta{commands} do not persist till the next iteration}. For instance, if
60 you add 1 to a counter inside \meta{commands} locally, then in the next
61 iteration the counter will have the same value it had at the beginning of
62 the first iteration. You have to add |\global| if you wish changes to
63 persist from iteration to iteration.
64
65
66 \medskip
67 \textbf{Syntax for the commands.}
68 Let us move on to a more complicated setting. The first complication occurs
69 when the \meta{commands} are not some text in curly braces. If the
70 |\foreach| statement does not encounter an opening brace, it will instead
71 scan everything up to the next semicolon and use this as \meta{commands}.
72 This is most useful in situations like the following:
73 %
74 \begin{codeexample}[]
75 \tikz
76 \foreach \x in {0,1,2,3}
77 \draw (\x,0) circle (0.2cm);
78 \end{codeexample}
79
80 However, the ``reading till the next semicolon'' is not the whole truth.
81 There is another rule: If a |\foreach| statement is directly followed by
82 another |\foreach| statement, this second foreach statement is collected as
83 \meta{commands}. This allows you to write the following:
84 %
85 \begin{codeexample}[]
86 \begin{tikzpicture}
87 \foreach \x in {0,1,2,3}
88 \foreach \y in {0,1,2,3}
89 {
90 \draw (\x,\y) circle (0.2cm);
91 \fill (\x,\y) circle (0.1cm);
92 }
93 \end{tikzpicture}
94 \end{codeexample}
95
96 \medskip
97 \textbf{The dots notation.}
98 The second complication concerns the \meta{list}. If this \meta{list}
99 contains the list item ``|...|'', this list item is replaced by the
100 ``missing values''. More precisely, the following happens:
101
102 Normally, when a list item |...| is encountered, there should already have
103 been \emph{two} list items before it, which were numbers. Examples of
104 \emph{numbers} are |1|, |-10|, or |-0.24|. Let us call these numbers $x$
105 and $y$ and let $d := y-x$ be their difference. Next, there should also be
106 one number following the three dots, let us call this number~$z$.
107
108 In this situation, the part of the list reading ``$x$|,|$y$|,...,|$z$'' is
109 replaced by ``$x$, $x+d$, $x+2d$, $x+3d$, \dots, $x+md$'', where the last
110 dots are semantic dots, not syntactic dots. The value $m$ is the largest
111 number such that $x + md \le z$ if $d$ is positive or such that $x+md \ge
112 z$ if $d$ is negative.
113
114 Perhaps it is best to explain this by some examples: The following
115 \meta{list} have the same effects:
116
117 |\foreach \x in {1,2,...,6} {\x, }| yields \foreach \x in {1,2,...,6} {\x, }
118
119 |\foreach \x in {1,2,3,...,6} {\x, }| yields \foreach \x in {1,2,3,...,6} {\x, }
120
121 |\foreach \x in {1,3,...,11} {\x, }| yields \foreach \x in {1,3,...,11} {\x, }
122
123 |\foreach \x in {1,3,...,10} {\x, }| yields \foreach \x in {1,3,...,10} {\x, }
124
125 |\foreach \x in {0,0.1,...,0.5} {\x, }| yields \foreach \x in {0,0.1,...,0.5} {\x, }
126
127 |\foreach \x in {a,b,9,8,...,1,2,2.125,...,2.5} {\x, }| yields \foreach \x in {a,b,9,8,...,1,2,2.125,...,2.5} {\x, }
128
129 As can be seen, for fractional steps that are not multiples of $2^{-n}$ for
130 some small $n$, rounding errors can occur pretty easily. Thus, in the
131 second last case, |0.5| should probably be replaced by |0.501| for
132 robustness.
133
134 There is another special case for the |...| statement: If the |...| is used
135 right after the first item in the list, that is, if there is an $x$, but no
136 $y$, the difference $d$ obviously cannot be computed and is set to $1$ if
137 the number $z$ following the dots is larger than $x$ and is set to $-1$ if
138 $z$ is smaller:
139
140 |\foreach \x in {1,...,6} {\x, }| yields \foreach \x in {1,...,6} {\x, }
141
142 |\foreach \x in {9,...,3.5} {\x, }| yields \foreach \x in {9,...,3.5} {\x, }
143
144 There is a yet another special case for the |...| statement, in that it can
145 indicate an alphabetic character sequence:
146
147 |\foreach \x in {a,...,m} {\x, }| yields \foreach \x in {a,...,m} {\x, }
148
149 |\foreach \x in {Z,X,...,M} {\x, }| yields \foreach \x in {Z,X,...,M} {\x, }
150
151 A final special case for the |...| statement is contextual replacement. If
152 the |...| is used in some context, for example, |sin(...)|, this context
153 will be interpreted correctly, provided that the list items prior to the
154 |...| statement have \emph{exactly} the same pattern, except that, instead
155 of dots, they have a number or a character:
156
157 |\foreach \x in {2^1,2^...,2^7} {$\x$, }| yields \foreach \x in {2^1,2^...,2^7} {$\x$, }
158
159 |\foreach \x in {0\pi,0.5\pi,...\pi,3\pi} {$\x$, }| yields \foreach \x in {0\pi,0.5\pi,...\pi,3\pi} {$\x$, }
160
161 |\foreach \x in {A_1,..._1,H_1} {$\x$, }| yields \foreach \x in {A_1,..._1,H_1} {$\x$, }
162
163
164 \textbf{Special handling of pairs.}
165 Different list items are separated by commas. However, this causes a
166 problem when the list items contain commas themselves as pairs like |(0,1)|
167 do. In this case, you should put the items containing commas in braces as
168 in |{(0,1)}|. However, since pairs are such a natural and useful case, they
169 get a special treatment by the |\foreach| statement. When a list item
170 starts with a |(| everything up to the next |)| is made part of the item.
171 Thus, we can write things like the following:
172 %
173 \begin{codeexample}[]
174 \tikz
175 \foreach \position in {(0,0), (1,1), (2,0), (3,1)}
176 \draw \position rectangle +(.25,.5);
177 \end{codeexample}
178
179
180 \medskip
181 \textbf{Using the foreach-statement inside paths.}
182 \tikzname\ allows you to use |foreach| and |\foreach| (both have the same
183 effect) inside a path construction. In such a case, the \meta{commands}
184 must be path construction commands. Here are two examples:
185 %
186 \begin{codeexample}[]
187 \tikz
188 \draw (0,0)
189 foreach \x in {1,...,3}
190 { -- (\x,1) -- (\x,0) }
191 ;
192 \end{codeexample}
193
194 \begin{codeexample}[]
195 \tikz \draw foreach \p in {1,...,3} {(\p,1)--(\p,3) (1,\p)--(3,\p)};
196 \end{codeexample}
197
198 Note that the |node| and |pic| path commands also support the |foreach|
199 statement in special ways.
200
201
202 \medskip
203 \textbf{Multiple variables.}
204 You will often wish to iterate over two variables at the same time. Since
205 you can nest |\foreach| loops, this is normally straight-forward. However,
206 you sometimes wish variables to iterate ``simultaneously''. For example, we
207 might be given a list of edges that connect two coordinates and might wish
208 to iterate over these edges. While doing so, we would like the source and
209 target of the edges to be set to two different variables.
210
211 To achieve this, you can use the following syntax: The \meta{variables} may
212 not only be a single \TeX-variable. Instead, it can also be a list of
213 variables separated by slashes (|/|). In this case the list items can also
214 be lists of values separated by slashes.
215
216 Assuming that the \meta{variables} and the list items are lists of values,
217 each time the \meta{commands} are executed, each of the variables in
218 \meta{variables} is set to one part of the list making up the current list
219 item. Here is an example to clarify this:
220
221 \example |\foreach \x / \y in {1/2,a/b} {``\x\ and \y''}| yields
222 \foreach \x / \y in {1/2,a/b} {``\x\ and \y''}.
223
224 If some entry in the \meta{list} does not have ``enough'' slashes, the last
225 entry will be repeated. Here is an example:
226 %
227 \begin{codeexample}[]
228 \begin{tikzpicture}
229 \foreach \x/\xtext in {0,...,3,2.72 / e}
230 \draw (\x,0) node{$\xtext$};
231 \end{tikzpicture}
232 \end{codeexample}
233
234 Here are more useful examples:
235 %
236 \begin{codeexample}[]
237 \begin{tikzpicture}
238 % Define some coordinates:
239 \path[nodes={circle,fill=yellow!80!black,draw}]
240 (0,0) node(a) {a}
241 (2,0.55) node(b) {b}
242 (1,1.5) node(c) {c}
243 (2,1.75) node(d) {d};
244
245 % Draw some connections:
246 \foreach \source/\target in {a/b, b/c, c/a, c/d}
247 \draw (\source) .. controls +(.75cm,0pt) and +(-.75cm,0pt)..(\target);
248 \end{tikzpicture}
249 \end{codeexample}
250
251 \begin{codeexample}[]
252 \begin{tikzpicture}
253 % Let's draw circles at interesting points:
254 \foreach \x / \y / \r in {0 / 0 / 2mm, 1 / 1 / 3mm, 2 / 0 / 1mm}
255 \draw (\x,\y) circle (\r);
256
257 % Same effect
258 \foreach \center/\r in {{(0,0)/2mm}, {(1,1)/3mm}, {(2,0)/1mm}}
259 \draw[yshift=2.5cm] \center circle (\r);
260 \end{tikzpicture}
261 \end{codeexample}
262
263 \begin{codeexample}[]
264 \begin{tikzpicture}[line cap=round,line width=3pt]
265 \filldraw [fill=yellow!80!black] (0,0) circle (2cm);
266
267 \foreach \angle / \label in
268 {0/3, 30/2, 60/1, 90/12, 120/11, 150/10, 180/9,
269 210/8, 240/7, 270/6, 300/5, 330/4}
270 {
271 \draw[line width=1pt] (\angle:1.8cm) -- (\angle:2cm);
272 \draw (\angle:1.4cm) node{\textsf{\label}};
273 }
274
275 \foreach \angle in {0,90,180,270}
276 \draw[line width=2pt] (\angle:1.6cm) -- (\angle:2cm);
277
278 \draw (0,0) -- (120:0.8cm); % hour
279 \draw (0,0) -- (90:1cm); % minute
280 \end{tikzpicture}%
281 \end{codeexample}
282
283 \begin{codeexample}[]
284 \tikz[shading=ball]
285 \foreach \x / \cola in {0/red,1/green,2/blue,3/yellow}
286 \foreach \y / \colb in {0/red,1/green,2/blue,3/yellow}
287 \shade[ball color=\cola!50!\colb] (\x,\y) circle (0.4cm);
288 \end{codeexample}
289
290
291 \medskip
292 \textbf{Options to customize the foreach-statement.}
293
294 The keys described below can be used in the \meta{options} argument to the
295 |\foreach| command. They all have the path |/pgf/foreach/|, however, the
296 path is set automatically when \meta{options} are parsed, so it does not
297 have to be explicitly stated.
298
299 \begin{key}{/pgf/foreach/var=\meta{variable}}
300 This key provides an alternative way to specify variables:
301 |\foreach [var=\x,var=\y]| is the same as |\foreach \x/\y|. If used,
302 this key should be used before the other keys.
303 \end{key}
304
305 \begin{key}{/pgf/foreach/evaluate=\meta{variable}| |\opt{|as |\meta{macro}| using |\meta{formula}}}
306 By default, list items are not evaluated: |1+2|, yields |1+2|, not |3|.
307 This key allows a variable to be evaluated using the mathematical
308 engine. The variable must have been specified either using the |var|
309 key or in the \meta{variables} argument of the |foreach| command. By
310 default, the result of the evaluation will be stored in
311 \meta{variable}. However, the optional |as |\meta{macro} statement can
312 be used to store the result in \meta{macro}.
313 %
314 \begin{codeexample}[]
315 \foreach \x [evaluate=\x] in {2^0,2^...,2^8}{$\x$, }
316 \end{codeexample}
317
318 \begin{codeexample}[]
319 \foreach \x [evaluate=\x as \xeval] in {2^0,2^...,2^8}{$\x=\xeval$, }
320 \end{codeexample}
321
322 The optional |using |\meta{formula} statement means an evaluation does
323 not have to be explicitly stated for each item in \meta{list}. The
324 \meta{formula} should contain at least one reference to
325 \meta{variable}.
326 %
327 \begin{codeexample}[]
328 \tikz\foreach \x [evaluate=\x as \shade using \x*10] in {0,1,...,10}
329 \node [fill=red!\shade!yellow, minimum size=0.65cm] at (\x,0) {\x};
330 \end{codeexample}
331 %
332 \end{key}
333
334 \begin{key}{/pgf/foreach/remember=\meta{variable}| as |\meta{macro}| |\opt{|(initially |\meta{value}|)|}}
335 This key allows the item value stored in \meta{variable} to be
336 remembered during the next iteration, stored in \meta{macro}. If a
337 variable is evaluated, the result of this evaluation is remembered. By
338 default the value of \meta{variable} is zero for the first iteration,
339 however, the optional |(initially |\meta{value}|)| statement, allows
340 the \meta{macro} to be initially defined as \meta{value}.
341 %
342 \begin{codeexample}[]
343 \foreach \x [remember=\x as \lastx (initially A)] in {B,...,H}{$\overrightarrow{\lastx\x}$, }
344 \end{codeexample}
345 %
346 \end{key}
347
348 \begin{key}{/pgf/foreach/count=\meta{macro}| |\opt{|from |\meta{value}}}
349 This key allows \meta{macro} to hold the position in the list of the
350 current item. The optional |from |\meta{value} statement allows the
351 counting to begin from \meta{value}.
352 %
353 \begin{codeexample}[]
354 \tikz[x=0.75cm,y=0.75cm]
355 \foreach \x [count=\xi] in {a,...,e}
356 \foreach \y [count=\yi] in {\x,...,e}
357 \node [draw, top color=white, bottom color=blue!50, minimum size=0.666cm]
358 at (\xi,-\yi) {$\mathstrut\x\y$};
359 \end{codeexample}
360 %
361 \end{key}
362
363 \begin{key}{/pgf/foreach/parse=\marg{boolean} (default false)}
364 If this key is set to true the upper bound in the loop will be
365 fed into |\pgfmathparse|. This allows to use complex expressions as
366 the upper bound. However, the expression must be safe for evaluation
367 in |\pgfmathparse|. It is known that internal \TeX\ registers can
368 cause trouble.
369 %
370 \begin{codeexample}[]
371 \foreach \x [parse=true] in {1,...,1.0e+1 - 1}{ \x }
372 \end{codeexample}
373 %
374 \end{key}
375
376 \begin{key}{/pgf/foreach/expand list=\marg{boolean} (default false)}
377 If this key is set to true the contents of the list are fully expanded
378 with |\edef| before further processing. This allows using complex
379 macros which generate a list upon expansion without having to use an
380 intermediate macro.
381 %
382 \begin{codeexample}[]
383 \def\Iota#1#2{%
384 \ifnum\numexpr#1\relax<\numexpr#2\relax
385 \the\numexpr#1\relax,%
386 \expandafter\Iota\expandafter{\the\numexpr(#1)+1\relax}{#2}%
387 \else
388 \the\numexpr#2\relax
389 \fi}
390 \foreach [expand list=true] \x in {\Iota{1}{5}} {
391 \x
392 }
393 \end{codeexample}
394 %
395 \end{key}
396 \end{command}
397
398 \begin{command}{\breakforeach}
399 If this command is given inside a |\foreach| command, no further executions
400 of the \meta{commands} will occur. However, the current execution of the
401 \meta{commands} is continued normally, so it is probably best to use this
402 command only at the end of a |\foreach| command.
403 %
404 \begin{codeexample}[]
405 \begin{tikzpicture}
406 \foreach \x in {1,...,4}
407 \foreach \y in {1,...,4}
408 {
409 \fill[red!50] (\x,\y) ellipse (3pt and 6pt);
410
411 \ifnum \x<\y
412 \breakforeach
413 \fi
414 }
415 \end{tikzpicture}
416 \end{codeexample}
417 %
418 \end{command}