Stage 18: try harder to reuse argv in recursion.
[m4/ericb.git] / doc / m4.texinfo
blob92a8effe18ff8c80230d7d755dae5667dc88195a
1 \input texinfo @c -*- texinfo -*-
2 @comment ========================================================
3 @comment %**start of header
4 @setfilename m4.info
5 @include version.texi
6 @settitle GNU M4 @value{VERSION} macro processor
7 @setchapternewpage odd
8 @ifnothtml
9 @setcontentsaftertitlepage
10 @end ifnothtml
11 @finalout
13 @c @tabchar{}
14 @c ----------
15 @c The testsuite expects literal tab output in some examples, but
16 @c literal tabs in texinfo lead to formatting issues.
17 @macro tabchar
18 @       @c
19 @end macro
21 @c @ovar{ARG}
22 @c -------------------
23 @c The ARG is an optional argument.  To be used for macro arguments in
24 @c their documentation.
25 @macro ovar{varname}
26 @r{[}@var{\varname\}@r{]}
27 @end macro
29 @c @dvar{ARG, DEFAULT}
30 @c -------------------
31 @c The ARG is an optional argument, defaulting to DEFAULT.  To be used
32 @c for macro arguments in their documentation.
33 @macro dvar{varname, default}
34 @r{[}@var{\varname\} = @samp{\default\}@r{]}
35 @end macro
37 @comment %**end of header
38 @comment ========================================================
40 @copying
42 This manual is for @acronym{GNU} M4 (version @value{VERSION}, @value{UPDATED}),
43 a package containing an implementation of the m4 macro language.
45 Copyright @copyright{} 1989, 1990, 1991, 1992, 1993, 1994, 2004, 2005,
46 2006, 2007, 2008 Free Software Foundation, Inc.
48 @quotation
49 Permission is granted to copy, distribute and/or modify this document
50 under the terms of the @acronym{GNU} Free Documentation License,
51 Version 1.2 or any later version published by the Free Software
52 Foundation; with no Invariant Sections, no Front-Cover Texts, and no
53 Back-Cover Texts.  A copy of the license is included in the section
54 entitled ``@acronym{GNU} Free Documentation License.''
55 @end quotation
56 @end copying
58 @dircategory Text creation and manipulation
59 @direntry
60 * M4: (m4).                     A powerful macro processor.
61 @end direntry
63 @titlepage
64 @title GNU M4, version @value{VERSION}
65 @subtitle A powerful macro processor
66 @subtitle Edition @value{EDITION}, @value{UPDATED}
67 @author by Ren@'e Seindal, Fran@,{c}ois Pinard,
68 @author Gary V. Vaughan, and Eric Blake
69 @author (@email{bug-m4@@gnu.org})
71 @page
72 @vskip 0pt plus 1filll
73 @insertcopying
74 @end titlepage
76 @contents
78 @ifnottex
79 @node Top
80 @top GNU M4
81 @insertcopying
82 @end ifnottex
84 @acronym{GNU} @code{m4} is an implementation of the traditional UNIX macro
85 processor.  It is mostly SVR4 compatible, although it has some
86 extensions (for example, handling more than 9 positional parameters
87 to macros).  @code{m4} also has builtin functions for including
88 files, running shell commands, doing arithmetic, etc.  Autoconf needs
89 @acronym{GNU} @code{m4} for generating @file{configure} scripts, but not for
90 running them.
92 @acronym{GNU} @code{m4} was originally written by Ren@'e Seindal, with
93 subsequent changes by Fran@,{c}ois Pinard and other volunteers
94 on the Internet.  All names and email addresses can be found in the
95 files @file{m4-@value{VERSION}/@/AUTHORS} and
96 @file{m4-@value{VERSION}/@/THANKS} from the @acronym{GNU} M4
97 distribution.
99 This is release @value{VERSION}.  It is now considered stable:  future
100 releases in the 1.4.x series are only meant to fix bugs, increase speed,
101 or improve documentation.  However@dots{}
103 An experimental feature, which would improve @code{m4} usefulness,
104 allows for changing the syntax for what is a @dfn{word} in @code{m4}.
105 You should use:
106 @comment ignore
107 @example
108 ./configure --enable-changeword
109 @end example
110 @noindent
111 if you want this feature compiled in.  The current implementation
112 slows down @code{m4} considerably and is hardly acceptable.  In the
113 future, @code{m4} 2.0 will come with a different set of new features
114 that provide similar capabilities, but without the inefficiencies, so
115 changeword will go away and @emph{you should not count on it}.
117 @menu
118 * Preliminaries::               Introduction and preliminaries
119 * Invoking m4::                 Invoking @code{m4}
120 * Syntax::                      Lexical and syntactic conventions
122 * Macros::                      How to invoke macros
123 * Definitions::                 How to define new macros
124 * Conditionals::                Conditionals, loops, and recursion
126 * Debugging::                   How to debug macros and input
128 * Input Control::               Input control
129 * File Inclusion::              File inclusion
130 * Diversions::                  Diverting and undiverting output
132 * Text handling::               Macros for text handling
133 * Arithmetic::                  Macros for doing arithmetic
134 * Shell commands::              Macros for running shell commands
135 * Miscellaneous::               Miscellaneous builtin macros
136 * Frozen files::                Fast loading of frozen state
138 * Compatibility::               Compatibility with other versions of @code{m4}
139 * Answers::                     Correct version of some examples
141 * Copying This Package::        How to make copies of the overall M4 package
142 * Copying This Manual::         How to make copies of this manual
143 * Indices::                     Indices of concepts and macros
145 @detailmenu
146  --- The Detailed Node Listing ---
148 Introduction and preliminaries
150 * Intro::                       Introduction to @code{m4}
151 * History::                     Historical references
152 * Bugs::                        Problems and bugs
153 * Manual::                      Using this manual
155 Invoking @code{m4}
157 * Operation modes::             Command line options for operation modes
158 * Preprocessor features::       Command line options for preprocessor features
159 * Limits control::              Command line options for limits control
160 * Frozen state::                Command line options for frozen state
161 * Debugging options::           Command line options for debugging
162 * Command line files::          Specifying input files on the command line
164 Lexical and syntactic conventions
166 * Names::                       Macro names
167 * Quoted strings::              Quoting input to @code{m4}
168 * Comments::                    Comments in @code{m4} input
169 * Other tokens::                Other kinds of input tokens
170 * Input processing::            How @code{m4} copies input to output
172 How to invoke macros
174 * Invocation::                  Macro invocation
175 * Inhibiting Invocation::       Preventing macro invocation
176 * Macro Arguments::             Macro arguments
177 * Quoting Arguments::           On Quoting Arguments to macros
178 * Macro expansion::             Expanding macros
180 How to define new macros
182 * Define::                      Defining a new macro
183 * Arguments::                   Arguments to macros
184 * Pseudo Arguments::            Special arguments to macros
185 * Undefine::                    Deleting a macro
186 * Defn::                        Renaming macros
187 * Pushdef::                     Temporarily redefining macros
189 * Indir::                       Indirect call of macros
190 * Builtin::                     Indirect call of builtins
192 Conditionals, loops, and recursion
194 * Ifdef::                       Testing if a macro is defined
195 * Ifelse::                      If-else construct, or multibranch
196 * Shift::                       Recursion in @code{m4}
197 * Forloop::                     Iteration by counting
198 * Foreach::                     Iteration by list contents
200 How to debug macros and input
202 * Dumpdef::                     Displaying macro definitions
203 * Trace::                       Tracing macro calls
204 * Debug Levels::                Controlling debugging output
205 * Debug Output::                Saving debugging output
207 Input control
209 * Dnl::                         Deleting whitespace in input
210 * Changequote::                 Changing the quote characters
211 * Changecom::                   Changing the comment delimiters
212 * Changeword::                  Changing the lexical structure of words
213 * M4wrap::                      Saving text until end of input
215 File inclusion
217 * Include::                     Including named files
218 * Search Path::                 Searching for include files
220 Diverting and undiverting output
222 * Divert::                      Diverting output
223 * Undivert::                    Undiverting output
224 * Divnum::                      Diversion numbers
225 * Cleardivert::                 Discarding diverted text
227 Macros for text handling
229 * Len::                         Calculating length of strings
230 * Index macro::                 Searching for substrings
231 * Regexp::                      Searching for regular expressions
232 * Substr::                      Extracting substrings
233 * Translit::                    Translating characters
234 * Patsubst::                    Substituting text by regular expression
235 * Format::                      Formatting strings (printf-like)
237 Macros for doing arithmetic
239 * Incr::                        Decrement and increment operators
240 * Eval::                        Evaluating integer expressions
242 Macros for running shell commands
244 * Platform macros::             Determining the platform
245 * Syscmd::                      Executing simple commands
246 * Esyscmd::                     Reading the output of commands
247 * Sysval::                      Exit status
248 * Mkstemp::                     Making temporary files
250 Miscellaneous builtin macros
252 * Errprint::                    Printing error messages
253 * Location::                    Printing current location
254 * M4exit::                      Exiting from @code{m4}
256 Fast loading of frozen state
258 * Using frozen files::          Using frozen files
259 * Frozen file format::          Frozen file format
261 Compatibility with other versions of @code{m4}
263 * Extensions::                  Extensions in @acronym{GNU} M4
264 * Incompatibilities::           Facilities in System V m4 not in GNU M4
265 * Other Incompatibilities::     Other incompatibilities
267 Correct version of some examples
269 * Improved exch::               Solution for @code{exch}
270 * Improved forloop::            Solution for @code{forloop}
271 * Improved foreach::            Solution for @code{foreach}
272 * Improved cleardivert::        Solution for @code{cleardivert}
273 * Improved capitalize::         Solution for @code{capitalize}
274 * Improved fatal_error::        Solution for @code{fatal_error}
276 How to make copies of the overall M4 package
278 * GNU General Public License::  License for copying the M4 package
280 How to make copies of this manual
282 * GNU Free Documentation License::  License for copying this manual
284 Indices of concepts and macros
286 * Macro index::                 Index for all @code{m4} macros
287 * Concept index::               Index for many concepts
289 @end detailmenu
290 @end menu
292 @node Preliminaries
293 @chapter Introduction and preliminaries
295 This first chapter explains what @acronym{GNU} @code{m4} is, where @code{m4}
296 comes from, how to read and use this documentation, how to call the
297 @code{m4} program, and how to report bugs about it.  It concludes by
298 giving tips for reading the remainder of the manual.
300 The following chapters then detail all the features of the @code{m4}
301 language.
303 @menu
304 * Intro::                       Introduction to @code{m4}
305 * History::                     Historical references
306 * Bugs::                        Problems and bugs
307 * Manual::                      Using this manual
308 @end menu
310 @node Intro
311 @section Introduction to @code{m4}
313 @cindex overview of @code{m4}
314 @code{m4} is a macro processor, in the sense that it copies its
315 input to the output, expanding macros as it goes.  Macros are either
316 builtin or user-defined, and can take any number of arguments.
317 Besides just doing macro expansion, @code{m4} has builtin functions
318 for including named files, running shell commands, doing integer
319 arithmetic, manipulating text in various ways, performing recursion,
320 etc.@dots{}  @code{m4} can be used either as a front-end to a compiler,
321 or as a macro processor in its own right.
323 The @code{m4} macro processor is widely available on all UNIXes, and has
324 been standardized by @acronym{POSIX}.
325 Usually, only a small percentage of users are aware of its existence.
326 However, those who find it often become committed users.  The
327 popularity of @acronym{GNU} Autoconf, which requires @acronym{GNU}
328 @code{m4} for @emph{generating} @file{configure} scripts, is an incentive
329 for many to install it, while these people will not themselves
330 program in @code{m4}.  @acronym{GNU} @code{m4} is mostly compatible with the
331 System V, Release 3 version, except for some minor differences.
332 @xref{Compatibility}, for more details.
334 Some people find @code{m4} to be fairly addictive.  They first use
335 @code{m4} for simple problems, then take bigger and bigger challenges,
336 learning how to write complex sets of @code{m4} macros along the way.
337 Once really addicted, users pursue writing of sophisticated @code{m4}
338 applications even to solve simple problems, devoting more time
339 debugging their @code{m4} scripts than doing real work.  Beware that
340 @code{m4} may be dangerous for the health of compulsive programmers.
342 @node History
343 @section Historical references
345 @cindex history of @code{m4}
346 @cindex @acronym{GNU} M4, history of
347 @code{GPM} was an important ancestor of @code{m4}.  See
348 C. Stratchey: ``A General Purpose Macro generator'', Computer Journal
349 8,3 (1965), pp.@: 225 ff.  @code{GPM} is also succinctly described into
350 David Gries classic ``Compiler Construction for Digital Computers''.
352 The classic B. Kernighan and P.J. Plauger: ``Software Tools'',
353 Addison-Wesley, Inc.@: (1976) describes and implements a Unix
354 macro-processor language, which inspired Dennis Ritchie to write
355 @code{m3}, a macro processor for the AP-3 minicomputer.
357 Kernighan and Ritchie then joined forces to develop the original
358 @code{m4}, as described in ``The M4 Macro Processor'', Bell
359 Laboratories (1977).  It had only 21 builtin macros.
361 While @code{GPM} was more @emph{pure}, @code{m4} is meant to deal with
362 the true intricacies of real life: macros can be recognized without
363 being pre-announced, skipping whitespace or end-of-lines is easier,
364 more constructs are builtin instead of derived, etc.
366 Originally, the Kernighan and Plauger macro-processor, and then
367 @code{m3}, formed the engine for the Rational FORTRAN preprocessor,
368 that is, the @code{Ratfor} equivalent of @code{cpp}.  Later, @code{m4}
369 was used as a front-end for @code{Ratfor}, @code{C} and @code{Cobol}.
371 Ren@'e Seindal released his implementation of @code{m4}, @acronym{GNU}
372 @code{m4},
373 in 1990, with the aim of removing the artificial limitations in many
374 of the traditional @code{m4} implementations, such as maximum line
375 length, macro size, or number of macros.
377 The late Professor A. Dain Samples described and implemented a further
378 evolution in the form of @code{M5}: ``User's Guide to the M5 Macro
379 Language: 2nd edition'', Electronic Announcement on comp.compilers
380 newsgroup (1992).
382 Fran@,{c}ois Pinard took over maintenance of @acronym{GNU} @code{m4} in
383 1992, until 1994 when he released @acronym{GNU} @code{m4} 1.4, which was
384 the stable release for 10 years.  It was at this time that @acronym{GNU}
385 Autoconf decided to require @acronym{GNU} @code{m4} as its underlying
386 engine, since all other implementations of @code{m4} had too many
387 limitations.
389 More recently, in 2004, Paul Eggert released 1.4.1 and 1.4.2 which
390 addressed some long standing bugs in the venerable 1.4 release.  Then in
391 2005, Gary V. Vaughan collected together the many patches to
392 @acronym{GNU} @code{m4} 1.4 that were floating around the net and
393 released 1.4.3 and 1.4.4.  And in 2006, Eric Blake joined the team and
394 prepared patches for the release of 1.4.5, 1.4.6, 1.4.7, and 1.4.8.
395 More bug fixes were incorporated in 2007, with releases 1.4.9 and
396 1.4.10.  In 2008, Eric additionally rewrote the scanning engine to
397 reduce recursive evaluation from quadratic to linear complexity for
398 1.4.11.  The 1.4.x branch remains open for bug fixes.
400 Meanwhile, development has continued on new features for @code{m4}, such
401 as dynamic module loading and additional builtins.  When complete,
402 @acronym{GNU} @code{m4} 2.0 will start a new series of releases.
404 @node Bugs
405 @section Problems and bugs
407 @cindex reporting bugs
408 @cindex bug reports
409 @cindex suggestions, reporting
410 If you have problems with @acronym{GNU} M4 or think you've found a bug,
411 please report it.  Before reporting a bug, make sure you've actually
412 found a real bug.  Carefully reread the documentation and see if it
413 really says you can do what you're trying to do.  If it's not clear
414 whether you should be able to do something or not, report that too; it's
415 a bug in the documentation!
417 Before reporting a bug or trying to fix it yourself, try to isolate it
418 to the smallest possible input file that reproduces the problem.  Then
419 send us the input file and the exact results @code{m4} gave you.  Also
420 say what you expected to occur; this will help us decide whether the
421 problem was really in the documentation.
423 Once you've got a precise problem, send e-mail to
424 @email{bug-m4@@gnu.org}.  Please include the version number of @code{m4}
425 you are using.  You can get this information with the command
426 @kbd{m4 --version}.  Also provide details about the platform you are
427 executing on.
429 Non-bug suggestions are always welcome as well.  If you have questions
430 about things that are unclear in the documentation or are just obscure
431 features, please report them too.
433 @node Manual
434 @section Using this manual
436 @cindex examples, understanding
437 This manual contains a number of examples of @code{m4} input and output,
438 and a simple notation is used to distinguish input, output and error
439 messages from @code{m4}.  Examples are set out from the normal text, and
440 shown in a fixed width font, like this
442 @comment ignore
443 @example
444 This is an example of an example!
445 @end example
447 To distinguish input from output, all output from @code{m4} is prefixed
448 by the string @samp{@result{}}, and all error messages by the string
449 @samp{@error{}}.  When showing how command line options affect matters,
450 the command line is shown with a prompt @samp{$ @kbd{like this}},
451 otherwise, you can assume that a simple @kbd{m4} invocation will work.
452 Thus:
454 @comment ignore
455 @example
456 $ @kbd{command line to invoke m4}
457 Example of input line
458 @result{}Output line from m4
459 @error{}and an error message
460 @end example
462 The sequence @samp{^D} in an example indicates the end of the input
463 file.  The sequence @samp{@key{NL}} refers to the newline character.
464 The majority of these examples are self-contained, and you can run them
465 with similar results by invoking @kbd{m4 -d}.  In fact, the testsuite
466 that is bundled in the @acronym{GNU} M4 package consists of the examples
467 in this document!  Some of the examples assume that your current
468 directory is located where you unpacked the installation, so if you plan
469 on following along, you may find it helpful to do this now:
471 @comment ignore
472 @example
473 $ @kbd{cd m4-@value{VERSION}}
474 @end example
476 As each of the predefined macros in @code{m4} is described, a prototype
477 call of the macro will be shown, giving descriptive names to the
478 arguments, e.g.,
480 @deffn Composite example (@var{string}, @dvar{count, 1}, @
481   @ovar{argument}@dots{})
482 This is a sample prototype.  There is not really a macro named
483 @code{example}, but this documents that if there were, it would be a
484 Composite macro, rather than a Builtin.  It requires at least one
485 argument, @var{string}.  Remember that in @code{m4}, there must not be a
486 space between the macro name and the opening parenthesis, unless it was
487 intended to call the macro without any arguments.  The brackets around
488 @var{count} and @var{argument} show that these arguments are optional.
489 If @var{count} is omitted, the macro behaves as if count were @samp{1},
490 whereas if @var{argument} is omitted, the macro behaves as if it were
491 the empty string.  A blank argument is not the same as an omitted
492 argument.  For example, @samp{example(`a')}, @samp{example(`a',`1')},
493 and @samp{example(`a',`1',)} would behave identically with @var{count}
494 set to @samp{1}; while @samp{example(`a',)} and @samp{example(`a',`')}
495 would explicitly pass the empty string for @var{count}.  The ellipses
496 (@samp{@dots{}}) show that the macro processes additional arguments
497 after @var{argument}, rather than ignoring them.
498 @end deffn
500 @cindex numbers
501 All macro arguments in @code{m4} are strings, but some are given
502 special interpretation, e.g., as numbers, file names, regular
503 expressions, etc.  The documentation for each macro will state how the
504 parameters are interpreted, and what happens if the argument cannot be
505 parsed according to the desired interpretation.  Unless specified
506 otherwise, a parameter specified to be a number is parsed as a decimal,
507 even if the argument has leading zeros; and parsing the empty string as
508 a number results in 0 rather than an error, although a warning will be
509 issued.
511 This document consistently writes and uses @dfn{builtin}, without a
512 hyphen, as if it were an English word.  This is how the @code{builtin}
513 primitive is spelled within @code{m4}.
515 @node Invoking m4
516 @chapter Invoking @code{m4}
518 @cindex command line
519 @cindex invoking @code{m4}
520 The format of the @code{m4} command is:
522 @comment ignore
523 @example
524 @code{m4} @r{[}@var{option}@dots{}@r{]} @r{[}@var{file}@dots{}@r{]}
525 @end example
527 @cindex command line, options
528 @cindex options, command line
529 @cindex @env{POSIXLY_CORRECT}
530 All options begin with @samp{-}, or if long option names are used, with
531 @samp{--}.  A long option name need not be written completely, any
532 unambiguous prefix is sufficient.  @acronym{POSIX} requires @code{m4} to
533 recognize arguments intermixed with files, even when
534 @env{POSIXLY_CORRECT} is set in the environment.  Most options take
535 effect at startup regardless of their position, but some are documented
536 below as taking effect after any files that occurred earlier in the
537 command line.  The argument @option{--} is a marker to denote the end of
538 options.
540 @comment FIXME option -d+f only works on head right now...
541 With short options, options that do not take arguments may be combined
542 into a single command line argument with subsequent options, options
543 with mandatory arguments may be provided either as a single command line
544 argument or as two arguments, and options with optional arguments must
545 be provided as a single argument.  In other words,
546 @kbd{m4 -QPDfoo -d a -d+f} is equivalent to
547 @kbd{m4 -Q -P -D foo -d -d+f -- ./a}, although the latter form is
548 considered canonical.
550 With long options, options with mandatory arguments may be provided with
551 an equal sign (@samp{=}) in a single argument, or as two arguments, and
552 options with optional arguments must be provided as a single argument.
553 In other words, @kbd{m4 --def foo --debug a} is equivalent to
554 @kbd{m4 --define=foo --debug= -- ./a}, although the latter form is
555 considered canonical (not to mention more robust, in case a future
556 version of @code{m4} introduces an option named @option{--default}).
558 @code{m4} understands the following options, grouped by functionality.
560 @menu
561 * Operation modes::             Command line options for operation modes
562 * Preprocessor features::       Command line options for preprocessor features
563 * Limits control::              Command line options for limits control
564 * Frozen state::                Command line options for frozen state
565 * Debugging options::           Command line options for debugging
566 * Command line files::          Specifying input files on the command line
567 @end menu
569 @node Operation modes
570 @section Command line options for operation modes
572 Several options control the overall operation of @code{m4}:
574 @table @code
575 @item --help
576 Print a help summary on standard output, then immediately exit
577 @code{m4} without reading any input files or performing any other
578 actions.
580 @item --version
581 Print the version number of the program on standard output, then
582 immediately exit @code{m4} without reading any input files or
583 performing any other actions.
585 @item -E
586 @itemx --fatal-warnings
587 @cindex errors, fatal
588 @cindex fatal errors
589 Controls the effect of warnings.  If unspecified, then execution
590 continues and exit status is unaffected when a warning is printed.  If
591 specified exactly once, warnings become fatal; when one is issued,
592 execution continues, but the exit status will be non-zero.  If specified
593 multiple times, then execution halts with non-zero status the first time
594 a warning is issued.  The introduction of behavior levels is new to M4
595 1.4.9; for behavior consistent with earlier versions, you should specify
596 @option{-E} twice.
598 @item -i
599 @itemx --interactive
600 @itemx -e
601 Makes this invocation of @code{m4} interactive.  This means that all
602 output will be unbuffered, and interrupts will be ignored.  The
603 spelling @option{-e} exists for compatibility with other @code{m4}
604 implementations, and issues a warning because it may be withdrawn in a
605 future version of @acronym{GNU} M4.
607 @item -P
608 @itemx --prefix-builtins
609 Internally modify @emph{all} builtin macro names so they all start with
610 the prefix @samp{m4_}.  For example, using this option, one should write
611 @samp{m4_define} instead of @samp{define}, and @samp{m4___file__}
612 instead of @samp{__file__}.  This option has no effect if @option{-R}
613 is also specified.
615 @item -Q
616 @itemx --quiet
617 @itemx --silent
618 Suppress warnings, such as missing or superfluous arguments in macro
619 calls, or treating the empty string as zero.
621 @item --warn-macro-sequence@r{[}=@var{REGEXP}@r{]}
622 Issue a warning if the regular expression @var{REGEXP} has a non-empty
623 match in any macro definition (either by @code{define} or
624 @code{pushdef}).  Empty matches are ignored; therefore, supplying the
625 empty string as @var{REGEXP} disables any warning.  If the optional
626 @var{REGEXP} is not supplied, then the default regular expression is
627 @samp{\$\(@{[^@}]*@}\|[0-9][0-9]+\)} (a literal @samp{$} followed by
628 multiple digits or by an open brace), since these sequences will
629 change semantics in the default operation of @acronym{GNU} M4 2.0 (due
630 to a change in how more than 9 arguments in a macro definition will be
631 handled, @pxref{Arguments}).  Providing an alternate regular
632 expression can provide a useful reverse lookup feature of finding
633 where a macro is defined to have a given definition.
635 @item -W @var{REGEXP}
636 @itemx --word-regexp=@var{REGEXP}
637 Use @var{REGEXP} as an alternative syntax for macro names.  This
638 experimental option will not be present in all @acronym{GNU} @code{m4}
639 implementations (@pxref{Changeword}).
640 @end table
642 @node Preprocessor features
643 @section Command line options for preprocessor features
645 @cindex macro definitions, on the command line
646 @cindex command line, macro definitions on the
647 @cindex preprocessor features
648 Several options allow @code{m4} to behave more like a preprocessor.
649 Macro definitions and deletions can be made on the command line, the
650 search path can be altered, and the output file can track where the
651 input came from.  These features occur with the following options:
653 @table @code
654 @item -D @var{NAME}@r{[}=@var{VALUE}@r{]}
655 @itemx --define=@var{NAME}@r{[}=@var{VALUE}@r{]}
656 This enters @var{NAME} into the symbol table.  If @samp{=@var{VALUE}} is
657 missing, the value is taken to be the empty string.  The @var{VALUE} can
658 be any string, and the macro can be defined to take arguments, just as
659 if it was defined from within the input.  This option may be given more
660 than once; order with respect to file names is significant, and
661 redefining the same @var{NAME} loses the previous value.
663 @item -I @var{DIRECTORY}
664 @itemx --include=@var{DIRECTORY}
665 Make @code{m4} search @var{DIRECTORY} for included files that are not
666 found in the current working directory.  @xref{Search Path}, for more
667 details.  This option may be given more than once.
669 @item -s
670 @itemx --synclines
671 @cindex synchronization lines
672 @cindex location, input
673 @cindex input location
674 Generate synchronization lines, for use by the C preprocessor or other
675 similar tools.  Order is significant with respect to file names.  This
676 option is useful, for example, when @code{m4} is used as a
677 front end to a compiler.  Source file name and line number information
678 is conveyed by directives of the form @samp{#line @var{linenum}
679 "@var{file}"}, which are inserted as needed into the middle of the
680 output.  Such directives mean that the following line originated or was
681 expanded from the contents of input file @var{file} at line
682 @var{linenum}.  The @samp{"@var{file}"} part is often omitted when
683 the file name did not change from the previous directive.
685 Synchronization directives are always given on complete lines by
686 themselves.  When a synchronization discrepancy occurs in the middle of
687 an output line, the associated synchronization directive is delayed
688 until the next newline that does not occur in the middle of a quoted
689 string or comment.
691 @comment options: -s
692 @example
693 define(`twoline', `1
695 @result{}#line 2 "stdin"
696 @result{}
697 changecom(`/*', `*/')
698 @result{}
699 define(`comment', `/*1
700 2*/')
701 @result{}#line 5
702 @result{}
703 dnl no line
704 hello
705 @result{}#line 7
706 @result{}hello
707 twoline
708 @result{}1
709 @result{}#line 8
710 @result{}2
711 comment
712 @result{}/*1
713 @result{}2*/
714 one comment `two
715 three'
716 @result{}#line 10
717 @result{}one /*1
718 @result{}2*/ two
719 @result{}three
720 goodbye
721 @result{}#line 12
722 @result{}goodbye
723 @end example
725 @item -U @var{NAME}
726 @itemx --undefine=@var{NAME}
727 This deletes any predefined meaning @var{NAME} might have.  Obviously,
728 only predefined macros can be deleted in this way.  This option may be
729 given more than once; undefining a @var{NAME} that does not have a
730 definition is silently ignored.  Order is significant with respect to
731 file names.
732 @end table
734 @node Limits control
735 @section Command line options for limits control
737 There are some limits within @code{m4} that can be tuned.  For
738 compatibility, @code{m4} also accepts some options that control limits
739 in other implementations, but which are automatically unbounded (limited
740 only by your hardware and operating system constraints) in @acronym{GNU}
741 @code{m4}.
743 @table @code
744 @item -G
745 @itemx --traditional
746 Suppress all the extensions made in this implementation, compared to the
747 System V version.  @xref{Compatibility}, for a list of these.
749 @item -H @var{NUM}
750 @itemx --hashsize=@var{NUM}
751 Make the internal hash table for symbol lookup be @var{NUM} entries big.
752 For better performance, the number should be prime, but this is not
753 checked.  The default is 509 entries.  It should not be necessary to
754 increase this value, unless you define an excessive number of macros.
756 @item -L @var{NUM}
757 @itemx --nesting-limit=@var{NUM}
758 @cindex nesting limit
759 @cindex limit, nesting
760 Artificially limit the nesting of macro calls to @var{NUM} levels,
761 stopping program execution if this limit is ever exceeded.  When not
762 specified, nesting is limited to 1024 levels.  A value of zero means
763 unlimited; but then heavily nested code could potentially cause a stack
764 overflow.
766 The precise effect of this option might be more correctly associated
767 with textual nesting than dynamic recursion.  It has been useful
768 when some complex @code{m4} input was generated by mechanical means.
769 Most users would never need this option.  If shown to be obtrusive,
770 this option (which is still experimental) might well disappear.
772 @cindex rescanning
773 This option does @emph{not} have the ability to break endless
774 rescanning loops, since these do not necessarily consume much memory
775 or stack space.  Through clever usage of rescanning loops, one can
776 request complex, time-consuming computations from @code{m4} with useful
777 results.  Putting limitations in this area would break @code{m4} power.
778 There are many pathological cases: @w{@samp{define(`a', `a')a}} is
779 only the simplest example (but @pxref{Compatibility}).  Expecting @acronym{GNU}
780 @code{m4} to detect these would be a little like expecting a compiler
781 system to detect and diagnose endless loops: it is a quite @emph{hard}
782 problem in general, if not undecidable!
784 @item -B @var{NUM}
785 @itemx -S @var{NUM}
786 @itemx -T @var{NUM}
787 These options are present for compatibility with System V @code{m4}, but
788 do nothing in this implementation.  They may disappear in future
789 releases, and issue a warning to that effect.
791 @item -N @var{NUM}
792 @itemx --diversions=@var{NUM}
793 These options are present only for compatibility with previous
794 versions of @acronym{GNU} @code{m4}, and were controlling the number of
795 possible diversions which could be used at the same time.  They do nothing,
796 because there is no fixed limit anymore.  They may disappear in future
797 releases, and issue a warning to that effect.
798 @end table
800 @node Frozen state
801 @section Command line options for frozen state
803 @acronym{GNU} @code{m4} comes with a feature of freezing internal state
804 (@pxref{Frozen files}).  This can be used to speed up @code{m4}
805 execution when reusing a common initialization script.
807 @table @code
808 @item -F @var{FILE}
809 @itemx --freeze-state=@var{FILE}
810 Once execution is finished, write out the frozen state on the specified
811 @var{FILE}.  It is conventional, but not required, for @var{FILE} to end
812 in @samp{.m4f}.
814 @item -R @var{FILE}
815 @itemx --reload-state=@var{FILE}
816 Before execution starts, recover the internal state from the specified
817 frozen @var{FILE}.  The options @option{-D}, @option{-U}, and
818 @option{-t} take effect after state is reloaded, but before the input
819 files are read.
820 @end table
822 @node Debugging options
823 @section Command line options for debugging
825 Finally, there are several options for aiding in debugging @code{m4}
826 scripts.
828 @table @code
829 @item -d@r{[}@var{FLAGS}@r{]}
830 @itemx --debug@r{[}=@var{FLAGS}@r{]}
831 Set the debug-level according to the flags @var{FLAGS}.  The debug-level
832 controls the format and amount of information presented by the debugging
833 functions.  @xref{Debug Levels}, for more details on the format and
834 meaning of @var{FLAGS}.  If omitted, @var{FLAGS} defaults to @samp{aeq}.
836 @item --debugfile=@var{FILE}
837 @itemx -o @var{FILE}
838 @itemx --error-output=@var{FILE}
839 Redirect @code{dumpdef} output, debug messages, and trace output to the
840 named @var{FILE}.  Warnings, error messages, and @code{errprint} output
841 are still printed to standard error.  If unspecified, debug output goes
842 to standard error; if empty, debug output is discarded.  @xref{Debug
843 Output}, for more details.  The spellings @option{-o} and
844 @option{--error-output} are misleading and inconsistent with other
845 @acronym{GNU} tools; for now they are silently accepted as synonyms of
846 @option{--debugfile}, but in a future version of M4, using them will
847 cause a warning to be issued.
849 @item -l @var{NUM}
850 @itemx --arglength=@var{NUM}
851 Restrict the size of the output generated by macro tracing to @var{NUM}
852 characters per trace line.  If unspecified or zero, output is
853 unlimited.  @xref{Debug Levels}, for more details.
855 @item -t @var{NAME}
856 @itemx --trace=@var{NAME}
857 This enables tracing for the macro @var{NAME}, at any point where it is
858 defined.  @var{NAME} need not be defined when this option is given.
859 This option may be given more than once, and order is significant with
860 respect to file names.  @xref{Trace}, for more details.
861 @end table
863 @node Command line files
864 @section Specifying input files on the command line
866 @cindex command line, file names on the
867 @cindex file names, on the command line
868 The remaining arguments on the command line are taken to be input file
869 names.  If no names are present, standard input is read.  A file
870 name of @file{-} is taken to mean standard input.  It is
871 conventional, but not required, for input files to end in @samp{.m4}.
873 The input files are read in the sequence given.  Standard input can be
874 read more than once, so the file name @file{-} may appear multiple times
875 on the command line; this makes a difference when input is from a
876 terminal or other special file type.  It is an error if an input file
877 ends in the middle of argument collection, a comment, or a quoted
878 string.
880 The options @option{--define} (@option{-D}), @option{--undefine}
881 (@option{-U}), @option{--synclines} (@option{-s}), and @option{--trace}
882 (@option{-t}) only take effect after processing input from any file
883 names that occur earlier on the command line.  For example, assume the
884 file @file{foo} contains:
886 @comment ignore
887 @example
888 $ @kbd{cat foo}
890 @end example
892 The text @samp{bar} can then be redefined over multiple uses of
893 @file{foo}:
895 @comment options: -Dbar=hello foo -Dbar=world foo
896 @example
897 $ @kbd{m4 -Dbar=hello foo -Dbar=world foo}
898 @result{}hello
899 @result{}world
900 @end example
902 If none of the input files invoked @code{m4exit} (@pxref{M4exit}), the
903 exit status of @code{m4} will be 0 for success, 1 for general failure
904 (such as problems with reading an input file), and 63 for version
905 mismatch (@pxref{Using frozen files}).
907 If you need to read a file whose name starts with a @file{-}, you can
908 specify it as @samp{./-file}, or use @option{--} to mark the end of
909 options.
911 @node Syntax
912 @chapter Lexical and syntactic conventions
914 @cindex input tokens
915 @cindex tokens
916 As @code{m4} reads its input, it separates it into @dfn{tokens}.  A
917 token is either a name, a quoted string, or any single character, that
918 is not a part of either a name or a string.  Input to @code{m4} can also
919 contain comments.  @acronym{GNU} @code{m4} does not yet understand
920 multibyte locales; all operations are byte-oriented rather than
921 character-oriented (although if your locale uses a single byte
922 encoding, such as @sc{ISO-8859-1}, you will not notice a difference).
923 However, @code{m4} is eight-bit clean, so you can
924 use non-@sc{ascii} characters in quoted strings (@pxref{Changequote}),
925 comments (@pxref{Changecom}), and macro names (@pxref{Indir}), with the
926 exception of the @sc{nul} character (the zero byte @samp{'\0'}).
928 @ignore
929 @comment FIXME - each builtin needs to document how it handles NUL, then
930 @comment update the above paragraph to mention that NUL is now handled
931 @comment transparently.  Meanwhile, test that we don't regress.
933 @comment xout: null.out
934 @comment xerr: null.err
935 @example
936 define(`m4exit')include(`null.m4')dnl
937 @end example
939 @comment status: 2
940 @example
941 include(`null.m4')
942 @result{}# This file tests m4 behavior on NUL bytes.
943 @end example
944 @end ignore
946 @menu
947 * Names::                       Macro names
948 * Quoted strings::              Quoting input to @code{m4}
949 * Comments::                    Comments in @code{m4} input
950 * Other tokens::                Other kinds of input tokens
951 * Input processing::            How @code{m4} copies input to output
952 @end menu
954 @node Names
955 @section Macro names
957 @cindex names
958 @cindex words
959 A name is any sequence of letters, digits, and the character @samp{_}
960 (underscore), where the first character is not a digit.  @code{m4} will
961 use the longest such sequence found in the input.  If a name has a
962 macro definition, it will be subject to macro expansion
963 (@pxref{Macros}).  Names are case-sensitive.
965 Examples of legal names are: @samp{foo}, @samp{_tmp}, and @samp{name01}.
967 @node Quoted strings
968 @section Quoting input to @code{m4}
970 @cindex quoted string
971 @cindex string, quoted
972 A quoted string is a sequence of characters surrounded by quote
973 strings, defaulting to
974 @samp{`} and @samp{'}, where the nested begin and end quotes within the
975 string are balanced.  The value of a string token is the text, with one
976 level of quotes stripped off.  Thus
978 @comment ignore
979 @example
981 @result{}
982 @end example
984 @noindent
985 is the empty string, and double-quoting turns into single-quoting.
987 @comment ignore
988 @example
989 ``quoted''
990 @result{}`quoted'
991 @end example
993 The quote characters can be changed at any time, using the builtin macro
994 @code{changequote}.  @xref{Changequote}, for more information.
996 @node Comments
997 @section Comments in @code{m4} input
999 @cindex comments
1000 Comments in @code{m4} are normally delimited by the characters @samp{#}
1001 and newline.  All characters between the comment delimiters are ignored,
1002 but the entire comment (including the delimiters) is passed through to
1003 the output---comments are @emph{not} discarded by @code{m4}.
1005 Comments cannot be nested, so the first newline after a @samp{#} ends
1006 the comment.  The commenting effect of the begin-comment string
1007 can be inhibited by quoting it.
1009 @example
1010 $ @kbd{m4}
1011 `quoted text' # `commented text'
1012 @result{}quoted text # `commented text'
1013 `quoting inhibits' `#' `comments'
1014 @result{}quoting inhibits # comments
1015 @end example
1017 The comment delimiters can be changed to any string at any time, using
1018 the builtin macro @code{changecom}.  @xref{Changecom}, for more
1019 information.
1021 @node Other tokens
1022 @section Other kinds of input tokens
1024 @cindex tokens, special
1025 Any character, that is neither a part of a name, nor of a quoted string,
1026 nor a comment, is a token by itself.  When not in the context of macro
1027 expansion, all of these tokens are just copied to output.  However,
1028 during macro expansion, whitespace characters (space, tab, newline,
1029 formfeed, carriage return, vertical tab), parentheses (@samp{(} and
1030 @samp{)}), comma (@samp{,}), and dollar (@samp{$}) have additional
1031 roles, explained later.
1033 @node Input processing
1034 @section How @code{m4} copies input to output
1036 As @code{m4} reads the input token by token, it will copy each token
1037 directly to the output immediately.
1039 The exception is when it finds a word with a macro definition.  In that
1040 case @code{m4} will calculate the macro's expansion, possibly reading
1041 more input to get the arguments.  It then inserts the expansion in front
1042 of the remaining input.  In other words, the resulting text from a macro
1043 call will be read and parsed into tokens again.
1045 @code{m4} expands a macro as soon as possible.  If it finds a macro call
1046 when collecting the arguments to another, it will expand the second call
1047 first.  This process continues until there are no more macro calls to
1048 expand and all the input has been consumed.
1050 For a running example, examine how @code{m4} handles this input:
1052 @comment ignore
1053 @example
1054 format(`Result is %d', eval(`2**15'))
1055 @end example
1057 @noindent
1058 First, @code{m4} sees that the token @samp{format} is a macro name, so
1059 it collects the tokens @samp{(}, @samp{`Result is %d'}, @samp{,},
1060 and @samp{@w{ }}, before encountering another potential macro.  Sure
1061 enough, @samp{eval} is a macro name, so the nested argument collection
1062 picks up @samp{(}, @samp{`2**15'}, and @samp{)}, invoking the eval macro
1063 with the lone argument of @samp{2**15}.  The expansion of
1064 @samp{eval(2**15)} is @samp{32768}, which is then rescanned as the five
1065 tokens @samp{3}, @samp{2}, @samp{7}, @samp{6}, and @samp{8}; and
1066 combined with the next @samp{)}, the format macro now has all its
1067 arguments, as if the user had typed:
1069 @comment ignore
1070 @example
1071 format(`Result is %d', 32768)
1072 @end example
1074 @noindent
1075 The format macro expands to @samp{Result is 32768}, and we have another
1076 round of scanning for the tokens @samp{Result}, @samp{@w{ }},
1077 @samp{is}, @samp{@w{ }}, @samp{3}, @samp{2}, @samp{7}, @samp{6}, and
1078 @samp{8}.  None of these are macros, so the final output is
1080 @comment ignore
1081 @example
1082 @result{}Result is 32768
1083 @end example
1085 As a more complicated example, we will contrast an actual code
1086 example from the Gnulib project@footnote{Derived from a patch in
1087 @uref{http://lists.gnu.org/archive/html/bug-gnulib/@/2007-01/@/msg00389.html},
1088 and a followup patch in
1089 @uref{http://lists.gnu.org/archive/html/bug-gnulib/@/2007-02/@/msg00000.html}},
1090 showing both a buggy approach and the desired results.  The user desires
1091 to output a shell assignment statement that takes its argument and turns
1092 it into a shell variable by converting it to uppercase and prepending a
1093 prefix.  The original attempt looks like this:
1095 @example
1096 changequote([,])dnl
1097 define([gl_STRING_MODULE_INDICATOR],
1098   [
1099     dnl comment
1100     GNULIB_]translit([$1],[a-z],[A-Z])[=1
1101   ])dnl
1102   gl_STRING_MODULE_INDICATOR([strcase])
1103 @result{} @w{ }
1104 @result{}        GNULIB_strcase=1
1105 @result{} @w{ }
1106 @end example
1108 Oops -- the argument did not get capitalized.  And although the manual
1109 is not able to easily show it, both lines that appear empty actually
1110 contain two trailing spaces.  By stepping through the parse, it is easy
1111 to see what happened.  First, @code{m4} sees the token
1112 @samp{changequote}, which it recognizes as a macro, followed by
1113 @samp{(}, @samp{[}, @samp{,}, @samp{]}, and @samp{)} to form the
1114 argument list.  The macro expands to the empty string, but changes the
1115 quoting characters to something more useful for generating shell code
1116 (unbalanced @samp{`} and @samp{'} appear all the time in shell scripts,
1117 but unbalanced @samp{[]} tend to be rare).  Also in the first line,
1118 @code{m4} sees the token @samp{dnl}, which it recognizes as a builtin
1119 macro that consumes the rest of the line, resulting in no output for
1120 that line.
1122 The second line starts a macro definition.  @code{m4} sees the token
1123 @samp{define}, which it recognizes as a macro, followed by a @samp{(},
1124 @samp{[gl_STRING_MODULE_INDICATOR]}, and @samp{,}.  Because an unquoted
1125 comma was encountered, the first argument is known to be the expansion
1126 of the single-quoted string token, or @samp{gl_STRING_MODULE_INDICATOR}.
1127 Next, @code{m4} sees @samp{@key{NL}}, @samp{ }, and @samp{ }, but this
1128 whitespace is discarded as part of argument collection.  Then comes a
1129 rather lengthy single-quoted string token, @samp{[@key{NL}@ @ @ @ dnl
1130 comment@key{NL}@ @ @ @ GNULIB_]}.  This is followed by the token
1131 @samp{translit}, which @code{m4} recognizes as a macro name, so a nested
1132 macro expansion has started.
1134 The arguments to the @code{translit} are found by the tokens @samp{(},
1135 @samp{[$1]}, @samp{,}, @samp{[a-z]}, @samp{,}, @samp{[A-Z]}, and finally
1136 @samp{)}.  All three string arguments are expanded (or in other words,
1137 the quotes are stripped), and since neither @samp{$} nor @samp{1} need
1138 capitalization, the result of the macro is @samp{$1}.  This expansion is
1139 rescanned, resulting in the two literal characters @samp{$} and
1140 @samp{1}.
1142 Scanning of the outer macro resumes, and picks up with
1143 @samp{[=1@key{NL}@ @ ]}, and finally @samp{)}.  The collected pieces of
1144 expanded text are concatenated, with the end result that the macro
1145 @samp{gl_STRING_MODULE_INDICATOR} is now defined to be the sequence
1146 @samp{@key{NL}@ @ @ @ dnl comment@key{NL}@ @ @ @ GNULIB_$1=1@key{NL}@ @ }.
1147 Once again, @samp{dnl} is recognized and avoids a newline in the output.
1149 The final line is then parsed, beginning with @samp{ } and @samp{ }
1150 that are output literally.  Then @samp{gl_STRING_MODULE_INDICATOR} is
1151 recognized as a macro name, with an argument list of @samp{(},
1152 @samp{[strcase]}, and @samp{)}.  Since the definition of the macro
1153 contains the sequence @samp{$1}, that sequence is replaced with the
1154 argument @samp{strcase} prior to starting the rescan.  The rescan sees
1155 @samp{@key{NL}} and four spaces, which are output literally, then
1156 @samp{dnl}, which discards the text @samp{ comment@key{NL}}.  Next
1157 comes four more spaces, also output literally, and the token
1158 @samp{GNULIB_strcase}, which resulted from the earlier parameter
1159 substitution.  Since that is not a macro name, it is output literally,
1160 followed by the literal tokens @samp{=}, @samp{1}, @samp{@key{NL}}, and
1161 two more spaces.  Finally, the original @samp{@key{NL}} seen after the
1162 macro invocation is scanned and output literally.
1164 Now for a corrected approach.  This rearranges the use of newlines and
1165 whitespace so that less whitespace is output (which, although harmless
1166 to shell scripts, can be visually unappealing), and fixes the quoting
1167 issues so that the capitalization occurs when the macro
1168 @samp{gl_STRING_MODULE_INDICATOR} is invoked, rather then when it is
1169 defined.
1171 @example
1172 changequote([,])dnl
1173 define([gl_STRING_MODULE_INDICATOR],
1174   [dnl comment
1175   GNULIB_[]translit([$1], [a-z], [A-Z])=1dnl
1176 ])dnl
1177   gl_STRING_MODULE_INDICATOR([strcase])
1178 @result{}    GNULIB_STRCASE=1
1179 @end example
1181 The parsing of the first line is unchanged.  The second line sees the
1182 name of the macro to define, then sees the discarded @samp{@key{NL}}
1183 and two spaces, as before.  But this time, the next token is
1184 @samp{[dnl comment@key{NL}@ @ GNULIB_[]translit([$1], [a-z],
1185 [A-Z])=1dnl@key{NL}]}, which includes nested quotes, followed by
1186 @samp{)} to end the macro definition and @samp{dnl} to skip the
1187 newline.  No early expansion of @code{translit} occurs, so the entire
1188 string becomes the definition of the macro.
1190 The final line is then parsed, beginning with two spaces that are
1191 output literally, and an invocation of
1192 @code{gl_STRING_MODULE_INDICATOR} with the argument @samp{strcase}.
1193 Again, the @samp{$1} in the macro definition is substituted prior to
1194 rescanning.  Rescanning first encounters @samp{dnl}, and discards
1195 @samp{ comment@key{NL}}.  Then two spaces are output literally.  Next
1196 comes the token @samp{GNULIB_}, but that is not a macro, so it is
1197 output literally.  The token @samp{[]} is an empty string, so it does
1198 not affect output.  Then the token @samp{translit} is encountered.
1200 This time, the arguments to @code{translit} are parsed as @samp{(},
1201 @samp{[strcase]}, @samp{,}, @samp{ }, @samp{[a-z]}, @samp{,}, @samp{ },
1202 @samp{[A-Z]}, and @samp{)}.  The two spaces are discarded, and the
1203 translit results in the desired result @samp{STRCASE}.  This is
1204 rescanned, but since it is not a macro name, it is output literally.
1205 Then the scanner sees @samp{=} and @samp{1}, which are output
1206 literally, followed by @samp{dnl} which discards the rest of the
1207 definition of @code{gl_STRING_MODULE_INDICATOR}.  The newline at the
1208 end of output is the literal @samp{@key{NL}} that appeared after the
1209 invocation of the macro.
1211 The order in which @code{m4} expands the macros can be further explored
1212 using the trace facilities of @acronym{GNU} @code{m4} (@pxref{Trace}).
1214 @node Macros
1215 @chapter How to invoke macros
1217 This chapter covers macro invocation, macro arguments and how macro
1218 expansion is treated.
1220 @menu
1221 * Invocation::                  Macro invocation
1222 * Inhibiting Invocation::       Preventing macro invocation
1223 * Macro Arguments::             Macro arguments
1224 * Quoting Arguments::           On Quoting Arguments to macros
1225 * Macro expansion::             Expanding macros
1226 @end menu
1228 @node Invocation
1229 @section Macro invocation
1231 @cindex macro invocation
1232 @cindex invoking macros
1233 Macro invocations has one of the forms
1235 @comment ignore
1236 @example
1237 name
1238 @end example
1240 @noindent
1241 which is a macro invocation without any arguments, or
1243 @comment ignore
1244 @example
1245 name(arg1, arg2, @dots{}, arg@var{n})
1246 @end example
1248 @noindent
1249 which is a macro invocation with @var{n} arguments.  Macros can have any
1250 number of arguments.  All arguments are strings, but different macros
1251 might interpret the arguments in different ways.
1253 The opening parenthesis @emph{must} follow the @var{name} directly, with
1254 no spaces in between.  If it does not, the macro is called with no
1255 arguments at all.
1257 For a macro call to have no arguments, the parentheses @emph{must} be
1258 left out.  The macro call
1260 @comment ignore
1261 @example
1262 name()
1263 @end example
1265 @noindent
1266 is a macro call with one argument, which is the empty string, not a call
1267 with no arguments.
1269 @node Inhibiting Invocation
1270 @section Preventing macro invocation
1272 An innovation of the @code{m4} language, compared to some of its
1273 predecessors (like Stratchey's @code{GPM}, for example), is the ability
1274 to recognize macro calls without resorting to any special, prefixed
1275 invocation character.  While generally useful, this feature might
1276 sometimes be the source of spurious, unwanted macro calls.  So, @acronym{GNU}
1277 @code{m4} offers several mechanisms or techniques for inhibiting the
1278 recognition of names as macro calls.
1280 @cindex @acronym{GNU} extensions
1281 @cindex blind macro
1282 @cindex macro, blind
1283 First of all, many builtin macros cannot meaningfully be called without
1284 arguments.  As a @acronym{GNU} extension, for any of these macros,
1285 whenever an opening parenthesis does not immediately follow their name,
1286 the builtin macro call is not triggered.  This solves the most usual
1287 cases, like for @samp{include} or @samp{eval}.  Later in this document,
1288 the sentence ``This macro is recognized only with parameters'' refers to
1289 this specific provision of @acronym{GNU} M4, also known as a blind
1290 builtin macro.  For the builtins defined by @acronym{POSIX} that bear
1291 this disclaimer, @acronym{POSIX} specifically states that invoking those
1292 builtins without arguments is unspecified, because many other
1293 implementations simply invoke the builtin as though it were given one
1294 empty argument instead.
1296 @example
1297 $ @kbd{m4}
1298 eval
1299 @result{}eval
1300 eval(`1')
1301 @result{}1
1302 @end example
1304 There is also a command line option (@option{--prefix-builtins}, or
1305 @option{-P}, @pxref{Operation modes, , Invoking m4}) that renames all
1306 builtin macros with a prefix of @samp{m4_} at startup.  The option has
1307 no effect whatsoever on user defined macros.  For example, with this option,
1308 one has to write @code{m4_dnl} and even @code{m4_m4exit}.  It also has
1309 no effect on whether a macro requires parameters.
1311 @comment options: -P
1312 @example
1313 $ @kbd{m4 -P}
1314 eval
1315 @result{}eval
1316 eval(`1')
1317 @result{}eval(1)
1318 m4_eval
1319 @result{}m4_eval
1320 m4_eval(`1')
1321 @result{}1
1322 @end example
1324 Another alternative is to redefine problematic macros to a name less
1325 likely to cause conflicts, @xref{Definitions}.
1327 If your version of @acronym{GNU} @code{m4} has the @code{changeword} feature
1328 compiled in, it offers far more flexibility in specifying the
1329 syntax of macro names, both builtin or user-defined.  @xref{Changeword},
1330 for more information on this experimental feature.
1332 Of course, the simplest way to prevent a name from being interpreted
1333 as a call to an existing macro is to quote it.  The remainder of
1334 this section studies a little more deeply how quoting affects macro
1335 invocation, and how quoting can be used to inhibit macro invocation.
1337 Even if quoting is usually done over the whole macro name, it can also
1338 be done over only a few characters of this name (provided, of course,
1339 that the unquoted portions are not also a macro).  It is also possible
1340 to quote the empty string, but this works only @emph{inside} the name.
1341 For example:
1343 @example
1344 `divert'
1345 @result{}divert
1346 `d'ivert
1347 @result{}divert
1348 di`ver't
1349 @result{}divert
1350 div`'ert
1351 @result{}divert
1352 @end example
1354 @noindent
1355 all yield the string @samp{divert}.  While in both:
1357 @example
1358 `'divert
1359 @result{}
1360 divert`'
1361 @result{}
1362 @end example
1364 @noindent
1365 the @code{divert} builtin macro will be called, which expands to the
1366 empty string.
1368 @cindex rescanning
1369 The output of macro evaluations is always rescanned.  In the following
1370 example, the input @samp{x`'y} yields the string @samp{bCD}, exactly as
1371 if @code{m4}
1372 has been given @w{@samp{substr(ab`'cde, `1', `3')}} as input:
1374 @example
1375 define(`cde', `CDE')
1376 @result{}
1377 define(`x', `substr(ab')
1378 @result{}
1379 define(`y', `cde, `1', `3')')
1380 @result{}
1381 x`'y
1382 @result{}bCD
1383 @end example
1385 @ignore
1386 @comment Similar, but with argument references, to ensure good test
1387 @comment coverage.
1388 @example
1389 define(`x1', `len(`$1'')
1390 @result{}
1391 define(`y1', ``$1')')
1392 @result{}
1393 x1(`01234567890123456789')y1(`98765432109876543210')
1394 @result{}40
1395 @end example
1396 @end ignore
1398 Unquoted strings on either side of a quoted string are subject to
1399 being recognized as macro names.  In the following example, quoting the
1400 empty string allows for the second @code{macro} to be recognized as such:
1402 @example
1403 define(`macro', `m')
1404 @result{}
1405 macro(`m')macro
1406 @result{}mmacro
1407 macro(`m')`'macro
1408 @result{}mm
1409 @end example
1411 Quoting may prevent recognizing as a macro name the concatenation of a
1412 macro expansion with the surrounding characters.  In this example:
1414 @example
1415 define(`macro', `di$1')
1416 @result{}
1417 macro(`v')`ert'
1418 @result{}divert
1419 macro(`v')ert
1420 @result{}
1421 @end example
1423 @noindent
1424 the input will produce the string @samp{divert}.  When the quotes were
1425 removed, the @code{divert} builtin was called instead.
1427 @node Macro Arguments
1428 @section Macro arguments
1430 @cindex macros, arguments to
1431 @cindex arguments to macros
1432 When a name is seen, and it has a macro definition, it will be expanded
1433 as a macro.
1435 If the name is followed by an opening parenthesis, the arguments will be
1436 collected before the macro is called.  If too few arguments are
1437 supplied, the missing arguments are taken to be the empty string.
1438 However, some builtins are documented to behave differently for a
1439 missing optional argument than for an explicit empty string.  If there
1440 are too many arguments, the excess arguments are ignored.  Unquoted
1441 leading whitespace is stripped off all arguments, but whitespace
1442 generated by a macro expansion or occurring after a macro that expanded
1443 to an empty string remains intact.  Whitespace includes space, tab,
1444 newline, carriage return, vertical tab, and formfeed.
1446 @example
1447 define(`macro', `$1')
1448 @result{}
1449 macro( unquoted leading space lost)
1450 @result{}unquoted leading space lost
1451 macro(` quoted leading space kept')
1452 @result{} quoted leading space kept
1453 macro(
1454  divert `unquoted space kept after expansion')
1455 @result{} unquoted space kept after expansion
1456 macro(macro(`
1457 ')`whitespace from expansion kept')
1458 @result{}
1459 @result{}whitespace from expansion kept
1460 macro(`unquoted trailing whitespace kept'
1462 @result{}unquoted trailing whitespace kept
1463 @result{}
1464 @end example
1466 @cindex warnings, suppressing
1467 @cindex suppressing warnings
1468 Normally @code{m4} will issue warnings if a builtin macro is called
1469 with an inappropriate number of arguments, but it can be suppressed with
1470 the @option{--quiet} command line option (or @option{--silent}, or
1471 @option{-Q}, @pxref{Operation modes, , Invoking m4}).  For user
1472 defined macros, there is no check of the number of arguments given.
1474 @example
1475 $ @kbd{m4}
1476 index(`abc')
1477 @error{}m4:stdin:1: Warning: index: too few arguments: 1 < 2
1478 @result{}0
1479 index(`abc',)
1480 @result{}0
1481 index(`abc', `b', `ignored')
1482 @error{}m4:stdin:3: Warning: index: extra arguments ignored: 3 > 2
1483 @result{}1
1484 @end example
1486 @comment options: -Q
1487 @example
1488 $ @kbd{m4 -Q}
1489 index(`abc')
1490 @result{}0
1491 index(`abc',)
1492 @result{}0
1493 index(`abc', `b', `ignored')
1494 @result{}1
1495 @end example
1497 Macros are expanded normally during argument collection, and whatever
1498 commas, quotes and parentheses that might show up in the resulting
1499 expanded text will serve to define the arguments as well.  Thus, if
1500 @var{foo} expands to @samp{, b, c}, the macro call
1502 @comment ignore
1503 @example
1504 bar(a foo, d)
1505 @end example
1507 @noindent
1508 is a macro call with four arguments, which are @samp{a }, @samp{b},
1509 @samp{c} and @samp{d}.  To understand why the first argument contains
1510 whitespace, remember that unquoted leading whitespace is never part
1511 of an argument, but trailing whitespace always is.
1513 It is possible for a macro's definition to change during argument
1514 collection, in which case the expansion uses the definition that was in
1515 effect at the time the opening @samp{(} was seen.
1517 @example
1518 define(`f', `1')
1519 @result{}
1520 f(define(`f', `2'))
1521 @result{}1
1523 @result{}2
1524 @end example
1526 It is an error if the end of file occurs while collecting arguments.
1528 @comment status: 1
1529 @example
1530 hello world
1531 @result{}hello world
1532 define(
1534 @error{}m4:stdin:2: define: end of file in argument list
1535 @end example
1537 @node Quoting Arguments
1538 @section On Quoting Arguments to macros
1540 @cindex quoted macro arguments
1541 @cindex macros, quoted arguments to
1542 @cindex arguments, quoted macro
1543 Each argument has unquoted leading whitespace removed.  Within each
1544 argument, all unquoted parentheses must match.  For example, if
1545 @var{foo} is a macro,
1547 @comment ignore
1548 @example
1549 foo(() (`(') `(')
1550 @end example
1552 @noindent
1553 is a macro call, with one argument, whose value is @samp{() (() (}.
1554 Commas separate arguments, except when they occur inside quotes,
1555 comments, or unquoted parentheses.  @xref{Pseudo Arguments}, for
1556 examples.
1558 It is common practice to quote all arguments to macros, unless you are
1559 sure you want the arguments expanded.  Thus, in the above
1560 example with the parentheses, the `right' way to do it is like this:
1562 @comment ignore
1563 @example
1564 foo(`() (() (')
1565 @end example
1567 @cindex quoting rule of thumb
1568 @cindex rule of thumb, quoting
1569 It is, however, in certain cases necessary (because nested expansion
1570 must occur to create the arguments for the outer macro) or convenient
1571 (because it uses fewer characters) to leave out quotes for some
1572 arguments, and there is nothing wrong in doing it.  It just makes life a
1573 bit harder, if you are not careful to follow a consistent quoting style.
1574 For consistency, this manual follows the rule of thumb that each layer
1575 of parentheses introduces another layer of single quoting, except when
1576 showing the consequences of quoting rules.  This is done even when the
1577 quoted string cannot be a macro, such as with integers when you have not
1578 changed the syntax via @code{changeword} (@pxref{Changeword}).
1580 The quoting rule of thumb of one level of quoting per parentheses has a
1581 nice property: when a macro name appears inside parentheses, you can
1582 determine when it will be expanded.  If it is not quoted, it will be
1583 expanded prior to the outer macro, so that its expansion becomes the
1584 argument.  If it is single-quoted, it will be expanded after the outer
1585 macro.  And if it is double-quoted, it will be used as literal text
1586 instead of a macro name.
1588 @example
1589 define(`active', `ACT, IVE')
1590 @result{}
1591 define(`show', `$1 $1')
1592 @result{}
1593 show(active)
1594 @result{}ACT ACT
1595 show(`active')
1596 @result{}ACT, IVE ACT, IVE
1597 show(``active'')
1598 @result{}active active
1599 @end example
1601 @node Macro expansion
1602 @section Macro expansion
1604 @cindex macros, expansion of
1605 @cindex expansion of macros
1606 When the arguments, if any, to a macro call have been collected, the
1607 macro is expanded, and the expansion text is pushed back onto the input
1608 (unquoted), and reread.  The expansion text from one macro call might
1609 therefore result in more macros being called, if the calls are included,
1610 completely or partially, in the first macro calls' expansion.
1612 Taking a very simple example, if @var{foo} expands to @samp{bar}, and
1613 @var{bar} expands to @samp{Hello}, the input
1615 @comment options: -Dbar=Hello -Dfoo=bar
1616 @example
1617 $ @kbd{m4 -Dbar=Hello -Dfoo=bar}
1619 @result{}Hello
1620 @end example
1622 @noindent
1623 will expand first to @samp{bar}, and when this is reread and
1624 expanded, into @samp{Hello}.
1626 @ignore
1627 @comment not worth documenting, but test that the command line can
1628 @comment define macros that take parameters
1630 @comment options: -Dfoo -Decho=$@
1631 @example
1632 $ @kbd{m4 -Dfoo -Decho='$@'}
1634 @result{}
1635 foo(`silently ignored')
1636 @result{}
1637 echo(`1', `2')
1638 @result{}1,2
1639 @end example
1640 @end ignore
1642 @node Definitions
1643 @chapter How to define new macros
1645 @cindex macros, how to define new
1646 @cindex defining new macros
1647 Macros can be defined, redefined and deleted in several different ways.
1648 Also, it is possible to redefine a macro without losing a previous
1649 value, and bring back the original value at a later time.
1651 @menu
1652 * Define::                      Defining a new macro
1653 * Arguments::                   Arguments to macros
1654 * Pseudo Arguments::            Special arguments to macros
1655 * Undefine::                    Deleting a macro
1656 * Defn::                        Renaming macros
1657 * Pushdef::                     Temporarily redefining macros
1659 * Indir::                       Indirect call of macros
1660 * Builtin::                     Indirect call of builtins
1661 @end menu
1663 @node Define
1664 @section Defining a macro
1666 The normal way to define or redefine macros is to use the builtin
1667 @code{define}:
1669 @deffn Builtin define (@var{name}, @ovar{expansion})
1670 Defines @var{name} to expand to @var{expansion}.  If
1671 @var{expansion} is not given, it is taken to be empty.
1673 The expansion of @code{define} is void.
1674 The macro @code{define} is recognized only with parameters.
1675 @end deffn
1677 The following example defines the macro @var{foo} to expand to the text
1678 @samp{Hello World.}.
1680 @example
1681 define(`foo', `Hello world.')
1682 @result{}
1684 @result{}Hello world.
1685 @end example
1687 The empty line in the output is there because the newline is not
1688 a part of the macro definition, and it is consequently copied to
1689 the output.  This can be avoided by use of the macro @code{dnl}.
1690 @xref{Dnl}, for details.
1692 The first argument to @code{define} should be quoted; otherwise, if the
1693 macro is already defined, you will be defining a different macro.  This
1694 example shows the problems with underquoting, since we did not want to
1695 redefine @code{one}:
1697 @example
1698 define(foo, one)
1699 @result{}
1700 define(foo, two)
1701 @result{}
1703 @result{}two
1704 @end example
1706 @cindex @acronym{GNU} extensions
1707 @acronym{GNU} @code{m4} normally replaces only the @emph{topmost}
1708 definition of a macro if it has several definitions from @code{pushdef}
1709 (@pxref{Pushdef}).  Some other implementations of @code{m4} replace all
1710 definitions of a macro with @code{define}.  @xref{Incompatibilities},
1711 for more details.
1713 As a @acronym{GNU} extension, the first argument to @code{define} does
1714 not have to be a simple word.
1715 It can be any text string, even the empty string.  A macro with a
1716 non-standard name cannot be invoked in the normal way, as the name is
1717 not recognized.  It can only be referenced by the builtins @code{indir}
1718 (@pxref{Indir}) and @code{defn} (@pxref{Defn}).
1720 @cindex arrays
1721 Arrays and associative arrays can be simulated by using non-standard
1722 macro names.
1724 @deffn Composite array (@var{index})
1725 @deffnx Composite array_set (@var{index}, @ovar{value})
1726 Provide access to entries within an array.  @code{array} reads the entry
1727 at location @var{index}, and @code{array_set} assigns @var{value} to
1728 location @var{index}.
1729 @end deffn
1731 @example
1732 define(`array', `defn(format(``array[%d]'', `$1'))')
1733 @result{}
1734 define(`array_set', `define(format(``array[%d]'', `$1'), `$2')')
1735 @result{}
1736 array_set(`4', `array element no. 4')
1737 @result{}
1738 array_set(`17', `array element no. 17')
1739 @result{}
1740 array(`4')
1741 @result{}array element no. 4
1742 array(eval(`10 + 7'))
1743 @result{}array element no. 17
1744 @end example
1746 Change the @samp{%d} to @samp{%s} and it is an associative array.
1748 @node Arguments
1749 @section Arguments to macros
1751 @cindex macros, arguments to
1752 @cindex arguments to macros
1753 Macros can have arguments.  The @var{n}th argument is denoted by
1754 @code{$n} in the expansion text, and is replaced by the @var{n}th actual
1755 argument, when the macro is expanded.  Replacement of arguments happens
1756 before rescanning, regardless of how many nesting levels of quoting
1757 appear in the expansion.  Here is an example of a macro with
1758 two arguments.
1760 @deffn Composite exch (@var{arg1}, @var{arg2})
1761 Expands to @var{arg2} followed by @var{arg1}, effectively exchanging
1762 their order.
1763 @end deffn
1765 @example
1766 define(`exch', `$2, $1')
1767 @result{}
1768 exch(`arg1', `arg2')
1769 @result{}arg2, arg1
1770 @end example
1772 This can be used, for example, if you like the arguments to
1773 @code{define} to be reversed.
1775 @example
1776 define(`exch', `$2, $1')
1777 @result{}
1778 define(exch(``expansion text'', ``macro''))
1779 @result{}
1780 macro
1781 @result{}expansion text
1782 @end example
1784 @xref{Quoting Arguments}, for an explanation of the double quotes.
1785 (You should try and improve this example so that clients of @code{exch}
1786 do not have to double quote; or @pxref{Improved exch, , Answers}).
1788 As a special case, the zeroth argument, @code{$0}, is always the name
1789 of the macro being expanded.
1791 @example
1792 define(`test', ``Macro name: $0'')
1793 @result{}
1794 test
1795 @result{}Macro name: test
1796 @end example
1798 If you want quoted text to appear as part of the expansion text,
1799 remember that quotes can be nested in quoted strings.  Thus, in
1801 @example
1802 define(`foo', `This is macro `foo'.')
1803 @result{}
1805 @result{}This is macro foo.
1806 @end example
1808 @noindent
1809 The @samp{foo} in the expansion text is @emph{not} expanded, since it is
1810 a quoted string, and not a name.
1812 @cindex @acronym{GNU} extensions
1813 @cindex nine arguments, more than
1814 @cindex more than nine arguments
1815 @cindex arguments, more than nine
1816 @cindex positional parameters, more than nine
1817 @acronym{GNU} @code{m4} allows the number following the @samp{$} to
1818 consist of one or more digits, allowing macros to have any number of
1819 arguments.  The extension of accepting multiple digits is incompatible
1820 with @acronym{POSIX}, and is different than traditional implementations
1821 of @code{m4}, which only recognize one digit.  Therefore, future
1822 versions of @acronym{GNU} M4 will phase out this feature.  To portably
1823 access beyond the ninth argument, you can use the @code{argn} macro
1824 documented later (@pxref{Shift}).
1826 @acronym{POSIX} also states that @samp{$} followed immediately by
1827 @samp{@{} in a macro definition is implementation-defined.  This version
1828 of M4 passes the literal characters @samp{$@{} through unchanged, but M4
1829 2.0 will implement an optional feature similar to @command{sh}, where
1830 @samp{$@{11@}} expands to the eleventh argument, to replace the current
1831 recognition of @samp{$11}.  Meanwhile, if you want to guarantee that you
1832 will get a literal @samp{$@{} in output when expanding a macro, even
1833 when you upgrade to M4 2.0, you can use nested quoting to your
1834 advantage:
1836 @example
1837 define(`foo', `single quoted $`'@{1@} output')
1838 @result{}
1839 define(`bar', ``double quoted $'`@{2@} output'')
1840 @result{}
1841 foo(`a', `b')
1842 @result{}single quoted $@{1@} output
1843 bar(`a', `b')
1844 @result{}double quoted $@{2@} output
1845 @end example
1847 To help you detect places in your M4 input files that might change in
1848 behavior due to the changed behavior of M4 2.0, you can use the
1849 @option{--warn-macro-sequence} command-line option (@pxref{Operation
1850 modes, , Invoking m4}) with the default regular expression.  This will
1851 add a warning any time a macro definition includes @samp{$} followed by
1852 multiple digits, or by @samp{@{}.  The warning is not enabled by
1853 default, because it triggers a number of warnings in Autoconf 2.61 (and
1854 Autoconf uses @option{-E} to treat warnings as errors), and because it
1855 will still be possible to restore older behavior in M4 2.0.
1857 @comment options: --warn-macro-sequence
1858 @example
1859 $ @kbd{m4 --warn-macro-sequence}
1860 define(`foo', `$001 $@{1@} $1')
1861 @error{}m4:stdin:1: Warning: definition of `foo' contains sequence `$001'
1862 @error{}m4:stdin:1: Warning: definition of `foo' contains sequence `$@{1@}'
1863 @result{}
1864 foo(`bar')
1865 @result{}bar $@{1@} bar
1866 @end example
1868 @node Pseudo Arguments
1869 @section Special arguments to macros
1871 @cindex special arguments to macros
1872 @cindex macros, special arguments to
1873 @cindex arguments to macros, special
1874 There is a special notation for the number of actual arguments supplied,
1875 and for all the actual arguments.
1877 The number of actual arguments in a macro call is denoted by @code{$#}
1878 in the expansion text.
1880 @deffn Composite nargs (@dots{})
1881 Expands to a count of the number of arguments supplied.
1882 @end deffn
1884 @example
1885 define(`nargs', `$#')
1886 @result{}
1887 nargs
1888 @result{}0
1889 nargs()
1890 @result{}1
1891 nargs(`arg1', `arg2', `arg3')
1892 @result{}3
1893 nargs(`commas can be quoted, like this')
1894 @result{}1
1895 nargs(arg1#inside comments, commas do not separate arguments
1896 still arg1)
1897 @result{}1
1898 nargs((unquoted parentheses, like this, group arguments))
1899 @result{}1
1900 @end example
1902 Remember that @samp{#} defaults to the comment character; if you forget
1903 quotes to inhibit the comment behavior, your macro definition may not
1904 end where you expected.
1906 @example
1907 dnl Attempt to define a macro to just `$#'
1908 define(underquoted, $#)
1909 oops)
1910 @result{}
1911 underquoted
1912 @result{}0)
1913 @result{}oops
1914 @end example
1916 The notation @code{$*} can be used in the expansion text to denote all
1917 the actual arguments, unquoted, with commas in between.  For example
1919 @example
1920 define(`echo', `$*')
1921 @result{}
1922 echo(arg1,    arg2, arg3 , arg4)
1923 @result{}arg1,arg2,arg3 ,arg4
1924 @end example
1926 Often each argument should be quoted, and the notation @code{$@@} handles
1927 that.  It is just like @code{$*}, except that it quotes each argument.
1928 A simple example of that is:
1930 @example
1931 define(`echo', `$@@')
1932 @result{}
1933 echo(arg1,    arg2, arg3 , arg4)
1934 @result{}arg1,arg2,arg3 ,arg4
1935 @end example
1937 Where did the quotes go?  Of course, they were eaten, when the expanded
1938 text were reread by @code{m4}.  To show the difference, try
1940 @example
1941 define(`echo1', `$*')
1942 @result{}
1943 define(`echo2', `$@@')
1944 @result{}
1945 define(`foo', `This is macro `foo'.')
1946 @result{}
1947 echo1(foo)
1948 @result{}This is macro This is macro foo..
1949 echo1(`foo')
1950 @result{}This is macro foo.
1951 echo2(foo)
1952 @result{}This is macro foo.
1953 echo2(`foo')
1954 @result{}foo
1955 @end example
1957 @noindent
1958 @xref{Trace}, if you do not understand this.  As another example of the
1959 difference, remember that comments encountered in arguments are passed
1960 untouched to the macro, and that quoting disables comments.
1962 @example
1963 define(`echo1', `$*')
1964 @result{}
1965 define(`echo2', `$@@')
1966 @result{}
1967 define(`foo', `bar')
1968 @result{}
1969 echo1(#foo'foo
1970 foo)
1971 @result{}#foo'foo
1972 @result{}bar
1973 echo2(#foo'foo
1974 foo)
1975 @result{}#foobar
1976 @result{}bar'
1977 @end example
1979 @ignore
1980 @comment Not worth putting in the manual, but this example is needed for
1981 @comment good test coverage of copying large strings across recursion
1982 @comment levels.
1984 @example
1985 define(`echo', `$@@')dnl
1986 echo(echo(`01234567890123456789', `01234567890123456789')
1987 echo(`98765432109876543210', `98765432109876543210'))
1988 @result{}01234567890123456789,01234567890123456789
1989 @result{}98765432109876543210,98765432109876543210
1990 len((echo(`01234567890123456789',
1991           `01234567890123456789')echo(`98765432109876543210',
1992                                       `98765432109876543210')))
1993 @result{}84
1994 indir(`echo', indir(`echo', `01234567890123456789',
1995                             `01234567890123456789')
1996 indir(`echo', `98765432109876543210', `98765432109876543210'))
1997 @result{}01234567890123456789,01234567890123456789
1998 @result{}98765432109876543210,98765432109876543210
1999 define(`argn', `$#')dnl
2000 define(`echo1', `-$@@-')define(`echo2', `,$@@,')dnl
2001 echo1(`1', `2', `3') argn(echo1(`1', `2', `3'))
2002 @result{}-1,2,3- 3
2003 echo2(`1', `2', `3') argn(echo2(`1', `2', `3'))
2004 @result{},1,2,3, 5
2005 @end example
2006 @end ignore
2008 A @samp{$} sign in the expansion text, that is not followed by anything
2009 @code{m4} understands, is simply copied to the macro expansion, as any
2010 other text is.
2012 @example
2013 define(`foo', `$$$ hello $$$')
2014 @result{}
2016 @result{}$$$ hello $$$
2017 @end example
2019 @cindex rescanning
2020 @cindex literal output
2021 @cindex output, literal
2022 If you want a macro to expand to something like @samp{$12}, the
2023 judicious use of nested quoting can put a safe character between the
2024 @code{$} and the next character, relying on the rescanning to remove the
2025 nested quote.  This will prevent @code{m4} from interpreting the
2026 @code{$} sign as a reference to an argument.
2028 @example
2029 define(`foo', `no nested quote: $1')
2030 @result{}
2031 foo(`arg')
2032 @result{}no nested quote: arg
2033 define(`foo', `nested quote around $: `$'1')
2034 @result{}
2035 foo(`arg')
2036 @result{}nested quote around $: $1
2037 define(`foo', `nested empty quote after $: $`'1')
2038 @result{}
2039 foo(`arg')
2040 @result{}nested empty quote after $: $1
2041 define(`foo', `nested quote around next character: $`1'')
2042 @result{}
2043 foo(`arg')
2044 @result{}nested quote around next character: $1
2045 define(`foo', `nested quote around both: `$1'')
2046 @result{}
2047 foo(`arg')
2048 @result{}nested quote around both: arg
2049 @end example
2051 @node Undefine
2052 @section Deleting a macro
2054 @cindex macros, how to delete
2055 @cindex deleting macros
2056 @cindex undefining macros
2057 A macro definition can be removed with @code{undefine}:
2059 @deffn Builtin undefine (@var{name}@dots{})
2060 For each argument, remove the macro @var{name}.  The macro names must
2061 necessarily be quoted, since they will be expanded otherwise.
2063 The expansion of @code{undefine} is void.
2064 The macro @code{undefine} is recognized only with parameters.
2065 @end deffn
2067 @example
2068 foo bar blah
2069 @result{}foo bar blah
2070 define(`foo', `some')define(`bar', `other')define(`blah', `text')
2071 @result{}
2072 foo bar blah
2073 @result{}some other text
2074 undefine(`foo')
2075 @result{}
2076 foo bar blah
2077 @result{}foo other text
2078 undefine(`bar', `blah')
2079 @result{}
2080 foo bar blah
2081 @result{}foo bar blah
2082 @end example
2084 Undefining a macro inside that macro's expansion is safe; the macro
2085 still expands to the definition that was in effect at the @samp{(}.
2087 @example
2088 define(`f', ``$0':$1')
2089 @result{}
2090 f(f(f(undefine(`f')`hello world')))
2091 @result{}f:f:f:hello world
2092 f(`bye')
2093 @result{}f(bye)
2094 @end example
2096 It is not an error for @var{name} to have no macro definition.  In that
2097 case, @code{undefine} does nothing.
2099 @node Defn
2100 @section Renaming macros
2102 @cindex macros, how to rename
2103 @cindex renaming macros
2104 @cindex macros, displaying definitions
2105 @cindex definitions, displaying macro
2106 It is possible to rename an already defined macro.  To do this, you need
2107 the builtin @code{defn}:
2109 @deffn Builtin defn (@var{name}@dots{})
2110 Expands to the @emph{quoted definition} of each @var{name}.  If an
2111 argument is not a defined macro, the expansion for that argument is
2112 empty.
2114 If @var{name} is a user-defined macro, the quoted definition is simply
2115 the quoted expansion text.  If, instead, there is only one @var{name}
2116 and it is a builtin, the
2117 expansion is a special token, which points to the builtin's internal
2118 definition.  This token is only meaningful as the second argument to
2119 @code{define} (and @code{pushdef}), and is silently converted to an
2120 empty string in most other contexts.  Using multiple @var{name} to
2121 combine a builtin with anything else is not supported; a warning is
2122 issued and the builtin is omitted from the final expansion.
2124 The macro @code{defn} is recognized only with parameters.
2125 @end deffn
2127 Its normal use is best understood through an example, which shows how to
2128 rename @code{undefine} to @code{zap}:
2130 @example
2131 define(`zap', defn(`undefine'))
2132 @result{}
2133 zap(`undefine')
2134 @result{}
2135 undefine(`zap')
2136 @result{}undefine(zap)
2137 @end example
2139 In this way, @code{defn} can be used to copy macro definitions, and also
2140 definitions of builtin macros.  Even if the original macro is removed,
2141 the other name can still be used to access the definition.
2143 The fact that macro definitions can be transferred also explains why you
2144 should use @code{$0}, rather than retyping a macro's name in its
2145 definition:
2147 @example
2148 define(`foo', `This is `$0'')
2149 @result{}
2150 define(`bar', defn(`foo'))
2151 @result{}
2153 @result{}This is bar
2154 @end example
2156 Macros used as string variables should be referred through @code{defn},
2157 to avoid unwanted expansion of the text:
2159 @example
2160 define(`string', `The macro dnl is very useful
2162 @result{}
2163 string
2164 @result{}The macro@w{ }
2165 defn(`string')
2166 @result{}The macro dnl is very useful
2167 @result{}
2168 @end example
2170 @cindex rescanning
2171 However, it is important to remember that @code{m4} rescanning is purely
2172 textual.  If an unbalanced end-quote string occurs in a macro
2173 definition, the rescan will see that embedded quote as the termination
2174 of the quoted string, and the remainder of the macro's definition will
2175 be rescanned unquoted.  Thus it is a good idea to avoid unbalanced
2176 end-quotes in macro definitions or arguments to macros.
2178 @example
2179 define(`foo', a'a)
2180 @result{}
2181 define(`a', `A')
2182 @result{}
2183 define(`echo', `$@@')
2184 @result{}
2186 @result{}A'A
2187 defn(`foo')
2188 @result{}aA'
2189 echo(foo)
2190 @result{}AA'
2191 @end example
2193 On the other hand, it is possible to exploit the fact that @code{defn}
2194 can concatenate multiple macros prior to the rescanning phase, in order
2195 to join the definitions of macros that, in isolation, have unbalanced
2196 quotes.  This is particularly useful when one has used several macros to
2197 accumulate text that M4 should rescan as a whole.  In the example below,
2198 note how the use of @code{defn} on @code{l} in isolation opens a string,
2199 which is not closed until the next line; but used on @code{l} and
2200 @code{r} together results in nested quoting.
2202 @example
2203 define(`l', `<[>')define(`r', `<]>')
2204 @result{}
2205 changequote(`[', `]')
2206 @result{}
2207 defn([l])defn([r])
2209 @result{}<[>]defn([r])
2210 @result{})
2211 defn([l], [r])
2212 @result{}<[>][<]>
2213 @end example
2215 @cindex builtins, special tokens
2216 @cindex tokens, builtin macro
2217 Using @code{defn} to generate special tokens for builtin macros outside
2218 of expected contexts can sometimes trigger warnings.  But most of the
2219 time, such tokens are silently converted to the empty string.
2221 @example
2222 defn(`defn')
2223 @result{}
2224 define(defn(`divnum'), `cannot redefine a builtin token')
2225 @error{}m4:stdin:2: Warning: define: invalid macro name ignored
2226 @result{}
2227 divnum
2228 @result{}0
2229 define(`echo', `$@@')
2230 @result{}
2231 define(`mydivnum', echo(defn(`divnum')))
2232 @result{}
2233 mydivnum
2234 @result{}
2235 @end example
2237 Also note that @code{defn} with multiple arguments can only join text
2238 macros, not builtins.  Likewise, when collecting macro arguments, a
2239 builtin token is preserved only when it occurs in isolation.  A future
2240 version of @acronym{GNU} M4 may lift these restrictions.
2242 @example
2243 define(`a', `A')define(`AA', `b')
2244 @result{}
2245 defn(`a', `divnum', `a')
2246 @error{}m4:stdin:2: Warning: defn: cannot concatenate builtin `divnum'
2247 @result{}AA
2248 define(`mydivnum', defn(`divnum', `divnum'))mydivnum
2249 @error{}m4:stdin:3: Warning: defn: cannot concatenate builtin `divnum'
2250 @error{}m4:stdin:3: Warning: defn: cannot concatenate builtin `divnum'
2251 @result{}
2252 define(`mydivnum', defn(`divnum')defn(`divnum'))mydivnum
2253 @error{}m4:stdin:4: Warning: define: cannot concatenate builtin `divnum'
2254 @error{}m4:stdin:4: Warning: define: cannot concatenate builtin `divnum'
2255 @result{}
2256 define(`mydivnum', defn(`divnum')`a')mydivnum
2257 @error{}m4:stdin:5: Warning: define: cannot concatenate builtin `divnum'
2258 @result{}A
2259 define(`mydivnum', `a'defn(`divnum'))mydivnum
2260 @error{}m4:stdin:6: Warning: define: cannot concatenate builtin `divnum'
2261 @result{}A
2262 @end example
2264 @node Pushdef
2265 @section Temporarily redefining macros
2267 @cindex macros, temporary redefinition of
2268 @cindex temporary redefinition of macros
2269 @cindex redefinition of macros, temporary
2270 @cindex definition stack
2271 @cindex stack, macro definition
2272 It is possible to redefine a macro temporarily, reverting to the
2273 previous definition at a later time.  This is done with the builtins
2274 @code{pushdef} and @code{popdef}:
2276 @deffn Builtin pushdef (@var{name}, @ovar{expansion})
2277 @deffnx Builtin popdef (@var{name}@dots{})
2278 Analogous to @code{define} and @code{undefine}.
2280 These macros work in a stack-like fashion.  A macro is temporarily
2281 redefined with @code{pushdef}, which replaces an existing definition of
2282 @var{name}, while saving the previous definition, before the new one is
2283 installed.  If there is no previous definition, @code{pushdef} behaves
2284 exactly like @code{define}.
2286 If a macro has several definitions (of which only one is accessible),
2287 the topmost definition can be removed with @code{popdef}.  If there is
2288 no previous definition, @code{popdef} behaves like @code{undefine}.
2290 The expansion of both @code{pushdef} and @code{popdef} is void.
2291 The macros @code{pushdef} and @code{popdef} are recognized only with
2292 parameters.
2293 @end deffn
2295 @example
2296 define(`foo', `Expansion one.')
2297 @result{}
2299 @result{}Expansion one.
2300 pushdef(`foo', `Expansion two.')
2301 @result{}
2303 @result{}Expansion two.
2304 pushdef(`foo', `Expansion three.')
2305 @result{}
2306 pushdef(`foo', `Expansion four.')
2307 @result{}
2308 popdef(`foo')
2309 @result{}
2311 @result{}Expansion three.
2312 popdef(`foo', `foo')
2313 @result{}
2315 @result{}Expansion one.
2316 popdef(`foo')
2317 @result{}
2319 @result{}foo
2320 @end example
2322 If a macro with several definitions is redefined with @code{define}, the
2323 topmost definition is @emph{replaced} with the new definition.  If it is
2324 removed with @code{undefine}, @emph{all} the definitions are removed,
2325 and not only the topmost one.  However, @acronym{POSIX} allows other
2326 implementations that treat @code{define} as replacing an entire stack
2327 of definitions with a single new definition, so to be portable to other
2328 implementations, it may be worth explicitly using @code{popdef} and
2329 @code{pushdef} rather than relying on the @acronym{GNU} behavior of
2330 @code{define}.
2332 @example
2333 define(`foo', `Expansion one.')
2334 @result{}
2336 @result{}Expansion one.
2337 pushdef(`foo', `Expansion two.')
2338 @result{}
2340 @result{}Expansion two.
2341 define(`foo', `Second expansion two.')
2342 @result{}
2344 @result{}Second expansion two.
2345 undefine(`foo')
2346 @result{}
2348 @result{}foo
2349 @end example
2351 @cindex local variables
2352 @cindex variables, local
2353 Local variables within macros are made with @code{pushdef} and
2354 @code{popdef}.  At the start of the macro a new definition is pushed,
2355 within the macro it is manipulated and at the end it is popped,
2356 revealing the former definition.
2358 It is possible to temporarily redefine a builtin with @code{pushdef}
2359 and @code{defn}.
2361 @node Indir
2362 @section Indirect call of macros
2364 @cindex indirect call of macros
2365 @cindex call of macros, indirect
2366 @cindex macros, indirect call of
2367 @cindex @acronym{GNU} extensions
2368 Any macro can be called indirectly with @code{indir}:
2370 @deffn Builtin indir (@var{name}, @ovar{args@dots{}})
2371 Results in a call to the macro @var{name}, which is passed the
2372 rest of the arguments @var{args}.  If @var{name} is not defined, an
2373 error message is printed, and the expansion is void.
2375 The macro @code{indir} is recognized only with parameters.
2376 @end deffn
2378 This can be used to call macros with computed or ``invalid''
2379 names (@code{define} allows such names to be defined):
2381 @example
2382 define(`$$internal$macro', `Internal macro (name `$0')')
2383 @result{}
2384 $$internal$macro
2385 @result{}$$internal$macro
2386 indir(`$$internal$macro')
2387 @result{}Internal macro (name $$internal$macro)
2388 @end example
2390 The point is, here, that larger macro packages can have private macros
2391 defined, that will not be called by accident.  They can @emph{only} be
2392 called through the builtin @code{indir}.
2394 One other point to observe is that argument collection occurs before
2395 @code{indir} invokes @var{name}, so if argument collection changes the
2396 value of @var{name}, that will be reflected in the final expansion.
2397 This is different than the behavior when invoking macros directly,
2398 where the definition that was in effect before argument collection is
2399 used.
2401 @example
2402 $ @kbd{m4 -d}
2403 define(`f', `1')
2404 @result{}
2405 f(define(`f', `2'))
2406 @result{}1
2407 indir(`f', define(`f', `3'))
2408 @result{}3
2409 indir(`f', undefine(`f'))
2410 @error{}m4:stdin:4: Warning: indir: undefined macro `f'
2411 @result{}
2412 @end example
2414 When handed the result of @code{defn} (@pxref{Defn}) as one of its
2415 arguments, @code{indir} defers to the invoked @var{name} for whether a
2416 token representing a builtin is recognized or flattened to the empty
2417 string.
2419 @example
2420 $ @kbd{m4 -d}
2421 indir(defn(`defn'), `divnum')
2422 @error{}m4:stdin:1: Warning: indir: invalid macro name ignored
2423 @result{}
2424 indir(`define', defn(`defn'), `divnum')
2425 @error{}m4:stdin:2: Warning: define: invalid macro name ignored
2426 @result{}
2427 indir(`define', `foo', defn(`divnum'))
2428 @result{}
2430 @result{}0
2431 indir(`divert', defn(`foo'))
2432 @error{}m4:stdin:5: Warning: divert: empty string treated as 0
2433 @result{}
2434 @end example
2436 Warning messages issued on behalf of an indirect macro use an
2437 unambiguous representation of the macro name, using escape sequences
2438 similar to C strings, and with colons also quoted.
2440 @example
2441 define(`%%:\
2442 odd', defn(`divnum'))
2443 @result{}
2444 indir(`%%:\
2445 odd', `extra')
2446 @error{}m4:stdin:3: Warning: %%\:\\\nodd: extra arguments ignored: 1 > 0
2447 @result{}0
2448 @end example
2450 @node Builtin
2451 @section Indirect call of builtins
2453 @cindex indirect call of builtins
2454 @cindex call of builtins, indirect
2455 @cindex builtins, indirect call of
2456 @cindex @acronym{GNU} extensions
2457 Builtin macros can be called indirectly with @code{builtin}:
2459 @deffn Builtin builtin (@var{name}, @ovar{args@dots{}})
2460 Results in a call to the builtin @var{name}, which is passed the
2461 rest of the arguments @var{args}.  If @var{name} does not name a
2462 builtin, an error message is printed, and the expansion is void.
2464 The macro @code{builtin} is recognized only with parameters.
2465 @end deffn
2467 This can be used even if @var{name} has been given another definition
2468 that has covered the original, or been undefined so that no macro
2469 maps to the builtin.
2471 @example
2472 pushdef(`define', `hidden')
2473 @result{}
2474 undefine(`undefine')
2475 @result{}
2476 define(`foo', `bar')
2477 @result{}hidden
2479 @result{}foo
2480 builtin(`define', `foo', defn(`divnum'))
2481 @result{}
2483 @result{}0
2484 builtin(`define', `foo', `BAR')
2485 @result{}
2487 @result{}BAR
2488 undefine(`foo')
2489 @result{}undefine(foo)
2491 @result{}BAR
2492 builtin(`undefine', `foo')
2493 @result{}
2495 @result{}foo
2496 @end example
2498 The @var{name} argument only matches the original name of the builtin,
2499 even when the @option{--prefix-builtins} option (or @option{-P},
2500 @pxref{Operation modes, , Invoking m4}) is in effect.  This is different
2501 from @code{indir}, which only tracks current macro names.
2503 @comment options: -P
2504 @example
2505 $ @kbd{m4 -P}
2506 m4_builtin(`divnum')
2507 @result{}0
2508 m4_builtin(`m4_divnum')
2509 @error{}m4:stdin:2: Warning: m4_builtin: undefined builtin `m4_divnum'
2510 @result{}
2511 m4_indir(`divnum')
2512 @error{}m4:stdin:3: Warning: m4_indir: undefined macro `divnum'
2513 @result{}
2514 m4_indir(`m4_divnum')
2515 @result{}0
2516 @end example
2518 Note that @code{indir} and @code{builtin} can be used to invoke builtins
2519 without arguments, even when they normally require parameters to be
2520 recognized; but it will provoke a warning, and result in a void expansion.
2522 @example
2523 builtin
2524 @result{}builtin
2525 builtin()
2526 @error{}m4:stdin:2: Warning: builtin: undefined builtin `'
2527 @result{}
2528 builtin(`builtin')
2529 @error{}m4:stdin:3: Warning: builtin: too few arguments: 0 < 1
2530 @result{}
2531 builtin(`builtin',)
2532 @error{}m4:stdin:4: Warning: builtin: undefined builtin `'
2533 @result{}
2534 @end example
2536 @ignore
2537 @comment This example is not worth putting in the manual, but it is
2538 @comment needed for full coverage.  Autoconf's m4_include relies heavily
2539 @comment on this feature.
2541 @example
2542 builtin(`include', `foo')dnl
2543 @result{}bar
2544 @end example
2545 @end ignore
2547 @node Conditionals
2548 @chapter Conditionals, loops, and recursion
2550 Macros, expanding to plain text, perhaps with arguments, are not quite
2551 enough.  We would like to have macros expand to different things, based
2552 on decisions taken at run-time.  For that, we need some kind of conditionals.
2553 Also, we would like to have some kind of loop construct, so we could do
2554 something a number of times, or while some condition is true.
2556 @menu
2557 * Ifdef::                       Testing if a macro is defined
2558 * Ifelse::                      If-else construct, or multibranch
2559 * Shift::                       Recursion in @code{m4}
2560 * Forloop::                     Iteration by counting
2561 * Foreach::                     Iteration by list contents
2562 @end menu
2564 @node Ifdef
2565 @section Testing if a macro is defined
2567 @cindex conditionals
2568 There are two different builtin conditionals in @code{m4}.  The first is
2569 @code{ifdef}:
2571 @deffn Builtin ifdef (@var{name}, @var{string-1}, @ovar{string-2})
2572 If @var{name} is defined as a macro, @code{ifdef} expands to
2573 @var{string-1}, otherwise to @var{string-2}.  If @var{string-2} is
2574 omitted, it is taken to be the empty string (according to the normal
2575 rules).
2577 The macro @code{ifdef} is recognized only with parameters.
2578 @end deffn
2580 @example
2581 ifdef(`foo', ``foo' is defined', ``foo' is not defined')
2582 @result{}foo is not defined
2583 define(`foo', `')
2584 @result{}
2585 ifdef(`foo', ``foo' is defined', ``foo' is not defined')
2586 @result{}foo is defined
2587 ifdef(`no_such_macro', `yes', `no', `extra argument')
2588 @error{}m4:stdin:4: Warning: ifdef: extra arguments ignored: 4 > 3
2589 @result{}no
2590 @end example
2592 @node Ifelse
2593 @section If-else construct, or multibranch
2595 @cindex comparing strings
2596 @cindex discarding input
2597 @cindex input, discarding
2598 The other conditional, @code{ifelse}, is much more powerful.  It can be
2599 used as a way to introduce a long comment, as an if-else construct, or
2600 as a multibranch, depending on the number of arguments supplied:
2602 @deffn Builtin ifelse (@var{comment})
2603 @deffnx Builtin ifelse (@var{string-1}, @var{string-2}, @var{equal}, @
2604   @ovar{not-equal})
2605 @deffnx Builtin ifelse (@var{string-1}, @var{string-2}, @var{equal-1}, @
2606   @var{string-3}, @var{string-4}, @var{equal-2}, @dots{}, @ovar{not-equal})
2607 Used with only one argument, the @code{ifelse} simply discards it and
2608 produces no output.
2610 If called with three or four arguments, @code{ifelse} expands into
2611 @var{equal}, if @var{string-1} and @var{string-2} are equal (character
2612 for character), otherwise it expands to @var{not-equal}.  A final fifth
2613 argument is ignored, after triggering a warning.
2615 If called with six or more arguments, and @var{string-1} and
2616 @var{string-2} are equal, @code{ifelse} expands into @var{equal-1},
2617 otherwise the first three arguments are discarded and the processing
2618 starts again.
2620 The macro @code{ifelse} is recognized only with parameters.
2621 @end deffn
2623 Using only one argument is a common @code{m4} idiom for introducing a
2624 block comment, as an alternative to repeatedly using @code{dnl}.  This
2625 special usage is recognized by @acronym{GNU} @code{m4}, so that in this
2626 case, the warning about missing arguments is never triggered.
2628 @example
2629 ifelse(`some comments')
2630 @result{}
2631 ifelse(`foo', `bar')
2632 @error{}m4:stdin:2: Warning: ifelse: too few arguments: 2 < 3
2633 @result{}
2634 @end example
2636 Using three or four arguments provides decision points.
2638 @example
2639 ifelse(`foo', `bar', `true')
2640 @result{}
2641 ifelse(`foo', `foo', `true')
2642 @result{}true
2643 define(`foo', `bar')
2644 @result{}
2645 ifelse(foo, `bar', `true', `false')
2646 @result{}true
2647 ifelse(foo, `foo', `true', `false')
2648 @result{}false
2649 @end example
2651 @cindex macro, blind
2652 @cindex blind macro
2653 Notice how the first argument was used unquoted; it is common to compare
2654 the expansion of a macro with a string.  With this macro, you can now
2655 reproduce the behavior of blind builtins, where the macro is recognized
2656 only with arguments.
2658 @example
2659 define(`foo', `ifelse(`$#', `0', ``$0'', `arguments:$#')')
2660 @result{}
2662 @result{}foo
2663 foo()
2664 @result{}arguments:1
2665 foo(`a', `b', `c')
2666 @result{}arguments:3
2667 @end example
2669 @cindex multibranches
2670 @cindex switch statement
2671 @cindex case statement
2672 However, @code{ifelse} can take more than four arguments.  If given more
2673 than four arguments, @code{ifelse} works like a @code{case} or @code{switch}
2674 statement in traditional programming languages.  If @var{string-1} and
2675 @var{string-2} are equal, @code{ifelse} expands into @var{equal-1}, otherwise
2676 the procedure is repeated with the first three arguments discarded.  This
2677 calls for an example:
2679 @example
2680 ifelse(`foo', `bar', `third', `gnu', `gnats')
2681 @error{}m4:stdin:1: Warning: ifelse: extra arguments ignored: 5 > 4
2682 @result{}gnu
2683 ifelse(`foo', `bar', `third', `gnu', `gnats', `sixth')
2684 @result{}
2685 ifelse(`foo', `bar', `third', `gnu', `gnats', `sixth', `seventh')
2686 @result{}seventh
2687 ifelse(`foo', `bar', `3', `gnu', `gnats', `6', `7', `8')
2688 @error{}m4:stdin:4: Warning: ifelse: extra arguments ignored: 8 > 7
2689 @result{}7
2690 @end example
2692 @ignore
2693 @comment Stress tests, not worth documenting.
2695 @comment Ensure that references compared to strings work regardless of
2696 @comment similar prefixes.
2697 @example
2698 define(`e', `$@@')define(`long', `01234567890123456789')
2699 @result{}
2700 ifelse(long, `01234567890123456789', `yes', `no')
2701 @result{}yes
2702 ifelse(`01234567890123456789', long, `yes', `no')
2703 @result{}yes
2704 ifelse(long, `01234567890123456789-', `yes', `no')
2705 @result{}no
2706 ifelse(`01234567890123456789-', long, `yes', `no')
2707 @result{}no
2708 ifelse(e(long), `01234567890123456789', `yes', `no')
2709 @result{}yes
2710 ifelse(`01234567890123456789', e(long), `yes', `no')
2711 @result{}yes
2712 ifelse(e(long), `01234567890123456789-', `yes', `no')
2713 @result{}no
2714 ifelse(`01234567890123456789-', e(long), `yes', `no')
2715 @result{}no
2716 ifelse(-e(long), `-01234567890123456789', `yes', `no')
2717 @result{}yes
2718 ifelse(-`01234567890123456789', -e(long), `yes', `no')
2719 @result{}yes
2720 ifelse(-e(long), `-01234567890123456789-', `yes', `no')
2721 @result{}no
2722 ifelse(`-01234567890123456789-', -e(long), `yes', `no')
2723 @result{}no
2724 ifelse(-e(long)-, `-01234567890123456789-', `yes', `no')
2725 @result{}yes
2726 ifelse(-`01234567890123456789-', -e(long)-, `yes', `no')
2727 @result{}yes
2728 ifelse(-e(long)-, `-01234567890123456789', `yes', `no')
2729 @result{}no
2730 ifelse(`-01234567890123456789', -e(long)-, `yes', `no')
2731 @result{}no
2732 ifelse(`-'e(long), `-01234567890123456789', `yes', `no')
2733 @result{}yes
2734 ifelse(-`01234567890123456789', `-'e(long), `yes', `no')
2735 @result{}yes
2736 ifelse(`-'e(long), `-01234567890123456789-', `yes', `no')
2737 @result{}no
2738 ifelse(`-01234567890123456789-', `-'e(long), `yes', `no')
2739 @result{}no
2740 ifelse(`-'e(long)`-', `-01234567890123456789-', `yes', `no')
2741 @result{}yes
2742 ifelse(-`01234567890123456789-', `-'e(long)`-', `yes', `no')
2743 @result{}yes
2744 ifelse(`-'e(long)`-', `-01234567890123456789', `yes', `no')
2745 @result{}no
2746 ifelse(`-01234567890123456789', `-'e(long)`-', `yes', `no')
2747 @result{}no
2748 @end example
2750 @comment It would be nice to pass builtin tokens through ifelse, m4wrap,
2751 @comment user macros; hence the fixmes.
2752 @example
2753 define(`e', `$@@')define(`q', ``$@@'')define(`u', `$*')
2754 @result{}
2755 define(`cmp', `ifelse($1, $2, `yes', `no')')define(`d', defn(`defn'))
2756 @result{}
2757 cmp(`defn(`defn')', `defn(`d')')
2758 @result{}yes
2759 cmp(`defn(`defn')', ``<defn>'')
2760 @result{}no
2761 cmp(`q(defn(`defn'))', `q(defn(`d'))')
2762 @result{}yes
2763 cmp(`q(defn(`defn'))', `q(`<defn>')')
2764 @result{}no
2765 cmp(`q(defn(`defn'))', ``'')
2766 @result{}no
2767 cmp(`q(`1', `2', defn(`defn'))', `q(`1', `2', defn(`d'))')
2768 @result{}yes
2769 cmp(`q(`1', `2', defn(`defn'))', `q(`1', `2', `<defn>')')
2770 @result{}no
2771 cmp(`q(`1', `2', defn(`defn'))', ```1',`2',<defn>'')
2772 @result{}no
2773 cmp(`q(`1', `2', defn(`defn'))', ```1',`2',`''')-fixme
2774 @result{}yes-fixme
2775 define(`cat', `$1`'ifelse(`$#', `1', `', `$0(shift($@@))')')
2776 @result{}
2777 cat(`define(`foo',', defn(`divnum'), `)foo')-fixme
2778 @result{}-fixme
2779 cat(e(`define(`bar',', defn(`divnum'), `)bar'))-fixme
2780 @result{}-fixme
2781 m4wrap(`u('q(`cat(`define(`baz','', defn(`divnum'), ``)baz')')`)-fixme
2783 @result{}
2785 @result{}-fixme
2786 @end example
2787 @end ignore
2789 Naturally, the normal case will be slightly more advanced than these
2790 examples.  A common use of @code{ifelse} is in macros implementing loops
2791 of various kinds.
2793 @node Shift
2794 @section Recursion in @code{m4}
2796 @cindex recursive macros
2797 @cindex macros, recursive
2798 There is no direct support for loops in @code{m4}, but macros can be
2799 recursive.  There is no limit on the number of recursion levels, other
2800 than those enforced by your hardware and operating system.
2802 @cindex loops
2803 Loops can be programmed using recursion and the conditionals described
2804 previously.
2806 There is a builtin macro, @code{shift}, which can, among other things,
2807 be used for iterating through the actual arguments to a macro:
2809 @deffn Builtin shift (@var{arg1}, @dots{})
2810 Takes any number of arguments, and expands to all its arguments except
2811 @var{arg1}, separated by commas, with each argument quoted.
2813 The macro @code{shift} is recognized only with parameters.
2814 @end deffn
2816 @example
2817 shift
2818 @result{}shift
2819 shift(`bar')
2820 @result{}
2821 shift(`foo', `bar', `baz')
2822 @result{}bar,baz
2823 @end example
2825 An example of the use of @code{shift} is this macro:
2827 @deffn Composite reverse (@dots{})
2828 Takes any number of arguments, and reverses their order.
2829 @end deffn
2831 It is implemented as:
2833 @example
2834 define(`reverse', `ifelse(`$#', `0', , `$#', `1', ``$1'',
2835                           `reverse(shift($@@)), `$1'')')
2836 @result{}
2837 reverse
2838 @result{}
2839 reverse(`foo')
2840 @result{}foo
2841 reverse(`foo', `bar', `gnats', `and gnus')
2842 @result{}and gnus, gnats, bar, foo
2843 @end example
2845 While not a very interesting macro, it does show how simple loops can be
2846 made with @code{shift}, @code{ifelse} and recursion.  It also shows
2847 that @code{shift} is usually used with @samp{$@@}.  Another example of
2848 this is an implementation of a short-circuiting conditional operator.
2850 @cindex short-circuiting conditional
2851 @cindex conditional, short-circuiting
2852 @deffn Composite cond (@var{test-1}, @var{string-1}, @var{equal-1}, @
2853   @ovar{test-2}, @ovar{string-2}, @ovar{equal-2}, @dots{}, @ovar{not-equal})
2854 Similar to @code{ifelse}, where an equal comparison between the first
2855 two strings results in the third, otherwise the first three arguments
2856 are discarded and the process repeats.  The difference is that each
2857 @var{test-<n>} is expanded only when it is encountered.  This means that
2858 every third argument to @code{cond} is normally given one more level of
2859 quoting than the corresponding argument to @code{ifelse}.
2860 @end deffn
2862 Here is the implementation of @code{cond}, along with a demonstration of
2863 how it can short-circuit the side effects in @code{side}.  Notice how
2864 all the unquoted side effects happen regardless of how many comparisons
2865 are made with @code{ifelse}, compared with only the relevant effects
2866 with @code{cond}.
2868 @example
2869 define(`cond',
2870 `ifelse(`$#', `1', `$1',
2871         `ifelse($1, `$2', `$3',
2872                 `$0(shift(shift(shift($@@))))')')')dnl
2873 define(`side', `define(`counter', incr(counter))$1')dnl
2874 define(`example1',
2875 `define(`counter', `0')dnl
2876 ifelse(side(`$1'), `yes', `one comparison: ',
2877        side(`$1'), `no', `two comparisons: ',
2878        side(`$1'), `maybe', `three comparisons: ',
2879        `side(`default answer: ')')counter')dnl
2880 define(`example2',
2881 `define(`counter', `0')dnl
2882 cond(`side(`$1')', `yes', `one comparison: ',
2883      `side(`$1')', `no', `two comparisons: ',
2884      `side(`$1')', `maybe', `three comparisons: ',
2885      `side(`default answer: ')')counter')dnl
2886 example1(`yes')
2887 @result{}one comparison: 3
2888 example1(`no')
2889 @result{}two comparisons: 3
2890 example1(`maybe')
2891 @result{}three comparisons: 3
2892 example1(`feeling rather indecisive today')
2893 @result{}default answer: 4
2894 example2(`yes')
2895 @result{}one comparison: 1
2896 example2(`no')
2897 @result{}two comparisons: 2
2898 example2(`maybe')
2899 @result{}three comparisons: 3
2900 example2(`feeling rather indecisive today')
2901 @result{}default answer: 4
2902 @end example
2904 Sometimes, a recursive algorithm requires adding quotes to each element,
2905 or treating multiple arguments as a single element:
2907 @deffn Composite quote (@dots{})
2908 @deffnx Composite dquote (@dots{})
2909 @deffnx Composite dquote_elt (@dots{})
2910 Takes any number of arguments, and adds quoting.  With @code{quote},
2911 only one level of quoting is added, effectively removing whitespace
2912 after commas and turning multiple arguments into a single string.  With
2913 @code{dquote}, two levels of quoting are added, one around each element,
2914 and one around the list.  And with @code{dquote_elt}, two levels of
2915 quoting are added around each element.
2916 @end deffn
2918 An actual implementation of these three macros is distributed as
2919 @file{m4-@value{VERSION}/@/examples/@/quote.m4} in this package.  First,
2920 let's examine their usage:
2922 @comment examples
2923 @example
2924 $ @kbd{m4 -I examples}
2925 include(`quote.m4')
2926 @result{}
2927 -quote-dquote-dquote_elt-
2928 @result{}----
2929 -quote()-dquote()-dquote_elt()-
2930 @result{}--`'-`'-
2931 -quote(`1')-dquote(`1')-dquote_elt(`1')-
2932 @result{}-1-`1'-`1'-
2933 -quote(`1', `2')-dquote(`1', `2')-dquote_elt(`1', `2')-
2934 @result{}-1,2-`1',`2'-`1',`2'-
2935 define(`n', `$#')dnl
2936 -n(quote(`1', `2'))-n(dquote(`1', `2'))-n(dquote_elt(`1', `2'))-
2937 @result{}-1-1-2-
2938 dquote(dquote_elt(`1', `2'))
2939 @result{}``1'',``2''
2940 dquote_elt(dquote(`1', `2'))
2941 @result{}``1',`2''
2942 @end example
2944 The last two lines show that when given two arguments, @code{dquote}
2945 results in one string, while @code{dquote_elt} results in two.  Now,
2946 examine the implementation.  Note that @code{quote} and
2947 @code{dquote_elt} make decisions based on their number of arguments, so
2948 that when called without arguments, they result in nothing instead of a
2949 quoted empty string; this is so that it is possible to distinguish
2950 between no arguments and an empty first argument.  @code{dquote}, on the
2951 other hand, results in a string no matter what, since it is still
2952 possible to tell whether it was invoked without arguments based on the
2953 resulting string.
2955 @comment examples
2956 @example
2957 $ @kbd{m4 -I examples}
2958 undivert(`quote.m4')dnl
2959 @result{}divert(`-1')
2960 @result{}# quote(args) - convert args to single-quoted string
2961 @result{}define(`quote', `ifelse(`$#', `0', `', ``$*'')')
2962 @result{}# dquote(args) - convert args to quoted list of quoted strings
2963 @result{}define(`dquote', ``$@@'')
2964 @result{}# dquote_elt(args) - convert args to list of double-quoted strings
2965 @result{}define(`dquote_elt', `ifelse(`$#', `0', `', `$#', `1', ```$1''',
2966 @result{}                             ```$1'',$0(shift($@@))')')
2967 @result{}divert`'dnl
2968 @end example
2970 @cindex nine arguments, more than
2971 @cindex more than nine arguments
2972 @cindex arguments, more than nine
2973 One more useful macro based on @code{shift} allows portably selecting
2974 an arbitrary argument (usually greater than the ninth argument), without
2975 relying on the @acronym{GNU} extension of multi-digit arguments
2976 (@pxref{Arguments}).
2978 @deffn Composite argn (@var{n}, @dots{})
2979 Expands to argument @var{n} out of the remaining arguments.  @var{n}
2980 must be a positive number.  Usually invoked as
2981 @samp{argn(`@var{n}',$@@)}.
2982 @end deffn
2984 It is implemented as:
2986 @example
2987 define(`argn', `ifelse(`$1', 1, ``$2'',
2988   `argn(decr(`$1'), shift(shift($@@)))')')
2989 @result{}
2990 argn(`1', `a')
2991 @result{}a
2992 define(`foo', `argn(`11', $@@)')
2993 @result{}
2994 foo(`a', `b', `c', `d', `e', `f', `g', `h', `i', `j', `k', `l')
2995 @result{}k
2996 @end example
2998 @node Forloop
2999 @section Iteration by counting
3001 @cindex for loops
3002 @cindex loops, counting
3003 @cindex counting loops
3004 Here is an example of a loop macro that implements a simple for loop.
3006 @deffn Composite forloop (@var{iterator}, @var{start}, @var{end}, @var{text})
3007 Takes the name in @var{iterator}, which must be a valid macro name, and
3008 successively assign it each integer value from @var{start} to @var{end},
3009 inclusive.  For each assignment to @var{iterator}, append @var{text} to
3010 the expansion of the @code{forloop}.  @var{text} may refer to
3011 @var{iterator}.  Any definition of @var{iterator} prior to this
3012 invocation is restored.
3013 @end deffn
3015 It can, for example, be used for simple counting:
3017 @comment examples
3018 @example
3019 $ @kbd{m4 -I examples}
3020 include(`forloop.m4')
3021 @result{}
3022 forloop(`i', `1', `8', `i ')
3023 @result{}1 2 3 4 5 6 7 8@w{ }
3024 @end example
3026 For-loops can be nested, like:
3028 @comment examples
3029 @example
3030 $ @kbd{m4 -I examples}
3031 include(`forloop.m4')
3032 @result{}
3033 forloop(`i', `1', `4', `forloop(`j', `1', `8', ` (i, j)')
3035 @result{} (1, 1) (1, 2) (1, 3) (1, 4) (1, 5) (1, 6) (1, 7) (1, 8)
3036 @result{} (2, 1) (2, 2) (2, 3) (2, 4) (2, 5) (2, 6) (2, 7) (2, 8)
3037 @result{} (3, 1) (3, 2) (3, 3) (3, 4) (3, 5) (3, 6) (3, 7) (3, 8)
3038 @result{} (4, 1) (4, 2) (4, 3) (4, 4) (4, 5) (4, 6) (4, 7) (4, 8)
3039 @result{}
3040 @end example
3042 The implementation of the @code{forloop} macro is fairly
3043 straightforward.  The @code{forloop} macro itself is simply a wrapper,
3044 which saves the previous definition of the first argument, calls the
3045 internal macro @code{@w{_forloop}}, and re-establishes the saved
3046 definition of the first argument.
3048 The macro @code{@w{_forloop}} expands the fourth argument once, and
3049 tests to see if the iterator has reached the final value.  If it has
3050 not finished, it increments the iterator (using the predefined macro
3051 @code{incr}, @pxref{Incr}), and recurses.
3053 Here is an actual implementation of @code{forloop}, distributed as
3054 @file{m4-@value{VERSION}/@/examples/@/forloop.m4} in this package:
3056 @comment examples
3057 @example
3058 $ @kbd{m4 -I examples}
3059 undivert(`forloop.m4')dnl
3060 @result{}divert(`-1')
3061 @result{}# forloop(var, from, to, stmt) - simple version
3062 @result{}define(`forloop', `pushdef(`$1', `$2')_forloop($@@)popdef(`$1')')
3063 @result{}define(`_forloop',
3064 @result{}       `$4`'ifelse($1, `$3', `', `define(`$1', incr($1))$0($@@)')')
3065 @result{}divert`'dnl
3066 @end example
3068 Notice the careful use of quotes.  Certain macro arguments are left
3069 unquoted, each for its own reason.  Try to find out @emph{why} these
3070 arguments are left unquoted, and see what happens if they are quoted.
3071 (As presented, these two macros are useful but not very robust for
3072 general use.  They lack even basic error handling for cases like
3073 @var{start} less than @var{end}, @var{end} not numeric, or
3074 @var{iterator} not being a macro name.  See if you can improve these
3075 macros; or @pxref{Improved forloop, , Answers}).
3077 @node Foreach
3078 @section Iteration by list contents
3080 @cindex for each loops
3081 @cindex loops, list iteration
3082 @cindex iterating over lists
3083 Here is an example of a loop macro that implements list iteration.
3085 @deffn Composite foreach (@var{iterator}, @var{paren-list}, @var{text})
3086 @deffnx Composite foreachq (@var{iterator}, @var{quote-list}, @var{text})
3087 Takes the name in @var{iterator}, which must be a valid macro name, and
3088 successively assign it each value from @var{paren-list} or
3089 @var{quote-list}.  In @code{foreach}, @var{paren-list} is a
3090 comma-separated list of elements contained in parentheses.  In
3091 @code{foreachq}, @var{quote-list} is a comma-separated list of elements
3092 contained in a quoted string.  For each assignment to @var{iterator},
3093 append @var{text} to the overall expansion.  @var{text} may refer to
3094 @var{iterator}.  Any definition of @var{iterator} prior to this
3095 invocation is restored.
3096 @end deffn
3098 As an example, this displays each word in a list inside of a sentence,
3099 using an implementation of @code{foreach} distributed as
3100 @file{m4-@value{VERSION}/@/examples/@/foreach.m4}, and @code{foreachq}
3101 in @file{m4-@value{VERSION}/@/examples/@/foreachq.m4}.
3103 @comment examples
3104 @example
3105 $ @kbd{m4 -I examples}
3106 include(`foreach.m4')
3107 @result{}
3108 foreach(`x', (foo, bar, foobar), `Word was: x
3109 ')dnl
3110 @result{}Word was: foo
3111 @result{}Word was: bar
3112 @result{}Word was: foobar
3113 include(`foreachq.m4')
3114 @result{}
3115 foreachq(`x', `foo, bar, foobar', `Word was: x
3116 ')dnl
3117 @result{}Word was: foo
3118 @result{}Word was: bar
3119 @result{}Word was: foobar
3120 @end example
3122 It is possible to be more complex; each element of the @var{paren-list}
3123 or @var{quote-list} can itself be a list, to pass as further arguments
3124 to a helper macro.  This example generates a shell case statement:
3126 @comment examples
3127 @example
3128 $ @kbd{m4 -I examples}
3129 include(`foreach.m4')
3130 @result{}
3131 define(`_case', `  $1)
3132     $2=" $1";;
3133 ')dnl
3134 define(`_cat', `$1$2')dnl
3135 case $`'1 in
3136 @result{}case $1 in
3137 foreach(`x', `(`(`a', `vara')', `(`b', `varb')', `(`c', `varc')')',
3138         `_cat(`_case', x)')dnl
3139 @result{}  a)
3140 @result{}    vara=" a";;
3141 @result{}  b)
3142 @result{}    varb=" b";;
3143 @result{}  c)
3144 @result{}    varc=" c";;
3145 esac
3146 @result{}esac
3147 @end example
3149 The implementation of the @code{foreach} macro is a bit more involved;
3150 it is a wrapper around two helper macros.  First, @code{@w{_arg1}} is
3151 needed to grab the first element of a list.  Second,
3152 @code{@w{_foreach}} implements the recursion, successively walking
3153 through the original list.  Here is a simple implementation of
3154 @code{foreach}:
3156 @comment examples
3157 @example
3158 $ @kbd{m4 -I examples}
3159 undivert(`foreach.m4')dnl
3160 @result{}divert(`-1')
3161 @result{}# foreach(x, (item_1, item_2, ..., item_n), stmt)
3162 @result{}#   parenthesized list, simple version
3163 @result{}define(`foreach', `pushdef(`$1')_foreach($@@)popdef(`$1')')
3164 @result{}define(`_arg1', `$1')
3165 @result{}define(`_foreach', `ifelse(`$2', `()', `',
3166 @result{}  `define(`$1', _arg1$2)$3`'$0(`$1', (shift$2), `$3')')')
3167 @result{}divert`'dnl
3168 @end example
3170 Unfortunately, that implementation is not robust to macro names as list
3171 elements.  Each iteration of @code{@w{_foreach}} is stripping another
3172 layer of quotes, leading to erratic results if list elements are not
3173 already fully expanded.  The first cut at implementing @code{foreachq}
3174 takes this into account.  Also, when using quoted elements in a
3175 @var{paren-list}, the overall list must be quoted.  A @var{quote-list}
3176 has the nice property of requiring fewer characters to create a list
3177 containing the same quoted elements.  To see the difference between the
3178 two macros, we attempt to pass double-quoted macro names in a list,
3179 expecting the macro name on output after one layer of quotes is removed
3180 during list iteration and the final layer removed during the final
3181 rescan:
3183 @comment examples
3184 @example
3185 $ @kbd{m4 -I examples}
3186 define(`a', `1')define(`b', `2')define(`c', `3')
3187 @result{}
3188 include(`foreach.m4')
3189 @result{}
3190 include(`foreachq.m4')
3191 @result{}
3192 foreach(`x', `(``a'', ``(b'', ``c)'')', `x
3194 @result{}1
3195 @result{}(2)1
3196 @result{}
3197 @result{}, x
3198 @result{})
3199 foreachq(`x', ```a'', ``(b'', ``c)''', `x
3200 ')dnl
3201 @result{}a
3202 @result{}(b
3203 @result{}c)
3204 @end example
3206 Obviously, @code{foreachq} did a better job; here is its implementation:
3208 @comment examples
3209 @example
3210 $ @kbd{m4 -I examples}
3211 undivert(`foreachq.m4')dnl
3212 @result{}include(`quote.m4')dnl
3213 @result{}divert(`-1')
3214 @result{}# foreachq(x, `item_1, item_2, ..., item_n', stmt)
3215 @result{}#   quoted list, simple version
3216 @result{}define(`foreachq', `pushdef(`$1')_foreachq($@@)popdef(`$1')')
3217 @result{}define(`_arg1', `$1')
3218 @result{}define(`_foreachq', `ifelse(quote($2), `', `',
3219 @result{}  `define(`$1', `_arg1($2)')$3`'$0(`$1', `shift($2)', `$3')')')
3220 @result{}divert`'dnl
3221 @end example
3223 Notice that @code{@w{_foreachq}} had to use the helper macro
3224 @code{quote} defined earlier (@pxref{Shift}), to ensure that the
3225 embedded @code{ifelse} call does not go haywire if a list element
3226 contains a comma.  Unfortunately, this implementation of @code{foreachq}
3227 has its own severe flaw.  Whereas the @code{foreach} implementation was
3228 linear, this macro is quadratic in the number of list elements, and is
3229 much more likely to trip up the limit set by the command line option
3230 @option{--nesting-limit} (or @option{-L}, @pxref{Limits control, ,
3231 Invoking m4}).  Additionally, this implementation does not expand
3232 @samp{defn(`@var{iterator}')} very well, when compared with
3233 @code{foreach}.
3235 @comment examples
3236 @example
3237 $ @kbd{m4 -I examples}
3238 include(`foreach.m4')include(`foreachq.m4')
3239 @result{}
3240 foreach(`name', `(`a', `b')', ` defn(`name')')
3241 @result{} a b
3242 foreachq(`name', ``a', `b'', ` defn(`name')')
3243 @result{} _arg1(`a', `b') _arg1(shift(`a', `b'))
3244 @end example
3246 It is possible to have robust iteration with linear behavior and sane
3247 @var{iterator} contents for either list style.  See if you can learn
3248 from the best elements of both of these implementations to create robust
3249 macros (or @pxref{Improved foreach, , Answers}).
3251 @node Debugging
3252 @chapter How to debug macros and input
3254 @cindex debugging macros
3255 @cindex macros, debugging
3256 When writing macros for @code{m4}, they often do not work as intended on
3257 the first try (as is the case with most programming languages).
3258 Fortunately, there is support for macro debugging in @code{m4}.
3260 @menu
3261 * Dumpdef::                     Displaying macro definitions
3262 * Trace::                       Tracing macro calls
3263 * Debug Levels::                Controlling debugging output
3264 * Debug Output::                Saving debugging output
3265 @end menu
3267 @node Dumpdef
3268 @section Displaying macro definitions
3270 @cindex displaying macro definitions
3271 @cindex macros, displaying definitions
3272 @cindex definitions, displaying macro
3273 @cindex standard error, output to
3274 If you want to see what a name expands into, you can use the builtin
3275 @code{dumpdef}:
3277 @deffn Builtin dumpdef (@ovar{names@dots{}})
3278 Accepts any number of arguments.  If called without any arguments,
3279 it displays the definitions of all known names, otherwise it displays
3280 the definitions of the @var{names} given.  The output is printed to the
3281 current debug file (usually standard error), and is sorted by name.  If
3282 an unknown name is encountered, a warning is printed.
3284 The expansion of @code{dumpdef} is void.
3285 @end deffn
3287 @example
3288 $ @kbd{m4 -d}
3289 define(`foo', `Hello world.')
3290 @result{}
3291 dumpdef(`foo')
3292 @error{}foo:@tabchar{}`Hello world.'
3293 @result{}
3294 dumpdef(`define')
3295 @error{}define:@tabchar{}<define>
3296 @result{}
3297 @end example
3299 The last example shows how builtin macros definitions are displayed.
3300 The definition that is dumped corresponds to what would occur if the
3301 macro were to be called at that point, even if other definitions are
3302 still live due to redefining a macro during argument collection.
3304 @example
3305 $ @kbd{m4 -d}
3306 pushdef(`f', ``$0'1')pushdef(`f', ``$0'2')
3307 @result{}
3308 f(popdef(`f')dumpdef(`f'))
3309 @error{}f:@tabchar{}``$0'1'
3310 @result{}f2
3311 f(popdef(`f')dumpdef(`f'))
3312 @error{}m4:stdin:3: Warning: dumpdef: undefined macro `f'
3313 @result{}f1
3314 @end example
3316 @xref{Debug Levels}, for information on controlling the details of the
3317 display.
3319 @node Trace
3320 @section Tracing macro calls
3322 @cindex tracing macro expansion
3323 @cindex macro expansion, tracing
3324 @cindex expansion, tracing macro
3325 @cindex standard error, output to
3326 It is possible to trace macro calls and expansions through the builtins
3327 @code{traceon} and @code{traceoff}:
3329 @deffn Builtin traceon (@ovar{names@dots{}})
3330 @deffnx Builtin traceoff (@ovar{names@dots{}})
3331 When called without any arguments, @code{traceon} and @code{traceoff}
3332 will turn tracing on and off, respectively, for all currently defined
3333 macros.
3335 When called with arguments, only the macros listed in @var{names} are
3336 affected, whether or not they are currently defined.
3338 The expansion of @code{traceon} and @code{traceoff} is void.
3339 @end deffn
3341 Whenever a traced macro is called and the arguments have been collected,
3342 the call is displayed.  If the expansion of the macro call is not void,
3343 the expansion can be displayed after the call.  The output is printed
3344 to the current debug file (defaulting to standard error, @pxref{Debug
3345 Output}).
3347 @example
3348 $ @kbd{m4 -d}
3349 define(`foo', `Hello World.')
3350 @result{}
3351 define(`echo', `$@@')
3352 @result{}
3353 traceon(`foo', `echo')
3354 @result{}
3356 @error{}m4trace: -1- foo -> `Hello World.'
3357 @result{}Hello World.
3358 echo(`gnus', `and gnats')
3359 @error{}m4trace: -1- echo(`gnus', `and gnats') -> ``gnus',`and gnats''
3360 @result{}gnus,and gnats
3361 @end example
3363 The number between dashes is the depth of the expansion.  It is one most
3364 of the time, signifying an expansion at the outermost level, but it
3365 increases when macro arguments contain unquoted macro calls.  The
3366 maximum number that will appear between dashes is controlled by the
3367 option @option{--nesting-limit} (or @option{-L}, @pxref{Limits control,
3368 , Invoking m4}).  Additionally, the option @option{--trace} (or
3369 @option{-t}) can be used to invoke @code{traceon(@var{name})} before
3370 parsing input.
3372 @comment The explicit -dp neutralizes the testsuite default of -d.
3373 @comment options: -dp -L3 -tifelse
3374 @comment status: 1
3375 @example
3376 $ @kbd{m4 -L 3 -t ifelse}
3377 ifelse(`one level')
3378 @error{}m4trace: -1- ifelse
3379 @result{}
3380 ifelse(ifelse(ifelse(`three levels')))
3381 @error{}m4trace: -3- ifelse
3382 @error{}m4trace: -2- ifelse
3383 @error{}m4trace: -1- ifelse
3384 @result{}
3385 ifelse(ifelse(ifelse(ifelse(`four levels'))))
3386 @error{}m4:stdin:3: recursion limit of 3 exceeded, use -L<N> to change it
3387 @end example
3389 Tracing by name is an attribute that is preserved whether the macro is
3390 defined or not.  This allows the selection of macros to trace before
3391 those macros are defined.
3393 @example
3394 $ @kbd{m4 -d}
3395 traceoff(`foo')
3396 @result{}
3397 traceon(`foo')
3398 @result{}
3400 @result{}foo
3401 define(`foo', `bar')
3402 @result{}
3404 @error{}m4trace: -1- foo -> `bar'
3405 @result{}bar
3406 undefine(`foo')
3407 @result{}
3408 ifdef(`foo', `yes', `no')
3409 @result{}no
3410 indir(`foo')
3411 @error{}m4:stdin:8: Warning: indir: undefined macro `foo'
3412 @result{}
3413 define(`foo', `blah')
3414 @result{}
3416 @error{}m4trace: -1- foo -> `blah'
3417 @result{}blah
3418 traceoff
3419 @result{}
3421 @result{}blah
3422 @end example
3424 Tracing even works on builtins.  However, @code{defn} (@pxref{Defn})
3425 does not transfer tracing status.
3427 @example
3428 $ @kbd{m4 -d}
3429 traceon(`eval', `m4_divnum')
3430 @result{}
3431 define(`m4_eval', defn(`eval'))
3432 @result{}
3433 define(`m4_divnum', defn(`divnum'))
3434 @result{}
3435 eval(divnum)
3436 @error{}m4trace: -1- eval(`0') -> `0'
3437 @result{}0
3438 m4_eval(m4_divnum)
3439 @error{}m4trace: -2- m4_divnum -> `0'
3440 @result{}0
3441 @end example
3443 @xref{Debug Levels}, for information on controlling the details of the
3444 display.
3446 @node Debug Levels
3447 @section Controlling debugging output
3449 @cindex controlling debugging output
3450 @cindex debugging output, controlling
3451 The @option{-d} option to @code{m4} (or @option{--debug},
3452 @pxref{Debugging options, , Invoking m4}) controls the amount of details
3453 presented in three
3454 categories of output.  Trace output is requested by @code{traceon}
3455 (@pxref{Trace}), and each line is prefixed by @samp{m4trace:} in
3456 relation to a macro invocation.  Debug output tracks useful events not
3457 associated with a macro invocation, and each line is prefixed by
3458 @samp{m4debug:}.  Finally, @code{dumpdef} (@pxref{Dumpdef}) output is
3459 affected, with no prefix added to the output lines.
3461 The @var{flags} following the option can be one or more of the
3462 following:
3464 @table @code
3465 @item a
3466 In trace output, show the actual arguments that were collected before
3467 invoking the macro.  This applies to all macro calls if the @samp{t}
3468 flag is used, otherwise only the macros covered by calls of
3469 @code{traceon}.  Arguments are subject to length truncation specified by
3470 the command line option @option{--arglength} (or @option{-l}).
3472 @item c
3473 In trace output, show several trace lines for each macro call.  A line
3474 is shown when the macro is seen, but before the arguments are collected;
3475 a second line when the arguments have been collected and a third line
3476 after the call has completed.
3478 @item e
3479 In trace output, show the expansion of each macro call, if it is not
3480 void.  This applies to all macro calls if the @samp{t} flag is used,
3481 otherwise only the macros covered by calls of @code{traceon}.  The
3482 expansion is subject to length truncation specified by the command line
3483 option @option{--arglength} (or @option{-l}).
3485 @item f
3486 In debug and trace output, include the name of the current input file in
3487 the output line.
3489 @item i
3490 In debug output, print a message each time the current input file is
3491 changed.
3493 @item l
3494 In debug and trace output, include the current input line number in the
3495 output line.
3497 @item p
3498 In debug output, print a message when a named file is found through the
3499 path search mechanism (@pxref{Search Path}), giving the actual file name
3500 used.
3502 @item q
3503 In trace and dumpdef output, quote actual arguments and macro expansions
3504 in the display with the current quotes.  This is useful in connection
3505 with the @samp{a} and @samp{e} flags above.
3507 @item t
3508 In trace output, trace all macro calls made in this invocation of
3509 @code{m4}, regardless of the settings of @code{traceon}.
3511 @item x
3512 In trace output, add a unique `macro call id' to each line of the trace
3513 output.  This is useful in connection with the @samp{c} flag above.
3515 @item V
3516 A shorthand for all of the above flags.
3517 @end table
3519 If no flags are specified with the @option{-d} option, the default is
3520 @samp{aeq}.  The examples throughout this manual assume the default
3521 flags.
3523 @cindex @acronym{GNU} extensions
3524 There is a builtin macro @code{debugmode}, which allows on-the-fly control of
3525 the debugging output format:
3527 @deffn Builtin debugmode (@ovar{flags})
3528 The argument @var{flags} should be a subset of the letters listed above.
3529 As special cases, if the argument starts with a @samp{+}, the flags are
3530 added to the current debug flags, and if it starts with a @samp{-}, they
3531 are removed.  If no argument is present, all debugging flags are cleared
3532 (as if no @option{-d} was given), and with an empty argument the flags
3533 are reset to the default of @samp{aeq}.
3535 The expansion of @code{debugmode} is void.
3536 @end deffn
3538 @comment The explicit -dp neutralizes the testsuite default of -d.
3539 @comment options: -dp
3540 @example
3541 $ @kbd{m4}
3542 define(`foo', `FOO')
3543 @result{}
3544 traceon(`foo')
3545 @result{}
3546 debugmode()
3547 @result{}
3549 @error{}m4trace: -1- foo -> `FOO'
3550 @result{}FOO
3551 debugmode
3552 @result{}
3554 @error{}m4trace: -1- foo
3555 @result{}FOO
3556 debugmode(`+l')
3557 @result{}
3559 @error{}m4trace:8: -1- foo
3560 @result{}FOO
3561 @end example
3563 The following example demonstrates the behavior of length truncation,
3564 when specified on the command line.  Note that each argument and the
3565 final result are individually truncated.  Also, the special tokens for
3566 builtin functions are not truncated.
3568 @comment options: -l6
3569 @example
3570 $ @kbd{m4 -d -l 6}
3571 define(`echo', `$@@')debugmode(`+t')
3572 @result{}
3573 echo(`1', `long string')
3574 @error{}m4trace: -1- echo(`1', `long s...') -> ``1',`l...'
3575 @result{}1,long string
3576 indir(`echo', defn(`changequote'))
3577 @error{}m4trace: -2- defn(`change...')
3578 @error{}m4trace: -1- indir(`echo', <changequote>) -> ``''
3579 @result{}
3580 @end example
3582 @node Debug Output
3583 @section Saving debugging output
3585 @cindex saving debugging output
3586 @cindex debugging output, saving
3587 @cindex output, saving debugging
3588 @cindex @acronym{GNU} extensions
3589 Debug and tracing output can be redirected to files using either the
3590 @option{--debugfile} option to @code{m4} (@pxref{Debugging options, ,
3591 Invoking m4}), or with the builtin macro @code{debugfile}:
3593 @deffn Builtin debugfile (@ovar{file})
3594 Sends all further debug and trace output to @var{file}, opened in append
3595 mode.  If @var{file} is the empty string, debug and trace output are
3596 discarded.  If @code{debugfile} is called without any arguments, debug
3597 and trace output are sent to standard error.  This does not affect
3598 warnings, error messages, or @code{errprint} output, which are
3599 always sent to standard error.  If @var{file} cannot be opened, the
3600 current debug file is unchanged, and an error is issued.
3602 The expansion of @code{debugfile} is void.
3603 @end deffn
3605 @example
3606 $ @kbd{m4 -d}
3607 traceon(`divnum')
3608 @result{}
3609 divnum(`extra')
3610 @error{}m4:stdin:2: Warning: divnum: extra arguments ignored: 1 > 0
3611 @error{}m4trace: -1- divnum(`extra') -> `0'
3612 @result{}0
3613 debugfile()
3614 @result{}
3615 divnum(`extra')
3616 @error{}m4:stdin:4: Warning: divnum: extra arguments ignored: 1 > 0
3617 @result{}0
3618 debugfile
3619 @result{}
3620 divnum
3621 @error{}m4trace: -1- divnum -> `0'
3622 @result{}0
3623 @end example
3625 @node Input Control
3626 @chapter Input control
3628 This chapter describes various builtin macros for controlling the input
3629 to @code{m4}.
3631 @menu
3632 * Dnl::                         Deleting whitespace in input
3633 * Changequote::                 Changing the quote characters
3634 * Changecom::                   Changing the comment delimiters
3635 * Changeword::                  Changing the lexical structure of words
3636 * M4wrap::                      Saving text until end of input
3637 @end menu
3639 @node Dnl
3640 @section Deleting whitespace in input
3642 @cindex deleting whitespace in input
3643 @cindex discarding input
3644 @cindex input, discarding
3645 The builtin @code{dnl} stands for ``Discard to Next Line'':
3647 @deffn Builtin dnl
3648 All characters, up to and including the next newline, are discarded
3649 without performing any macro expansion.  A warning is issued if the end
3650 of the file is encountered without a newline.
3652 The expansion of @code{dnl} is void.
3653 @end deffn
3655 It is often used in connection with @code{define}, to remove the
3656 newline that follows the call to @code{define}.  Thus
3658 @example
3659 define(`foo', `Macro `foo'.')dnl A very simple macro, indeed.
3661 @result{}Macro foo.
3662 @end example
3664 The input up to and including the next newline is discarded, as opposed
3665 to the way comments are treated (@pxref{Comments}).
3667 Usually, @code{dnl} is immediately followed by an end of line or some
3668 other whitespace.  @acronym{GNU} @code{m4} will produce a warning diagnostic if
3669 @code{dnl} is followed by an open parenthesis.  In this case, @code{dnl}
3670 will collect and process all arguments, looking for a matching close
3671 parenthesis.  All predictable side effects resulting from this
3672 collection will take place.  @code{dnl} will return no output.  The
3673 input following the matching close parenthesis up to and including the
3674 next newline, on whatever line containing it, will still be discarded.
3676 @example
3677 dnl(`args are ignored, but side effects occur',
3678 define(`foo', `like this')) while this text is ignored: undefine(`foo')
3679 @error{}m4:stdin:1: Warning: dnl: extra arguments ignored: 2 > 0
3680 See how `foo' was defined, foo?
3681 @result{}See how foo was defined, like this?
3682 @end example
3684 If the end of file is encountered without a newline character, a
3685 warning is issued and dnl stops consuming input.
3687 @example
3688 m4wrap(`m4wrap(`2 hi
3689 ')0 hi dnl 1 hi')
3690 @result{}
3691 define(`hi', `HI')
3692 @result{}
3694 @error{}m4:stdin:1: Warning: dnl: end of file treated as newline
3695 @result{}0 HI 2 HI
3696 @end example
3698 @node Changequote
3699 @section Changing the quote characters
3701 @cindex changing quote delimiters
3702 @cindex quote delimiters, changing
3703 @cindex delimiters, changing
3704 The default quote delimiters can be changed with the builtin
3705 @code{changequote}:
3707 @deffn Builtin changequote (@dvar{start, `}, @dvar{end, '})
3708 This sets @var{start} as the new begin-quote delimiter and @var{end} as
3709 the new end-quote delimiter.  If both arguments are missing, the default
3710 quotes (@code{`} and @code{'}) are used.  If @var{start} is void, then
3711 quoting is disabled.  Otherwise, if @var{end} is missing or void, the
3712 default end-quote delimiter (@code{'}) is used.  The quote delimiters
3713 can be of any length.
3715 The expansion of @code{changequote} is void.
3716 @end deffn
3718 @example
3719 changequote(`[', `]')
3720 @result{}
3721 define([foo], [Macro [foo].])
3722 @result{}
3724 @result{}Macro foo.
3725 @end example
3727 The quotation strings can safely contain eight-bit characters.
3728 @ignore
3729 @comment Yuck.  I know of no clean way to render an 8-bit character in
3730 @comment both info and dvi.  This example uses the `open-guillemot' and
3731 @comment `close-guillemot' characters of the Latin-1 character set.
3733 @example
3734 define(`a', `b')
3735 @result{}
3736 «a»
3737 @result{}«b»
3738 changequote(`«', `»')
3739 @result{}
3740 «a»
3741 @result{}a
3742 @end example
3743 @end ignore
3744 If no single character is appropriate, @var{start} and @var{end} can be
3745 of any length.  Other implementations cap the delimiter length to five
3746 characters, but @acronym{GNU} has no inherent limit.
3748 @example
3749 changequote(`[[[', `]]]')
3750 @result{}
3751 define([[[foo]]], [[[Macro [[[[[foo]]]]].]]])
3752 @result{}
3754 @result{}Macro [[foo]].
3755 @end example
3757 Calling @code{changequote} with @var{start} as the empty string will
3758 effectively disable the quoting mechanism, leaving no way to quote text.
3759 However, using an empty string is not portable, as some other
3760 implementations of @code{m4} revert to the default quoting, while others
3761 preserve the prior non-empty delimiter.  If @var{start} is not empty,
3762 then an empty @var{end} will use the default end-quote delimiter of
3763 @samp{'}, as otherwise, it would be impossible to end a quoted string.
3764 Again, this is not portable, as some other @code{m4} implementations
3765 reuse @var{start} as the end-quote delimiter, while others preserve the
3766 previous non-empty value.  Omitting both arguments restores the default
3767 begin-quote and end-quote delimiters; fortunately this behavior is
3768 portable to all implementations of @code{m4}.
3770 @example
3771 define(`foo', `Macro `FOO'.')
3772 @result{}
3773 changequote(`', `')
3774 @result{}
3776 @result{}Macro `FOO'.
3777 `foo'
3778 @result{}`Macro `FOO'.'
3779 changequote(`,)
3780 @result{}
3782 @result{}Macro FOO.
3783 @end example
3785 There is no way in @code{m4} to quote a string containing an unmatched
3786 begin-quote, except using @code{changequote} to change the current
3787 quotes.
3789 If the quotes should be changed from, say, @samp{[} to @samp{[[},
3790 temporary quote characters have to be defined.  To achieve this, two
3791 calls of @code{changequote} must be made, one for the temporary quotes
3792 and one for the new quotes.
3794 Macros are recognized in preference to the begin-quote string, so if a
3795 prefix of @var{start} can be recognized as part of a potential macro
3796 name, the quoting mechanism is effectively disabled.  Unless you use
3797 @code{changeword} (@pxref{Changeword}), this means that @var{start}
3798 should not begin with a letter, digit, or @samp{_} (underscore).
3799 However, even though quoted strings are not recognized, the quote
3800 characters can still be discerned in macro expansion and in trace
3801 output.
3803 @example
3804 define(`echo', `$@@')
3805 @result{}
3806 define(`hi', `HI')
3807 @result{}
3808 changequote(`q', `Q')
3809 @result{}
3810 q hi Q hi
3811 @result{}q HI Q HI
3812 echo(hi)
3813 @result{}qHIQ
3814 changequote
3815 @result{}
3816 changequote(`-', `EOF')
3817 @result{}
3818 - hi EOF hi
3819 @result{} hi  HI
3820 changequote
3821 @result{}
3822 changequote(`1', `2')
3823 @result{}
3824 hi1hi2
3825 @result{}hi1hi2
3826 hi 1hi2
3827 @result{}HI hi
3828 @end example
3830 Quotes are recognized in preference to argument collection.  In
3831 particular, if @var{start} is a single @samp{(}, then argument
3832 collection is effectively disabled.  For portability with other
3833 implementations, it is a good idea to avoid @samp{(}, @samp{,}, and
3834 @samp{)} as the first character in @var{start}.
3836 @example
3837 define(`echo', `$#:$@@:')
3838 @result{}
3839 define(`hi', `HI')
3840 @result{}
3841 changequote(`(',`)')
3842 @result{}
3843 echo(hi)
3844 @result{}0::hi
3845 changequote
3846 @result{}
3847 changequote(`((', `))')
3848 @result{}
3849 echo(hi)
3850 @result{}1:HI:
3851 echo((hi))
3852 @result{}0::hi
3853 changequote
3854 @result{}
3855 changequote(`,', `)')
3856 @result{}
3857 echo(hi,hi)bye)
3858 @result{}1:HIhibye:
3859 @end example
3861 However, if you are not worried about portability, using @samp{(} and
3862 @samp{)} as quoting characters has an interesting property---you can use
3863 it to compute a quoted string containing the expansion of any quoted
3864 text, as long as the expansion results in both balanced quotes and
3865 balanced parentheses.  The trick is realizing @code{expand} uses
3866 @samp{$1} unquoted, to trigger its expansion using the normal quoting
3867 characters, but uses extra parentheses to group unquoted commas that
3868 occur in the expansion without consuming whitespace following those
3869 commas.  Then @code{_expand} uses @code{changequote} to convert the
3870 extra parentheses back into quoting characters.  Note that it takes two
3871 more @code{changequote} invocations to restore the original quotes.
3872 Contrast the behavior on whitespace when using @samp{$*}, via
3873 @code{quote}, to attempt the same task.
3875 @example
3876 changequote(`[', `]')dnl
3877 define([a], [1, (b)])dnl
3878 define([b], [2])dnl
3879 define([quote], [[$*]])dnl
3880 define([expand], [_$0(($1))])dnl
3881 define([_expand],
3882   [changequote([(], [)])$1changequote`'changequote(`[', `]')])dnl
3883 expand([a, a, [a, a], [[a, a]]])
3884 @result{}1, (2), 1, (2), a, a, [a, a]
3885 quote(a, a, [a, a], [[a, a]])
3886 @result{}1,(2),1,(2),a, a,[a, a]
3887 @end example
3889 If @var{end} is a prefix of @var{start}, the end-quote will be
3890 recognized in preference to a nested begin-quote.  In particular,
3891 changing the quotes to have the same string for @var{start} and
3892 @var{end} disables nesting of quotes.  When quote nesting is disabled,
3893 it is impossible to double-quote strings across macro expansions, so
3894 using the same string is not done very often.
3896 @example
3897 define(`hi', `HI')
3898 @result{}
3899 changequote(`""', `"')
3900 @result{}
3901 ""hi"""hi"
3902 @result{}hihi
3903 ""hi" ""hi"
3904 @result{}hi hi
3905 ""hi"" "hi"
3906 @result{}hi" "HI"
3907 changequote
3908 @result{}
3909 `hi`hi'hi'
3910 @result{}hi`hi'hi
3911 changequote(`"', `"')
3912 @result{}
3913 "hi"hi"hi"
3914 @result{}hiHIhi
3915 @end example
3917 @ignore
3918 @comment And another stress test, not worth documenting in the manual.
3919 @example
3920 define(`aaaaaaaaaaaaaaaaaaaa', `A')define(`q', `"$@@"')
3921 @result{}
3922 changequote(`"', `"')
3923 @result{}
3924 q(q("aaaaaaaaaaaaaaaaaaaa", "a"))
3925 @result{}A,a
3926 @end example
3927 @end ignore
3929 It is an error if the end of file occurs within a quoted string.
3931 @comment status: 1
3932 @example
3933 `hello world'
3934 @result{}hello world
3935 `dangling quote
3937 @error{}m4:stdin:2: end of file in string
3938 @end example
3940 @comment status: 1
3941 @example
3942 ifelse(`dangling quote
3944 @error{}m4:stdin:1: ifelse: end of file in string
3945 @end example
3947 @node Changecom
3948 @section Changing the comment delimiters
3950 @cindex changing comment delimiters
3951 @cindex comment delimiters, changing
3952 @cindex delimiters, changing
3953 The default comment delimiters can be changed with the builtin
3954 macro @code{changecom}:
3956 @deffn Builtin changecom (@ovar{start}, @dvar{end, @key{NL}})
3957 This sets @var{start} as the new begin-comment delimiter and @var{end}
3958 as the new end-comment delimiter.  If both arguments are missing, or
3959 @var{start} is void, then comments are disabled.  Otherwise, if
3960 @var{end} is missing or void, the default end-comment delimiter of
3961 newline is used.  The comment delimiters can be of any length.
3963 The expansion of @code{changecom} is void.
3964 @end deffn
3966 @example
3967 define(`comment', `COMMENT')
3968 @result{}
3969 # A normal comment
3970 @result{}# A normal comment
3971 changecom(`/*', `*/')
3972 @result{}
3973 # Not a comment anymore
3974 @result{}# Not a COMMENT anymore
3975 But: /* this is a comment now */ while this is not a comment
3976 @result{}But: /* this is a comment now */ while this is not a COMMENT
3977 @end example
3979 @cindex comments, copied to output
3980 Note how comments are copied to the output, much as if they were quoted
3981 strings.  If you want the text inside a comment expanded, quote the
3982 begin-comment delimiter.
3984 Calling @code{changecom} without any arguments, or with @var{start} as
3985 the empty string, will effectively disable the commenting mechanism.  To
3986 restore the original comment start of @samp{#}, you must explicitly ask
3987 for it.  If @var{start} is not empty, then an empty @var{end} will use
3988 the default end-comment delimiter of newline, as otherwise, it would be
3989 impossible to end a comment.  However, this is not portable, as some
3990 other @code{m4} implementations preserve the previous non-empty
3991 delimiters instead.
3993 @example
3994 define(`comment', `COMMENT')
3995 @result{}
3996 changecom
3997 @result{}
3998 # Not a comment anymore
3999 @result{}# Not a COMMENT anymore
4000 changecom(`#', `')
4001 @result{}
4002 # comment again
4003 @result{}# comment again
4004 @end example
4006 The comment strings can safely contain eight-bit characters.
4007 @ignore
4008 @comment Yuck.  I know of no clean way to render an 8-bit character in
4009 @comment both info and dvi.  This example uses the `open-guillemot' and
4010 @comment `close-guillemot' characters of the Latin-1 character set.
4012 @example
4013 define(`a', `b')
4014 @result{}
4015 «a»
4016 @result{}«b»
4017 changecom(`«', `»')
4018 @result{}
4019 «a»
4020 @result{}«a»
4021 @end example
4022 @end ignore
4023 If no single character is appropriate, @var{start} and @var{end} can be
4024 of any length.  Other implementations cap the delimiter length to five
4025 characters, but @acronym{GNU} has no inherent limit.
4027 Comments are recognized in preference to macros.  However, this is not
4028 compatible with other implementations, where macros and even quoting
4029 takes precedence over comments, so it may change in a future release.
4030 For portability, this means that @var{start} should not begin with a
4031 letter, digit, or @samp{_} (underscore), and that neither the
4032 start-quote nor the start-comment string should be a prefix of the
4033 other.
4035 @example
4036 define(`hi', `HI')
4037 @result{}
4038 define(`hi1hi2', `hello')
4039 @result{}
4040 changecom(`q', `Q')
4041 @result{}
4042 q hi Q hi
4043 @result{}q hi Q HI
4044 changecom(`1', `2')
4045 @result{}
4046 hi1hi2
4047 @result{}hello
4048 hi 1hi2
4049 @result{}HI 1hi2
4050 @end example
4052 Comments are recognized in preference to argument collection.  In
4053 particular, if @var{start} is a single @samp{(}, then argument
4054 collection is effectively disabled.  For portability with other
4055 implementations, it is a good idea to avoid @samp{(}, @samp{,}, and
4056 @samp{)} as the first character in @var{start}.
4058 @example
4059 define(`echo', `$#:$*:$@@:')
4060 @result{}
4061 define(`hi', `HI')
4062 @result{}
4063 changecom(`(',`)')
4064 @result{}
4065 echo(hi)
4066 @result{}0:::(hi)
4067 changecom
4068 @result{}
4069 changecom(`((', `))')
4070 @result{}
4071 echo(hi)
4072 @result{}1:HI:HI:
4073 echo((hi))
4074 @result{}0:::((hi))
4075 changecom(`,', `)')
4076 @result{}
4077 echo(hi,hi)bye)
4078 @result{}1:HI,hi)bye:HI,hi)bye:
4079 changecom
4080 @result{}
4081 echo(hi,`,`'hi',hi)
4082 @result{}3:HI,,HI,HI:HI,,`'hi,HI:
4083 echo(hi,`,`'hi',hi`'changecom(`,,', `hi'))
4084 @result{}3:HI,,`'hi,HI:HI,,`'hi,HI:
4085 @end example
4087 It is an error if the end of file occurs within a comment.
4089 @comment status: 1
4090 @example
4091 changecom(`/*', `*/')
4092 @result{}
4093 /*dangling comment
4095 @error{}m4:stdin:2: end of file in comment
4096 @end example
4098 @comment status: 1
4099 @example
4100 changecom(`/*', `*/')
4101 @result{}
4102 len(/*dangling comment
4104 @error{}m4:stdin:2: len: end of file in comment
4105 @end example
4107 @node Changeword
4108 @section Changing the lexical structure of words
4110 @cindex lexical structure of words
4111 @cindex words, lexical structure of
4112 @cindex syntax, changing
4113 @cindex changing syntax
4114 @cindex regular expressions
4115 @quotation
4116 The macro @code{changeword} and all associated functionality is
4117 experimental.  It is only available if the @option{--enable-changeword}
4118 option was given to @code{configure}, at @acronym{GNU} @code{m4} installation
4119 time.  The functionality will go away in the future, to be replaced by
4120 other new features that are more efficient at providing the same
4121 capabilities.  @emph{Do not rely on it}.  Please direct your comments
4122 about it the same way you would do for bugs.
4123 @end quotation
4125 A file being processed by @code{m4} is split into quoted strings, words
4126 (potential macro names) and simple tokens (any other single character).
4127 Initially a word is defined by the following regular expression:
4129 @comment ignore
4130 @example
4131 [_a-zA-Z][_a-zA-Z0-9]*
4132 @end example
4134 Using @code{changeword}, you can change this regular expression:
4136 @deffn {Optional builtin} changeword (@var{regex})
4137 Changes the regular expression for recognizing macro names to be
4138 @var{regex}.  If @var{regex} is empty, use
4139 @samp{[_a-zA-Z][_a-zA-Z0-9]*}.  @var{regex} must obey the constraint
4140 that every prefix of the desired final pattern is also accepted by the
4141 regular expression.  If @var{regex} contains grouping parentheses, the
4142 macro invoked is the portion that matched the first group, rather than
4143 the entire matching string.
4145 The expansion of @code{changeword} is void.
4146 The macro @code{changeword} is recognized only with parameters.
4147 @end deffn
4149 Relaxing the lexical rules of @code{m4} might be useful (for example) if
4150 you wanted to apply translations to a file of numbers:
4152 @example
4153 ifdef(`changeword', `', `errprint(` skipping: no changeword support
4154 ')m4exit(`77')')dnl
4155 changeword(`[_a-zA-Z0-9]+')
4156 @result{}
4157 define(`1', `0')1
4158 @result{}0
4159 @end example
4161 Tightening the lexical rules is less useful, because it will generally
4162 make some of the builtins unavailable.  You could use it to prevent
4163 accidental call of builtins, for example:
4165 @example
4166 ifdef(`changeword', `', `errprint(` skipping: no changeword support
4167 ')m4exit(`77')')dnl
4168 define(`_indir', defn(`indir'))
4169 @result{}
4170 changeword(`_[_a-zA-Z0-9]*')
4171 @result{}
4172 esyscmd(`foo')
4173 @result{}esyscmd(foo)
4174 _indir(`esyscmd', `echo hi')
4175 @result{}hi
4176 @result{}
4177 @end example
4179 Because @code{m4} constructs its words a character at a time, there
4180 is a restriction on the regular expressions that may be passed to
4181 @code{changeword}.  This is that if your regular expression accepts
4182 @samp{foo}, it must also accept @samp{f} and @samp{fo}.
4184 @example
4185 ifdef(`changeword', `', `errprint(` skipping: no changeword support
4186 ')m4exit(`77')')dnl
4187 define(`foo
4188 ', `bar
4190 @result{}
4191 dnl This example wants to recognize changeword, dnl, and `foo\n'.
4192 dnl First, we check that our regexp will match.
4193 regexp(`changeword', `[cd][a-z]*\|foo[
4195 @result{}0
4196 regexp(`foo
4197 ', `[cd][a-z]*\|foo[
4199 @result{}0
4200 regexp(`f', `[cd][a-z]*\|foo[
4202 @result{}-1
4204 @result{}foo
4205 changeword(`[cd][a-z]*\|foo[
4207 @result{}
4208 dnl Even though `foo\n' matches, we forgot to allow `f'.
4210 @result{}foo
4211 changeword(`[cd][a-z]*\|fo*[
4212 ]?')
4213 @result{}
4214 dnl Now we can call `foo\n'.
4216 @result{}bar
4217 @end example
4219 @ignore
4220 @comment One more test of including newline in a macro name; but this
4221 @comment does not need to be displayed in the manual.  This ensures
4222 @comment that line numbering is correct when dnl cuts across include
4223 @comment file boundaries, and when __file__ or __line__ is the last
4224 @comment token in an include file.
4226 @example
4227 ifdef(`changeword', `', `errprint(` skipping: no changeword support
4228 ')m4exit(`77')')dnl
4229 define(`bar
4230 ', defn(`dnl'))dnl
4231 define(`baz', `dnl
4232 include(`foo') ignored
4233 dnl')dnl
4234 changeword(`\([_a-zA-Z][_a-zA-Z0-9]*\|bar
4235 \)')
4236 @result{}
4237 __file__:__line__
4238 @result{}stdin:10
4239 include(`foo') ignored
4240 __file__:__line__
4241 @result{}stdin:12
4242 baz ignored
4243 __file__:__line__
4244 @result{}stdin:14
4245 define(`bar
4246 ', defn(`__file__'))
4247 @result{}
4248 include(`foo')
4249 @result{}../examples/foo
4250 define(`bar
4251 ', defn(`__line__'))
4252 @result{}
4253 include(`foo')
4254 @result{}1
4255 __file__:__line__
4256 @result{}stdin:21
4257 @end example
4258 @end ignore
4260 @code{changeword} has another function.  If the regular expression
4261 supplied contains any grouped subexpressions, then text outside
4262 the first of these is discarded before symbol lookup.  So:
4264 @example
4265 ifdef(`changeword', `', `errprint(` skipping: no changeword support
4266 ')m4exit(`77')')dnl
4267 ifdef(`__unix__', ,
4268       `errprint(` skipping: syscmd does not have unix semantics
4269 ')m4exit(`77')')dnl
4270 changecom(`/*', `*/')dnl
4271 define(`foo', `bar')dnl
4272 changeword(`#\([_a-zA-Z0-9]*\)')
4273 @result{}
4274 #esyscmd(`echo foo \#foo')
4275 @result{}foo bar
4276 @result{}
4277 @end example
4279 @code{m4} now requires a @samp{#} mark at the beginning of every
4280 macro invocation, so one can use @code{m4} to preprocess plain
4281 text without losing various words like @samp{divert}.
4283 In @code{m4}, macro substitution is based on text, while in @TeX{}, it
4284 is based on tokens.  @code{changeword} can throw this difference into
4285 relief.  For example, here is the same idea represented in @TeX{} and
4286 @code{m4}.  First, the @TeX{} version:
4288 @comment ignore
4289 @example
4290 \def\a@{\message@{Hello@}@}
4291 \catcode`\@@=0
4292 \catcode`\\=12
4294 @@bye
4295 @result{}Hello
4296 @end example
4298 @noindent
4299 Then, the @code{m4} version:
4301 @example
4302 ifdef(`changeword', `', `errprint(` skipping: no changeword support
4303 ')m4exit(`77')')dnl
4304 define(`a', `errprint(`Hello')')dnl
4305 changeword(`@@\([_a-zA-Z0-9]*\)')
4306 @result{}
4308 @result{}errprint(Hello)
4309 @end example
4311 In the @TeX{} example, the first line defines a macro @code{a} to
4312 print the message @samp{Hello}.  The second line defines @key{@@} to
4313 be usable instead of @key{\} as an escape character.  The third line
4314 defines @key{\} to be a normal printing character, not an escape.
4315 The fourth line invokes the macro @code{a}.  So, when @TeX{} is run
4316 on this file, it displays the message @samp{Hello}.
4318 When the @code{m4} example is passed through @code{m4}, it outputs
4319 @samp{errprint(Hello)}.  The reason for this is that @TeX{} does
4320 lexical analysis of macro definition when the macro is @emph{defined}.
4321 @code{m4} just stores the text, postponing the lexical analysis until
4322 the macro is @emph{used}.
4324 You should note that using @code{changeword} will slow @code{m4} down
4325 by a factor of about seven, once it is changed to something other
4326 than the default regular expression.  You can invoke @code{changeword}
4327 with the empty string to restore the default word definition, and regain
4328 the parsing speed.
4330 @node M4wrap
4331 @section Saving text until end of input
4333 @cindex saving input
4334 @cindex input, saving
4335 @cindex deferring expansion
4336 @cindex expansion, deferring
4337 It is possible to `save' some text until the end of the normal input has
4338 been seen.  Text can be saved, to be read again by @code{m4} when the
4339 normal input has been exhausted.  This feature is normally used to
4340 initiate cleanup actions before normal exit, e.g., deleting temporary
4341 files.
4343 To save input text, use the builtin @code{m4wrap}:
4345 @deffn Builtin m4wrap (@var{string}, @dots{})
4346 Stores @var{string} in a safe place, to be reread when end of input is
4347 reached.  As a @acronym{GNU} extension, additional arguments are
4348 concatenated with a space to the @var{string}.
4350 The expansion of @code{m4wrap} is void.
4351 The macro @code{m4wrap} is recognized only with parameters.
4352 @end deffn
4354 @example
4355 define(`cleanup', `This is the `cleanup' action.
4357 @result{}
4358 m4wrap(`cleanup')
4359 @result{}
4360 This is the first and last normal input line.
4361 @result{}This is the first and last normal input line.
4363 @result{}This is the cleanup action.
4364 @end example
4366 The saved input is only reread when the end of normal input is seen, and
4367 not if @code{m4exit} is used to exit @code{m4}.
4369 @comment FIXME: this contradicts POSIX, which requires that "If the
4370 @comment m4wrap macro is used multiple times, the arguments specified
4371 @comment shall be processed in the order in which the m4wrap macros were
4372 @comment processed."
4373 It is safe to call @code{m4wrap} from saved text, but then the order in
4374 which the saved text is reread is undefined.  If @code{m4wrap} is not used
4375 recursively, the saved pieces of text are reread in the opposite order
4376 in which they were saved (LIFO---last in, first out).  However, this
4377 behavior is likely to change in a future release, to match
4378 @acronym{POSIX}, so you should not depend on this order.
4380 Here is an example of implementing a factorial function using
4381 @code{m4wrap}:
4383 @example
4384 define(`f', `ifelse(`$1', `0', `Answer: 0!=1
4385 ', eval(`$1>1'), `0', `Answer: $2$1=eval(`$2$1')
4386 ', `m4wrap(`f(decr(`$1'), `$2$1*')')')')
4387 @result{}
4388 f(`10')
4389 @result{}
4391 @result{}Answer: 10*9*8*7*6*5*4*3*2*1=3628800
4392 @end example
4394 Invocations of @code{m4wrap} at the same recursion level are
4395 concatenated and rescanned as usual:
4397 @example
4398 define(`aa', `AA
4400 @result{}
4401 m4wrap(`a')m4wrap(`a')
4402 @result{}
4404 @result{}AA
4405 @end example
4407 @noindent
4408 however, the transition between recursion levels behaves like an end of
4409 file condition between two input files.
4411 @comment status: 1
4412 @example
4413 m4wrap(`m4wrap(`)')len(abc')
4414 @result{}
4416 @error{}m4:stdin:1: len: end of file in argument list
4417 @end example
4419 @node File Inclusion
4420 @chapter File inclusion
4422 @cindex file inclusion
4423 @cindex inclusion, of files
4424 @code{m4} allows you to include named files at any point in the input.
4426 @menu
4427 * Include::                     Including named files
4428 * Search Path::                 Searching for include files
4429 @end menu
4431 @node Include
4432 @section Including named files
4434 There are two builtin macros in @code{m4} for including files:
4436 @deffn Builtin include (@var{file})
4437 @deffnx Builtin sinclude (@var{file})
4438 Both macros cause the file named @var{file} to be read by
4439 @code{m4}.  When the end of the file is reached, input is resumed from
4440 the previous input file.
4442 The expansion of @code{include} and @code{sinclude} is therefore the
4443 contents of @var{file}.
4445 If @var{file} does not exist (or cannot be read), the expansion is void,
4446 and @code{include} will fail with an error while @code{sinclude} is
4447 silent.  The empty string counts as a file that does not exist.
4449 The macros @code{include} and @code{sinclude} are recognized only with
4450 parameters.
4451 @end deffn
4453 @comment status: 1
4454 @example
4455 include(`n')
4456 @error{}m4:stdin:1: include: cannot open `n': No such file or directory
4457 @result{}
4458 include()
4459 @error{}m4:stdin:2: include: cannot open `': No such file or directory
4460 @result{}
4461 sinclude(`n')
4462 @result{}
4463 sinclude()
4464 @result{}
4465 @end example
4467 The rest of this section assumes that @code{m4} is invoked with the
4468 @option{-I} option (@pxref{Preprocessor features, , Invoking m4})
4469 pointing to the @file{m4-@value{VERSION}/@/examples}
4470 directory shipped as part of the @acronym{GNU} @code{m4} package.  The
4471 file @file{m4-@value{VERSION}/@/examples/@/incl.m4} in the distribution
4472 contains the lines:
4474 @comment ignore
4475 @example
4476 $ @kbd{cat examples/incl.m4}
4477 @result{}Include file start
4478 @result{}foo
4479 @result{}Include file end
4480 @end example
4482 Normally file inclusion is used to insert the contents of a file
4483 into the input stream.  The contents of the file will be read by
4484 @code{m4} and macro calls in the file will be expanded:
4486 @comment examples
4487 @example
4488 $ @kbd{m4 -I examples}
4489 define(`foo', `FOO')
4490 @result{}
4491 include(`incl.m4')
4492 @result{}Include file start
4493 @result{}FOO
4494 @result{}Include file end
4495 @result{}
4496 @end example
4498 The fact that @code{include} and @code{sinclude} expand to the contents
4499 of the file can be used to define macros that operate on entire files.
4500 Here is an example, which defines @samp{bar} to expand to the contents
4501 of @file{incl.m4}:
4503 @comment examples
4504 @example
4505 $ @kbd{m4 -I examples}
4506 define(`bar', include(`incl.m4'))
4507 @result{}
4508 This is `bar':  >>bar<<
4509 @result{}This is bar:  >>Include file start
4510 @result{}foo
4511 @result{}Include file end
4512 @result{}<<
4513 @end example
4515 This use of @code{include} is not trivial, though, as files can contain
4516 quotes, commas, and parentheses, which can interfere with the way the
4517 @code{m4} parser works.  @acronym{GNU} @code{m4} seamlessly concatenates
4518 the file contents with the next character, even if the included file
4519 ended in the middle of a comment, string, or macro call.  These
4520 conditions are only treated as end of file errors if specified as input
4521 files on the command line.
4523 In @acronym{GNU} @code{m4}, an alternative method of reading files is
4524 using @code{undivert} (@pxref{Undivert}) on a named file.
4526 @node Search Path
4527 @section Searching for include files
4529 @cindex search path for included files
4530 @cindex included files, search path for
4531 @cindex @acronym{GNU} extensions
4532 @acronym{GNU} @code{m4} allows included files to be found in other directories
4533 than the current working directory.
4535 @cindex @env{M4PATH}
4536 If the @option{--prepend-include} or @option{-B} command-line option was
4537 provided (@pxref{Preprocessor features, , Invoking m4}), those
4538 directories are searched first, in reverse order that those options were
4539 listed on the command line.  Then @code{m4} looks in the current working
4540 directory.  Next comes the directories specified with the
4541 @option{--include} or @option{-I} option, in the order found on the
4542 command line.  Finally, if the @env{M4PATH} environment variable is set,
4543 it is expected to contain a colon-separated list of directories, which
4544 will be searched in order.
4546 If the automatic search for include-files causes trouble, the @samp{p}
4547 debug flag (@pxref{Debug Levels}) can help isolate the problem.
4549 @node Diversions
4550 @chapter Diverting and undiverting output
4552 @cindex deferring output
4553 Diversions are a way of temporarily saving output.  The output of
4554 @code{m4} can at any time be diverted to a temporary file, and be
4555 reinserted into the output stream, @dfn{undiverted}, again at a later
4556 time.
4558 @cindex @env{TMPDIR}
4559 Numbered diversions are counted from 0 upwards, diversion number 0
4560 being the normal output stream.  The number of simultaneous diversions
4561 is limited mainly by the memory used to describe them, because @acronym{GNU}
4562 @code{m4} tries to keep diversions in memory.  However, there is a
4563 limit to the overall memory usable by all diversions taken altogether
4564 (512K, currently).  When this maximum is about to be exceeded,
4565 a temporary file is opened to receive the contents of the biggest
4566 diversion still in memory, freeing this memory for other diversions.
4567 When creating the temporary file, @code{m4} honors the value of the
4568 environment variable @env{TMPDIR}, and falls back to @file{/tmp}.
4569 So, it is theoretically possible that the number and aggregate size of
4570 diversions is limited only by available disk space.
4572 @ignore
4573 @comment We need to test spilled diversions, but don't need to expose
4574 @comment this highly repetitive test in the manual.
4576 @example
4577 divert(`-1')define(`f', `.')
4578 define(`f', defn(`f')defn(`f'))
4579 define(`f', defn(`f')defn(`f'))
4580 define(`f', defn(`f')defn(`f'))
4581 define(`f', defn(`f')defn(`f'))
4582 define(`f', defn(`f')defn(`f'))
4583 define(`f', defn(`f')defn(`f'))
4584 define(`f', defn(`f')defn(`f'))
4585 define(`f', defn(`f')defn(`f'))
4586 define(`f', defn(`f')defn(`f'))
4587 define(`f', defn(`f')defn(`f'))
4588 define(`f', defn(`f')defn(`f'))
4589 define(`f', defn(`f')defn(`f'))
4590 define(`f', defn(`f')defn(`f'))
4591 define(`f', defn(`f')defn(`f'))
4592 define(`f', defn(`f')defn(`f'))
4593 define(`f', defn(`f')defn(`f'))
4594 define(`f', defn(`f')defn(`f'))
4595 define(`f', defn(`f')defn(`f'))
4596 define(`f', defn(`f')defn(`f'))
4597 define(`f', defn(`f')defn(`f'))
4598 divert`'dnl
4599 len(f)
4600 @result{}1048576
4601 divert(`1')
4603 divert(`-1')undivert
4604 @end example
4606 @comment Another test of spilled diversions.
4608 @example
4609 divert(`-1')define(`f', `.')
4610 define(`f', defn(`f')defn(`f'))
4611 define(`f', defn(`f')defn(`f'))
4612 define(`f', defn(`f')defn(`f'))
4613 define(`f', defn(`f')defn(`f'))
4614 define(`f', defn(`f')defn(`f'))
4615 define(`f', defn(`f')defn(`f'))
4616 define(`f', defn(`f')defn(`f'))
4617 define(`f', defn(`f')defn(`f'))
4618 define(`f', defn(`f')defn(`f'))
4619 define(`f', defn(`f')defn(`f'))
4620 define(`f', defn(`f')defn(`f'))
4621 define(`f', defn(`f')defn(`f'))
4622 define(`f', defn(`f')defn(`f'))
4623 define(`f', defn(`f')defn(`f'))
4624 define(`f', defn(`f')defn(`f'))
4625 define(`f', defn(`f')defn(`f'))
4626 define(`f', defn(`f')defn(`f'))
4627 define(`f', defn(`f')defn(`f'))
4628 define(`f', defn(`f')defn(`f'))
4629 define(`f', defn(`f')defn(`f'))
4630 divert`'dnl
4631 len(f)
4632 @result{}1048576
4633 divert(`1')
4635 m4exit
4636 @end example
4637 @end ignore
4639 Diversions make it possible to generate output in a different order than
4640 the input was read.  It is possible to implement topological sorting
4641 dependencies.  For example, @acronym{GNU} Autoconf makes use of
4642 diversions under the hood to ensure that the expansion of a prerequisite
4643 macro appears in the output prior to the expansion of a dependent macro,
4644 regardless of which order the two macros were invoked in the user's
4645 input file.
4647 @menu
4648 * Divert::                      Diverting output
4649 * Undivert::                    Undiverting output
4650 * Divnum::                      Diversion numbers
4651 * Cleardivert::                 Discarding diverted text
4652 @end menu
4654 @node Divert
4655 @section Diverting output
4657 @cindex diverting output to files
4658 @cindex output, diverting to files
4659 @cindex files, diverting output to
4660 Output is diverted using @code{divert}:
4662 @deffn Builtin divert (@dvar{number, 0})
4663 The current diversion is changed to @var{number}.  If @var{number} is left
4664 out or empty, it is assumed to be zero.  If @var{number} cannot be
4665 parsed, the diversion is unchanged.
4667 The expansion of @code{divert} is void.
4668 @end deffn
4670 When all the @code{m4} input will have been processed, all existing
4671 diversions are automatically undiverted, in numerical order.
4673 @example
4674 divert(`1')
4675 This text is diverted.
4676 divert
4677 @result{}
4678 This text is not diverted.
4679 @result{}This text is not diverted.
4681 @result{}
4682 @result{}This text is diverted.
4683 @end example
4685 Several calls of @code{divert} with the same argument do not overwrite
4686 the previous diverted text, but append to it.  Diversions are printed
4687 after any wrapped text is expanded.
4689 @example
4690 define(`text', `TEXT')
4691 @result{}
4692 divert(`1')`diverted text.'
4693 divert
4694 @result{}
4695 m4wrap(`Wrapped text precedes ')
4696 @result{}
4698 @result{}Wrapped TEXT precedes diverted text.
4699 @end example
4701 @cindex discarding input
4702 @cindex input, discarding
4703 If output is diverted to a negative diversion, it is simply discarded.
4704 This can be used to suppress unwanted output.  A common example of
4705 unwanted output is the trailing newlines after macro definitions.  Here
4706 is a common programming idiom in @code{m4} for avoiding them.
4708 @example
4709 divert(`-1')
4710 define(`foo', `Macro `foo'.')
4711 define(`bar', `Macro `bar'.')
4712 divert
4713 @result{}
4714 @end example
4716 @cindex @acronym{GNU} extensions
4717 Traditional implementations only supported ten diversions.  But as a
4718 @acronym{GNU} extension, diversion numbers can be as large as positive
4719 integers will allow, rather than treating a multi-digit diversion number
4720 as a request to discard text.
4722 @example
4723 divert(eval(`1<<28'))world
4724 divert(`2')hello
4726 @result{}hello
4727 @result{}world
4728 @end example
4730 Note that @code{divert} is an English word, but also an active macro
4731 without arguments.  When processing plain text, the word might appear in
4732 normal text and be unintentionally swallowed as a macro invocation.  One
4733 way to avoid this is to use the @option{-P} option to rename all
4734 builtins (@pxref{Operation modes, , Invoking m4}).  Another is to write
4735 a wrapper that requires a parameter to be recognized.
4737 @example
4738 We decided to divert the stream for irrigation.
4739 @result{}We decided to  the stream for irrigation.
4740 define(`divert', `ifelse(`$#', `0', ``$0'', `builtin(`$0', $@@)')')
4741 @result{}
4742 divert(`-1')
4743 Ignored text.
4744 divert(`0')
4745 @result{}
4746 We decided to divert the stream for irrigation.
4747 @result{}We decided to divert the stream for irrigation.
4748 @end example
4750 @node Undivert
4751 @section Undiverting output
4753 Diverted text can be undiverted explicitly using the builtin
4754 @code{undivert}:
4756 @deffn Builtin undivert (@ovar{diversions@dots{}})
4757 Undiverts the numeric @var{diversions} given by the arguments, in the
4758 order given.  If no arguments are supplied, all diversions are
4759 undiverted, in numerical order.
4761 @cindex file inclusion
4762 @cindex inclusion, of files
4763 @cindex @acronym{GNU} extensions
4764 As a @acronym{GNU} extension, @var{diversions} may contain non-numeric
4765 strings, which are treated as the names of files to copy into the output
4766 without expansion.  A warning is issued if a file could not be opened.
4768 The expansion of @code{undivert} is void.
4769 @end deffn
4771 @example
4772 divert(`1')
4773 This text is diverted.
4774 divert
4775 @result{}
4776 This text is not diverted.
4777 @result{}This text is not diverted.
4778 undivert(`1')
4779 @result{}
4780 @result{}This text is diverted.
4781 @result{}
4782 @end example
4784 Notice the last two blank lines.  One of them comes from the newline
4785 following @code{undivert}, the other from the newline that followed the
4786 @code{divert}!  A diversion often starts with a blank line like this.
4788 When diverted text is undiverted, it is @emph{not} reread by @code{m4},
4789 but rather copied directly to the current output, and it is therefore
4790 not an error to undivert into a diversion.  Undiverting the empty string
4791 is the same as specifying diversion 0; in either case nothing happens
4792 since the output has already been flushed.
4794 @example
4795 divert(`1')diverted text
4796 divert
4797 @result{}
4798 undivert()
4799 @result{}
4800 undivert(`0')
4801 @result{}
4802 undivert
4803 @result{}diverted text
4804 @result{}
4805 @end example
4807 When a diversion has been undiverted, the diverted text is discarded,
4808 and it is not possible to bring back diverted text more than once.
4810 @example
4811 divert(`1')
4812 This text is diverted first.
4813 divert(`0')undivert(`1')dnl
4814 @result{}
4815 @result{}This text is diverted first.
4816 undivert(`1')
4817 @result{}
4818 divert(`1')
4819 This text is also diverted but not appended.
4820 divert(`0')undivert(`1')dnl
4821 @result{}
4822 @result{}This text is also diverted but not appended.
4823 @end example
4825 Attempts to undivert the current diversion are silently ignored.  Thus,
4826 when the current diversion is not 0, the current diversion does not get
4827 rearranged among the other diversions.
4829 @example
4830 divert(`1')one
4831 divert(`2')two
4832 divert(`3')three
4833 divert(`2')undivert`'dnl
4834 divert`'undivert`'dnl
4835 @result{}two
4836 @result{}one
4837 @result{}three
4838 @end example
4840 @cindex @acronym{GNU} extensions
4841 @cindex file inclusion
4842 @cindex inclusion, of files
4843 @acronym{GNU} @code{m4} allows named files to be undiverted.  Given a
4844 non-numeric argument, the contents of the file named will be copied,
4845 uninterpreted, to the current output.  This complements the builtin
4846 @code{include} (@pxref{Include}).  To illustrate the difference, assume
4847 the file @file{foo} contains:
4849 @comment ignore
4850 @example
4851 $ @kbd{cat foo}
4853 @end example
4855 @noindent
4856 then
4858 @example
4859 define(`bar', `BAR')
4860 @result{}
4861 undivert(`foo')
4862 @result{}bar
4863 @result{}
4864 include(`foo')
4865 @result{}BAR
4866 @result{}
4867 @end example
4869 If the file is not found (or cannot be read), an error message is
4870 issued, and the expansion is void.  It is possible to intermix files
4871 and diversion numbers.
4873 @example
4874 divert(`1')diversion one
4875 divert(`2')undivert(`foo')dnl
4876 divert(`3')diversion three
4877 divert`'dnl
4878 undivert(`1', `2', `foo', `3')dnl
4879 @result{}diversion one
4880 @result{}bar
4881 @result{}bar
4882 @result{}diversion three
4883 @end example
4885 @node Divnum
4886 @section Diversion numbers
4888 @cindex diversion numbers
4889 The current diversion is tracked by the builtin @code{divnum}:
4891 @deffn Builtin divnum
4892 Expands to the number of the current diversion.
4893 @end deffn
4895 @example
4896 Initial divnum
4897 @result{}Initial 0
4898 divert(`1')
4899 Diversion one: divnum
4900 divert(`2')
4901 Diversion two: divnum
4903 @result{}
4904 @result{}Diversion one: 1
4905 @result{}
4906 @result{}Diversion two: 2
4907 @end example
4909 @node Cleardivert
4910 @section Discarding diverted text
4912 @cindex discarding diverted text
4913 @cindex diverted text, discarding
4914 Often it is not known, when output is diverted, whether the diverted
4915 text is actually needed.  Since all non-empty diversion are brought back
4916 on the main output stream when the end of input is seen, a method of
4917 discarding a diversion is needed.  If all diversions should be
4918 discarded, the easiest is to end the input to @code{m4} with
4919 @samp{divert(`-1')} followed by an explicit @samp{undivert}:
4921 @example
4922 divert(`1')
4923 Diversion one: divnum
4924 divert(`2')
4925 Diversion two: divnum
4926 divert(`-1')
4927 undivert
4929 @end example
4931 @noindent
4932 No output is produced at all.
4934 Clearing selected diversions can be done with the following macro:
4936 @deffn Composite cleardivert (@ovar{diversions@dots{}})
4937 Discard the contents of each of the listed numeric @var{diversions}.
4938 @end deffn
4940 @example
4941 define(`cleardivert',
4942 `pushdef(`_n', divnum)divert(`-1')undivert($@@)divert(_n)popdef(`_n')')
4943 @result{}
4944 @end example
4946 It is called just like @code{undivert}, but the effect is to clear the
4947 diversions, given by the arguments.  (This macro has a nasty bug!  You
4948 should try to see if you can find it and correct it; or @pxref{Improved
4949 cleardivert, , Answers}).
4951 @node Text handling
4952 @chapter Macros for text handling
4954 There are a number of builtins in @code{m4} for manipulating text in
4955 various ways, extracting substrings, searching, substituting, and so on.
4957 @menu
4958 * Len::                         Calculating length of strings
4959 * Index macro::                 Searching for substrings
4960 * Regexp::                      Searching for regular expressions
4961 * Substr::                      Extracting substrings
4962 * Translit::                    Translating characters
4963 * Patsubst::                    Substituting text by regular expression
4964 * Format::                      Formatting strings (printf-like)
4965 @end menu
4967 @node Len
4968 @section Calculating length of strings
4970 @cindex length of strings
4971 @cindex strings, length of
4972 The length of a string can be calculated by @code{len}:
4974 @deffn Builtin len (@var{string})
4975 Expands to the length of @var{string}, as a decimal number.
4977 The macro @code{len} is recognized only with parameters.
4978 @end deffn
4980 @example
4981 len()
4982 @result{}0
4983 len(`abcdef')
4984 @result{}6
4985 @end example
4987 @node Index macro
4988 @section Searching for substrings
4990 @cindex substrings, locating
4991 Searching for substrings is done with @code{index}:
4993 @deffn Builtin index (@var{string}, @var{substring})
4994 Expands to the index of the first occurrence of @var{substring} in
4995 @var{string}.  The first character in @var{string} has index 0.  If
4996 @var{substring} does not occur in @var{string}, @code{index} expands to
4997 @samp{-1}.
4999 The macro @code{index} is recognized only with parameters.
5000 @end deffn
5002 @example
5003 index(`gnus, gnats, and armadillos', `nat')
5004 @result{}7
5005 index(`gnus, gnats, and armadillos', `dag')
5006 @result{}-1
5007 @end example
5009 Omitting @var{substring} evokes a warning, but still produces output;
5010 contrast this with an empty @var{substring}.
5012 @example
5013 index(`abc')
5014 @error{}m4:stdin:1: Warning: index: too few arguments: 1 < 2
5015 @result{}0
5016 index(`abc', `')
5017 @result{}0
5018 index(`abc', `b')
5019 @result{}1
5020 @end example
5022 @node Regexp
5023 @section Searching for regular expressions
5025 @cindex basic regular expressions
5026 @cindex regular expressions
5027 @cindex expressions, regular
5028 @cindex @acronym{GNU} extensions
5029 Searching for regular expressions is done with the builtin
5030 @code{regexp}:
5032 @deffn Builtin regexp (@var{string}, @var{regexp}, @ovar{replacement})
5033 Searches for @var{regexp} in @var{string}.  The syntax for regular
5034 expressions is the same as in @acronym{GNU} Emacs, which is similar to
5035 @acronym{BRE, Basic Regular Expressions} in @acronym{POSIX}.
5036 @ifnothtml
5037 @xref{Regexps, , Syntax of Regular Expressions, emacs, The GNU Emacs
5038 Manual}.
5039 @end ifnothtml
5040 @ifhtml
5042 @uref{http://www.gnu.org/@/software/@/emacs/@/manual/@/emacs.html#Regexps,
5043 Syntax of Regular Expressions} in the @acronym{GNU} Emacs Manual.
5044 @end ifhtml
5045 Support for @acronym{ERE, Extended Regular Expressions} is not
5046 available, but will be added in @acronym{GNU} M4 2.0.
5048 If @var{replacement} is omitted, @code{regexp} expands to the index of
5049 the first match of @var{regexp} in @var{string}.  If @var{regexp} does
5050 not match anywhere in @var{string}, it expands to -1.
5052 If @var{replacement} is supplied, and there was a match, @code{regexp}
5053 changes the expansion to this argument, with @samp{\@var{n}} substituted
5054 by the text matched by the @var{n}th parenthesized sub-expression of
5055 @var{regexp}, up to nine sub-expressions.  The escape @samp{\&} is
5056 replaced by the text of the entire regular expression matched.  For
5057 all other characters, @samp{\} treats the next character literally.  A
5058 warning is issued if there were fewer sub-expressions than the
5059 @samp{\@var{n}} requested, or if there is a trailing @samp{\}.  If there
5060 was no match, @code{regexp} expands to the empty string.
5062 The macro @code{regexp} is recognized only with parameters.
5063 @end deffn
5065 @example
5066 regexp(`GNUs not Unix', `\<[a-z]\w+')
5067 @result{}5
5068 regexp(`GNUs not Unix', `\<Q\w*')
5069 @result{}-1
5070 regexp(`GNUs not Unix', `\w\(\w+\)$', `*** \& *** \1 ***')
5071 @result{}*** Unix *** nix ***
5072 regexp(`GNUs not Unix', `\<Q\w*', `*** \& *** \1 ***')
5073 @result{}
5074 @end example
5076 Here are some more examples on the handling of backslash:
5078 @example
5079 regexp(`abc', `\(b\)', `\\\10\a')
5080 @result{}\b0a
5081 regexp(`abc', `b', `\1\')
5082 @error{}m4:stdin:2: Warning: regexp: sub-expression 1 not present
5083 @error{}m4:stdin:2: Warning: regexp: trailing \ ignored in replacement
5084 @result{}
5085 regexp(`abc', `\(\(d\)?\)\(c\)', `\1\2\3\4\5\6')
5086 @error{}m4:stdin:3: Warning: regexp: sub-expression 4 not present
5087 @error{}m4:stdin:3: Warning: regexp: sub-expression 5 not present
5088 @error{}m4:stdin:3: Warning: regexp: sub-expression 6 not present
5089 @result{}c
5090 @end example
5092 Omitting @var{regexp} evokes a warning, but still produces output;
5093 contrast this with an empty @var{regexp} argument.
5095 @example
5096 regexp(`abc')
5097 @error{}m4:stdin:1: Warning: regexp: too few arguments: 1 < 2
5098 @result{}0
5099 regexp(`abc', `')
5100 @result{}0
5101 regexp(`abc', `', `\\def')
5102 @result{}\def
5103 @end example
5105 @node Substr
5106 @section Extracting substrings
5108 @cindex extracting substrings
5109 @cindex substrings, extracting
5110 Substrings are extracted with @code{substr}:
5112 @deffn Builtin substr (@var{string}, @var{from}, @ovar{length})
5113 Expands to the substring of @var{string}, which starts at index
5114 @var{from}, and extends for @var{length} characters, or to the end of
5115 @var{string}, if @var{length} is omitted.  The starting index of a string
5116 is always 0.  The expansion is empty if there is an error parsing
5117 @var{from} or @var{length}, if @var{from} is beyond the end of
5118 @var{string}, or if @var{length} is negative.
5120 The macro @code{substr} is recognized only with parameters.
5121 @end deffn
5123 @example
5124 substr(`gnus, gnats, and armadillos', `6')
5125 @result{}gnats, and armadillos
5126 substr(`gnus, gnats, and armadillos', `6', `5')
5127 @result{}gnats
5128 @end example
5130 Omitting @var{from} evokes a warning, but still produces output.
5132 @example
5133 substr(`abc')
5134 @error{}m4:stdin:1: Warning: substr: too few arguments: 1 < 2
5135 @result{}abc
5136 substr(`abc',)
5137 @error{}m4:stdin:2: Warning: substr: empty string treated as 0
5138 @result{}abc
5139 @end example
5141 @node Translit
5142 @section Translating characters
5144 @cindex translating characters
5145 @cindex characters, translating
5146 Character translation is done with @code{translit}:
5148 @deffn Builtin translit (@var{string}, @var{chars}, @ovar{replacement})
5149 Expands to @var{string}, with each character that occurs in
5150 @var{chars} translated into the character from @var{replacement} with
5151 the same index.
5153 If @var{replacement} is shorter than @var{chars}, the excess characters
5154 of @var{chars} are deleted from the expansion; if @var{chars} is
5155 shorter, the excess characters in @var{replacement} are silently
5156 ignored.  If @var{replacement} is omitted, all characters in
5157 @var{string} that are present in @var{chars} are deleted from the
5158 expansion.  If a character appears more than once in @var{chars}, only
5159 the first instance is used in making the translation.  Only a single
5160 translation pass is made, even if characters in @var{replacement} also
5161 appear in @var{chars}.
5163 As a @acronym{GNU} extension, both @var{chars} and @var{replacement} can
5164 contain character-ranges, e.g., @samp{a-z} (meaning all lowercase
5165 letters) or @samp{0-9} (meaning all digits).  To include a dash @samp{-}
5166 in @var{chars} or @var{replacement}, place it first or last in the
5167 entire string, or as the last character of a range.  Back-to-back ranges
5168 can share a common endpoint.  It is not an error for the last character
5169 in the range to be `larger' than the first.  In that case, the range
5170 runs backwards, i.e., @samp{9-0} means the string @samp{9876543210}.
5171 The expansion of a range is dependent on the underlying encoding of
5172 characters, so using ranges is not always portable between machines.
5174 The macro @code{translit} is recognized only with parameters.
5175 @end deffn
5177 @example
5178 translit(`GNUs not Unix', `A-Z')
5179 @result{}s not nix
5180 translit(`GNUs not Unix', `a-z', `A-Z')
5181 @result{}GNUS NOT UNIX
5182 translit(`GNUs not Unix', `A-Z', `z-a')
5183 @result{}tmfs not fnix
5184 translit(`+,-12345', `+--1-5', `<;>a-c-a')
5185 @result{}<;>abcba
5186 translit(`abcdef', `aabdef', `bcged')
5187 @result{}bgced
5188 @end example
5190 In the @sc{ascii} encoding, the first example deletes all uppercase
5191 letters, the second converts lowercase to uppercase, and the third
5192 `mirrors' all uppercase letters, while converting them to lowercase.
5193 The two first cases are by far the most common, even though they are not
5194 portable to @sc{ebcdic} or other encodings.  The fourth example shows a
5195 range ending in @samp{-}, as well as back-to-back ranges.  The final
5196 example shows that @samp{a} is mapped to @samp{b}, not @samp{c}; the
5197 resulting @samp{b} is not further remapped to @samp{g}; the @samp{d} and
5198 @samp{e} are swapped, and the @samp{f} is discarded.
5200 @ignore
5201 @comment No need to fight 8-bit characters, as it is difficult to get
5202 @comment rendering right in both info and dvi.
5204 @example
5205 translit(`«abc~', `~-»')
5206 @result{}abc
5207 @end example
5208 @end ignore
5210 Omitting @var{chars} evokes a warning, but still produces output.
5212 @example
5213 translit(`abc')
5214 @error{}m4:stdin:1: Warning: translit: too few arguments: 1 < 2
5215 @result{}abc
5216 @end example
5218 @node Patsubst
5219 @section Substituting text by regular expression
5221 @cindex basic regular expressions
5222 @cindex regular expressions
5223 @cindex expressions, regular
5224 @cindex pattern substitution
5225 @cindex substitution by regular expression
5226 @cindex @acronym{GNU} extensions
5227 Global substitution in a string is done by @code{patsubst}:
5229 @deffn Builtin patsubst (@var{string}, @var{regexp}, @ovar{replacement})
5230 Searches @var{string} for matches of @var{regexp}, and substitutes
5231 @var{replacement} for each match.  The syntax for regular expressions
5232 is the same as in @acronym{GNU} Emacs (@pxref{Regexp}).
5234 The parts of @var{string} that are not covered by any match of
5235 @var{regexp} are copied to the expansion.  Whenever a match is found, the
5236 search proceeds from the end of the match, so a character from
5237 @var{string} will never be substituted twice.  If @var{regexp} matches a
5238 string of zero length, the start position for the search is incremented,
5239 to avoid infinite loops.
5241 When a replacement is to be made, @var{replacement} is inserted into
5242 the expansion, with @samp{\@var{n}} substituted by the text matched by
5243 the @var{n}th parenthesized sub-expression of @var{patsubst}, for up to
5244 nine sub-expressions.  The escape @samp{\&} is replaced by the text of
5245 the entire regular expression matched.  For all other characters,
5246 @samp{\} treats the next character literally.  A warning is issued if
5247 there were fewer sub-expressions than the @samp{\@var{n}} requested, or
5248 if there is a trailing @samp{\}.
5250 The @var{replacement} argument can be omitted, in which case the text
5251 matched by @var{regexp} is deleted.
5253 The macro @code{patsubst} is recognized only with parameters.
5254 @end deffn
5256 @example
5257 patsubst(`GNUs not Unix', `^', `OBS: ')
5258 @result{}OBS: GNUs not Unix
5259 patsubst(`GNUs not Unix', `\<', `OBS: ')
5260 @result{}OBS: GNUs OBS: not OBS: Unix
5261 patsubst(`GNUs not Unix', `\w*', `(\&)')
5262 @result{}(GNUs)() (not)() (Unix)()
5263 patsubst(`GNUs not Unix', `\w+', `(\&)')
5264 @result{}(GNUs) (not) (Unix)
5265 patsubst(`GNUs not Unix', `[A-Z][a-z]+')
5266 @result{}GN not@w{ }
5267 patsubst(`GNUs not Unix', `not', `NOT\')
5268 @error{}m4:stdin:6: Warning: patsubst: trailing \ ignored in replacement
5269 @result{}GNUs NOT Unix
5270 @end example
5272 Here is a slightly more realistic example, which capitalizes individual
5273 words or whole sentences, by substituting calls of the macros
5274 @code{upcase} and @code{downcase} into the strings.
5276 @deffn Composite upcase (@var{text})
5277 @deffnx Composite downcase (@var{text})
5278 @deffnx Composite capitalize (@var{text})
5279 Expand to @var{text}, but with capitalization changed: @code{upcase}
5280 changes all letters to upper case, @code{downcase} changes all letters
5281 to lower case, and @code{capitalize} changes the first character of each
5282 word to upper case and the remaining characters to lower case.
5283 @end deffn
5285 First, an example of their usage, using implementations distributed in
5286 @file{m4-@value{VERSION}/@/examples/@/capitalize.m4}.
5288 @comment examples
5289 @example
5290 $ @kbd{m4 -I examples}
5291 include(`capitalize.m4')
5292 @result{}
5293 upcase(`GNUs not Unix')
5294 @result{}GNUS NOT UNIX
5295 downcase(`GNUs not Unix')
5296 @result{}gnus not unix
5297 capitalize(`GNUs not Unix')
5298 @result{}Gnus Not Unix
5299 @end example
5301 Now for the implementation.  There is a helper macro @code{_capitalize}
5302 which puts only its first word in mixed case.  Then @code{capitalize}
5303 merely parses out the words, and replaces them with an invocation of
5304 @code{_capitalize}.  (As presented here, the @code{capitalize} macro has
5305 some subtle flaws.  You should try to see if you can find and correct
5306 them; or @pxref{Improved capitalize, , Answers}).
5308 @comment examples
5309 @example
5310 $ @kbd{m4 -I examples}
5311 undivert(`capitalize.m4')dnl
5312 @result{}divert(`-1')
5313 @result{}# upcase(text)
5314 @result{}# downcase(text)
5315 @result{}# capitalize(text)
5316 @result{}#   change case of text, simple version
5317 @result{}define(`upcase', `translit(`$*', `a-z', `A-Z')')
5318 @result{}define(`downcase', `translit(`$*', `A-Z', `a-z')')
5319 @result{}define(`_capitalize',
5320 @result{}       `regexp(`$1', `^\(\w\)\(\w*\)',
5321 @result{}               `upcase(`\1')`'downcase(`\2')')')
5322 @result{}define(`capitalize', `patsubst(`$1', `\w+', `_$0(`\&')')')
5323 @result{}divert`'dnl
5324 @end example
5326 While @code{regexp} replaces the whole input with the replacement as
5327 soon as there is a match, @code{patsubst} replaces each
5328 @emph{occurrence} of a match and preserves non-matching pieces:
5330 @example
5331 define(`patreg',
5332 `patsubst($@@)
5333 regexp($@@)')dnl
5334 patreg(`bar foo baz Foo', `foo\|Foo', `FOO')
5335 @result{}bar FOO baz FOO
5336 @result{}FOO
5337 patreg(`aba abb 121', `\(.\)\(.\)\1', `\2\1\2')
5338 @result{}bab abb 212
5339 @result{}bab
5340 @end example
5342 Omitting @var{regexp} evokes a warning, but still produces output;
5343 contrast this with an empty @var{regexp} argument.
5345 @example
5346 patsubst(`abc')
5347 @error{}m4:stdin:1: Warning: patsubst: too few arguments: 1 < 2
5348 @result{}abc
5349 patsubst(`abc', `')
5350 @result{}abc
5351 patsubst(`abc', `', `\\-')
5352 @result{}\-a\-b\-c\-
5353 @end example
5355 @node Format
5356 @section Formatting strings (printf-like)
5358 @cindex formatted output
5359 @cindex output, formatted
5360 @cindex @acronym{GNU} extensions
5361 Formatted output can be made with @code{format}:
5363 @deffn Builtin format (@var{format-string}, @dots{})
5364 Works much like the C function @code{printf}.  The first argument
5365 @var{format-string} can contain @samp{%} specifications which are
5366 satisfied by additional arguments, and the expansion of @code{format} is
5367 the formatted string.
5369 The macro @code{format} is recognized only with parameters.
5370 @end deffn
5372 Its use is best described by a few examples:
5374 @comment This test is a bit fragile, if someone tries to port to a
5375 @comment platform without infinity.
5376 @example
5377 define(`foo', `The brown fox jumped over the lazy dog')
5378 @result{}
5379 format(`The string "%s" uses %d characters', foo, len(foo))
5380 @result{}The string "The brown fox jumped over the lazy dog" uses 38 characters
5381 format(`%*.*d', `-1', `-1', `1')
5382 @result{}1
5383 format(`%.0f', `56789.9876')
5384 @result{}56790
5385 len(format(`%-*X', `5000', `1'))
5386 @result{}5000
5387 ifelse(format(`%010F', `infinity'), `       INF', `success',
5388        format(`%010F', `infinity'), `  INFINITY', `success',
5389        format(`%010F', `infinity'))
5390 @result{}success
5391 ifelse(format(`%.1A', `1.999'), `0X1.0P+1', `success',
5392        format(`%.1A', `1.999'), `0X2.0P+0', `success',
5393        format(`%.1A', `1.999'))
5394 @result{}success
5395 @end example
5397 Using the @code{forloop} macro defined earlier (@pxref{Forloop}), this
5398 example shows how @code{format} can be used to produce tabular output.
5400 @comment examples
5401 @example
5402 $ @kbd{m4 -I examples}
5403 include(`forloop.m4')
5404 @result{}
5405 forloop(`i', `1', `10', `format(`%6d squared is %10d
5406 ', i, eval(i**2))')
5407 @result{}     1 squared is          1
5408 @result{}     2 squared is          4
5409 @result{}     3 squared is          9
5410 @result{}     4 squared is         16
5411 @result{}     5 squared is         25
5412 @result{}     6 squared is         36
5413 @result{}     7 squared is         49
5414 @result{}     8 squared is         64
5415 @result{}     9 squared is         81
5416 @result{}    10 squared is        100
5417 @result{}
5418 @end example
5420 The builtin @code{format} is modeled after the ANSI C @samp{printf}
5421 function, and supports these @samp{%} specifiers: @samp{c}, @samp{s},
5422 @samp{d}, @samp{o}, @samp{x}, @samp{X}, @samp{u}, @samp{a}, @samp{A},
5423 @samp{e}, @samp{E}, @samp{f}, @samp{F}, @samp{g}, @samp{G}, and
5424 @samp{%}; it supports field widths and precisions, and the flags
5425 @samp{+}, @samp{-}, @samp{ }, @samp{0}, @samp{#}, and @samp{'}.  For
5426 integer specifiers, the width modifiers @samp{hh}, @samp{h}, and
5427 @samp{l} are recognized, and for floating point specifiers, the width
5428 modifier @samp{l} is recognized.  Items not yet supported include
5429 positional arguments, the @samp{n}, @samp{p}, @samp{S}, and @samp{C}
5430 specifiers, the @samp{z}, @samp{t}, @samp{j}, @samp{L} and @samp{ll}
5431 modifiers, and any platform extensions available in the native
5432 @code{printf}.  For more details on the functioning of @code{printf},
5433 see the C Library Manual, or the @acronym{POSIX} specification (for
5434 example, @samp{%a} is supported even on platforms that haven't yet
5435 implemented C99 hexadecimal floating point output natively).
5437 Warnings are issued for unrecognized specifiers, an improper number of
5438 arguments, or difficulty parsing an argument according to the format
5439 string (such as overflow or extra characters).  It is anticipated that a
5440 future release of @acronym{GNU} @code{m4} will support more specifiers.
5441 Likewise, escape sequences are not yet recognized.
5443 @example
5444 format(`%p', `0')
5445 @error{}m4:stdin:1: Warning: format: unrecognized specifier in `%p'
5446 @result{}
5447 format(`%*d', `')
5448 @error{}m4:stdin:2: Warning: format: empty string treated as 0
5449 @error{}m4:stdin:2: Warning: format: too few arguments: 2 < 3
5450 @result{}0
5451 format(`%.1f', `2a')
5452 @error{}m4:stdin:3: Warning: format: non-numeric argument `2a'
5453 @result{}2.0
5454 @end example
5456 @node Arithmetic
5457 @chapter Macros for doing arithmetic
5459 @cindex arithmetic
5460 @cindex integer arithmetic
5461 Integer arithmetic is included in @code{m4}, with a C-like syntax.  As
5462 convenient shorthands, there are builtins for simple increment and
5463 decrement operations.
5465 @menu
5466 * Incr::                        Decrement and increment operators
5467 * Eval::                        Evaluating integer expressions
5468 @end menu
5470 @node Incr
5471 @section Decrement and increment operators
5473 @cindex decrement operator
5474 @cindex increment operator
5475 Increment and decrement of integers are supported using the builtins
5476 @code{incr} and @code{decr}:
5478 @deffn Builtin incr (@var{number})
5479 @deffnx Builtin decr (@var{number})
5480 Expand to the numerical value of @var{number}, incremented
5481 or decremented, respectively, by one.  Except for the empty string, the
5482 expansion is empty if @var{number} could not be parsed.
5484 The macros @code{incr} and @code{decr} are recognized only with
5485 parameters.
5486 @end deffn
5488 @example
5489 incr(`4')
5490 @result{}5
5491 decr(`7')
5492 @result{}6
5493 incr()
5494 @error{}m4:stdin:3: Warning: incr: empty string treated as 0
5495 @result{}1
5496 decr()
5497 @error{}m4:stdin:4: Warning: decr: empty string treated as 0
5498 @result{}-1
5499 @end example
5501 @node Eval
5502 @section Evaluating integer expressions
5504 @cindex integer expression evaluation
5505 @cindex evaluation, of integer expressions
5506 @cindex expressions, evaluation of integer
5507 Integer expressions are evaluated with @code{eval}:
5509 @deffn Builtin eval (@var{expression}, @dvar{radix, 10}, @ovar{width})
5510 Expands to the value of @var{expression}.  The expansion is empty
5511 if a problem is encountered while parsing the arguments.  If specified,
5512 @var{radix} and @var{width} control the format of the output.
5514 Calculations are done with 32-bit signed numbers.  Overflow silently
5515 results in wraparound.  A warning is issued if division by zero is
5516 attempted, or if @var{expression} could not be parsed.
5518 Expressions can contain the following operators, listed in order of
5519 decreasing precedence.
5521 @table @samp
5522 @item ()
5523 Parentheses
5524 @item +  -  ~  !
5525 Unary plus and minus, and bitwise and logical negation
5526 @item **
5527 Exponentiation
5528 @item *  /  %
5529 Multiplication, division, and modulo
5530 @item +  -
5531 Addition and subtraction
5532 @item <<  >>
5533 Shift left or right
5534 @item >  >=  <  <=
5535 Relational operators
5536 @item ==  !=
5537 Equality operators
5538 @item &
5539 Bitwise and
5540 @item ^
5541 Bitwise exclusive-or
5542 @item |
5543 Bitwise or
5544 @item &&
5545 Logical and
5546 @item ||
5547 Logical or
5548 @end table
5550 The macro @code{eval} is recognized only with parameters.
5551 @end deffn
5553 All binary operators, except exponentiation, are left associative.  C
5554 operators that perform variable assignment, such as @samp{+=} or
5555 @samp{--}, are not implemented, since @code{eval} only operates on
5556 constants, not variables.  Attempting to use them results in an error.
5557 However, since traditional implementations treated @samp{=} as an
5558 undocumented alias for @samp{==} as opposed to an assignment operator,
5559 this usage is supported as a special case.  Be aware that a future
5560 version of @acronym{GNU} M4 may support assignment semantics as an
5561 extension when @acronym{POSIX} mode is not requested, and that using
5562 @samp{=} to check equality is not portable.
5564 @comment status: 1
5565 @example
5566 eval(`2 = 2')
5567 @error{}m4:stdin:1: Warning: eval: recommend ==, not =, for equality
5568 @result{}1
5569 eval(`++0')
5570 @error{}m4:stdin:2: eval: invalid operator: ++0
5571 @result{}
5572 eval(`0 |= 1')
5573 @error{}m4:stdin:3: eval: invalid operator: 0 |= 1
5574 @result{}
5575 @end example
5577 Note that some older @code{m4} implementations use @samp{^} as an
5578 alternate operator for the exponentiation, although @acronym{POSIX}
5579 requires the C behavior of bitwise exclusive-or.  The precedence of the
5580 negation operators, @samp{~} and @samp{!}, was traditionally lower than
5581 equality.  The unary operators could not be used reliably more than once
5582 on the same term without intervening parentheses.  The traditional
5583 precedence of the equality operators @samp{==} and @samp{!=} was
5584 identical instead of lower than the relational operators such as
5585 @samp{<}, even through @acronym{GNU} M4 1.4.8.  Starting with version
5586 1.4.9, @acronym{GNU} M4 correctly follows @acronym{POSIX} precedence
5587 rules.  M4 scripts designed to be portable between releases must be
5588 aware that parentheses may be required to enforce C precedence rules.
5589 Likewise, division by zero, even in the unused branch of a
5590 short-circuiting operator, is not always well-defined in other
5591 implementations.
5593 Following are some examples where the current version of M4 follows C
5594 precedence rules, but where older versions and some other
5595 implementations of @code{m4} require explicit parentheses to get the
5596 correct result:
5598 @example
5599 eval(`1 == 2 > 0')
5600 @result{}1
5601 eval(`(1 == 2) > 0')
5602 @result{}0
5603 eval(`! 0 * 2')
5604 @result{}2
5605 eval(`! (0 * 2)')
5606 @result{}1
5607 eval(`1 | 1 ^ 1')
5608 @result{}1
5609 eval(`(1 | 1) ^ 1')
5610 @result{}0
5611 eval(`+ + - ~ ! ~ 0')
5612 @result{}1
5613 eval(`2 || 1 / 0')
5614 @result{}1
5615 eval(`0 || 1 / 0')
5616 @error{}m4:stdin:9: Warning: eval: divide by zero: 0 || 1 / 0
5617 @result{}
5618 eval(`0 && 1 % 0')
5619 @result{}0
5620 eval(`2 && 1 % 0')
5621 @error{}m4:stdin:11: Warning: eval: modulo by zero: 2 && 1 % 0
5622 @result{}
5623 @end example
5625 @cindex @acronym{GNU} extensions
5626 As a @acronym{GNU} extension, the operator @samp{**} performs integral
5627 exponentiation.  The operator is right-associative, and if evaluated,
5628 the exponent must be non-negative, and at least one of the arguments
5629 must be non-zero, or a warning is issued.
5631 @example
5632 eval(`2 ** 3 ** 2')
5633 @result{}512
5634 eval(`(2 ** 3) ** 2')
5635 @result{}64
5636 eval(`0 ** 1')
5637 @result{}0
5638 eval(`2 ** 0')
5639 @result{}1
5640 eval(`0 ** 0')
5641 @result{}
5642 @error{}m4:stdin:5: Warning: eval: divide by zero: 0 ** 0
5643 eval(`4 ** -2')
5644 @error{}m4:stdin:6: Warning: eval: negative exponent: 4 ** -2
5645 @result{}
5646 @end example
5648 Within @var{expression}, (but not @var{radix} or @var{width}), numbers
5649 without a special prefix are decimal.  A simple @samp{0} prefix
5650 introduces an octal number.  @samp{0x} introduces a hexadecimal number.
5651 As @acronym{GNU} extensions, @samp{0b} introduces a binary number.
5652 @samp{0r} introduces a number expressed in any radix between 1 and 36:
5653 the prefix should be immediately followed by the decimal expression of
5654 the radix, a colon, then the digits making the number.  For radix 1,
5655 leading zeros are ignored, and all remaining digits must be @samp{1};
5656 for all other radices, the digits are @samp{0}, @samp{1}, @samp{2},
5657 @dots{}.  Beyond @samp{9}, the digits are @samp{a}, @samp{b} @dots{} up
5658 to @samp{z}.  Lower and upper case letters can be used interchangeably
5659 in numbers prefixes and as number digits.
5661 Parentheses may be used to group subexpressions whenever needed.  For the
5662 relational operators, a true relation returns @code{1}, and a false
5663 relation return @code{0}.
5665 Here are a few examples of use of @code{eval}.
5667 @example
5668 eval(`-3 * 5')
5669 @result{}-15
5670 eval(`-99 / 10')
5671 @result{}-9
5672 eval(`-99 % 10')
5673 @result{}-9
5674 eval(`99 % -10')
5675 @result{}9
5676 eval(index(`Hello world', `llo') >= 0)
5677 @result{}1
5678 eval(`0r1:0111 + 0b100 + 0r3:12')
5679 @result{}12
5680 define(`square', `eval(`($1) ** 2')')
5681 @result{}
5682 square(`9')
5683 @result{}81
5684 square(square(`5')` + 1')
5685 @result{}676
5686 define(`foo', `666')
5687 @result{}
5688 eval(`foo / 6')
5689 @error{}m4:stdin:11: Warning: eval: bad expression: foo / 6
5690 @result{}
5691 eval(foo / 6)
5692 @result{}111
5693 @end example
5695 As the last two lines show, @code{eval} does not handle macro
5696 names, even if they expand to a valid expression (or part of a valid
5697 expression).  Therefore all macros must be expanded before they are
5698 passed to @code{eval}.
5700 Some calculations are not portable to other implementations, since they
5701 have undefined semantics in C, but @acronym{GNU} @code{m4} has
5702 well-defined behavior on overflow.  When shifting, an out-of-range shift
5703 amount is implicitly brought into the range of 32-bit signed integers
5704 using an implicit bit-wise and with 0x1f).
5706 @example
5707 define(`max_int', eval(`0x7fffffff'))
5708 @result{}
5709 define(`min_int', incr(max_int))
5710 @result{}
5711 eval(min_int` < 0')
5712 @result{}1
5713 eval(max_int` > 0')
5714 @result{}1
5715 ifelse(eval(min_int` / -1'), min_int, `overflow occurred')
5716 @result{}overflow occurred
5717 min_int
5718 @result{}-2147483648
5719 eval(`0x80000000 % -1')
5720 @result{}0
5721 eval(`-4 >> 1')
5722 @result{}-2
5723 eval(`-4 >> 33')
5724 @result{}-2
5725 @end example
5727 If @var{radix} is specified, it specifies the radix to be used in the
5728 expansion.  The default radix is 10; this is also the case if
5729 @var{radix} is the empty string.  A warning results if the radix is
5730 outside the range of 1 through 36, inclusive.  The result of @code{eval}
5731 is always taken to be signed.  No radix prefix is output, and for
5732 radices greater than 10, the digits are lower case.  The @var{width}
5733 argument specifies the minimum output width, excluding any negative
5734 sign.  The result is zero-padded to extend the expansion to the
5735 requested width.  A warning results if the width is negative.  If
5736 @var{radix} or @var{width} is out of bounds, the expansion of
5737 @code{eval} is empty.
5739 @example
5740 eval(`666', `10')
5741 @result{}666
5742 eval(`666', `11')
5743 @result{}556
5744 eval(`666', `6')
5745 @result{}3030
5746 eval(`666', `6', `10')
5747 @result{}0000003030
5748 eval(`-666', `6', `10')
5749 @result{}-0000003030
5750 eval(`10', `', `0')
5751 @result{}10
5752 `0r1:'eval(`10', `1', `11')
5753 @result{}0r1:01111111111
5754 eval(`10', `16')
5755 @result{}a
5756 eval(`1', `37')
5757 @error{}m4:stdin:9: Warning: eval: radix 37 out of range
5758 @result{}
5759 eval(`1', , `-1')
5760 @error{}m4:stdin:10: Warning: eval: negative width
5761 @result{}
5762 eval()
5763 @error{}m4:stdin:11: Warning: eval: empty string treated as 0
5764 @result{}0
5765 @end example
5767 @node Shell commands
5768 @chapter Macros for running shell commands
5770 @cindex UNIX commands, running
5771 @cindex executing shell commands
5772 @cindex running shell commands
5773 @cindex shell commands, running
5774 @cindex commands, running shell
5775 There are a few builtin macros in @code{m4} that allow you to run shell
5776 commands from within @code{m4}.
5778 Note that the definition of a valid shell command is system dependent.
5779 On UNIX systems, this is the typical @command{/bin/sh}.  But on other
5780 systems, such as native Windows, the shell has a different syntax of
5781 commands that it understands.  Some examples in this chapter assume
5782 @command{/bin/sh}, and also demonstrate how to quit early with a known
5783 exit value if this is not the case.
5785 @menu
5786 * Platform macros::             Determining the platform
5787 * Syscmd::                      Executing simple commands
5788 * Esyscmd::                     Reading the output of commands
5789 * Sysval::                      Exit status
5790 * Mkstemp::                     Making temporary files
5791 @end menu
5793 @node Platform macros
5794 @section Determining the platform
5796 @cindex platform macros
5797 Sometimes it is desirable for an input file to know which platform
5798 @code{m4} is running on.  @acronym{GNU} @code{m4} provides several
5799 macros that are predefined to expand to the empty string; checking for
5800 their existence will confirm platform details.
5802 @deffn {Optional builtin} __gnu__
5803 @deffnx {Optional builtin} __os2__
5804 @deffnx {Optional builtin} os2
5805 @deffnx {Optional builtin} __unix__
5806 @deffnx {Optional builtin} unix
5807 @deffnx {Optional builtin} __windows__
5808 @deffnx {Optional builtin} windows
5809 Each of these macros is conditionally defined as needed to describe the
5810 environment of @code{m4}.  If defined, each macro expands to the empty
5811 string.  For now, these macros silently ignore all arguments, but in a
5812 future release of M4, they might warn if arguments are present.
5813 @end deffn
5815 When @acronym{GNU} extensions are in effect (that is, when you did not
5816 use the @option{-G} option, @pxref{Limits control, , Invoking m4}),
5817 @acronym{GNU} @code{m4} will define the macro @code{@w{__gnu__}} to
5818 expand to the empty string.
5820 @example
5821 $ @kbd{m4}
5822 __gnu__
5823 @result{}
5824 __gnu__(`ignored')
5825 @result{}
5826 Extensions are ifdef(`__gnu__', `active', `inactive')
5827 @result{}Extensions are active
5828 @end example
5830 @comment options: -G
5831 @example
5832 $ @kbd{m4 -G}
5833 __gnu__
5834 @result{}__gnu__
5835 __gnu__(`ignored')
5836 @result{}__gnu__(ignored)
5837 Extensions are ifdef(`__gnu__', `active', `inactive')
5838 @result{}Extensions are inactive
5839 @end example
5841 On UNIX systems, @acronym{GNU} @code{m4} will define @code{@w{__unix__}}
5842 by default, or @code{unix} when the @option{-G} option is specified.
5844 On native Windows systems, @acronym{GNU} @code{m4} will define
5845 @code{@w{__windows__}} by default, or @code{windows} when the
5846 @option{-G} option is specified.
5848 On OS/2 systems, @acronym{GNU} @code{m4} will define @code{@w{__os2__}}
5849 by default, or @code{os2} when the @option{-G} option is specified.
5851 If @acronym{GNU} @code{m4} does not provide a platform macro for your system,
5852 please report that as a bug.
5854 @example
5855 define(`provided', `0')
5856 @result{}
5857 ifdef(`__unix__', `define(`provided', incr(provided))')
5858 @result{}
5859 ifdef(`__windows__', `define(`provided', incr(provided))')
5860 @result{}
5861 ifdef(`__os2__', `define(`provided', incr(provided))')
5862 @result{}
5863 provided
5864 @result{}1
5865 @end example
5867 @node Syscmd
5868 @section Executing simple commands
5870 Any shell command can be executed, using @code{syscmd}:
5872 @deffn Builtin syscmd (@var{shell-command})
5873 Executes @var{shell-command} as a shell command.
5875 The expansion of @code{syscmd} is void, @emph{not} the output from
5876 @var{shell-command}!  Output or error messages from @var{shell-command}
5877 are not read by @code{m4}.  @xref{Esyscmd}, if you need to process the
5878 command output.
5880 Prior to executing the command, @code{m4} flushes its buffers.
5881 The default standard input, output and error of @var{shell-command} are
5882 the same as those of @code{m4}.
5884 The macro @code{syscmd} is recognized only with parameters.
5885 @end deffn
5887 @example
5888 define(`foo', `FOO')
5889 @result{}
5890 syscmd(`echo foo')
5891 @result{}foo
5892 @result{}
5893 @end example
5895 Note how the expansion of @code{syscmd} keeps the trailing newline of
5896 the command, as well as using the newline that appeared after the macro.
5898 The following is an example of @var{shell-command} using the same
5899 standard input as @code{m4}:
5901 @comment ignore
5902 @example
5903 $ @kbd{echo "m4wrap(\`syscmd(\`cat')')" | m4}
5904 @result{}
5905 @end example
5907 @ignore
5908 @comment If the user types the example below with stdin being an
5909 @comment interactive terminal, then cat will hang waiting for additional
5910 @comment input after m4 has exited.  But the testsuite is using a pipe
5911 @comment for stdin.  Hence, we have two versions - the one we feed the
5912 @comment testsuite below, and the one we display to the user above that
5913 @comment more accurately shows what the testsuite is really doing but
5914 @comment which the testsuite cannot parse.
5916 @example
5917 m4wrap(`syscmd(`cat')')
5918 @result{}
5920 @end example
5921 @end ignore
5923 It tells @code{m4} to read all of its input before executing the wrapped
5924 text, then hand a valid (albeit emptied) pipe as standard input for the
5925 @code{cat} subcommand.  Therefore, you should be careful when using
5926 standard input (either by specifying no files, or by passing @samp{-} as
5927 a file name on the command line, @pxref{Command line files, , Invoking
5928 m4}), and also invoking subcommands via @code{syscmd} or @code{esyscmd}
5929 that consume data from standard input.  When standard input is a
5930 seekable file, the subprocess will pick up with the next character not
5931 yet processed by @code{m4}; when it is a pipe or other non-seekable
5932 file, there is no guarantee how much data will already be buffered by
5933 @code{m4} and thus unavailable to the child.
5935 @node Esyscmd
5936 @section Reading the output of commands
5938 @cindex @acronym{GNU} extensions
5939 If you want @code{m4} to read the output of a shell command, use
5940 @code{esyscmd}:
5942 @deffn Builtin esyscmd (@var{shell-command})
5943 Expands to the standard output of the shell command
5944 @var{shell-command}.
5946 Prior to executing the command, @code{m4} flushes its buffers.
5947 The default standard input and standard error of @var{shell-command} are
5948 the same as those of @code{m4}.  The error output of @var{shell-command}
5949 is not a part of the expansion: it will appear along with the error
5950 output of @code{m4}.
5952 The macro @code{esyscmd} is recognized only with parameters.
5953 @end deffn
5955 @example
5956 define(`foo', `FOO')
5957 @result{}
5958 esyscmd(`echo foo')
5959 @result{}FOO
5960 @result{}
5961 @end example
5963 Note how the expansion of @code{esyscmd} keeps the trailing newline of
5964 the command, as well as using the newline that appeared after the macro.
5966 Just as with @code{syscmd}, care must be exercised when sharing standard
5967 input between @code{m4} and the child process of @code{esyscmd}.
5969 @node Sysval
5970 @section Exit status
5972 @cindex UNIX commands, exit status from
5973 @cindex exit status from shell commands
5974 @cindex shell commands, exit status from
5975 @cindex commands, exit status from shell
5976 @cindex status of shell commands
5977 To see whether a shell command succeeded, use @code{sysval}:
5979 @deffn Builtin sysval
5980 Expands to the exit status of the last shell command run with
5981 @code{syscmd} or @code{esyscmd}.  Expands to 0 if no command has been
5982 run yet.
5983 @end deffn
5985 @example
5986 sysval
5987 @result{}0
5988 syscmd(`false')
5989 @result{}
5990 ifelse(sysval, `0', `zero', `non-zero')
5991 @result{}non-zero
5992 syscmd(`exit 2')
5993 @result{}
5994 sysval
5995 @result{}2
5996 syscmd(`true')
5997 @result{}
5998 sysval
5999 @result{}0
6000 esyscmd(`false')
6001 @result{}
6002 ifelse(sysval, `0', `zero', `non-zero')
6003 @result{}non-zero
6004 esyscmd(`exit 2')
6005 @result{}
6006 sysval
6007 @result{}2
6008 esyscmd(`true')
6009 @result{}
6010 sysval
6011 @result{}0
6012 @end example
6014 @code{sysval} results in 127 if there was a problem executing the
6015 command, for example, if the system-imposed argument length is exceeded,
6016 or if there were not enough resources to fork.  It is not possible to
6017 distinguish between failed execution and successful execution that had
6018 an exit status of 127.
6020 On UNIX platforms, where it is possible to detect when command execution
6021 is terminated by a signal, rather than a normal exit, the result is the
6022 signal number shifted left by eight bits.
6024 @comment This test has difficulties being portable, even on platforms
6025 @comment where syscmd invokes /bin/sh.  Kill is not portable with signal
6026 @comment names.  According to autoconf, the only portable signal numbers
6027 @comment are 1 (HUP), 2 (INT), 9 (KILL), 13 (PIPE) and 15 (TERM).  But
6028 @comment all shells handle SIGINT, and ksh handles HUP (as in, the shell
6029 @comment exits normally rather than letting the signal terminate it).
6030 @comment Also, TERM is flaky, as it can also kill the running m4 on
6031 @comment systems where /bin/sh does not create its own process group.
6032 @comment And PIPE is unreliable, since people tend to run with it
6033 @comment ignored, with m4 inheriting that choice.  That leaves KILL as
6034 @comment the only signal we can reliably test.
6035 @example
6036 dnl This test assumes kill is a shell builtin, and that signals are
6037 dnl recognizable.
6038 ifdef(`__unix__', ,
6039       `errprint(` skipping: syscmd does not have unix semantics
6040 ')m4exit(`77')')dnl
6041 syscmd(`kill -9 $$')
6042 @result{}
6043 sysval
6044 @result{}2304
6045 syscmd()
6046 @result{}
6047 sysval
6048 @result{}0
6049 esyscmd(`kill -9 $$')
6050 @result{}
6051 sysval
6052 @result{}2304
6053 @end example
6055 @node Mkstemp
6056 @section Making temporary files
6058 @cindex temporary file names
6059 @cindex files, names of temporary
6060 Commands specified to @code{syscmd} or @code{esyscmd} might need a
6061 temporary file, for output or for some other purpose.  There is a
6062 builtin macro, @code{mkstemp}, for making a temporary file:
6064 @deffn Builtin mkstemp (@var{template})
6065 @deffnx Builtin maketemp (@var{template})
6066 Expands to the quoted name of a new, empty file, made from the string
6067 @var{template}, which should end with the string @samp{XXXXXX}.  The six
6068 @samp{X} characters are then replaced with random characters matching
6069 the regular expression @samp{[a-zA-Z0-9._-]}, in order to make the file
6070 name unique.  If fewer than six @samp{X} characters are found at the end
6071 of @code{template}, the result will be longer than the template.  The
6072 created file will have access permissions as if by @kbd{chmod =rw,go=},
6073 meaning that the current umask of the @code{m4} process is taken into
6074 account, and at most only the current user can read and write the file.
6076 The traditional behavior, standardized by @acronym{POSIX}, is that
6077 @code{maketemp} merely replaces the trailing @samp{X} with the process
6078 id, without creating a file or quoting the expansion, and without
6079 ensuring that the resulting
6080 string is a unique file name.  In part, this means that using the same
6081 @var{template} twice in the same input file will result in the same
6082 expansion.  This behavior is a security hole, as it is very easy for
6083 another process to guess the name that will be generated, and thus
6084 interfere with a subsequent use of @code{syscmd} trying to manipulate
6085 that file name.  Hence, @acronym{POSIX} has recommended that all new
6086 implementations of @code{m4} provide the secure @code{mkstemp} builtin,
6087 and that users of @code{m4} check for its existence.
6089 The expansion is void and an error issued if a temporary file could
6090 not be created.
6092 The macros @code{mkstemp} and @code{maketemp} are recognized only with
6093 parameters.
6094 @end deffn
6096 If you try this next example, you will most likely get different output
6097 for the two file names, since the replacement characters are randomly
6098 chosen:
6100 @comment ignore
6101 @example
6102 $ @kbd{m4}
6103 define(`tmp', `oops')
6104 @result{}
6105 maketemp(`/tmp/fooXXXXXX')
6106 @result{}/tmp/fooa07346
6107 ifdef(`mkstemp', `define(`maketemp', defn(`mkstemp'))',
6108       `define(`mkstemp', defn(`maketemp'))dnl
6109 errprint(`warning: potentially insecure maketemp implementation
6110 ')')
6111 @result{}
6112 mkstemp(`doc')
6113 @result{}docQv83Uw
6114 @end example
6116 @cindex @acronym{GNU} extensions
6117 Unless you use the @option{--traditional} command line option (or
6118 @option{-G}, @pxref{Limits control, , Invoking m4}), the @acronym{GNU}
6119 version of @code{maketemp} is secure.  This means that using the same
6120 template to multiple calls will generate multiple files.  However, we
6121 recommend that you use the new @code{mkstemp} macro, introduced in
6122 @acronym{GNU} M4 1.4.8, which is secure even in traditional mode.  Also,
6123 as of M4 1.4.11, the secure implementation quotes the resulting file
6124 name, so that you are guaranteed to know what file was created even if
6125 the random file name happens to match an existing macro.  Notice that
6126 this example is careful to use @code{defn} to avoid unintended expansion
6127 of @samp{foo}.
6129 @example
6130 $ @kbd{m4}
6131 define(`foo', `errprint(`oops')')
6132 @result{}
6133 syscmd(`rm -f foo-??????')sysval
6134 @result{}0
6135 define(`file1', maketemp(`foo-XXXXXX'))dnl
6136 ifelse(esyscmd(`echo \` foo-?????? \''), ` foo-?????? ',
6137        `no file', `created')
6138 @result{}created
6139 define(`file2', maketemp(`foo-XX'))dnl
6140 define(`file3', mkstemp(`foo-XXXXXX'))dnl
6141 ifelse(len(defn(`file1')), len(defn(`file2')),
6142        `same length', `different')
6143 @result{}same length
6144 ifelse(defn(`file1'), defn(`file2'), `same', `different file')
6145 @result{}different file
6146 ifelse(defn(`file2'), defn(`file3'), `same', `different file')
6147 @result{}different file
6148 ifelse(defn(`file1'), defn(`file3'), `same', `different file')
6149 @result{}different file
6150 syscmd(`rm 'defn(`file1') defn(`file2') defn(`file3'))
6151 @result{}
6152 sysval
6153 @result{}0
6154 @end example
6156 @ignore
6157 @c Not worth documenting, but make sure we don't leave trailing NUL in
6158 @c the expansion.
6160 @example
6161 syscmd(`rm -f foo??????')sysval
6162 @result{}0
6163 len(mkstemp(`fooXXXXX'))
6164 @result{}9
6165 syscmd(`rm foo??????')sysval
6166 @result{}0
6167 @end example
6169 @c Likewise, and ensure that traditional mode leaves the result unquoted
6170 @c without creating a file.
6172 @comment options: -G
6173 @example
6174 syscmd(`rm -f foo-*')sysval
6175 @result{}0
6176 len(maketemp(`foo-XXXXX'))
6177 @error{}m4:stdin:2: Warning: maketemp: recommend using mkstemp instead
6178 @result{}9
6179 define(`abc', `def')
6180 @result{}
6181 maketemp(`foo-abc')
6182 @result{}foo-def
6183 @error{}m4:stdin:4: Warning: maketemp: recommend using mkstemp instead
6184 syscmd(`test -f foo-*')sysval
6185 @result{}1
6186 @end example
6187 @end ignore
6189 @node Miscellaneous
6190 @chapter Miscellaneous builtin macros
6192 This chapter describes various builtins, that do not really belong in
6193 any of the previous chapters.
6195 @menu
6196 * Errprint::                    Printing error messages
6197 * Location::                    Printing current location
6198 * M4exit::                      Exiting from @code{m4}
6199 @end menu
6201 @node Errprint
6202 @section Printing error messages
6204 @cindex printing error messages
6205 @cindex error messages, printing
6206 @cindex messages, printing error
6207 @cindex standard error, output to
6208 You can print error messages using @code{errprint}:
6210 @deffn Builtin errprint (@var{message}, @dots{})
6211 Prints @var{message} and the rest of the arguments to standard error,
6212 separated by spaces.  Standard error is used, regardless of the
6213 @option{--debugfile} option (@pxref{Debugging options, , Invoking m4}).
6215 The expansion of @code{errprint} is void.
6216 The macro @code{errprint} is recognized only with parameters.
6217 @end deffn
6219 @example
6220 errprint(`Invalid arguments to forloop
6222 @error{}Invalid arguments to forloop
6223 @result{}
6224 errprint(`1')errprint(`2',`3
6226 @error{}12 3
6227 @result{}
6228 @end example
6230 A trailing newline is @emph{not} printed automatically, so it should be
6231 supplied as part of the argument, as in the example.  Unfortunately, the
6232 exact output of @code{errprint} is not very portable to other @code{m4}
6233 implementations: @acronym{POSIX} requires that all arguments be printed,
6234 but some implementations of @code{m4} only print the first.
6235 Furthermore, some @acronym{BSD} implementations always append a newline
6236 for each @code{errprint} call, regardless of whether the last argument
6237 already had one, and @acronym{POSIX} is silent on whether this is
6238 acceptable.
6240 @node Location
6241 @section Printing current location
6243 @cindex location, input
6244 @cindex input location
6245 To make it possible to specify the location of an error, three
6246 utility builtins exist:
6248 @deffn Builtin __file__
6249 @deffnx Builtin __line__
6250 @deffnx Builtin __program__
6251 Expand to the quoted name of the current input file, the
6252 current input line number in that file, and the quoted name of the
6253 current invocation of @code{m4}.
6254 @end deffn
6256 @example
6257 errprint(__program__:__file__:__line__: `input error
6259 @error{}m4:stdin:1: input error
6260 @result{}
6261 @end example
6263 Line numbers start at 1 for each file.  If the file was found due to the
6264 @option{-I} option or @env{M4PATH} environment variable, that is
6265 reflected in the file name.  The syncline option (@option{-s},
6266 @pxref{Preprocessor features, , Invoking m4}), and the
6267 @samp{f} and @samp{l} flags of @code{debugmode} (@pxref{Debug Levels}),
6268 also use this notion of current file and line.  Redefining the three
6269 location macros has no effect on syncline, debug, warning, or error
6270 message output.
6272 This example reuses the file @file{incl.m4} mentioned earlier
6273 (@pxref{Include}):
6275 @comment examples
6276 @example
6277 $ @kbd{m4 -I examples}
6278 define(`foo', ``$0' called at __file__:__line__')
6279 @result{}
6281 @result{}foo called at stdin:2
6282 include(`incl.m4')
6283 @result{}Include file start
6284 @result{}foo called at ../examples/incl.m4:2
6285 @result{}Include file end
6286 @result{}
6287 @end example
6289 The location of macros invoked during the rescanning of macro expansion
6290 text corresponds to the location in the file where the expansion was
6291 triggered, regardless of how many newline characters the expansion text
6292 contains.  As of @acronym{GNU} M4 1.4.8, the location of text wrapped
6293 with @code{m4wrap} (@pxref{M4wrap}) is the point at which the
6294 @code{m4wrap} was invoked.  Previous versions, however, behaved as
6295 though wrapped text came from line 0 of the file ``''.
6297 @example
6298 define(`echo', `$@@')
6299 @result{}
6300 define(`foo', `echo(__line__
6301 __line__)')
6302 @result{}
6303 echo(__line__
6304 __line__)
6305 @result{}4
6306 @result{}5
6307 m4wrap(`foo
6309 @result{}
6310 foo(errprint(__line__
6311 __line__
6313 @error{}8
6314 @error{}9
6315 @result{}8
6316 @result{}8
6317 __line__
6318 @result{}11
6320 @result{}6
6321 @result{}6
6322 @end example
6324 The @code{@w{__program__}} macro behaves like @samp{$0} in shell
6325 terminology.  If you invoke @code{m4} through an absolute path or a link
6326 with a different spelling, rather than by relying on a @env{PATH} search
6327 for plain @samp{m4}, it will affect how @code{@w{__program__}} expands.
6328 The intent is that you can use it to produce error messages with the
6329 same formatting that @code{m4} produces internally.  It can also be used
6330 within @code{syscmd} (@pxref{Syscmd}) to pick the same version of
6331 @code{m4} that is currently running, rather than whatever version of
6332 @code{m4} happens to be first in @env{PATH}.  It was first introduced in
6333 @acronym{GNU} M4 1.4.6.
6335 @node M4exit
6336 @section Exiting from @code{m4}
6338 @cindex exiting from @code{m4}
6339 @cindex status, setting @code{m4} exit
6340 If you need to exit from @code{m4} before the entire input has been
6341 read, you can use @code{m4exit}:
6343 @deffn Builtin m4exit (@dvar{code, 0})
6344 Causes @code{m4} to exit, with exit status @var{code}.  If @var{code} is
6345 left out, the exit status is zero.  If @var{code} cannot be parsed, or
6346 is outside the range of 0 to 255, the exit status is one.  No further
6347 input is read, and all wrapped and diverted text is discarded.
6348 @end deffn
6350 @example
6351 m4wrap(`This text is lost due to `m4exit'.')
6352 @result{}
6353 divert(`1') So is this.
6354 divert
6355 @result{}
6356 m4exit And this is never read.
6357 @end example
6359 A common use of this is to abort processing:
6361 @deffn Composite fatal_error (@var{message})
6362 Abort processing with an error message and non-zero status.  Prefix
6363 @var{message} with details about where the error occurred, and print the
6364 resulting string to standard error.
6365 @end deffn
6367 @comment status: 1
6368 @example
6369 define(`fatal_error',
6370        `errprint(__program__:__file__:__line__`: fatal error: $*
6371 ')m4exit(`1')')
6372 @result{}
6373 fatal_error(`this is a BAD one, buster')
6374 @error{}m4:stdin:4: fatal error: this is a BAD one, buster
6375 @end example
6377 After this macro call, @code{m4} will exit with exit status 1.  This macro
6378 is only intended for error exits, since the normal exit procedures are
6379 not followed, i.e., diverted text is not undiverted, and saved text
6380 (@pxref{M4wrap}) is not reread.  (This macro could be made more robust
6381 to earlier versions of @code{m4}.  You should try to see if you can find
6382 weaknesses and correct them; or @pxref{Improved fatal_error, , Answers}).
6384 Note that it is still possible for the exit status to be different than
6385 what was requested by @code{m4exit}.  If @code{m4} detects some other
6386 error, such as a write error on standard output, the exit status will be
6387 non-zero even if @code{m4exit} requested zero.
6389 If standard input is seekable, then the file will be positioned at the
6390 next unread character.  If it is a pipe or other non-seekable file,
6391 then there are no guarantees how much data @code{m4} might have read
6392 into buffers, and thus discarded.
6394 @node Frozen files
6395 @chapter Fast loading of frozen state
6397 Some bigger @code{m4} applications may be built over a common base
6398 containing hundreds of definitions and other costly initializations.
6399 Usually, the common base is kept in one or more declarative files,
6400 which files are listed on each @code{m4} invocation prior to the
6401 user's input file, or else each input file uses @code{include}.
6403 Reading the common base of a big application, over and over again, may
6404 be time consuming.  @acronym{GNU} @code{m4} offers some machinery to
6405 speed up the start of an application using lengthy common bases.
6407 @menu
6408 * Using frozen files::          Using frozen files
6409 * Frozen file format::          Frozen file format
6410 @end menu
6412 @node Using frozen files
6413 @section Using frozen files
6415 @cindex fast loading of frozen files
6416 @cindex frozen files for fast loading
6417 @cindex initialization, frozen state
6418 @cindex dumping into frozen file
6419 @cindex reloading a frozen file
6420 @cindex @acronym{GNU} extensions
6421 Suppose a user has a library of @code{m4} initializations in
6422 @file{base.m4}, which is then used with multiple input files:
6424 @comment ignore
6425 @example
6426 $ @kbd{m4 base.m4 input1.m4}
6427 $ @kbd{m4 base.m4 input2.m4}
6428 $ @kbd{m4 base.m4 input3.m4}
6429 @end example
6431 Rather than spending time parsing the fixed contents of @file{base.m4}
6432 every time, the user might rather execute:
6434 @comment ignore
6435 @example
6436 $ @kbd{m4 -F base.m4f base.m4}
6437 @end example
6439 @noindent
6440 once, and further execute, as often as needed:
6442 @comment ignore
6443 @example
6444 $ @kbd{m4 -R base.m4f input1.m4}
6445 $ @kbd{m4 -R base.m4f input2.m4}
6446 $ @kbd{m4 -R base.m4f input3.m4}
6447 @end example
6449 @noindent
6450 with the varying input.  The first call, containing the @option{-F}
6451 option, only reads and executes file @file{base.m4}, defining
6452 various application macros and computing other initializations.
6453 Once the input file @file{base.m4} has been completely processed, @acronym{GNU}
6454 @code{m4} produces in @file{base.m4f} a @dfn{frozen} file, that is, a
6455 file which contains a kind of snapshot of the @code{m4} internal state.
6457 Later calls, containing the @option{-R} option, are able to reload
6458 the internal state of @code{m4}, from @file{base.m4f},
6459 @emph{prior} to reading any other input files.  This means
6460 instead of starting with a virgin copy of @code{m4}, input will be
6461 read after having effectively recovered the effect of a prior run.
6462 In our example, the effect is the same as if file @file{base.m4} has
6463 been read anew.  However, this effect is achieved a lot faster.
6465 Only one frozen file may be created or read in any one @code{m4}
6466 invocation.  It is not possible to recover two frozen files at once.
6467 However, frozen files may be updated incrementally, through using
6468 @option{-R} and @option{-F} options simultaneously.  For example, if
6469 some care is taken, the command:
6471 @comment ignore
6472 @example
6473 $ @kbd{m4 file1.m4 file2.m4 file3.m4 file4.m4}
6474 @end example
6476 @noindent
6477 could be broken down in the following sequence, accumulating the same
6478 output:
6480 @comment ignore
6481 @example
6482 $ @kbd{m4 -F file1.m4f file1.m4}
6483 $ @kbd{m4 -R file1.m4f -F file2.m4f file2.m4}
6484 $ @kbd{m4 -R file2.m4f -F file3.m4f file3.m4}
6485 $ @kbd{m4 -R file3.m4f file4.m4}
6486 @end example
6488 Some care is necessary because not every effort has been made for
6489 this to work in all cases.  In particular, the trace attribute of
6490 macros is not handled, nor the current setting of @code{changeword}.
6491 Currently, @code{m4wrap} and @code{sysval} also have problems.
6492 Also, interactions for some options of @code{m4}, being used in one call
6493 and not in the next, have not been fully analyzed yet.  On the other
6494 end, you may be confident that stacks of @code{pushdef} definitions
6495 are handled correctly, as well as undefined or renamed builtins, and
6496 changed strings for quotes or comments.  And future releases of
6497 @acronym{GNU} M4 will improve on the utility of frozen files.
6499 @ignore
6500 @c This example is not worth putting in the manual, but caused core
6501 @c dumps in all versions prior to 1.4.11.
6503 @comment options: -F /dev/null
6504 @example
6505 ifdef(`__unix__', ,
6506       `errprint(` skipping: /dev/null not known to exist
6507 ')m4exit(`77')')dnl
6508 traceon(`undefined')dnl
6509 @end example
6510 @end ignore
6512 When an @code{m4} run is to be frozen, the automatic undiversion
6513 which takes place at end of execution is inhibited.  Instead, all
6514 positively numbered diversions are saved into the frozen file.
6515 The active diversion number is also transmitted.
6517 A frozen file to be reloaded need not reside in the current directory.
6518 It is looked up the same way as an @code{include} file (@pxref{Search
6519 Path}).
6521 If the frozen file was generated with a newer version of @code{m4}, and
6522 contains directives that an older @code{m4} cannot parse, attempting to
6523 load the frozen file with option @option{-R} will cause @code{m4} to
6524 exit with status 63 to indicate version mismatch.
6526 @node Frozen file format
6527 @section Frozen file format
6529 @cindex frozen file format
6530 @cindex file format, frozen file
6531 Frozen files are sharable across architectures.  It is safe to write
6532 a frozen file on one machine and read it on another, given that the
6533 second machine uses the same or newer version of @acronym{GNU} @code{m4}.
6534 It is conventional, but not required, to give a frozen file the suffix
6535 of @code{.m4f}.
6537 These are simple (editable) text files, made up of directives,
6538 each starting with a capital letter and ending with a newline
6539 (@key{NL}).  Wherever a directive is expected, the character
6540 @samp{#} introduces a comment line; empty lines are also ignored if they
6541 are not part of an embedded string.
6542 In the following descriptions, each @var{len} refers to the length of
6543 the corresponding strings @var{str} in the next line of input.  Numbers
6544 are always expressed in decimal.  There are no escape characters.  The
6545 directives are:
6547 @table @code
6548 @item C @var{len1} , @var{len2} @key{NL} @var{str1} @var{str2} @key{NL}
6549 Uses @var{str1} and @var{str2} as the begin-comment and
6550 end-comment strings.  If omitted, then @samp{#} and @key{NL} are the
6551 comment delimiters.
6553 @item D @var{number}, @var{len} @key{NL} @var{str} @key{NL}
6554 Selects diversion @var{number}, making it current, then copy
6555 @var{str} in the current diversion.  @var{number} may be a negative
6556 number for a non-existing diversion.  To merely specify an active
6557 selection, use this command with an empty @var{str}.  With 0 as the
6558 diversion @var{number}, @var{str} will be issued on standard output
6559 at reload time.  @acronym{GNU} @code{m4} will not produce the @samp{D}
6560 directive with non-zero length for diversion 0, but this can be done
6561 with manual edits.  This directive may
6562 appear more than once for the same diversion, in which case the
6563 diversion is the concatenation of the various uses.  If omitted, then
6564 diversion 0 is current.
6566 @item F @var{len1} , @var{len2} @key{NL} @var{str1} @var{str2} @key{NL}
6567 Defines, through @code{pushdef}, a definition for @var{str1}
6568 expanding to the function whose builtin name is @var{str2}.  If the
6569 builtin does not exist (for example, if the frozen file was produced by
6570 a copy of @code{m4} compiled with changeword support, but the version
6571 of @code{m4} reloading was compiled without it), the reload is silent,
6572 but any subsequent use of the definition of @var{str1} will result in
6573 a warning.  This directive may appear more than once for the same name,
6574 and its order, along with @samp{T}, is important.  If omitted, you will
6575 have no access to any builtins.
6577 @item Q @var{len1} , @var{len2} @key{NL} @var{str1} @var{str2} @key{NL}
6578 Uses @var{str1} and @var{str2} as the begin-quote and end-quote
6579 strings.  If omitted, then @samp{`} and @samp{'} are the quote
6580 delimiters.
6582 @item T @var{len1} , @var{len2} @key{NL} @var{str1} @var{str2} @key{NL}
6583 Defines, though @code{pushdef}, a definition for @var{str1}
6584 expanding to the text given by @var{str2}.  This directive may appear
6585 more than once for the same name, and its order, along with @samp{F}, is
6586 important.
6588 @item V @var{number} @key{NL}
6589 Confirms the format of the file.  @code{m4} @value{VERSION} only creates
6590 and understands frozen files where @var{number} is 1.  This directive
6591 must be the first non-comment in the file, and may not appear more than
6592 once.
6593 @end table
6595 @node Compatibility
6596 @chapter Compatibility with other versions of @code{m4}
6598 @cindex compatibility
6599 This chapter describes the many of the differences between this
6600 implementation of @code{m4}, and of other implementations found under
6601 UNIX, such as System V Release 3, Solaris, and @acronym{BSD} flavors.
6602 In particular, it lists the known differences and extensions to
6603 @acronym{POSIX}.  However, the list is not necessarily comprehensive.
6605 At the time of this writing, @acronym{POSIX} 2001 (also known as IEEE
6606 Std 1003.1-2001) is the latest standard, although a new version of
6607 @acronym{POSIX} is under development and includes several proposals for
6608 modifying what @code{m4} is required to do.  The requirements for
6609 @code{m4} are shared between @acronym{SUSv3} and @acronym{POSIX}, and
6610 can be viewed at
6611 @uref{http://www.opengroup.org/onlinepubs/@/000095399/@/utilities/@/m4.html}.
6613 @menu
6614 * Extensions::                  Extensions in @acronym{GNU} M4
6615 * Incompatibilities::           Facilities in System V m4 not in GNU M4
6616 * Other Incompatibilities::     Other incompatibilities
6617 @end menu
6619 @node Extensions
6620 @section Extensions in @acronym{GNU} M4
6622 @cindex @acronym{GNU} extensions
6623 @cindex @acronym{POSIX}
6624 This version of @code{m4} contains a few facilities that do not exist
6625 in System V @code{m4}.  These extra facilities are all suppressed by
6626 using the @option{-G} command line option (@pxref{Limits control, ,
6627 Invoking m4}), unless overridden by other command line options.
6629 @itemize @bullet
6630 @item
6631 In the @code{$@var{n}} notation for macro arguments, @var{n} can contain
6632 several digits, while the System V @code{m4} only accepts one digit.
6633 This allows macros in @acronym{GNU} @code{m4} to take any number of
6634 arguments, and not only nine (@pxref{Arguments}).
6636 This means that @code{define(`foo', `$11')} is ambiguous between
6637 implementations.  To portably choose between grabbing the first
6638 parameter and appending 1 to the expansion, or grabbing the eleventh
6639 parameter, you can do the following:
6641 @example
6642 define(`a1', `A1')
6643 @result{}
6644 dnl First argument, concatenated with 1
6645 define(`_1', `$1')define(`first1', `_1($@@)1')
6646 @result{}
6647 dnl Eleventh argument, portable
6648 define(`_9', `$9')define(`eleventh', `_9(shift(shift($@@)))')
6649 @result{}
6650 dnl Eleventh argument, GNU style
6651 define(`Eleventh', `$11')
6652 @result{}
6653 first1(`a', `b', `c', `d', `e', `f', `g', `h', `i', `j', `k')
6654 @result{}A1
6655 eleventh(`a', `b', `c', `d', `e', `f', `g', `h', `i', `j', `k')
6656 @result{}k
6657 Eleventh(`a', `b', `c', `d', `e', `f', `g', `h', `i', `j', `k')
6658 @result{}k
6659 @end example
6661 @noindent
6662 Also see the @code{argn} macro (@pxref{Shift}).
6664 @item
6665 The @code{divert} (@pxref{Divert}) macro can manage more than 9
6666 diversions.  @acronym{GNU} @code{m4} treats all positive numbers as valid
6667 diversions, rather than discarding diversions greater than 9.
6669 @item
6670 Files included with @code{include} and @code{sinclude} are sought in a
6671 user specified search path, if they are not found in the working
6672 directory.  The search path is specified by the @option{-I} option and the
6673 @env{M4PATH} environment variable (@pxref{Search Path}).
6675 @item
6676 Arguments to @code{undivert} can be non-numeric, in which case the named
6677 file will be included uninterpreted in the output (@pxref{Undivert}).
6679 @item
6680 Formatted output is supported through the @code{format} builtin, which
6681 is modeled after the C library function @code{printf} (@pxref{Format}).
6683 @item
6684 Searches and text substitution through basic regular expressions are
6685 supported by the @code{regexp} (@pxref{Regexp}) and @code{patsubst}
6686 (@pxref{Patsubst}) builtins.  Some @acronym{BSD} implementations use
6687 extended regular expressions instead.
6689 @item
6690 The output of shell commands can be read into @code{m4} with
6691 @code{esyscmd} (@pxref{Esyscmd}).
6693 @item
6694 There is indirect access to any builtin macro with @code{builtin}
6695 (@pxref{Builtin}).
6697 @item
6698 Macros can be called indirectly through @code{indir} (@pxref{Indir}).
6700 @item
6701 The name of the program, the current input file, and the current input
6702 line number are accessible through the builtins @code{@w{__program__}},
6703 @code{@w{__file__}}, and @code{@w{__line__}} (@pxref{Location}).
6705 @item
6706 The format of the output from @code{dumpdef} and macro tracing can be
6707 controlled with @code{debugmode} (@pxref{Debug Levels}).
6709 @item
6710 The destination of trace and debug output can be controlled with
6711 @code{debugfile} (@pxref{Debug Output}).
6713 @item
6714 The @code{maketemp} (@pxref{Mkstemp}) macro behaves like @code{mkstemp},
6715 creating a new file with a unique name on every invocation, rather than
6716 following the insecure behavior of replacing the trailing @samp{X}
6717 characters with the @code{m4} process id.
6719 @item
6720 @acronym{POSIX} only requires support for the command line options
6721 @option{-s}, @option{-D}, and @option{-U}, so all other options accepted
6722 by @acronym{GNU} M4 are extensions.  @xref{Invoking m4}, for a
6723 description of these options.
6725 The debugging and tracing facilities in @acronym{GNU} @code{m4} are much
6726 more extensive than in most other versions of @code{m4}.
6727 @end itemize
6729 @node Incompatibilities
6730 @section Facilities in System V @code{m4} not in @acronym{GNU} @code{m4}
6732 The version of @code{m4} from System V contains a few facilities that
6733 have not been implemented in @acronym{GNU} @code{m4} yet.  Additionally,
6734 @acronym{POSIX} requires some behaviors that @acronym{GNU} @code{m4} has not
6735 implemented yet.  Relying on these behaviors is non-portable, as a
6736 future release of @acronym{GNU} @code{m4} may change.
6738 @itemize @bullet
6739 @item
6740 @acronym{POSIX} requires support for multiple arguments to @code{defn},
6741 without any clarification on how @code{defn} behaves when one of the
6742 multiple arguments names a builtin.  System V @code{m4} and some other
6743 implementations allow mixing builtins and text macros into a single
6744 macro.  @acronym{GNU} @code{m4} only supports joining multiple text
6745 arguments, although a future implementation may lift this restriction to
6746 behave more like System V@.  The only portable way to join text macros
6747 with builtins is via helper macros and implicit concatenation of macro
6748 results.
6750 @item
6751 @acronym{POSIX} requires an application to exit with non-zero status if
6752 it wrote an error message to stderr.  This has not yet been consistently
6753 implemented for the various builtins that are required to issue an error
6754 (such as @code{eval} (@pxref{Eval}) when an argument cannot be parsed).
6756 @item
6757 Some traditional implementations only allow reading standard input
6758 once, but @acronym{GNU} @code{m4} correctly handles multiple instances
6759 of @samp{-} on the command line.
6761 @item
6762 @acronym{POSIX} requires @code{m4wrap} (@pxref{M4wrap}) to act in FIFO
6763 (first-in, first-out) order, but @acronym{GNU} @code{m4} currently uses
6764 LIFO order.  Furthermore, @acronym{POSIX} states that only the first
6765 argument to @code{m4wrap} is saved for later evaluation, but
6766 @acronym{GNU} @code{m4} saves and processes all arguments, with output
6767 separated by spaces.
6769 However, it is possible to emulate @acronym{POSIX} behavior by
6770 including the file @file{m4-@value{VERSION}/@/examples/@/wrapfifo.m4}
6771 from the distribution:
6773 @example
6774 undivert(`wrapfifo.m4')dnl
6775 @result{}dnl Redefine m4wrap to have FIFO semantics.
6776 @result{}define(`_m4wrap_level', `0')dnl
6777 @result{}define(`m4wrap',
6778 @result{}`ifdef(`m4wrap'_m4wrap_level,
6779 @result{}       `define(`m4wrap'_m4wrap_level,
6780 @result{}               defn(`m4wrap'_m4wrap_level)`$1')',
6781 @result{}       `builtin(`m4wrap', `define(`_m4wrap_level',
6782 @result{}                                  incr(_m4wrap_level))dnl
6783 @result{}m4wrap'_m4wrap_level)dnl
6784 @result{}define(`m4wrap'_m4wrap_level, `$1')')')dnl
6785 include(`wrapfifo.m4')
6786 @result{}
6787 m4wrap(`a`'m4wrap(`c
6788 ', `d')')m4wrap(`b')
6789 @result{}
6791 @result{}abc
6792 @end example
6794 @item
6795 @acronym{POSIX} states that builtins that require arguments, but are
6796 called without arguments, have undefined behavior.  Traditional
6797 implementations simply behave as though empty strings had been passed.
6798 For example, @code{a`'define`'b} would expand to @code{ab}.  But
6799 @acronym{GNU} @code{m4} ignores certain builtins if they have missing
6800 arguments, giving @code{adefineb} for the above example.
6802 @item
6803 Traditional implementations handle @code{define(`f',`1')} (@pxref{Define})
6804 by undefining the entire stack of previous definitions, and if doing
6805 @code{undefine(`f')} first.  @acronym{GNU} @code{m4} replaces just the top
6806 definition on the stack, as if doing @code{popdef(`f')} followed by
6807 @code{pushdef(`f',`1')}.  @acronym{POSIX} allows either behavior.
6809 @item
6810 @acronym{POSIX} 2001 requires @code{syscmd} (@pxref{Syscmd}) to evaluate
6811 command output for macro expansion, but this was a mistake that is
6812 anticipated to be corrected in the next version of @acronym{POSIX}.
6813 @acronym{GNU} @code{m4} follows traditional behavior in @code{syscmd}
6814 where output is not rescanned, and provides the extension @code{esyscmd}
6815 that does scan the output.
6817 @item
6818 At one point, @acronym{POSIX} required @code{changequote(@var{arg})}
6819 (@pxref{Changequote}) to use newline as the close quote, but this was a
6820 bug, and the next version of @acronym{POSIX} is anticipated to state
6821 that using empty strings or just one argument is unspecified.
6822 Meanwhile, the @acronym{GNU} @code{m4} behavior of treating an empty
6823 end-quote delimiter as @samp{'} is not portable, as Solaris treats it as
6824 repeating the start-quote delimiter, and BSD treats it as leaving the
6825 previous end-quote delimiter unchanged.  For predictable results, never
6826 call changequote with just one argument, or with empty strings for
6827 arguments.
6829 @item
6830 At one point, @acronym{POSIX} required @code{changecom(@var{arg},)}
6831 (@pxref{Changecom}) to make it impossible to end a comment, but this is
6832 a bug, and the next version of @acronym{POSIX} is anticipated to state
6833 that using empty strings is unspecified.  Meanwhile, the @acronym{GNU}
6834 @code{m4} behavior of treating an empty end-comment delimiter as newline
6835 is not portable, as BSD treats it as leaving the previous end-comment
6836 delimiter unchanged.  It is also impossible in BSD implementations to
6837 disable comments, even though that is required by @acronym{POSIX}.  For
6838 predictable results, never call changecom with empty strings for
6839 arguments.
6841 @item
6842 Most implementations of @code{m4} give macros a higher precedence than
6843 comments when parsing, meaning that if the start delimiter given to
6844 @code{changecom} (@pxref{Changecom}) starts with a macro name, comments
6845 are effectively disabled.  @acronym{POSIX} does not specify what the
6846 precedence is, so this version of @acronym{GNU} @code{m4} parser
6847 recognizes comments, then macros, then quoted strings.
6849 @item
6850 Traditional implementations allow argument collection, but not string
6851 and comment processing, to span file boundaries.  Thus, if @file{a.m4}
6852 contains @samp{len(}, and @file{b.m4} contains @samp{abc)},
6853 @kbd{m4 a.m4 b.m4} outputs @samp{3} with traditional @code{m4}, but
6854 gives an error message that the end of file was encountered inside a
6855 macro with @acronym{GNU} @code{m4}.  On the other hand, traditional
6856 implementations do end of file processing for files included with
6857 @code{include} or @code{sinclude} (@pxref{Include}), while @acronym{GNU}
6858 @code{m4} seamlessly integrates the content of those files.  Thus
6859 @code{include(`a.m4')include(`b.m4')} will output @samp{3} instead of
6860 giving an error.
6862 @item
6863 Traditional @code{m4} treats @code{traceon} (@pxref{Trace}) without
6864 arguments as a global variable, independent of named macro tracing.
6865 Also, once a macro is undefined, named tracing of that macro is lost.
6866 On the other hand, when @acronym{GNU} @code{m4} encounters
6867 @code{traceon} without
6868 arguments, it turns tracing on for all existing definitions at the time,
6869 but does not trace future definitions; @code{traceoff} without arguments
6870 turns tracing off for all definitions regardless of whether they were
6871 also traced by name; and tracing by name, such as with @option{-tfoo} at
6872 the command line or @code{traceon(`foo')} in the input, is an attribute
6873 that is preserved even if the macro is currently undefined.
6875 @item
6876 @acronym{POSIX} requires @code{eval} (@pxref{Eval}) to treat all
6877 operators with the same precedence as C@.  However, earlier versions of
6878 @acronym{GNU} @code{m4} followed the traditional behavior of other
6879 @code{m4} implementations, where bitwise and logical negation (@samp{~}
6880 and @samp{!}) have lower precedence than equality operators; and where
6881 equality operators (@samp{==} and @samp{!=}) had the same precedence as
6882 relational operators (such as @samp{<}).  Use explicit parentheses to
6883 ensure proper precedence.  As extensions to @acronym{POSIX},
6884 @acronym{GNU} @code{m4} gives well-defined semantics to operations that
6885 C leaves undefined, such as when overflow occurs, when shifting negative
6886 numbers, or when performing division by zero.  @acronym{POSIX} also
6887 requires @samp{=} to cause an error, but many traditional
6888 implementations allowed it as an alias for @samp{==}.
6890 @item
6891 @acronym{POSIX} 2001 requires @code{translit} (@pxref{Translit}) to
6892 treat each character of the second and third arguments literally.
6893 However, it is anticipated that the next version of @acronym{POSIX} will
6894 allow the @acronym{GNU} @code{m4} behavior of treating @samp{-} as a
6895 range operator.
6897 @item
6898 @acronym{POSIX} requires @code{m4} to honor the locale environment
6899 variables of @env{LANG}, @env{LC_ALL}, @env{LC_CTYPE},
6900 @env{LC_MESSAGES}, and @env{NLSPATH}, but this has not yet been
6901 implemented in @acronym{GNU} @code{m4}.
6903 @item
6904 @acronym{POSIX} states that only unquoted leading newlines and blanks
6905 (that is, space and tab) are ignored when collecting macro arguments.
6906 However, this appears to be a bug in @acronym{POSIX}, since most
6907 traditional implementations also ignore all whitespace (formfeed,
6908 carriage return, and vertical tab).  @acronym{GNU} @code{m4} follows
6909 tradition and ignores all leading unquoted whitespace.
6910 @end itemize
6912 @node Other Incompatibilities
6913 @section Other incompatibilities
6915 There are a few other incompatibilities between this implementation of
6916 @code{m4}, and the System V version.
6918 @itemize @bullet
6919 @item
6920 @acronym{GNU} @code{m4} implements sync lines differently from System V
6921 @code{m4}, when text is being diverted.  @acronym{GNU} @code{m4} outputs
6922 the sync lines when the text is being diverted, and System V @code{m4}
6923 when the diverted text is being brought back.
6925 The problem is which lines and file names should be attached to text
6926 that is being, or has been, diverted.  System V @code{m4} regards all
6927 the diverted text as being generated by the source line containing the
6928 @code{undivert} call, whereas @acronym{GNU} @code{m4} regards the
6929 diverted text as being generated at the time it is diverted.
6931 The sync line option is used mostly when using @code{m4} as
6932 a front end to a compiler.  If a diverted line causes a compiler error,
6933 the error messages should most probably refer to the place where the
6934 diversion was made, and not where it was inserted again.
6936 @comment options: -s
6937 @example
6938 divert(2)2
6939 divert(1)1
6940 divert`'0
6941 @result{}#line 3 "stdin"
6942 @result{}0
6944 @result{}#line 2 "stdin"
6945 @result{}1
6946 @result{}#line 1 "stdin"
6947 @result{}2
6948 @end example
6950 The current @code{m4} implementation has a limitation that the syncline
6951 output at the start of each diversion occurs no matter what, even if the
6952 previous diversion did not end with a newline.  This goes contrary to
6953 the claim that synclines appear on a line by themselves, so this
6954 limitation may be corrected in a future version of @code{m4}.  In the
6955 meantime, when using @option{-s}, it is wisest to make sure all
6956 diversions end with newline.
6958 @item
6959 @acronym{GNU} @code{m4} makes no attempt at prohibiting self-referential
6960 definitions like:
6962 @example
6963 define(`x', `x')
6964 @result{}
6965 define(`x', `x ')
6966 @result{}
6967 @end example
6969 @cindex rescanning
6970 There is nothing inherently wrong with defining @samp{x} to
6971 return @samp{x}.  The wrong thing is to expand @samp{x} unquoted,
6972 because that would cause an infinite rescan loop.
6973 In @code{m4}, one might use macros to hold strings, as we do for
6974 variables in other programming languages, further checking them with:
6976 @comment ignore
6977 @example
6978 ifelse(defn(`@var{holder}'), `@var{value}', @dots{})
6979 @end example
6981 @noindent
6982 In cases like this one, an interdiction for a macro to hold its own name
6983 would be a useless limitation.  Of course, this leaves more rope for the
6984 @acronym{GNU} @code{m4} user to hang himself!  Rescanning hangs may be
6985 avoided through careful programming, a little like for endless loops in
6986 traditional programming languages.
6987 @end itemize
6989 @node Answers
6990 @chapter Correct version of some examples
6992 Some of the examples in this manuals are buggy or not very robust, for
6993 demonstration purposes.  Improved versions of these composite macros are
6994 presented here.
6996 @menu
6997 * Improved exch::               Solution for @code{exch}
6998 * Improved forloop::            Solution for @code{forloop}
6999 * Improved foreach::            Solution for @code{foreach}
7000 * Improved cleardivert::        Solution for @code{cleardivert}
7001 * Improved capitalize::         Solution for @code{capitalize}
7002 * Improved fatal_error::        Solution for @code{fatal_error}
7003 @end menu
7005 @node Improved exch
7006 @section Solution for @code{exch}
7008 The @code{exch} macro (@pxref{Arguments}) as presented requires clients
7009 to double quote their arguments.  A nicer definition, which lets
7010 clients follow the rule of thumb of one level of quoting per level of
7011 parentheses, involves adding quotes in the definition of @code{exch}, as
7012 follows:
7014 @example
7015 define(`exch', ``$2', `$1'')
7016 @result{}
7017 define(exch(`expansion text', `macro'))
7018 @result{}
7019 macro
7020 @result{}expansion text
7021 @end example
7023 @node Improved forloop
7024 @section Solution for @code{forloop}
7026 The @code{forloop} macro (@pxref{Forloop}) as presented earlier can go
7027 into an infinite loop if given an iterator that is not parsed as a macro
7028 name.  It does not do any sanity checking on its numeric bounds, and
7029 only permits decimal numbers for bounds.  Here is an improved version,
7030 shipped as @file{m4-@value{VERSION}/@/examples/@/forloop2.m4}; this
7031 version also optimizes based on the fact that the starting bound does
7032 not need to be passed to the helper @code{@w{_forloop}}.
7034 @comment examples
7035 @example
7036 $ @kbd{m4 -I examples}
7037 undivert(`forloop2.m4')dnl
7038 @result{}divert(`-1')
7039 @result{}# forloop(var, from, to, stmt) - improved version:
7040 @result{}#   works even if VAR is not a strict macro name
7041 @result{}#   performs sanity check that FROM is larger than TO
7042 @result{}#   allows complex numerical expressions in TO and FROM
7043 @result{}define(`forloop', `ifelse(eval(`($3) >= ($2)'), `1',
7044 @result{}  `pushdef(`$1', eval(`$2'))_$0(`$1',
7045 @result{}    eval(`$3'), `$4')popdef(`$1')')')
7046 @result{}define(`_forloop',
7047 @result{}  `$3`'ifelse(indir(`$1'), `$2', `',
7048 @result{}    `define(`$1', incr(indir(`$1')))$0($@@)')')
7049 @result{}divert`'dnl
7050 include(`forloop2.m4')
7051 @result{}
7052 forloop(`i', `2', `1', `no iteration occurs')
7053 @result{}
7054 forloop(`', `1', `2', ` odd iterator name')
7055 @result{} odd iterator name odd iterator name
7056 forloop(`i', `5 + 5', `0xc', ` 0x`'eval(i, `16')')
7057 @result{} 0xa 0xb 0xc
7058 forloop(`i', `a', `b', `non-numeric bounds')
7059 @error{}m4:stdin:6: Warning: eval: bad expression (bad input): (b) >= (a)
7060 @result{}
7061 @end example
7063 One other change to notice is that the improved version used @samp{_$0}
7064 rather than @samp{_foreach} to invoke the helper routine.  In general,
7065 this is a good practice to follow, because then the set of macros can be
7066 uniformly transformed.  The following example shows a transformation
7067 that doubles the current quoting and appends a suffix @samp{2} to each
7068 transformed macro.  If @code{foreach} refers to the literal
7069 @samp{_foreach}, then @code{foreach2} invokes @code{_foreach} instead of
7070 the intended @code{_foreach2}, and the mixing of quoting paradigms leads
7071 to an infinite recursion loop in this example.
7073 @comment options: -L9
7074 @comment status: 1
7075 @comment examples
7076 @example
7077 $ @kbd{m4 -d -L 9 -I examples}
7078 define(`arg1', `$1')include(`forloop2.m4')include(`quote.m4')
7079 @result{}
7080 define(`double', `define(`$1'`2',
7081   arg1(patsubst(dquote(defn(`$1')), `[`']', `\&\&')))')
7082 @result{}
7083 double(`forloop')double(`_forloop')defn(`forloop2')
7084 @result{}ifelse(eval(``($3) >= ($2)''), ``1'',
7085 @result{}  ``pushdef(``$1'', eval(``$2''))_$0(``$1'',
7086 @result{}    eval(``$3''), ``$4'')popdef(``$1'')'')
7087 forloop(i, 1, 5, `ifelse(')forloop(i, 1, 5, `)')
7088 @result{}
7089 changequote(`[', `]')changequote([``], [''])
7090 @result{}
7091 forloop2(i, 1, 5, ``ifelse('')forloop2(i, 1, 5, ``)'')
7092 @result{}
7093 changequote`'include(`forloop.m4')
7094 @result{}
7095 double(`forloop')double(`_forloop')defn(`forloop2')
7096 @result{}pushdef(``$1'', ``$2'')_forloop($@@)popdef(``$1'')
7097 forloop(i, 1, 5, `ifelse(')forloop(i, 1, 5, `)')
7098 @result{}
7099 changequote(`[', `]')changequote([``], [''])
7100 @result{}
7101 forloop2(i, 1, 5, ``ifelse('')forloop2(i, 1, 5, ``)'')
7102 @error{}m4:stdin:12: recursion limit of 9 exceeded, use -L<N> to change it
7103 @end example
7105 Of course, it is possible to make even more improvements, such as
7106 adding an optional step argument, or allowing iteration through
7107 descending sequences.  @acronym{GNU} Autoconf provides some of these
7108 additional bells and whistles in its @code{m4_for} macro.
7110 @node Improved foreach
7111 @section Solution for @code{foreach}
7113 The @code{foreach} and @code{foreachq} macros (@pxref{Foreach}) as
7114 presented earlier each have flaws.  First, we will examine and fix the
7115 quadratic behavior of @code{foreachq}:
7117 @comment examples
7118 @example
7119 $ @kbd{m4 -I examples}
7120 include(`foreachq.m4')
7121 @result{}
7122 traceon(`shift')debugmode(`aq')
7123 @result{}
7124 foreachq(`x', ``1', `2', `3', `4'', `x
7125 ')dnl
7126 @result{}1
7127 @error{}m4trace: -3- shift(`1', `2', `3', `4')
7128 @error{}m4trace: -2- shift(`1', `2', `3', `4')
7129 @result{}2
7130 @error{}m4trace: -4- shift(`1', `2', `3', `4')
7131 @error{}m4trace: -3- shift(`2', `3', `4')
7132 @error{}m4trace: -3- shift(`1', `2', `3', `4')
7133 @error{}m4trace: -2- shift(`2', `3', `4')
7134 @result{}3
7135 @error{}m4trace: -5- shift(`1', `2', `3', `4')
7136 @error{}m4trace: -4- shift(`2', `3', `4')
7137 @error{}m4trace: -3- shift(`3', `4')
7138 @error{}m4trace: -4- shift(`1', `2', `3', `4')
7139 @error{}m4trace: -3- shift(`2', `3', `4')
7140 @error{}m4trace: -2- shift(`3', `4')
7141 @result{}4
7142 @error{}m4trace: -6- shift(`1', `2', `3', `4')
7143 @error{}m4trace: -5- shift(`2', `3', `4')
7144 @error{}m4trace: -4- shift(`3', `4')
7145 @error{}m4trace: -3- shift(`4')
7146 @end example
7148 @cindex quadratic behavior, avoiding
7149 @cindex avoiding quadratic behavior
7150 Each successive iteration was adding more quoted @code{shift}
7151 invocations, and the entire list contents were passing through every
7152 iteration.  In general, when recursing, it is a good idea to make the
7153 recursion use fewer arguments, rather than adding additional quoted
7154 uses of @code{shift}.  By doing so, @code{m4} uses less memory, invokes
7155 fewer macros, is less likely to run into machine limits, and most
7156 importantly, performs faster.  The fixed version of @code{foreachq} can
7157 be found in @file{m4-@value{VERSION}/@/examples/@/foreachq2.m4}:
7159 @comment examples
7160 @example
7161 $ @kbd{m4 -I examples}
7162 include(`foreachq2.m4')
7163 @result{}
7164 undivert(`foreachq2.m4')dnl
7165 @result{}include(`quote.m4')dnl
7166 @result{}divert(`-1')
7167 @result{}# foreachq(x, `item_1, item_2, ..., item_n', stmt)
7168 @result{}#   quoted list, improved version
7169 @result{}define(`foreachq', `pushdef(`$1')_$0($@@)popdef(`$1')')
7170 @result{}define(`_arg1q', ``$1'')
7171 @result{}define(`_rest', `ifelse(`$#', `1', `', `dquote(shift($@@))')')
7172 @result{}define(`_foreachq', `ifelse(`$2', `', `',
7173 @result{}  `define(`$1', _arg1q($2))$3`'$0(`$1', _rest($2), `$3')')')
7174 @result{}divert`'dnl
7175 traceon(`shift')debugmode(`aq')
7176 @result{}
7177 foreachq(`x', ``1', `2', `3', `4'', `x
7178 ')dnl
7179 @result{}1
7180 @error{}m4trace: -3- shift(`1', `2', `3', `4')
7181 @result{}2
7182 @error{}m4trace: -3- shift(`2', `3', `4')
7183 @result{}3
7184 @error{}m4trace: -3- shift(`3', `4')
7185 @result{}4
7186 @end example
7188 Note that the fixed version calls unquoted helper macros in
7189 @code{@w{_foreachq}} to trim elements immediately; those helper macros
7190 in turn must re-supply the layer of quotes lost in the macro invocation.
7191 Contrast the use of @code{@w{_arg1q}}, which quotes the first list
7192 element, with @code{@w{_arg1}} of the earlier implementation that
7193 returned the first list element directly.  Additionally, by calling the
7194 helper method immediately, the @samp{defn(`@var{iterator}')} no longer
7195 contains unexpanded macros.
7197 The astute m4 programmer might notice that the solution above still uses
7198 more macro invocations than strictly necessary.  Note that @samp{$2},
7199 which contains an arbitrarily long quoted list, is expanded and
7200 rescanned three times per iteration of @code{_foreachq}.  Furthermore,
7201 every iteration of the algorithm effectively unboxes then reboxes the
7202 list, which costs a couple of macro invocations.  It is possible to
7203 rewrite the algorithm by swapping the order of the arguments to
7204 @code{_foreachq} in order to operate on an unboxed list in the first
7205 place, and by using the fixed-length @samp{$#} instead of an arbitrary
7206 length list as the key to end recursion.  The result is eight macro
7207 invocations per loop, instead of nine.  This alternative approach is
7208 available as @file{m4-@value{VERSION}/@/examples/@/foreach3.m4}:
7210 @comment examples
7211 @example
7212 $ @kbd{m4 -I examples}
7213 include(`foreachq3.m4')
7214 @result{}
7215 undivert(`foreachq3.m4')dnl
7216 @result{}divert(`-1')
7217 @result{}# foreachq(x, `item_1, item_2, ..., item_n', stmt)
7218 @result{}#   quoted list, alternate improved version
7219 @result{}define(`foreachq',
7220 @result{}`pushdef(`$1')_$0(`$1', `$3'ifelse(`$2', `', `',
7221 @result{}  `, $2'))popdef(`$1')')
7222 @result{}define(`_foreachq', `ifelse(`$#', `2', `',
7223 @result{}  `define(`$1', `$3')$2`'$0(`$1', `$2'ifelse(`$#', `3', `',
7224 @result{}    `, shift(shift(shift($@@)))'))')')
7225 @result{}divert`'dnl
7226 traceon(`shift')debugmode(`aq')
7227 @result{}
7228 foreachq(`x', ``1', `2', `3', `4'', `x
7229 ')dnl
7230 @result{}1
7231 @error{}m4trace: -4- shift(`x', `x
7232 @error{}', `1', `2', `3', `4')
7233 @error{}m4trace: -3- shift(`x
7234 @error{}', `1', `2', `3', `4')
7235 @error{}m4trace: -2- shift(`1', `2', `3', `4')
7236 @result{}2
7237 @error{}m4trace: -4- shift(`x', `x
7238 @error{}', `2', `3', `4')
7239 @error{}m4trace: -3- shift(`x
7240 @error{}', `2', `3', `4')
7241 @error{}m4trace: -2- shift(`2', `3', `4')
7242 @result{}3
7243 @error{}m4trace: -4- shift(`x', `x
7244 @error{}', `3', `4')
7245 @error{}m4trace: -3- shift(`x
7246 @error{}', `3', `4')
7247 @error{}m4trace: -2- shift(`3', `4')
7248 @result{}4
7249 @end example
7251 Prior to M4 1.4.11, every instance of @samp{$@@} was rescanned as it was
7252 encountered.  Thus, the @file{foreachq3.m4} alternative used much less
7253 memory than @file{foreachq2.m4}, and executed as much as 10% faster,
7254 since each iteration encountered fewer @samp{$@@}.  However, the
7255 implementation of rescanning every byte in @samp{$@@} was quadratic in
7256 the number of bytes scanned (for example, making the broken version in
7257 @file{foreachq.m4} cubic, rather than quadratic, in behavior).  Once the
7258 underlying M4 implementation was improved in 1.4.11 to reuse results of
7259 previous scans, both styles of @code{foreachq} become linear in the
7260 number of bytes scanned, and the difference in timing is no longer
7261 noticeable; in fact, after the change, the @file{foreachq2.m4} version
7262 uses slightly less memory since it tracks fewer arguments per macro
7263 invocation.
7265 For yet another approach, the improved version of @code{foreach},
7266 available in @file{m4-@value{VERSION}/@/examples/@/foreach2.m4}, simply
7267 overquotes the arguments to @code{@w{_foreach}} to begin with, using
7268 @code{dquote_elt}.  Then @code{@w{_foreach}} can just use
7269 @code{@w{_arg1}} to remove the extra layer of quoting that was added up
7270 front:
7272 @comment examples
7273 @example
7274 $ @kbd{m4 -I examples}
7275 include(`foreach2.m4')
7276 @result{}
7277 undivert(`foreach2.m4')dnl
7278 @result{}include(`quote.m4')dnl
7279 @result{}divert(`-1')
7280 @result{}# foreach(x, (item_1, item_2, ..., item_n), stmt)
7281 @result{}#   parenthesized list, improved version
7282 @result{}define(`foreach', `pushdef(`$1')_$0(`$1',
7283 @result{}  (dquote(dquote_elt$2)), `$3')popdef(`$1')')
7284 @result{}define(`_arg1', `$1')
7285 @result{}define(`_foreach', `ifelse(`$2', `(`')', `',
7286 @result{}  `define(`$1', _arg1$2)$3`'$0(`$1', (dquote(shift$2)), `$3')')')
7287 @result{}divert`'dnl
7288 traceon(`shift')debugmode(`aq')
7289 @result{}
7290 foreach(`x', `(`1', `2', `3', `4')', `x
7291 ')dnl
7292 @error{}m4trace: -4- shift(`1', `2', `3', `4')
7293 @error{}m4trace: -4- shift(`2', `3', `4')
7294 @error{}m4trace: -4- shift(`3', `4')
7295 @result{}1
7296 @error{}m4trace: -3- shift(``1'', ``2'', ``3'', ``4'')
7297 @result{}2
7298 @error{}m4trace: -3- shift(``2'', ``3'', ``4'')
7299 @result{}3
7300 @error{}m4trace: -3- shift(``3'', ``4'')
7301 @result{}4
7302 @error{}m4trace: -3- shift(``4'')
7303 @end example
7305 In summary, recursion over list elements is trickier than it appeared at
7306 first glance, but provides a powerful idiom within @code{m4} processing.
7307 As a final demonstration, both list styles are now able to handle
7308 several scenarios that would wreak havoc on one or both of the original
7309 implementations.  This points out one other difference between the
7310 list styles.  @code{foreach} evaluates unquoted list elements only once,
7311 in preparation for calling @code{@w{_foreach}}, similary for
7312 @code{foreachq} as provided by @file{foreachq3.m4}.  But
7313 @code{foreachq}, as provided by @file{foreachq2.m4},
7314 evaluates unquoted list elements twice while visiting the first list
7315 element, once in @code{@w{_arg1q}} and once in @code{@w{_rest}}.  When
7316 deciding which list style to use, one must take into account whether
7317 repeating the side effects of unquoted list elements will have any
7318 detrimental effects.
7320 @comment examples
7321 @example
7322 $ @kbd{m4 -d -I examples}
7323 include(`foreach2.m4')
7324 @result{}
7325 include(`foreachq2.m4')
7326 @result{}
7327 dnl 0-element list:
7328 foreach(`x', `', `<x>') / foreachq(`x', `', `<x>')
7329 @result{} /@w{ }
7330 dnl 1-element list of empty element
7331 foreach(`x', `()', `<x>') / foreachq(`x', ``'', `<x>')
7332 @result{}<> / <>
7333 dnl 2-element list of empty elements
7334 foreach(`x', `(`',`')', `<x>') / foreachq(`x', ``',`'', `<x>')
7335 @result{}<><> / <><>
7336 dnl 1-element list of a comma
7337 foreach(`x', `(`,')', `<x>') / foreachq(`x', ``,'', `<x>')
7338 @result{}<,> / <,>
7339 dnl 2-element list of unbalanced parentheses
7340 foreach(`x', `(`(', `)')', `<x>') / foreachq(`x', ``(', `)'', `<x>')
7341 @result{}<(><)> / <(><)>
7342 define(`ab', `oops')dnl using defn(`iterator')
7343 foreach(`x', `(`a', `b')', `defn(`x')') /dnl
7344  foreachq(`x', ``a', `b'', `defn(`x')')
7345 @result{}ab / ab
7346 define(`active', `ACT, IVE')
7347 @result{}
7348 traceon(`active')
7349 @result{}
7350 dnl list of unquoted macros; expansion occurs before recursion
7351 foreach(`x', `(active, active)', `<x>
7352 ')dnl
7353 @error{}m4trace: -4- active -> `ACT, IVE'
7354 @error{}m4trace: -4- active -> `ACT, IVE'
7355 @result{}<ACT>
7356 @result{}<IVE>
7357 @result{}<ACT>
7358 @result{}<IVE>
7359 foreachq(`x', `active, active', `<x>
7360 ')dnl
7361 @error{}m4trace: -3- active -> `ACT, IVE'
7362 @error{}m4trace: -3- active -> `ACT, IVE'
7363 @result{}<ACT>
7364 @error{}m4trace: -3- active -> `ACT, IVE'
7365 @error{}m4trace: -3- active -> `ACT, IVE'
7366 @result{}<IVE>
7367 @result{}<ACT>
7368 @result{}<IVE>
7369 dnl list of quoted macros; expansion occurs during recursion
7370 foreach(`x', `(`active', `active')', `<x>
7371 ')dnl
7372 @error{}m4trace: -1- active -> `ACT, IVE'
7373 @result{}<ACT, IVE>
7374 @error{}m4trace: -1- active -> `ACT, IVE'
7375 @result{}<ACT, IVE>
7376 foreachq(`x', ``active', `active'', `<x>
7377 ')dnl
7378 @error{}m4trace: -1- active -> `ACT, IVE'
7379 @result{}<ACT, IVE>
7380 @error{}m4trace: -1- active -> `ACT, IVE'
7381 @result{}<ACT, IVE>
7382 dnl list of double-quoted macro names; no expansion
7383 foreach(`x', `(``active'', ``active'')', `<x>
7384 ')dnl
7385 @result{}<active>
7386 @result{}<active>
7387 foreachq(`x', ```active'', ``active''', `<x>
7388 ')dnl
7389 @result{}<active>
7390 @result{}<active>
7391 @end example
7393 @ignore
7394 @comment Not worth putting in the manual, but make sure that performance
7395 @comment on recursive algorithms is not quadratic.
7397 @comment boxed recursion
7399 @comment examples
7400 @comment options: -Dlimit=10 -Dverbose
7401 @example
7402 $ @kbd {m4 -I examples -Dlimit=10 -Dverbose}
7403 include(`loop.m4')dnl
7404 @result{} 1 2 3 4 5 6 7 8 9 10
7405 @end example
7407 @comment examples
7408 @comment options: -Dlimit=2500
7409 @example
7410 $ @kbd {m4 -I examples -Dlimit=2500}
7411 include(`loop.m4')dnl
7412 @end example
7414 @comment examples
7415 @comment options: -Dlimit=10000
7416 @example
7417 $ @kbd {m4 -I examples -Dlimit=10000}
7418 define(`debug', `define(`popdef',`divert`'i')')
7419 @result{}
7420 include(`loop.m4')dnl
7421 @result{}10000
7422 @end example
7424 @comment unboxed recursion
7426 @comment examples
7427 @comment options: -Dlimit=10 -Dverbose -Dalt
7428 @example
7429 $ @kbd {m4 -I examples -Dlimit=10 -Dverbose -Dalt}
7430 include(`loop.m4')dnl
7431 @result{} 1 2 3 4 5 6 7 8 9 10
7432 @end example
7434 @comment examples
7435 @comment options: -Dlimit=2500 -Dalt
7436 @example
7437 $ @kbd {m4 -I examples -Dlimit=2500 -Dalt}
7438 include(`loop.m4')dnl
7439 @end example
7441 @comment examples
7442 @comment options: -Dlimit=10000 -Dalt
7443 @example
7444 $ @kbd {m4 -I examples -Dlimit=10000 -Dalt}
7445 define(`debug', `define(`popdef',`divert`'i')')
7446 @result{}
7447 include(`loop.m4')dnl
7448 @result{}10000
7449 @end example
7451 @end ignore
7453 @node Improved cleardivert
7454 @section Solution for @code{cleardivert}
7456 The @code{cleardivert} macro (@pxref{Cleardivert}) cannot, as it stands, be
7457 called without arguments to clear all pending diversions.  That is
7458 because using undivert with an empty string for an argument is different
7459 than using it with no arguments at all.  Compare the earlier definition
7460 with one that takes the number of arguments into account:
7462 @example
7463 define(`cleardivert',
7464   `pushdef(`_n', divnum)divert(`-1')undivert($@@)divert(_n)popdef(`_n')')
7465 @result{}
7466 divert(`1')one
7467 divert
7468 @result{}
7469 cleardivert
7470 @result{}
7471 undivert
7472 @result{}one
7473 @result{}
7474 define(`cleardivert',
7475   `pushdef(`_num', divnum)divert(`-1')ifelse(`$#', `0',
7476     `undivert`'', `undivert($@@)')divert(_num)popdef(`_num')')
7477 @result{}
7478 divert(`2')two
7479 divert
7480 @result{}
7481 cleardivert
7482 @result{}
7483 undivert
7484 @result{}
7485 @end example
7487 @node Improved capitalize
7488 @section Solution for @code{capitalize}
7490 The @code{capitalize} macro (@pxref{Patsubst}) as presented earlier does
7491 not allow clients to follow the quoting rule of thumb.  Consider the
7492 three macros @code{active}, @code{Active}, and @code{ACTIVE}, and the
7493 difference between calling @code{capitalize} with the expansion of a
7494 macro, expanding the result of a case change, and changing the case of a
7495 double-quoted string:
7497 @comment examples
7498 @example
7499 $ @kbd{m4 -I examples}
7500 include(`capitalize.m4')dnl
7501 define(`active', `act1, ive')dnl
7502 define(`Active', `Act2, Ive')dnl
7503 define(`ACTIVE', `ACT3, IVE')dnl
7504 upcase(active)
7505 @result{}ACT1,IVE
7506 upcase(`active')
7507 @result{}ACT3, IVE
7508 upcase(``active'')
7509 @result{}ACTIVE
7510 downcase(ACTIVE)
7511 @result{}act3,ive
7512 downcase(`ACTIVE')
7513 @result{}act1, ive
7514 downcase(``ACTIVE'')
7515 @result{}active
7516 capitalize(active)
7517 @result{}Act1
7518 capitalize(`active')
7519 @result{}Active
7520 capitalize(``active'')
7521 @result{}_capitalize(`active')
7522 define(`A', `OOPS')
7523 @result{}
7524 capitalize(active)
7525 @result{}OOPSct1
7526 capitalize(`active')
7527 @result{}OOPSctive
7528 @end example
7530 First, when @code{capitalize} is called with more than one argument, it
7531 was throwing away later arguments, whereas @code{upcase} and
7532 @code{downcase} used @samp{$*} to collect them all.  The fix is simple:
7533 use @samp{$*} consistently.
7535 Next, with single-quoting, @code{capitalize} outputs a single character,
7536 a set of quotes, then the rest of the characters, making it impossible
7537 to invoke @code{Active} after the fact, and allowing the alternate macro
7538 @code{A} to interfere.  Here, the solution is to use additional quoting
7539 in the helper macros, then pass the final over-quoted output string
7540 through @code{_arg1} to remove the extra quoting and finally invoke the
7541 concatenated portions as a single string.
7543 Finally, when passed a double-quoted string, the nested macro
7544 @code{_capitalize} is never invoked because it ended up nested inside
7545 quotes.  This one is the toughest to fix.  In short, we have no idea how
7546 many levels of quotes are in effect on the substring being altered by
7547 @code{patsubst}.  If the replacement string cannot be expressed entirely
7548 in terms of literal text and backslash substitutions, then we need a
7549 mechanism to guarantee that the helper macros are invoked outside of
7550 quotes.  In other words, this sounds like a job for @code{changequote}
7551 (@pxref{Changequote}).  By changing the active quoting characters, we
7552 can guarantee that replacement text injected by @code{patsubst} always
7553 occurs in the middle of a string that has exactly one level of
7554 over-quoting using alternate quotes; so the replacement text closes the
7555 quoted string, invokes the helper macros, then reopens the quoted
7556 string.  In turn, that means the replacement text has unbalanced quotes,
7557 necessitating another round of @code{changequote}.
7559 In the fixed version below, (also shipped as
7560 @file{m4-@value{VERSION}/@/examples/@/capitalize.m4}), @code{capitalize}
7561 uses the alternate quotes of @samp{<<[} and @samp{]>>} (the longer
7562 strings are chosen so as to be less likely to appear in the text being
7563 converted).  The helpers @code{_to_alt} and @code{_from_alt} merely
7564 reduce the number of characters required to perform a
7565 @code{changequote}, since the definition changes twice.  The outermost
7566 pair means that @code{patsubst} and @code{_capitalize_alt} are invoked
7567 with alternate quoting; the innermost pair is used so that the third
7568 argument to @code{patsubst} can contain an unbalanced
7569 @samp{]>>}/@samp{<<[} pair.  Note that @code{upcase} and @code{downcase}
7570 must be redefined as @code{_upcase_alt} and @code{_downcase_alt}, since
7571 they contain nested quotes but are invoked with the alternate quoting
7572 scheme in effect.
7574 @comment examples
7575 @example
7576 $ @kbd{m4 -I examples}
7577 include(`capitalize2.m4')dnl
7578 define(`active', `act1, ive')dnl
7579 define(`Active', `Act2, Ive')dnl
7580 define(`ACTIVE', `ACT3, IVE')dnl
7581 define(`A', `OOPS')dnl
7582 capitalize(active; `active'; ``active''; ```actIVE''')
7583 @result{}Act1,Ive; Act2, Ive; Active; `Active'
7584 undivert(`capitalize2.m4')dnl
7585 @result{}divert(`-1')
7586 @result{}# upcase(text)
7587 @result{}# downcase(text)
7588 @result{}# capitalize(text)
7589 @result{}#   change case of text, improved version
7590 @result{}define(`upcase', `translit(`$*', `a-z', `A-Z')')
7591 @result{}define(`downcase', `translit(`$*', `A-Z', `a-z')')
7592 @result{}define(`_arg1', `$1')
7593 @result{}define(`_to_alt', `changequote(`<<[', `]>>')')
7594 @result{}define(`_from_alt', `changequote(<<[`]>>, <<[']>>)')
7595 @result{}define(`_upcase_alt', `translit(<<[$*]>>, <<[a-z]>>, <<[A-Z]>>)')
7596 @result{}define(`_downcase_alt', `translit(<<[$*]>>, <<[A-Z]>>, <<[a-z]>>)')
7597 @result{}define(`_capitalize_alt',
7598 @result{}  `regexp(<<[$1]>>, <<[^\(\w\)\(\w*\)]>>,
7599 @result{}    <<[_upcase_alt(<<[<<[\1]>>]>>)_downcase_alt(<<[<<[\2]>>]>>)]>>)')
7600 @result{}define(`capitalize',
7601 @result{}  `_arg1(_to_alt()patsubst(<<[<<[$*]>>]>>, <<[\w+]>>,
7602 @result{}    _from_alt()`]>>_$0_alt(<<[\&]>>)<<['_to_alt())_from_alt())')
7603 @result{}divert`'dnl
7604 @end example
7606 @node Improved fatal_error
7607 @section Solution for @code{fatal_error}
7609 The @code{fatal_error} macro (@pxref{M4exit}) is not robust to versions
7610 of @acronym{GNU} M4 earlier than 1.4.8, where invoking
7611 @code{@w{__file__}} (@pxref{Location}) inside @code{m4wrap} would result
7612 in an empty string, and @code{@w{__line__}} resulted in @samp{0} even
7613 though all files start at line 1.  Furthermore, versions earlier than
7614 1.4.6 did not support the @code{@w{__program__}} macro.  If you want
7615 @code{fatal_error} to work across the entire 1.4.x release series, a
7616 better implementation would be:
7618 @comment status: 1
7619 @example
7620 define(`fatal_error',
7621   `errprint(ifdef(`__program__', `__program__', ``m4'')'dnl
7622 `:ifelse(__line__, `0', `',
7623     `__file__:__line__:')` fatal error: $*
7624 ')m4exit(`1')')
7625 @result{}
7626 m4wrap(`divnum(`demo of internal message')
7627 fatal_error(`inside wrapped text')')
7628 @result{}
7630 @error{}m4:stdin:6: Warning: divnum: extra arguments ignored: 1 > 0
7631 @result{}0
7632 @error{}m4:stdin:6: fatal error: inside wrapped text
7633 @end example
7635 @c ========================================================== Appendices
7637 @node Copying This Package
7638 @appendix How to make copies of the overall M4 package
7639 @cindex License, code
7641 This appendix covers the license for copying the source code of the
7642 overall M4 package.  This manual is under a different set of
7643 restrictions, covered later (@pxref{Copying This Manual}).
7645 @menu
7646 * GNU General Public License::  License for copying the M4 package
7647 @end menu
7649 @node GNU General Public License
7650 @appendixsec License for copying the M4 package
7651 @cindex GPL, GNU General Public License
7652 @cindex GNU General Public License
7653 @cindex General Public License (GPL), GNU
7654 @include gpl-3.0.texi
7656 @node Copying This Manual
7657 @appendix How to make copies of this manual
7658 @cindex License, manual
7660 This appendix covers the license for copying this manual.  Note that
7661 some of the longer examples in this manual are also distributed in the
7662 directory @file{m4-@value{VERSION}/@/examples/}, where a more
7663 permissive license is in effect when copying just the examples.
7665 @menu
7666 * GNU Free Documentation License::  License for copying this manual
7667 @end menu
7669 @node GNU Free Documentation License
7670 @appendixsec License for copying this manual
7671 @cindex FDL, GNU Free Documentation License
7672 @cindex GNU Free Documentation License
7673 @cindex Free Documentation License (FDL), GNU
7674 @include fdl.texi
7676 @node Indices
7677 @appendix Indices of concepts and macros
7679 @menu
7680 * Macro index::                 Index for all @code{m4} macros
7681 * Concept index::               Index for many concepts
7682 @end menu
7684 @node Macro index
7685 @appendixsec Index for all @code{m4} macros
7687 This index covers all @code{m4} builtins, as well as several useful
7688 composite macros.  References are exclusively to the places where a
7689 macro is introduced the first time.
7691 @printindex fn
7693 @node Concept index
7694 @appendixsec Index for many concepts
7696 @printindex cp
7698 @bye
7700 @c Local Variables:
7701 @c coding: iso-8859-1
7702 @c fill-column: 72
7703 @c ispell-local-dictionary: "american"
7704 @c indent-tabs-mode: nil
7705 @c whitespace-check-buffer-indent: nil
7706 @c End: