72d7a052cd4379bb9fb475c76530b669fcef1f9b
[pspp] / doc / flow-control.texi
1 @c PSPP - a program for statistical analysis.
2 @c Copyright (C) 2017, 2020 Free Software Foundation, Inc.
3 @c Permission is granted to copy, distribute and/or modify this document
4 @c under the terms of the GNU Free Documentation License, Version 1.3
5 @c or any later version published by the Free Software Foundation;
6 @c with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
7 @c A copy of the license is included in the section entitled "GNU
8 @c Free Documentation License".
9 @c
10
11 @node Conditionals and Looping
12 @chapter Conditional and Looping Constructs
13 @cindex conditionals
14 @cindex loops
15 @cindex flow of control
16 @cindex control flow
17
18 This chapter documents @pspp{} commands used for conditional execution,
19 looping, and flow of control.
20
21 @menu
22 * BREAK::                       Exit a loop.
23 * DEFINE::                      Define a macro.
24 * DO IF::                       Conditionally execute a block of code.
25 * DO REPEAT::                   Textually repeat a code block.
26 * LOOP::                        Repeat a block of code.
27 @end menu
28
29 @node BREAK
30 @section BREAK
31 @vindex BREAK
32
33 @display
34 BREAK.
35 @end display
36
37 @cmd{BREAK} terminates execution of the innermost currently executing
38 @cmd{LOOP} construct.
39
40 @cmd{BREAK} is allowed only inside @cmd{LOOP}@dots{}@cmd{END LOOP}.
41 @xref{LOOP}, for more details.
42
43 @node DEFINE
44 @section DEFINE
45 @vindex DEFINE
46 @cindex macro
47
48 @node Macro Overview
49 @subsection Overview
50
51 @display
52 @t{DEFINE} @i{macro_name}@t{(}@r{[}@i{argument}@r{[}@t{/}@i{argument}@r{]@dots{}]}@t{)}
53 @dots{}@i{body}@dots{}
54 @t{!ENDDEFINE.}
55 @end display
56
57 @noindent
58 Each @i{argument} takes the following form:
59 @display
60 @r{@{}@i{!arg_name}@t{=} @math{|} @t{!POSITIONAL}@r{@}}
61 @r{[}@t{!DEFAULT(}@i{default}@t{)}@r{]}
62 @r{[}@t{!NOEXPAND}@r{]}
63 @r{@{}@t{!TOKENS(}@i{count}@t{)} @math{|} @t{!CHAREND('}@i{token}@t{')} @math{|} @t{!ENCLOSE('}@i{start}@t{' @math{|} '}@i{end}@t{')} @math{|} @t{!CMDEND}@}
64 @end display
65
66 @noindent
67 The following directives may be used within @i{body}:
68 @example
69 !OFFEXPAND
70 !ONEXPAND
71 @end example
72
73 @noindent
74 The following functions may be used within the body:
75 @display
76 @t{!BLANKS(}@i{count}@t{)}
77 @t{!CONCAT(}@i{arg}@dots{}@t{)}
78 @t{!EVAL(}@i{arg}@t{)}
79 @t{!HEAD(}@i{arg}@t{)}
80 @t{!INDEX(}@i{haystack}@t{,} @i{needle}@t{)}
81 @t{!LENGTH(}@i{arg}@t{)}
82 @t{!NULL}
83 @t{!QUOTE(}@i{arg}@t{)}
84 @t{!SUBSTR(}@i{arg}@t{,} @i{start}[@t{,} @i{count}]@t{)}
85 @t{!TAIL(}@i{arg}@t{)}
86 @t{!UNQUOTE(}@i{arg}@t{)}
87 @t{!UPCASE(}@i{arg}@t{)}
88 @end display
89
90 @noindent
91 The body may also include the following constructs:
92 @display
93 @t{!IF (}@i{condition}@t{) !THEN} @i{true-expansion} @t{!ENDIF}
94 @t{!IF (}@i{condition}@t{) !THEN} @i{true-expansion} @t{!ELSE} @i{false-expansion} @t{!ENDIF}
95
96 @t{!DO} @i{!var} @t{=} @i{start} @t{!TO} @i{end} [@t{!BY} @i{step}]
97   @i{body}
98 @t{!DOEND}
99 @t{!DO} @i{!var} @t{!IN} @t{(}@i{expression}@t{)}
100   @i{body}
101 @t{!DOEND}
102
103 @t{!LET} @i{!var} @t{=} @i{expression}
104 @end display
105
106 @node Macro Introduction
107 @subsection Introduction
108
109 The DEFINE command creates a @dfn{macro}, which is a name for a
110 fragment of PSPP syntax called the macro's @dfn{body}.  Following the
111 DEFINE command, syntax may @dfn{call} the macro by name any number of
112 times.  Each call substitutes, or @dfn{expands}, the macro's body in
113 place of the call, as if the body had been written in its place.
114
115 The following syntax defines a macro named @code{!vars} that expands
116 to the variable names @code{v1 v2 v3}.  The macro's name begins with
117 @samp{!}, which is optional for macro names.  The @code{()} following
118 the macro name are required:
119
120 @example
121 DEFINE !vars()
122 v1 v2 v3
123 !ENDDEFINE.
124 @end example
125
126 Here are two ways that @code{!vars} might be called given the
127 preceding definition:
128
129 @example
130 DESCRIPTIVES !vars.
131 FREQUENCIES /VARIABLES=!vars.
132 @end example
133
134 With macro expansion, the above calls are equivalent to the following:
135
136 @example
137 DESCRIPTIVES v1 v2 v3.
138 FREQUENCIES /VARIABLES=v1 v2 v3.
139 @end example
140
141 The @code{!vars} macro expands to a fixed body.  Macros may have more
142 sophisticated contents:
143
144 @itemize @bullet
145 @item
146 Macro @dfn{arguments} that are substituted into the body whenever they
147 are named.  The values of a macro's arguments are specified each time
148 it is called.  @xref{Macro Arguments}.
149
150 @item
151 Macro @dfn{functions}, expanded when the macro is called.  @xref{Macro
152 Functions}.
153
154 @item
155 @code{!IF} constructs, for conditional expansion.  @xref{Macro
156 Conditional Expansion}.
157
158 @item
159 Two forms of @code{!DO} construct, for looping over a numerical range
160 or a collection of tokens.  @xref{Macro Loops}.
161
162 @item
163 @code{!LET} constructs, for assigning to macro variables.  @xref{Macro
164 Variable Assignment}.
165 @end itemize
166
167 Many identifiers associated with macros begin with @samp{!}, a
168 character not normally allowed in identifiers.  These identifiers are
169 reserved only for use with macros, which helps keep them from being
170 confused with other kinds of identifiers.
171
172 The following sections provide more details on macro syntax and
173 semantics.
174
175 @node Macro Bodies
176 @subsection Macro Bodies
177
178 As previously shown, a macro body may contain a fragment of a PSPP
179 command (such as a variable name).  A macro body may also contain full
180 PSPP commands.  In the latter case, the macro body should also contain
181 the command terminators.
182
183 Most PSPP commands may occur within a macro.  The @code{DEFINE}
184 command itself is one exception, because the inner @code{!ENDDEFINE}
185 ends the outer macro definition.  For compatibility, @code{BEGIN
186 DATA}@dots{}@code{END DATA.} should not be used within a macro.
187
188 The body of a macro may call another macro.  The following shows one
189 way that could work:
190
191 @example
192 DEFINE !commands()
193 DESCRIPTIVES !vars.
194 FREQUENCIES /VARIABLES=!vars.
195 !ENDDEFINE.
196
197 DEFINE !vars() v1 v2 v3 !ENDDEFINE.
198 !commands
199
200 * We can redefine the variables macro to analyze different variables:
201 DEFINE !vars() v4 v5 !ENDDEFINE.
202 !commands
203 @end example
204
205 The @code{!commands} macro would be easier to use if it took the
206 variables to analyze as an argument rather than through another macro.
207 The following section shows how to do that.
208
209 @node Macro Arguments
210 @subsection Macro Arguments
211
212 This section explains how to use macro arguments.  As an initial
213 example, the following syntax defines a macro named @code{!analyze}
214 that takes all the syntax up to the first command terminator as an
215 argument:
216
217 @example
218 DEFINE !analyze(!POSITIONAL !CMDEND)
219 DESCRIPTIVES !1.
220 FREQUENCIES /VARIABLES=!1.
221 !ENDDEFINE.
222 @end example
223
224 @noindent When @code{!analyze} is called, it expands to a pair of analysis
225 commands with each @code{!1} in the body replaced by the argument.
226 That is, these calls:
227
228 @example
229 !analyze v1 v2 v3.
230 !analyze v4 v5.
231 @end example
232
233 @noindent act like the following:
234
235 @example
236 DESCRIPTIVES v1 v2 v3.
237 FREQUENCIES /VARIABLES=v1 v2 v3.
238 DESCRIPTIVES v4 v5.
239 FREQUENCIES /VARIABLES=v4 v5.
240 @end example
241
242 Macros may take any number of arguments, described within the
243 parentheses in the DEFINE command.  Arguments come in two varieties
244 based on how their values are specified when the macro is called:
245
246 @itemize @bullet
247 @item
248 A @dfn{positional} argument has a required value that follows the
249 macro's name.  Use the @code{!POSITIONAL} keyword to declare a
250 positional argument.
251
252 When a macro is called, the positional argument values appear in the
253 same order as their definitions, before any keyword argument values.
254
255 References to a positional argument in a macro body are numbered:
256 @code{!1} is the first positional argument, @code{!2} the second, and
257 so on.  In addition, @code{!*} expands to all of the positional
258 arguments' values, separated by spaces.
259
260 The following example uses a positional argument:
261
262 @example
263 DEFINE !analyze(!POSITIONAL !CMDEND)
264 DESCRIPTIVES !1.
265 FREQUENCIES /VARIABLES=!1.
266 !ENDDEFINE.
267
268 !analyze v1 v2 v3.
269 !analyze v4 v5.
270 @end example
271
272 @item
273 A @dfn{keyword} argument has a name.  In the macro call, its value is
274 specified with the syntax @code{@i{name}=@i{value}}.  The names allow
275 keyword argument values to take any order in the call.
276
277 In declaration and calls, a keyword argument's name may not begin with
278 @samp{!}, but references to it in the macro body do start with a
279 leading @samp{!}.
280
281 The following example uses a keyword argument that defaults to ALL if
282 the argument is not assigned a value:
283
284 @example
285 DEFINE !analyze_kw(vars=!DEFAULT(ALL) !CMDEND)
286 DESCRIPTIVES !vars.
287 FREQUENCIES /VARIABLES=!vars.
288 !ENDDEFINE.
289
290 !analyze_kw vars=v1 v2 v3.  /* Analyze specified variables.
291 !analyze_kw.                /* Analyze all variables.
292 @end example
293 @end itemize
294
295 If a macro has both positional and keyword arguments, then the
296 positional arguments must come first in the DEFINE command, and their
297 values also come first in macro calls.  A keyword argument may be
298 omitted by leaving its keyword out of the call, and a positional
299 argument may be omitted by putting a command terminator where it would
300 appear.  (The latter case also omits any following positional
301 arguments and all keyword arguments, if there are any.)  When an
302 argument is omitted, a default value is used: either the value
303 specified in @code{!DEFAULT(@i{value})}, or an empty value otherwise.
304
305 Each argument declaration specifies the form of its value:
306
307 @table @code
308 @item !TOKENS(@i{count})
309 Exactly @var{count} tokens, e.g.@: @code{!TOKENS(1)} for a single
310 token.  Each identifier, number, quoted string, operator, or
311 punctuator is a token.  @xref{Tokens}, for a complete definition.
312
313 The following variant of @code{!analyze_kw} accepts only a single
314 variable name (or @code{ALL}) as its argument:
315
316 @example
317 DEFINE !analyze_one_var(!POSITIONAL !TOKENS(1))
318 DESCRIPTIVES !1.
319 FREQUENCIES /VARIABLES=!1.
320 !ENDDEFINE.
321
322 !analyze_one_var v1.
323 @end example
324
325 @item !CHAREND('@var{token}')
326 Any number of tokens up to @var{token}, which should be an operator or
327 punctuator token such as @samp{/} or @samp{+}.  The @var{token} does
328 not become part of the value.
329
330 With the following variant of @code{!analyze_kw}, the variables must
331 be following by @samp{/}:
332
333 @example
334 DEFINE !analyze_parens(vars=!CHARNED('/'))
335 DESCRIPTIVES !vars.
336 FREQUENCIES /VARIABLES=!vars.
337 !ENDDEFINE.
338
339 !analyze_parens vars=v1 v2 v3/.
340 @end example
341
342 @item !ENCLOSE('@var{start}','@var{end}')
343 Any number of tokens enclosed between @var{start} and @var{end}, which
344 should each be operator or punctuator tokens.  For example, use
345 @code{!ENCLOSE('(',')')} for a value enclosed within parentheses.
346 (Such a value could never have right parentheses inside it, even
347 paired with left parentheses.)  The start and end tokens are not part
348 of the value.
349
350 With the following variant of @code{!analyze_kw}, the variables must
351 be specified within parentheses:
352
353 @example
354 DEFINE !analyze_parens(vars=!ENCLOSE('(',')'))
355 DESCRIPTIVES !vars.
356 FREQUENCIES /VARIABLES=!vars.
357 !ENDDEFINE.
358
359 !analyze_parens vars=(v1 v2 v3).
360 @end example
361
362 @item !CMDEND
363 Any number of tokens up to the end of the command.  This should be
364 used only for the last positional parameter, since it consumes all of
365 the tokens in the command calling the macro.
366
367 The following variant of @code{!analyze_kw} takes all the variable
368 names up to the end of the command as its argument:
369
370 @example
371 DEFINE !analyze_kw(vars=!CMDEND)
372 DESCRIPTIVES !vars.
373 FREQUENCIES /VARIABLES=!vars.
374 !ENDDEFINE.
375
376 !analyze_kw vars=v1 v2 v3.
377 @end example
378 @end table
379
380 By default, when an argument's value contains a macro call, the call
381 is expanded each time the argument appears in the macro's body.  The
382 @code{!NOEXPAND} keyword in an argument declaration suppresses this
383 expansion.  @xref{Controlling Macro Expansion}.
384
385 @node Controlling Macro Expansion
386 @subsection Controlling Macro Expansion
387
388 Multiple factors control whether macro calls are expanded in different
389 situations.  At the highest level, @code{SET MEXPAND} controls whether
390 macro calls are expanded.  By default, it is enabled.  @xref{SET
391 MEXPAND}, for details.
392
393 A macro body may contain macro calls.  By default, these are expanded.
394 If a macro body contains @code{!OFFEXPAND} or @code{!ONEXPAND}
395 directives, then @code{!OFFEXPAND} disables expansion of macro calls
396 until the following @code{!ONEXPAND}.
397
398 A macro argument's value may contain a macro call.  These macro calls
399 are expanded, unless the argument was declared with the
400 @code{!NOEXPAND} keyword.
401
402 The argument to a macro function is a special context that does not
403 expand macro calls.  For example, if @code{!vars} is the name of a
404 macro, then @code{!LENGTH(!vars)} expands to 5, as does
405 @code{!LENGTH(!1)} if positional argument 1 has value @code{!vars}.
406 To expand macros in these cases, use the @code{!EVAL} macro function,
407 e.g.@: @code{!LENGTH(!EVAL(!vars))} or @code{!LENGTH(!EVAL(!1))}.
408 @xref{Macro Functions}, for details.
409
410 These rules apply to macro calls, not to uses within a macro body of
411 macro functions, macro arguments, and macro variables created by
412 @code{!DO} or @code{!LET}, which are always expanded.
413
414 @node Macro Functions
415 @subsection Macro Functions
416
417 Macro bodies may manipulate syntax using macro functions.  Macro
418 functions accept tokens as arguments and expand to sequences of
419 characters.
420
421 The arguments to macro functions have a restricted form.  They may
422 only be a single token (such as an identifier or a string), a macro
423 argument, or a call to a macro function.  Thus, the following are
424 valid macro arguments:
425 @example
426 x    5.0    x    !1    "5 + 6"    !CONCAT(x,y)
427 @end example
428 @noindent and the following are not:
429 @example
430 x y    5+6
431 @end example
432
433 Macro functions expand to sequences of characters.  When these
434 character strings are processed further as character strings, e.g.@:
435 with @code{!LENGTH}, any character string is valid.  When they are
436 interpreted as PSPP syntax, e.g.@: when the expansion becomes part of
437 a command, they need to be valid for that purpose.  For example,
438 @code{!UNQUOTE("It's")} will yield an error if the expansion
439 @code{It's} becomes part of a PSPP command, because it contains
440 unbalanced single quotes, but @code{!LENGTH(!UNQUOTE("It's"))} expands
441 to 4.
442
443 The following macro functions are available.  Each function's
444 documentation includes examples in the form @code{@var{call}
445 @expansion{} @var{expansion}}.
446
447 @deffn {Macro Function} !BLANKS (count)
448 Expands to @var{count} unquoted spaces, where @var{count} is a
449 nonnegative integer.  Outside quotes, any positive number of spaces
450 are equivalent; for a quoted string of spaces, use
451 @code{!QUOTE(!BLANKS(@var{count}))}.
452
453 In the examples below, @samp{_} stands in for a space to make the
454 results visible.
455
456 @c Keep these examples in sync with the test for !BLANKS in
457 @c tests/language/control/define.at:
458 @example
459 !BLANKS(0)                  @expansion{} @r{empty}
460 !BLANKS(1)                  @expansion{} _
461 !BLANKS(2)                  @expansion{} __
462 !QUOTE(!BLANKS(5))          @expansion{} '_____'
463 @end example
464 @end deffn
465
466 @deffn {Macro Function} !CONCAT (arg@dots{})
467 Expands to the concatenation of all of the arguments.  Before
468 concatenation, each quoted string argument is unquoted, as if
469 @code{!UNQUOTE} were applied.  This allows for ``token pasting'',
470 combining two (or more) tokens into a single one:
471
472 @c Keep these examples in sync with the test for !CONCAT in
473 @c tests/language/control/define.at:
474 @example
475 !CONCAT(x, y)                @expansion{} xy
476 !CONCAT('x', 'y')            @expansion{} xy
477 !CONCAT(12, 34)              @expansion{} 1234
478 !CONCAT(!NULL, 123)          @expansion{} 123
479 @end example
480
481 @code{!CONCAT} is often used for constructing a series of similar
482 variable names from a prefix followed by a number and perhaps a
483 suffix.  For example:
484
485 @c Keep these examples in sync with the test for !CONCAT in
486 @c tests/language/control/define.at:
487 @example
488 !CONCAT(x, 0)                @expansion{} x0
489 !CONCAT(x, 0, y)             @expansion{} x0y
490 @end example
491
492 An identifier token must begin with a letter (or @samp{#} or
493 @samp{@@}), which means that attempting to use a number as the first
494 part of an identifier will produce a pair of distinct tokens rather
495 than a single one.  For example:
496
497 @c Keep these examples in sync with the test for !CONCAT in
498 @c tests/language/control/define.at:
499 @example
500 !CONCAT(0, x)                @expansion{} 0 x
501 !CONCAT(0, x, y)             @expansion{} 0 xy
502 @end example
503 @end deffn
504
505 @deffn {Macro Function} !EVAL (arg)
506 Expands macro calls in @var{arg}.  This is especially useful if
507 @var{arg} is the name of a macro or a macro argument that expands to
508 one, because arguments to macro functions are not expanded by default
509 (@pxref{Controlling Macro Expansion}).
510
511 The following examples assume that @code{!vars} is a macro that
512 expands to @code{a b c}:
513
514 @example
515 !vars                        @expansion{} a b c
516 !QUOTE(!vars)                @expansion{} '!vars'
517 !EVAL(!vars)                 @expansion{} a b c
518 !QUOTE(!EVAL(!vars))         @expansion{} 'a b c'
519 @end example
520
521 These examples additionally assume that argument @code{!1} has value
522 @code{!vars}:
523
524 @example
525 !1                           @expansion{} a b c
526 !QUOTE(!1)                   @expansion{} '!vars'
527 !EVAL(!1)                    @expansion{} a b c
528 !QUOTE(!EVAL(!1))            @expansion{} 'a b c'
529 @end example
530 @end deffn
531
532 @deffn {Macro Function} !HEAD (arg)
533 @deffnx {Macro Function} !TAIL (arg)
534 @code{!HEAD} expands to just the first token in an unquoted version of
535 @var{arg}, and @code{!TAIL} to all the tokens after the first.
536
537 @example
538 !HEAD('a b c')               @expansion{} a
539 !HEAD('a')                   @expansion{} a
540 !HEAD(!NULL)                 @expansion{} @r{empty}
541 !HEAD('')                    @expansion{} @r{empty}
542
543 !TAIL('a b c')               @expansion{} b c
544 !TAIL('a')                   @expansion{} @r{empty}
545 !TAIL(!NULL)                 @expansion{} @r{empty}
546 !TAIL('')                    @expansion{} @r{empty}
547 @end example
548 @end deffn
549
550 @deffn {Macro Function} !INDEX (haystack, needle)
551 Looks for @var{needle} in @var{haystack}.  If it is present, expands
552 to the 1-based index of its first occurrence; if not, expands to 0.
553
554 @example
555 !INDEX(banana, an)           @expansion{} 2
556 !INDEX(banana, nan)          @expansion{} 3
557 !INDEX(banana, apple)        @expansion{} 0
558 !INDEX("banana", nan)        @expansion{} 4
559 !INDEX("banana", "nan")      @expansion{} 0
560 !INDEX(!UNQUOTE("banana"), !UNQUOTE("nan")) @expansion{} 3
561 @end example
562 @end deffn
563
564 @deffn {Macro Function} !LENGTH (arg)
565 Expands to a number token representing the number of characters in
566 @var{arg}.
567
568 @example
569 !LENGTH(123)                 @expansion{} 3
570 !LENGTH(123.00)              @expansion{} 6
571 !LENGTH( 123 )               @expansion{} 3
572 !LENGTH("123")               @expansion{} 5
573 !LENGTH(xyzzy)               @expansion{} 5
574 !LENGTH("xyzzy")             @expansion{} 7
575 !LENGTH("xy""zzy")           @expansion{} 9
576 !LENGTH(!UNQUOTE("xyzzy"))   @expansion{} 5
577 !LENGTH(!UNQUOTE("xy""zzy")) @expansion{} 6
578 !LENGTH(!1)                  @expansion{} 5 @r{if @t{!1} is @t{a b c}}
579 !LENGTH(!1)                  @expansion{} 0 @r{if @t{!1} is empty}
580 !LENGTH(!NULL)               @expansion{} 0
581 @end example
582 @end deffn
583
584 @deffn {Macro Function} !NULL
585 Expands to an empty character sequence.
586
587 @c Keep these examples in sync with the test for !NULL in
588 @c tests/language/control/define.at:
589 @example
590 !NULL                        @expansion{} @r{empty}
591 !QUOTE(!NULL)                @expansion{} ''
592 @end example
593 @end deffn
594
595 @deffn {Macro Function} !QUOTE (arg)
596 @deffnx {Macro Function} !UNQUOTE (arg)
597 The @code{!QUOTE} function expands to its argument surrounded by
598 apostrophes, doubling any apostrophes inside the argument to make sure
599 that it is valid PSPP syntax for a string.  If the argument was
600 already a quoted string, @code{!QUOTE} expands to it unchanged.
601
602 Given a quoted string argument, the @code{!UNQUOTED} function expands
603 to the string's contents, with the quotes removed and any doubled
604 quote marks reduced to singletons.  If the argument was not a quoted
605 string, @code{!UNQUOTE} expands to the argument unchanged.
606
607 @c Keep these examples in sync with the test for !QUOTE and !UNQUOTE in
608 @c tests/language/control/define.at:
609 @example
610 !QUOTE(123.0)                @expansion{} '123.0'
611 !QUOTE( 123 )                @expansion{} '123'
612 !QUOTE('a b c')              @expansion{} 'a b c'
613 !QUOTE("a b c")              @expansion{} "a b c"
614 !QUOTE(!1)                   @expansion{} 'a ''b'' c' @r{if @t{!1} is @t{a 'b' c}}
615
616 !UNQUOTE(123.0)              @expansion{} 123.0
617 !UNQUOTE( 123 )              @expansion{} 123
618 !UNQUOTE('a b c')            @expansion{} a b c
619 !UNQUOTE("a b c")            @expansion{} a b c
620 !UNQUOTE(!1)                 @expansion{} a 'b' c @r{if @t{!1} is @t{a 'b' c}}
621
622 !QUOTE(!UNQUOTE(123.0))      @expansion{} '123.0'
623 !QUOTE(!UNQUOTE( 123 ))      @expansion{} '123'
624 !QUOTE(!UNQUOTE('a b c'))    @expansion{} 'a b c'
625 !QUOTE(!UNQUOTE("a b c"))    @expansion{} 'a b c'
626 !QUOTE(!UNQUOTE(!1))         @expansion{} 'a ''b'' c' @r{if @t{!1} is @t{a 'b' c}}
627 @end example
628 @end deffn
629
630 @deffn {Macro Function} !SUBSTR (arg, start[, count])
631 Expands to a substring of @var{arg} starting from 1-based position
632 @var{start}.  If @var{count} is given, it limits the number of
633 characters in the expansion; if it is omitted, then the expansion
634 extends to the end of @var{arg}.
635
636 @example
637 !SUBSTR(banana, 3)           @expansion{} nana
638 !SUBSTR(banana, 3, 3)        @expansion{} nan
639 !SUBSTR("banana", 1, 3)         @expansion{} @r{error (@code{"ba} is not a valid token)}
640 !SUBSTR(!UNQUOTE("banana"), 3) @expansion{} nana
641 !SUBSTR("banana", 3, 3)      @expansion{} ana
642
643 !SUBSTR(banana, 3, 0)        @expansion{} @r{empty}
644 !SUBSTR(banana, 3, 10)       @expansion{} nana
645 !SUBSTR(banana, 10, 3)       @expansion{} @r{empty}
646 @end example
647 @end deffn
648
649 @deffn {Macro Function} !UPCASE (arg)
650 Expands to an unquoted version of @var{arg} with all letters converted
651 to uppercase.
652
653 @example
654 !UPCASE(freckle)             @expansion{} FRECKLE
655 !UPCASE('freckle')           @expansion{} FRECKLE
656 !UPCASE('a b c')             @expansion{} A B C
657 !UPCASE('A B C')             @expansion{} A B C
658 @end example
659 @end deffn
660
661 @node Macro Expressions
662 @subsection Macro Expressions
663
664 Macro expressions are used in conditional expansion and loops, which
665 are described in the following sections.  A macro expression may use
666 the following operators, listed in descending order of operator
667 precedence:
668
669 @table @code
670 @item ()
671 Parentheses override the default operator precedence.
672
673 @item !EQ !NE !GT !LT !GE !LE = ~= <> > < >= <=
674 Relational operators compare their operands and yield a Boolean
675 result, either @samp{0} for false or @samp{1} for true.
676
677 These operators always compare their operands as strings.  This can be
678 surprising when the strings are numbers because, e.g.,@: @code{1 <
679 1.0} and @code{10 < 2} both evaluate to @samp{1} (true).
680
681 Comparisons are case sensitive, so that @code{a = A} evaluates to
682 @samp{0} (false).
683
684 @item !NOT ~
685 @itemx !AND &
686 @itemx !OR |
687 Logical operators interpret their operands as Boolean values, where
688 quoted or unquoted @samp{0} is false and anything else is true, and
689 yield a Boolean result, either @samp{0} for false or @samp{1} for
690 true.
691 @end table
692
693 Macro expressions do not include any arithmetic operators.
694
695 An operand in an expression may be a single token (including a macro
696 argument name) or a macro function invocation.  Either way, the
697 expression evaluator unquotes the operand, so that @code{1 = '1'} is
698 true.
699
700 @node Macro Conditional Expansion
701 @subsection Macro Conditional Expansion
702
703 The @code{!IF} construct may be used inside a macro body to allow for
704 conditional expansion.  It takes the following forms:
705
706 @example
707 !IF (@var{expression}) !THEN @var{true-expansion} !IFEND
708 !IF (@var{expression}) !THEN @var{true-expansion} !ELSE @var{false-expansion} !IFEND
709 @end example
710
711 When @var{expression} evaluates to true, the macro processor expands
712 @var{true-expansion}; otherwise, it expands @var{false-expansion}, if
713 it is present.  The macro processor considers quoted or unquoted
714 @samp{0} to be false, and anything else to be true.
715
716 @node Macro Loops
717 @subsection Macro Loops
718
719 The body of a macro may include two forms of loops: loops over
720 numerical ranges and loops over tokens.  Both forms expand a @dfn{loop
721 body} multiple times, each time setting a named @dfn{loop variable} to
722 a different value.  The loop body typically expands the loop variable
723 at least once.
724
725 The MITERATE setting (@pxref{SET MITERATE}) limits the number of
726 iterations in a loop.  This is a safety measure to ensure that macro
727 expansion terminates.  PSPP issues a warning when the MITERATE limit
728 is exceeded.
729
730 @subsubheading Loops Over Ranges
731
732 @example
733 !DO @var{!var} = @var{start} !TO @var{end} [!BY @var{step}]
734   @var{body}
735 !DOEND
736 @end example
737
738 A loop over a numerical range has the form shown above.  @var{start},
739 @var{end}, and @var{step} (if included) must be expressions with
740 numeric values.  The macro processor accepts both integers and real
741 numbers.  The macro processor expands @var{body} for each numeric
742 value from @var{start} to @var{end}, inclusive.
743
744 The default value for @var{step} is 1.  If @var{step} is positive and
745 @math{@var{first} > @var{last}}, or if @var{step} is negative and
746 @math{@var{first} < @var{last}}, then the macro processor doesn't
747 expand the body at all.  @var{step} may not be zero.
748
749 @subsubheading Loops Over Tokens
750
751 @example
752 !DO @var{!var} !IN (@var{expression})
753   @var{body}
754 !DOEND
755 @end example
756
757 A loop over tokens takes the form shown above.  The macro processor
758 evaluates @var{expression} and expands @var{body} once per token in
759 the result, substituting the token for @var{!var} each time it
760 appears.
761
762 @node Macro Variable Assignment
763 @subsection Macro Variable Assignment
764
765 The @code{!LET} construct evaluates an expression and assigns the
766 result to a macro variable.  It may create a new macro variable or
767 change the value of one created by a previous @code{!LET} or
768 @code{!DO}, but it may not change the value of a macro argument.
769 @code{!LET} has the following form:
770
771 @example
772 !LET @var{!var} = @var{expression}
773 @end example
774
775 If @var{expression} is more than one token, it must be enclosed in
776 parentheses.
777
778 @node Macro Settings
779 @subsection Macro Settings
780
781 Some macro behavior is controlled through the SET command
782 (@pxref{SET}).  This section describes these settings.
783
784 Any SET command that changes these settings within a macro body only
785 takes effect following the macro.  This is because PSPP expands a
786 macro's entire body at once, so that the SET command inside the body
787 only executes afterwards.
788
789 The MEXPAND setting (@pxref{SET MEXPAND}) controls whether macros will
790 be expanded at all.  By default, macro expansion is on.  To avoid
791 expansion of macros called within a macro body, use @code{!OFFEXPAND}
792 and @code{!ONEXPAND} (@pxref{Controlling Macro Expansion}).
793
794 When MPRINT (@pxref{SET MPRINT}) is turned on, PSPP outputs an
795 expansion of each macro called.  This feature can be useful for
796 debugging macro definitions.  For reading the expanded version, note
797 that macro expansion removes comments and standardizes white space.
798
799 MNEST (@pxref{SET MNEST}) limits the depth of expansion of macro
800 calls, that is, the nesting level of macro expansion.  The default is
801 50.  This is mainly useful to avoid infinite expansion in the case of
802 a macro that calls itself.
803
804 MITERATE (@pxref{SET MITERATE}) limits the number of iterations in a
805 @code{!DO} construct.  The default is 1000.
806
807 PRESERVE...RESTORE
808
809 SET MEXPAND, etc. doesn't work inside macro bodies.
810
811 @node Macro Notes
812 @subsection Additional Notes
813
814 @subsubsection Calling Macros from Macros
815
816 If the body of macro A includes a call to macro B, the call can use
817 macro arguments (including @code{!*}) and macro variables as part of
818 arguments to B.  For @code{!TOKENS} arguments, the argument or
819 variable name counts as one token regardless of the number that
820 expands into, for @code{!CHAREND} and @code{!ENCLOSE} arguments the
821 delimiters come only from the call, not the expansions, and
822 @code{!CMDEND} ends at the calling command, not any end of command
823 within an argument or variable.
824
825 Macro functions are not supported as part of the arguments in a macro
826 call.  To get the same effect, use @code{!LET} to define a macro
827 variable, then pass the macro variable to the macro.
828
829 When macro A calls macro B, the order of their @code{DEFINE} commands
830 doesn't matter, as long as macro B has been defined when A is called.
831
832 @subsubsection Command Terminators
833
834 Macros and command terminators require care.  Macros honor the syntax
835 differences between interactive and batch syntax (@pxref{Syntax
836 Variants}), which means that the interpretation of a macro can vary
837 depending on the syntax mode in use.  We assume here that interactive
838 mode is in use, in which @samp{.}@: at the end of a line is the
839 primary way to end a command.
840
841 The @code{DEFINE} command needs to end with @samp{.}@: following the
842 @code{!ENDDEFINE}.  The macro body may contain @samp{.}@: if it is
843 intended to expand to whole commands, but using @samp{.}@: within a
844 macro body that expands to just syntax fragments (such as a list of
845 variables) will cause syntax errors.
846
847 Macro directives such as @code{!IF} and @code{!DO} do not end with
848 @samp{.}.
849
850 @subsubsection Expansion Contexts
851
852 Macros do not expand within comments, whether introduced within a line
853 by @code{/*} or as a separate COMMENT or @samp{*} commands
854 (@pxref{COMMENT}).  (SPSS does expand macros in COMMENT and @samp{*}.)
855
856 Macros do not expand within quoted strings.
857
858 Macros are expanded in the @code{TITLE} and @code{SUBTITLE} commands
859 as long as their arguments are not quoted strings.
860
861 @subsubsection PRESERVE and RESTORE
862
863 Some macro bodies might use the SET command to change certain
864 settings.  When this is the case, consider using the PRESERVE and
865 RESTORE commands to save and then restore these settings.
866 @xref{PRESERVE and RESTORE}.
867
868 @node DO IF
869 @section DO IF
870 @vindex DO IF
871
872 @display
873 DO IF condition.
874         @dots{}
875 [ELSE IF condition.
876         @dots{}
877 ]@dots{}
878 [ELSE.
879         @dots{}]
880 END IF.
881 @end display
882
883 @cmd{DO IF} allows one of several sets of transformations to be
884 executed, depending on user-specified conditions.
885
886 If the specified boolean expression evaluates as true, then the block
887 of code following @cmd{DO IF} is executed.  If it evaluates as
888 missing, then
889 none of the code blocks is executed.  If it is false, then
890 the boolean expression on the first @cmd{ELSE IF}, if present, is tested in
891 turn, with the same rules applied.  If all expressions evaluate to
892 false, then the @cmd{ELSE} code block is executed, if it is present.
893
894 When @cmd{DO IF} or @cmd{ELSE IF} is specified following @cmd{TEMPORARY}
895 (@pxref{TEMPORARY}), the @cmd{LAG} function may not be used
896 (@pxref{LAG}).
897
898 @node DO REPEAT
899 @section DO REPEAT
900 @vindex DO REPEAT
901
902 @display
903 DO REPEAT dummy_name=expansion@dots{}.
904         @dots{}
905 END REPEAT [PRINT].
906
907 expansion takes one of the following forms:
908         var_list
909         num_or_range@dots{}
910         'string'@dots{}
911         ALL
912
913 num_or_range takes one of the following forms:
914         number
915         num1 TO num2
916 @end display
917
918 @cmd{DO REPEAT} repeats a block of code, textually substituting
919 different variables, numbers, or strings into the block with each
920 repetition.
921
922 Specify a dummy variable name followed by an equals sign (@samp{=})
923 and the list of replacements.  Replacements can be a list of existing
924 or new variables, numbers, strings, or @code{ALL} to specify all
925 existing variables.  When numbers are specified, runs of increasing
926 integers may be indicated as @code{@var{num1} TO @var{num2}}, so that
927 @samp{1 TO 5} is short for @samp{1 2 3 4 5}.
928
929 Multiple dummy variables can be specified.  Each
930 variable must have the same number of replacements.
931
932 The code within @cmd{DO REPEAT} is repeated as many times as there are
933 replacements for each variable.  The first time, the first value for
934 each dummy variable is substituted; the second time, the second value
935 for each dummy variable is substituted; and so on.
936
937 Dummy variable substitutions work like macros.  They take place
938 anywhere in a line that the dummy variable name occurs.  This includes
939 command and subcommand names, so command and subcommand names that
940 appear in the code block should not be used as dummy variable
941 identifiers.  Dummy variable substitutions do not occur inside quoted
942 strings, comments, unquoted strings (such as the text on the
943 @cmd{TITLE} or @cmd{DOCUMENT} command), or inside @cmd{BEGIN
944 DATA}@dots{}@cmd{END DATA}.
945
946 Substitution occurs only on whole words, so that, for example, a dummy
947 variable PRINT would not be substituted into the word PRINTOUT.
948
949 New variable names used as replacements are not automatically created
950 as variables, but only if used in the code block in a context that
951 would create them, @i{e.g.}@: on a @cmd{NUMERIC} or @cmd{STRING} command
952 or on the left side of a @cmd{COMPUTE} assignment.
953
954 Any command may appear within @subcmd{DO REPEAT}, including nested @subcmd{DO REPEAT}
955 commands.  If @cmd{INCLUDE} or @cmd{INSERT} appears within @subcmd{DO REPEAT},
956 the substitutions do not apply to the included file.
957
958 If @subcmd{PRINT} is specified on @cmd{END REPEAT}, the commands after
959 substitutions are made should be printed to the listing file, prefixed
960 by a plus sign (@samp{+}).  This feature is not yet implemented.
961
962 @node LOOP
963 @section LOOP
964 @vindex LOOP
965
966 @display
967 LOOP [@var{index_var}=@var{start} TO @var{end} [BY @var{incr}]] [IF @var{condition}].
968         @dots{}
969 END LOOP [IF @var{condition}].
970 @end display
971
972 @cmd{LOOP} iterates a group of commands.  A number of
973 termination options are offered.
974
975 Specify index_var to make that variable count from one value to
976 another by a particular increment.  @var{index_var} must be a pre-existing
977 numeric variable.  @var{start}, @var{end}, and @var{incr} are numeric expressions
978 (@pxref{Expressions}.)
979
980 During the first iteration, @var{index_var} is set to the value of @var{start}.
981 During each successive iteration, @var{index_var} is increased by the value of
982 @var{incr}.  If @var{end} > @var{start}, then the loop terminates
983 when @var{index_var} > @var{end};
984 otherwise it terminates when @var{index_var} < @var{end}.  If @var{incr} is not specified
985 then it defaults to +1 or -1 as appropriate.
986
987 If @var{end} > @var{start} and @var{incr} < 0, or if @var{end} < @var{start} and
988  @var{incr} > 0, then the
989 loop is never executed.  @var{index_var} is nevertheless set to the value of
990 start.
991
992 Modifying @var{index_var} within the loop is allowed, but it has no effect on
993 the value of @var{index_var} in the next iteration.
994
995 Specify a boolean expression for the condition on @cmd{LOOP} to
996 cause the loop to be executed only if the condition is true.  If the
997 condition is false or missing before the loop contents are executed the
998 first time, the loop contents are not executed at all.
999
1000 If index and condition clauses are both present on @cmd{LOOP}, the
1001 index variable is always set before the condition is evaluated.  Thus,
1002 a condition that makes use of the index variable will always see the
1003 index value to be used in the next execution of the body.
1004
1005 Specify a boolean expression for the condition on @cmd{END LOOP} to cause
1006 the loop to terminate if the condition is true after the enclosed
1007 code block is executed.  The condition is evaluated at the end of the
1008 loop, not at the beginning, so that the body of a loop with only a
1009 condition on @cmd{END LOOP} will always execute at least once.
1010
1011 If the index clause is not present, then the global @code{MXLOOPS}
1012 setting, which defaults to 40, limits the number of iterations
1013 (@pxref{SET MXLOOPS}).
1014
1015 @cmd{BREAK} also terminates @cmd{LOOP} execution (@pxref{BREAK}).
1016
1017 Loop index variables are by default reset to system-missing from one
1018 case to another, not left, unless a scratch variable is used as index.
1019 When loops are nested, this is usually undesired behavior, which can
1020 be corrected with @cmd{LEAVE} (@pxref{LEAVE}) or by using a scratch
1021 variable as the loop index.
1022
1023 When @cmd{LOOP} or @cmd{END LOOP} is specified following @cmd{TEMPORARY}
1024 (@pxref{TEMPORARY}), the @cmd{LAG} function may not be used
1025 (@pxref{LAG}).