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