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