Reserve all uses of raw ${} in macro definitions, not just
[m4.git] / doc / m4.texinfo
blob4983adcf51d3ef1636dba77a93b88091e008319c
1 \input texinfo @c -*- texinfo -*-
2 @comment ========================================================
3 @comment %**start of header
4 @setfilename m4.info
5 @settitle GNU M4 macro processor
6 @setchapternewpage odd
7 @ifnothtml
8 @setcontentsaftertitlepage
9 @end ifnothtml
10 @finalout
12 @include version.texi
14 @c @tabchar{}
15 @c ----------
16 @c The testsuite expects literal tab output in some examples, but
17 @c literal tabs in texinfo lead to formatting issues.
18 @macro tabchar
19 @       @c
20 @end macro
22 @c @ovar{ARG}
23 @c -------------------
24 @c The ARG is an optional argument.  To be used for macro arguments in
25 @c their documentation.
26 @macro ovar{varname}
27 @r{[}@var{\varname\}@r{]}
28 @end macro
30 @c @dvar{ARG, DEFAULT}
31 @c -------------------
32 @c The ARG is an optional argument, defaulting to DEFAULT.  To be used
33 @c for macro arguments in their documentation.
34 @macro dvar{varname, default}
35 @r{[}@var{\varname\} = @samp{\default\}@r{]}
36 @end macro
38 @comment %**end of header
39 @comment ========================================================
41 @copying
43 This manual is for @acronym{GNU} M4 (version @value{VERSION}, @value{UPDATED}),
44 a package containing an implementation of the m4 macro language.
46 Copyright @copyright{} 1989, 1990, 1991, 1992, 1993, 1994, 2004, 2005,
47 2006, 2007 Free Software Foundation, Inc.
49 @quotation
50 Permission is granted to copy, distribute and/or modify this document
51 under the terms of the @acronym{GNU} Free Documentation License,
52 Version 1.2 or any later version published by the Free Software
53 Foundation; with no Invariant Sections, no Front-Cover Texts, and no
54 Back-Cover Texts.  A copy of the license is included in the section
55 entitled ``@acronym{GNU} Free Documentation License.''
56 @end quotation
57 @end copying
59 @dircategory GNU programming tools
60 @direntry
61 * M4: (m4).                     A powerful macro processor.
62 @end direntry
64 @titlepage
65 @title GNU M4, version @value{VERSION}
66 @subtitle A powerful macro processor
67 @subtitle Edition @value{EDITION}, @value{UPDATED}
68 @author by Ren@'e Seindal
70 @page
71 @vskip 0pt plus 1filll
72 @insertcopying
73 @end titlepage
75 @contents
77 @ifnottex
78 @node Top
79 @top GNU M4
80 @insertcopying
81 @end ifnottex
83 @acronym{GNU} @code{m4} is an implementation of the traditional UNIX macro
84 processor.  It is mostly SVR4 compatible, although it has some
85 extensions (for example, handling more than 9 positional parameters
86 to macros).  @code{m4} also has builtin functions for including
87 files, running shell commands, doing arithmetic, etc.  Autoconf needs
88 @acronym{GNU} @code{m4} for generating @file{configure} scripts, but not for
89 running them.
91 @acronym{GNU} @code{m4} was originally written by Ren@'e Seindal, with
92 subsequent changes by Fran@,{c}ois Pinard and other volunteers
93 on the Internet.  All names and email addresses can be found in the
94 files @file{m4-@value{VERSION}/@/AUTHORS} and
95 @file{m4-@value{VERSION}/@/THANKS} from the @acronym{GNU} M4
96 distribution.
98 This is release @value{VERSION}.  It is now considered stable:  future
99 releases in the 1.4.x series are only meant to fix bugs, increase speed,
100 or improve documentation.  However@dots{}
102 An experimental feature, which would improve @code{m4} usefulness,
103 allows for changing the syntax for what is a @dfn{word} in @code{m4}.
104 You should use:
105 @comment ignore
106 @example
107 ./configure --enable-changeword
108 @end example
109 @noindent
110 if you want this feature compiled in.  The current implementation
111 slows down @code{m4} considerably and is hardly acceptable.  In the
112 future, @code{m4} 2.0 will come with a different set of new features
113 that provide similar capabilities, but without the inefficiencies, so
114 changeword will go away and @emph{you should not count on it}.
116 @menu
117 * Preliminaries::               Introduction and preliminaries
118 * Invoking m4::                 Invoking @code{m4}
119 * Syntax::                      Lexical and syntactic conventions
121 * Macros::                      How to invoke macros
122 * Definitions::                 How to define new macros
123 * Conditionals::                Conditionals, loops, and recursion
125 * Debugging::                   How to debug macros and input
127 * Input Control::               Input control
128 * File Inclusion::              File inclusion
129 * Diversions::                  Diverting and undiverting output
131 * Text handling::               Macros for text handling
132 * Arithmetic::                  Macros for doing arithmetic
133 * Shell commands::              Macros for running shell commands
134 * Miscellaneous::               Miscellaneous builtin macros
135 * Frozen files::                Fast loading of frozen state
137 * Compatibility::               Compatibility with other versions of @code{m4}
138 * Answers::                     Correct version of some examples
139 * Copying This Manual::         How to make copies of this manual
140 * Indices::                     Indices of concepts and macros
142 @detailmenu
143  --- The Detailed Node Listing ---
145 Introduction and preliminaries
147 * Intro::                       Introduction to @code{m4}
148 * History::                     Historical references
149 * Bugs::                        Problems and bugs
150 * Manual::                      Using this manual
152 Invoking @code{m4}
154 * Operation modes::             Command line options for operation modes
155 * Preprocessor features::       Command line options for preprocessor features
156 * Limits control::              Command line options for limits control
157 * Frozen state::                Command line options for frozen state
158 * Debugging options::           Command line options for debugging
159 * Command line files::          Specifying input files on the command line
161 Lexical and syntactic conventions
163 * Names::                       Macro names
164 * Quoted strings::              Quoting input to @code{m4}
165 * Comments::                    Comments in @code{m4} input
166 * Other tokens::                Other kinds of input tokens
167 * Input processing::            How @code{m4} copies input to output
169 How to invoke macros
171 * Invocation::                  Macro invocation
172 * Inhibiting Invocation::       Preventing macro invocation
173 * Macro Arguments::             Macro arguments
174 * Quoting Arguments::           On Quoting Arguments to macros
175 * Macro expansion::             Expanding macros
177 How to define new macros
179 * Define::                      Defining a new macro
180 * Arguments::                   Arguments to macros
181 * Pseudo Arguments::            Special arguments to macros
182 * Undefine::                    Deleting a macro
183 * Defn::                        Renaming macros
184 * Pushdef::                     Temporarily redefining macros
186 * Indir::                       Indirect call of macros
187 * Builtin::                     Indirect call of builtins
189 Conditionals, loops, and recursion
191 * Ifdef::                       Testing if a macro is defined
192 * Ifelse::                      If-else construct, or multibranch
193 * Shift::                       Recursion in @code{m4}
194 * Forloop::                     Iteration by counting
195 * Foreach::                     Iteration by list contents
197 How to debug macros and input
199 * Dumpdef::                     Displaying macro definitions
200 * Trace::                       Tracing macro calls
201 * Debug Levels::                Controlling debugging output
202 * Debug Output::                Saving debugging output
204 Input control
206 * Dnl::                         Deleting whitespace in input
207 * Changequote::                 Changing the quote characters
208 * Changecom::                   Changing the comment delimiters
209 * Changeword::                  Changing the lexical structure of words
210 * M4wrap::                      Saving text until end of input
212 File inclusion
214 * Include::                     Including named files
215 * Search Path::                 Searching for include files
217 Diverting and undiverting output
219 * Divert::                      Diverting output
220 * Undivert::                    Undiverting output
221 * Divnum::                      Diversion numbers
222 * Cleardivert::                 Discarding diverted text
224 Macros for text handling
226 * Len::                         Calculating length of strings
227 * Index macro::                 Searching for substrings
228 * Regexp::                      Searching for regular expressions
229 * Substr::                      Extracting substrings
230 * Translit::                    Translating characters
231 * Patsubst::                    Substituting text by regular expression
232 * Format::                      Formatting strings (printf-like)
234 Macros for doing arithmetic
236 * Incr::                        Decrement and increment operators
237 * Eval::                        Evaluating integer expressions
239 Macros for running shell commands
241 * Platform macros::             Determining the platform
242 * Syscmd::                      Executing simple commands
243 * Esyscmd::                     Reading the output of commands
244 * Sysval::                      Exit status
245 * Mkstemp::                     Making temporary files
247 Miscellaneous builtin macros
249 * Errprint::                    Printing error messages
250 * Location::                    Printing current location
251 * M4exit::                      Exiting from @code{m4}
253 Fast loading of frozen state
255 * Using frozen files::          Using frozen files
256 * Frozen file format::          Frozen file format
258 Compatibility with other versions of @code{m4}
260 * Extensions::                  Extensions in @acronym{GNU} M4
261 * Incompatibilities::           Facilities in System V m4 not in GNU M4
262 * Other Incompatibilities::     Other incompatibilities
264 Correct version of some examples
266 * Improved exch::               Solution for @code{exch}
267 * Improved forloop::            Solution for @code{forloop}
268 * Improved foreach::            Solution for @code{foreach}
269 * Improved cleardivert::        Solution for @code{cleardivert}
270 * Improved fatal_error::        Solution for @code{fatal_error}
272 How to make copies of this manual
274 * GNU Free Documentation License::  License for copying this manual
276 Indices of concepts and macros
278 * Concept index::               Index for many concepts
279 * Macro index::                 Index for all @code{m4} macros
281 @end detailmenu
282 @end menu
284 @node Preliminaries
285 @chapter Introduction and preliminaries
287 This first chapter explains what @acronym{GNU} @code{m4} is, where @code{m4}
288 comes from, how to read and use this documentation, how to call the
289 @code{m4} program, and how to report bugs about it.  It concludes by
290 giving tips for reading the remainder of the manual.
292 The following chapters then detail all the features of the @code{m4}
293 language.
295 @menu
296 * Intro::                       Introduction to @code{m4}
297 * History::                     Historical references
298 * Bugs::                        Problems and bugs
299 * Manual::                      Using this manual
300 @end menu
302 @node Intro
303 @section Introduction to @code{m4}
305 @code{m4} is a macro processor, in the sense that it copies its
306 input to the output, expanding macros as it goes.  Macros are either
307 builtin or user-defined, and can take any number of arguments.
308 Besides just doing macro expansion, @code{m4} has builtin functions
309 for including named files, running shell commands, doing integer
310 arithmetic, manipulating text in various ways, performing recursion,
311 etc.@dots{}  @code{m4} can be used either as a front-end to a compiler,
312 or as a macro processor in its own right.
314 The @code{m4} macro processor is widely available on all UNIXes, and has
315 been standardized by @acronym{POSIX}.
316 Usually, only a small percentage of users are aware of its existence.
317 However, those who find it often become committed users.  The
318 popularity of @acronym{GNU} Autoconf, which requires @acronym{GNU}
319 @code{m4} for @emph{generating} @file{configure} scripts, is an incentive
320 for many to install it, while these people will not themselves
321 program in @code{m4}.  @acronym{GNU} @code{m4} is mostly compatible with the
322 System V, Release 3 version, except for some minor differences.
323 @xref{Compatibility}, for more details.
325 Some people find @code{m4} to be fairly addictive.  They first use
326 @code{m4} for simple problems, then take bigger and bigger challenges,
327 learning how to write complex sets of @code{m4} macros along the way.
328 Once really addicted, users pursue writing of sophisticated @code{m4}
329 applications even to solve simple problems, devoting more time
330 debugging their @code{m4} scripts than doing real work.  Beware that
331 @code{m4} may be dangerous for the health of compulsive programmers.
333 @node History
334 @section Historical references
336 @code{GPM} was an important ancestor of @code{m4}.  See
337 C. Stratchey: ``A General Purpose Macro generator'', Computer Journal
338 8,3 (1965), pp. 225 ff.  @code{GPM} is also succinctly described into
339 David Gries classic ``Compiler Construction for Digital Computers''.
341 The classic B. Kernighan and P.J. Plauger: ``Software Tools'',
342 Addison-Wesley, Inc. (1976) describes and implements a Unix
343 macro-processor language, which inspired Dennis Ritchie to write
344 @code{m3}, a macro processor for the AP-3 minicomputer.
346 Kernighan and Ritchie then joined forces to develop the original
347 @code{m4}, as described in ``The M4 Macro Processor'', Bell
348 Laboratories (1977).  It had only 21 builtin macros.
350 While @code{GPM} was more @emph{pure}, @code{m4} is meant to deal with
351 the true intricacies of real life: macros can be recognized without
352 being pre-announced, skipping whitespace or end-of-lines is easier,
353 more constructs are builtin instead of derived, etc.
355 Originally, the Kernighan and Plauger macro-processor, and then
356 @code{m3}, formed the engine for the Rational FORTRAN preprocessor,
357 that is, the @code{Ratfor} equivalent of @code{cpp}.  Later, @code{m4}
358 was used as a front-end for @code{Ratfor}, @code{C} and @code{Cobol}.
360 Ren@'e Seindal released his implementation of @code{m4}, @acronym{GNU}
361 @code{m4},
362 in 1990, with the aim of removing the artificial limitations in many
363 of the traditional @code{m4} implementations, such as maximum line
364 length, macro size, or number of macros.
366 The late Professor A. Dain Samples described and implemented a further
367 evolution in the form of @code{M5}: ``User's Guide to the M5 Macro
368 Language: 2nd edition'', Electronic Announcement on comp.compilers
369 newsgroup (1992).
371 Fran@,{c}ois Pinard took over maintenance of @acronym{GNU} @code{m4} in
372 1992, until 1994 when he released @acronym{GNU} @code{m4} 1.4, which was
373 the stable release for 10 years.  It was at this time that @acronym{GNU}
374 Autoconf decided to require @acronym{GNU} @code{m4} as its underlying
375 engine, since all other implementations of @code{m4} had too many
376 limitations.
378 More recently, in 2004, Paul Eggert released 1.4.1 and 1.4.2 which
379 addressed some long standing bugs in the venerable 1.4 release.  Then in
380 2005, Gary V. Vaughan collected together the many patches to
381 @acronym{GNU} @code{m4} 1.4 that were floating around the net and
382 released 1.4.3 and 1.4.4.  And in 2006, Eric Blake joined the team and
383 prepared patches for the release of 1.4.5, 1.4.6, 1.4.7, and 1.4.8.  The
384 1.4.x series remains open for bug fixes, including release 1.4.9 in
385 2007.
387 Meanwhile, development has continued on new features for @code{m4}, such
388 as dynamic module loading and additional builtins.  When complete,
389 @acronym{GNU} @code{m4} 2.0 will start a new series of releases.
391 @node Bugs
392 @section Problems and bugs
394 If you have problems with @acronym{GNU} M4 or think you've found a bug,
395 please report it.  Before reporting a bug, make sure you've actually
396 found a real bug.  Carefully reread the documentation and see if it
397 really says you can do what you're trying to do.  If it's not clear
398 whether you should be able to do something or not, report that too; it's
399 a bug in the documentation!
401 Before reporting a bug or trying to fix it yourself, try to isolate it
402 to the smallest possible input file that reproduces the problem.  Then
403 send us the input file and the exact results @code{m4} gave you.  Also
404 say what you expected to occur; this will help us decide whether the
405 problem was really in the documentation.
407 Once you've got a precise problem, send e-mail to (Internet)
408 @email{bug-m4@@gnu.org}.  Please include the version number of @code{m4}
409 you are using.  You can get this information with the command
410 @kbd{m4 --version}.  Also provide details about the platform you are
411 executing on.
413 Non-bug suggestions are always welcome as well.  If you have questions
414 about things that are unclear in the documentation or are just obscure
415 features, please report them too.
417 @node Manual
418 @section Using this manual
420 This manual contains a number of examples of @code{m4} input and output,
421 and a simple notation is used to distinguish input, output and error
422 messages from @code{m4}.  Examples are set out from the normal text, and
423 shown in a fixed width font, like this
425 @comment ignore
426 @example
427 This is an example of an example!
428 @end example
430 To distinguish input from output, all output from @code{m4} is prefixed
431 by the string @samp{@result{}}, and all error messages by the string
432 @samp{@error{}}.  Thus
434 @comment ignore
435 @example
436 Example of input line
437 @result{}Output line from m4
438 @error{}and an error message
439 @end example
441 The sequence @samp{^D} in an example indicates the end of the input
442 file.  The sequence @samp{@key{NL}} refers to the newline character.
443 The majority of these examples are self-contained, and you can run them
444 with similar results by invoking @kbd{m4 -d}.  In fact, the testsuite
445 that is bundled in the @acronym{GNU} M4 package consists of the examples
446 in this document!
448 As each of the predefined macros in @code{m4} is described, a prototype
449 call of the macro will be shown, giving descriptive names to the
450 arguments, e.g.,
452 @deffn Composite example (@var{string}, @dvar{count, 1}, @
453   @ovar{argument}@dots{})
454 This is a sample prototype.  There is not really a macro named
455 @code{example}, but this documents that if there were, it would be a
456 Composite macro, rather than a Builtin.  It requires at least one
457 argument, @var{string}.  Remember that in @code{m4}, there must not be a
458 space between the macro name and the opening parenthesis, unless it was
459 intended to call the macro without any arguments.  The brackets around
460 @var{count} and @var{argument} show that these arguments are optional.
461 If @var{count} is omitted, the macro behaves as if count were @samp{1},
462 whereas if @var{argument} is omitted, the macro behaves as if it were
463 the empty string.  A blank argument is not the same as an omitted
464 argument.  For example, @samp{example(`a')}, @samp{example(`a',`1')},
465 and @samp{example(`a',`1',)} would behave identically with @var{count}
466 set to @samp{1}; while @samp{example(`a',)} and @samp{example(`a',`')}
467 would explicitly pass the empty string for @var{count}.  The ellipses
468 (@samp{@dots{}}) show that the macro processes additional arguments
469 after @var{argument}, rather than ignoring them.
470 @end deffn
472 All macro arguments in @code{m4} are strings, but some are given
473 special interpretation, e.g., as numbers, file names, regular
474 expressions, etc.  The documentation for each macro will state how the
475 parameters are interpreted, and what happens if the argument cannot be
476 parsed according to the desired interpretation.  Unless specified
477 otherwise, a parameter specified to be a number is parsed as a decimal,
478 even if the argument has leading zeros; and parsing the empty string as
479 a number results in 0 rather than an error, although a warning will be
480 issued.
482 This document consistently writes and uses @dfn{builtin}, without a
483 hyphen, as if it were an English word.  This is how the @code{builtin}
484 primitive is spelled within @code{m4}.
486 @node Invoking m4
487 @chapter Invoking @code{m4}
489 The format of the @code{m4} command is:
491 @comment ignore
492 @example
493 @code{m4} @r{[}@var{option}@dots{}@r{]} @r{[}@var{file}@dots{}@r{]}
494 @end example
496 @cindex command line, options
497 @cindex options, command line
498 @cindex @env{POSIXLY_CORRECT}
499 All options begin with @samp{-}, or if long option names are used, with
500 @samp{--}.  A long option name need not be written completely, any
501 unambiguous prefix is sufficient.  @acronym{POSIX} requires @code{m4} to
502 recognize arguments intermixed with files, even when
503 @env{POSIXLY_CORRECT} is set in the environment.  Most options take
504 effect at startup regardless of their position, but some are documented
505 below as taking effect after any files that occurred earlier in the
506 command line.  The argument @option{--} is a marker to denote the end of
507 options.
509 With short options, options that do not take arguments may be combined
510 into a single command line argument with subsequent options, options
511 with mandatory arguments may be provided either as a single command line
512 argument or as two arguments, and options with optional arguments must
513 be provided as a single argument.  In other words,
514 @kbd{m4 -QPDfoo -d a -d+f} is equivalent to
515 @kbd{m4 -Q -P -D foo -d -d+f -- ./a}, although the latter form is
516 considered canonical.
518 With long options, options with mandatory arguments may be provided with
519 an equal sign (@samp{=}) in a single argument, or as two arguments, and
520 options with optional arguments must be provided as a single argument.
521 In other words, @kbd{m4 --def foo --debug a} is equivalent to
522 @kbd{m4 --define=foo --debug= -- ./a}, although the latter form is
523 considered canonical (not to mention more robust, in case a future
524 version of @code{m4} introduces an option named @option{--default}).
526 @code{m4} understands the following options, grouped by functionality.
528 @menu
529 * Operation modes::             Command line options for operation modes
530 * Preprocessor features::       Command line options for preprocessor features
531 * Limits control::              Command line options for limits control
532 * Frozen state::                Command line options for frozen state
533 * Debugging options::           Command line options for debugging
534 * Command line files::          Specifying input files on the command line
535 @end menu
537 @node Operation modes
538 @section Command line options for operation modes
540 Several options control the overall operation of @code{m4}:
542 @table @code
543 @item --help
544 Print a help summary on standard output, then immediately exit
545 @code{m4} without reading any input files or performing any other
546 actions.
548 @item --version
549 Print the version number of the program on standard output, then
550 immediately exit @code{m4} without reading any input files or
551 performing any other actions.
553 @item -E
554 @itemx --fatal-warnings
555 Controls the effect of warnings.  If unspecified, then execution
556 continues and exit status is unaffected when a warning is printed.  If
557 specified exactly once, warnings become fatal; when one is issued,
558 execution continues, but the exit status will be non-zero.  If specified
559 multiple times, then execution halts with non-zero status the first time
560 a warning is issued.  The introduction of behavior levels is new to M4
561 1.4.9; for behavior consistent with earlier versions, you should specify
562 @option{-E} twice.
564 @item -i
565 @itemx --interactive
566 @itemx -e
567 Makes this invocation of @code{m4} interactive.  This means that all
568 output will be unbuffered, and interrupts will be ignored.  The
569 spelling @option{-e} exists for compatibility with other @code{m4}
570 implementations, and issues a warning because it may be withdrawn in a
571 future version of @acronym{GNU} M4.
573 @item -P
574 @itemx --prefix-builtins
575 Internally modify @emph{all} builtin macro names so they all start with
576 the prefix @samp{m4_}.  For example, using this option, one should write
577 @samp{m4_define} instead of @samp{define}, and @samp{m4___file__}
578 instead of @samp{__file__}.  This option has no effect if @option{-R}
579 is also specified.
581 @item -Q
582 @itemx --quiet
583 @itemx --silent
584 Suppress warnings, such as missing or superfluous arguments in macro
585 calls, or treating the empty string as zero.
587 @item --warn-macro-sequence@r{[}=@var{REGEXP}@r{]}
588 Issue a warning if the regular expression @var{REGEXP} has a non-empty
589 match in any macro definition (either by @code{define} or
590 @code{pushdef}).  Empty matches are ignored; therefore, supplying the
591 empty string as @var{REGEXP} disables any warning.  If the optional
592 @var{REGEXP} is not supplied, then the default regular expression is
593 @samp{\$\(@{[^@}]*@}\|[0-9][0-9]+\)} (a literal @samp{$} followed by
594 multiple digits or by an open brace), since these sequences will
595 change semantics in the default operation of @acronym{GNU} M4 2.0 (due
596 to a change in how more than 9 arguments in a macro definition will be
597 handled, @pxref{Arguments}).  Providing an alternate regular
598 expression can provide a useful reverse lookup feature of finding
599 where a macro is defined to have a given definition.
601 @item -W @var{REGEXP}
602 @itemx --word-regexp=@var{REGEXP}
603 Use @var{REGEXP} as an alternative syntax for macro names.  This
604 experimental option will not be present in all @acronym{GNU} @code{m4}
605 implementations (@pxref{Changeword}).
606 @end table
608 @node Preprocessor features
609 @section Command line options for preprocessor features
611 @cindex macro definitions, on the command line
612 @cindex command line, macro definitions on the
613 Several options allow @code{m4} to behave more like a preprocessor.
614 Macro definitions and deletions can be made on the command line, the
615 search path can be altered, and the output file can track where the
616 input came from.  These features occur with the following options:
618 @table @code
619 @item -D @var{NAME}@r{[}=@var{VALUE}@r{]}
620 @itemx --define=@var{NAME}@r{[}=@var{VALUE}@r{]}
621 This enters @var{NAME} into the symbol table, before any input files are
622 read.  If @samp{=@var{VALUE}} is missing, the value is taken to be the
623 empty string.  The @var{VALUE} can be any string, and the macro can be
624 defined to take arguments, just as if it was defined from within the
625 input.  This option may be given more than once; order with respect to
626 file names is significant, and redefining the same @var{NAME} loses the
627 previous value.
629 @item -I @var{DIRECTORY}
630 @itemx --include=@var{DIRECTORY}
631 Make @code{m4} search @var{DIRECTORY} for included files that are not
632 found in the current working directory.  @xref{Search Path}, for more
633 details.  This option may be given more than once.
635 @item -s
636 @itemx --synclines
637 Generate synchronization lines, for use by the C preprocessor or other
638 similar tools.  Order is significant with respect to file names.  This
639 option is useful, for example, when @code{m4} is used as a
640 front end to a compiler.  Source file name and line number information
641 is conveyed by directives of the form @samp{#line @var{linenum}
642 "@var{file}"}, which are inserted as needed into the middle of the
643 output.  Such directives mean that the following line originated or was
644 expanded from the contents of input file @var{file} at line
645 @var{linenum}.  The @samp{"@var{file}"} part is often omitted when
646 the file name did not change from the previous directive.
648 Synchronization directives are always given on complete lines by
649 themselves.  When a synchronization discrepancy occurs in the middle of
650 an output line, the associated synchronization directive is delayed
651 until the beginning of the next generated line.
653 @item -U @var{NAME}
654 @itemx --undefine=@var{NAME}
655 This deletes any predefined meaning @var{NAME} might have.  Obviously,
656 only predefined macros can be deleted in this way.  This option may be
657 given more than once; undefining a @var{NAME} that does not have a
658 definition is silently ignored.  Order is significant with respect to
659 file names.
660 @end table
662 @node Limits control
663 @section Command line options for limits control
665 There are some limits within @code{m4} that can be tuned.  For
666 compatibility, @code{m4} also accepts some options that control limits
667 in other implementations, but which are automatically unbounded (limited
668 only by your hardware and operating system constraints) in @acronym{GNU}
669 @code{m4}.
671 @table @code
672 @item -G
673 @itemx --traditional
674 Suppress all the extensions made in this implementation, compared to the
675 System V version.  @xref{Compatibility}, for a list of these.
677 @item -H @var{NUM}
678 @itemx --hashsize=@var{NUM}
679 Make the internal hash table for symbol lookup be @var{NUM} entries big.
680 For better performance, the number should be prime, but this is not
681 checked.  The default is 509 entries.  It should not be necessary to
682 increase this value, unless you define an excessive number of macros.
684 @item -L @var{NUM}
685 @itemx --nesting-limit=@var{NUM}
686 Artificially limit the nesting of macro calls to @var{NUM} levels,
687 stopping program execution if this limit is ever exceeded.  When not
688 specified, nesting is limited to 1024 levels.  A value of zero means
689 unlimited; but then heavily nested code could potentially cause a stack
690 overflow.
692 The precise effect of this option might be more correctly associated
693 with textual nesting than dynamic recursion.  It has been useful
694 when some complex @code{m4} input was generated by mechanical means.
695 Most users would never need this option.  If shown to be obtrusive,
696 this option (which is still experimental) might well disappear.
698 This option does @emph{not} have the ability to break endless
699 rescanning loops, since these do not necessarily consume much memory
700 or stack space.  Through clever usage of rescanning loops, one can
701 request complex, time-consuming computations from @code{m4} with useful
702 results.  Putting limitations in this area would break @code{m4} power.
703 There are many pathological cases: @w{@samp{define(`a', `a')a}} is
704 only the simplest example (but @pxref{Compatibility}).  Expecting @acronym{GNU}
705 @code{m4} to detect these would be a little like expecting a compiler
706 system to detect and diagnose endless loops: it is a quite @emph{hard}
707 problem in general, if not undecidable!
709 @item -B @var{NUM}
710 @itemx -S @var{NUM}
711 @itemx -T @var{NUM}
712 These options are present for compatibility with System V @code{m4}, but
713 do nothing in this implementation.  They may disappear in future
714 releases, and issue a warning to that effect.
716 @item -N @var{NUM}
717 @itemx --diversions=@var{NUM}
718 These options are present only for compatibility with previous
719 versions of @acronym{GNU} @code{m4}, and were controlling the number of
720 possible diversions which could be used at the same time.  They do nothing,
721 because there is no fixed limit anymore.  They may disappear in future
722 releases, and issue a warning to that effect.
723 @end table
725 @node Frozen state
726 @section Command line options for frozen state
728 @acronym{GNU} @code{m4} comes with a feature of freezing internal state
729 (@pxref{Frozen files}).  This can be used to speed up @code{m4}
730 execution when reusing a common initialization script.
732 @table @code
733 @item -F @var{FILE}
734 @itemx --freeze-state=@var{FILE}
735 Once execution is finished, write out the frozen state on the specified
736 @var{FILE}.  It is conventional, but not required, for @var{FILE} to end
737 in @samp{.m4f}.
739 @item -R @var{FILE}
740 @itemx --reload-state=@var{FILE}
741 Before execution starts, recover the internal state from the specified
742 frozen @var{FILE}.  The options @option{-D}, @option{-U}, and
743 @option{-t} take effect after state is reloaded, but before the input
744 files are read.
745 @end table
747 @node Debugging options
748 @section Command line options for debugging
750 Finally, there are several options for aiding in debugging @code{m4}
751 scripts.
753 @table @code
754 @item -d@r{[}@var{FLAGS}@r{]}
755 @itemx --debug@r{[}=@var{FLAGS}@r{]}
756 Set the debug-level according to the flags @var{FLAGS}.  The debug-level
757 controls the format and amount of information presented by the debugging
758 functions.  @xref{Debug Levels}, for more details on the format and
759 meaning of @var{FLAGS}.  If omitted, @var{FLAGS} defaults to @samp{aeq}.
761 @item --debugfile=@var{FILE}
762 @itemx -o @var{FILE}
763 @itemx --error-output=@var{FILE}
764 Redirect @code{dumpdef} output, debug messages, and trace output to the
765 named @var{FILE}.  Warnings, error messages, and @code{errprint} output
766 are still printed to standard error.  If unspecified, debug output goes
767 to standard error; if empty, debug output is discarded.  @xref{Debug
768 Output}, for more details.  The spellings @option{-o} and
769 @option{--error-output} are misleading and inconsistent with other
770 @acronym{GNU} tools; for now they are silently accepted as synonyms of
771 @option{--debugfile}, but in a future version of M4, using them will
772 cause a warning to be issued.
774 @item -l @var{NUM}
775 @itemx --arglength=@var{NUM}
776 Restrict the size of the output generated by macro tracing to @var{NUM}
777 characters per trace line.  If unspecified or zero, output is
778 unlimited.  @xref{Debug Levels}, for more details.
780 @item -t @var{NAME}
781 @itemx --trace=@var{NAME}
782 This enables tracing for the macro @var{NAME}, at any point where it is
783 defined.  @var{NAME} need not be defined when this option is given.
784 This option may be given more than once, and order is significant with
785 respect to file names.  @xref{Trace}, for more details.
786 @end table
788 @node Command line files
789 @section Specifying input files on the command line
791 @cindex command line, file names on the
792 @cindex file names, on the command line
793 The remaining arguments on the command line are taken to be input file
794 names.  If no names are present, standard input is read.  A file
795 name of @file{-} is taken to mean standard input.  It is
796 conventional, but not required, for input files to end in @samp{.m4}.
798 The input files are read in the sequence given.  Standard input can be
799 read more than once, so the file name @file{-} may appear multiple times
800 on the command line; this makes a difference when input is from a
801 terminal or other special file type.  It is an error if an input file
802 ends in the middle of argument collection, a comment, or a quoted
803 string.
805 The options @option{--define} (@option{-D}), @option{--undefine}
806 (@option{-U}), @option{--synclines} (@option{-s}), and @option{--trace}
807 (@option{-t}) only take effect after processing input from any file
808 names that occur earlier on the command line.
810 If none of the input files invoked @code{m4exit} (@pxref{M4exit}), the
811 exit status of @code{m4} will be 0 for success, 1 for general failure
812 (such as problems with reading an input file), and 63 for version
813 mismatch (@pxref{Using frozen files}).
815 If you need to read a file whose name starts with a @file{-}, you can
816 specify it as @samp{./-file}, or use @option{--} to mark the end of
817 options.
819 @node Syntax
820 @chapter Lexical and syntactic conventions
822 @cindex input tokens
823 @cindex tokens
824 As @code{m4} reads its input, it separates it into @dfn{tokens}.  A
825 token is either a name, a quoted string, or any single character, that
826 is not a part of either a name or a string.  Input to @code{m4} can also
827 contain comments.  @acronym{GNU} @code{m4} does not yet understand
828 locales; all operations are byte-oriented rather than
829 character-oriented (although if your locale uses a single byte
830 encoding, such as @sc{ISO-8859-1}, you will not notice a difference).
831 However, @code{m4} is eight-bit clean, so you can
832 use non-@sc{ascii} characters in quoted strings (@pxref{Changequote}),
833 comments (@pxref{Changecom}), and macro names (@pxref{Indir}), with the
834 exception of the @sc{nul} character (the zero byte @samp{'\0'}).
836 @menu
837 * Names::                       Macro names
838 * Quoted strings::              Quoting input to @code{m4}
839 * Comments::                    Comments in @code{m4} input
840 * Other tokens::                Other kinds of input tokens
841 * Input processing::            How @code{m4} copies input to output
842 @end menu
844 @node Names
845 @section Macro names
847 @cindex names
848 A name is any sequence of letters, digits, and the character @samp{_}
849 (underscore), where the first character is not a digit.  @code{m4} will
850 use the longest such sequence found in the input.  If a name has a
851 macro definition, it will be subject to macro expansion
852 (@pxref{Macros}).  Names are case-sensitive.
854 Examples of legal names are: @samp{foo}, @samp{_tmp}, and @samp{name01}.
856 @node Quoted strings
857 @section Quoting input to @code{m4}
859 @cindex quoted string
860 A quoted string is a sequence of characters surrounded by quote
861 strings, defaulting to
862 @samp{`} and @samp{'}, where the nested begin and end quotes within the
863 string are balanced.  The value of a string token is the text, with one
864 level of quotes stripped off.  Thus
866 @comment ignore
867 @example
869 @result{}
870 @end example
872 @noindent
873 is the empty string, and double-quoting turns into single-quoting.
875 @comment ignore
876 @example
877 ``quoted''
878 @result{}`quoted'
879 @end example
881 The quote characters can be changed at any time, using the builtin macro
882 @code{changequote}.  @xref{Changequote}, for more information.
884 @node Comments
885 @section Comments in @code{m4} input
887 @cindex comments
888 Comments in @code{m4} are normally delimited by the characters @samp{#}
889 and newline.  All characters between the comment delimiters are ignored,
890 but the entire comment (including the delimiters) is passed through to
891 the output---comments are @emph{not} discarded by @code{m4}.
893 Comments cannot be nested, so the first newline after a @samp{#} ends
894 the comment.  The commenting effect of the begin-comment string
895 can be inhibited by quoting it.
897 @example
898 `quoted text' # `commented text'
899 @result{}quoted text # `commented text'
900 `quoting inhibits' `#' `comments'
901 @result{}quoting inhibits # comments
902 @end example
904 The comment delimiters can be changed to any string at any time, using
905 the builtin macro @code{changecom}.  @xref{Changecom}, for more
906 information.
908 @node Other tokens
909 @section Other kinds of input tokens
911 Any character, that is neither a part of a name, nor of a quoted string,
912 nor a comment, is a token by itself.  When not in the context of macro
913 expansion, all of these tokens are just copied to output.  However,
914 during macro expansion, whitespace characters (space, tab, newline,
915 formfeed, carriage return, vertical tab), parentheses (@samp{(} and
916 @samp{)}), comma (@samp{,}), and dollar (@samp{$}) have additional
917 roles, explained later.
919 @node Input processing
920 @section How @code{m4} copies input to output
922 As @code{m4} reads the input token by token, it will copy each token
923 directly to the output immediately.
925 The exception is when it finds a word with a macro definition.  In that
926 case @code{m4} will calculate the macro's expansion, possibly reading
927 more input to get the arguments.  It then inserts the expansion in front
928 of the remaining input.  In other words, the resulting text from a macro
929 call will be read and parsed into tokens again.
931 @code{m4} expands a macro as soon as possible.  If it finds a macro call
932 when collecting the arguments to another, it will expand the second call
933 first.  This process continues until there are no more macro calls to
934 expand and all the input has been consumed.
936 For a running example, examine how @code{m4} handles this input:
938 @comment ignore
939 @example
940 format(`Result is %d', eval(`2**15'))
941 @end example
943 @noindent
944 First, @code{m4} sees that the token @samp{format} is a macro name, so
945 it collects the tokens @samp{(}, @samp{`Result is %d'}, @samp{,},
946 and @samp{@w{ }}, before encountering another potential macro.  Sure
947 enough, @samp{eval} is a macro name, so the nested argument collection
948 picks up @samp{(}, @samp{`2**15'}, and @samp{)}, invoking the eval macro
949 with the lone argument of @samp{2**15}.  The expansion of
950 @samp{eval(2**15)} is @samp{32768}, which is then rescanned as the five
951 tokens @samp{3}, @samp{2}, @samp{7}, @samp{6}, and @samp{8}; and
952 combined with the next @samp{)}, the format macro now has all its
953 arguments, as if the user had typed:
955 @comment ignore
956 @example
957 format(`Result is %d', 32768)
958 @end example
960 @noindent
961 The format macro expands to @samp{Result is 32768}, and we have another
962 round of scanning for the tokens @samp{Result}, @samp{@w{ }},
963 @samp{is}, @samp{@w{ }}, @samp{3}, @samp{2}, @samp{7}, @samp{6}, and
964 @samp{8}.  None of these are macros, so the final output is
966 @comment ignore
967 @example
968 @result{}Result is 32768
969 @end example
971 As a more complicated example, we will contrast an actual code
972 example from the Gnulib project@footnote{Derived from a patch in
973 @uref{http://lists.gnu.org/archive/html/bug-gnulib/@/2007-01/@/msg00389.html},
974 and a followup patch in
975 @uref{http://lists.gnu.org/archive/html/bug-gnulib/@/2007-02/@/msg00000.html}},
976 showing both a buggy approach and the desired results.  The user desires
977 to output a shell assignment statement that takes its argument and turns
978 it into a shell variable by converting it to uppercase and prepending a
979 prefix.  The original attempt looks like this:
981 @example
982 changequote([,])dnl
983 define([gl_STRING_MODULE_INDICATOR],
984   [
985     dnl comment
986     GNULIB_]translit([$1],[a-z],[A-Z])[=1
987   ])dnl
988   gl_STRING_MODULE_INDICATOR([strcase])
989 @result{} @w{ }
990 @result{}        GNULIB_strcase=1
991 @result{} @w{ }
992 @end example
994 Oops -- the argument did not get capitalized.  And although the manual
995 is not able to easily show it, both lines that appear empty actually
996 contain two trailing spaces.  By stepping through the parse, it is easy
997 to see what happened.  First, @code{m4} sees the token
998 @samp{changequote}, which it recognizes as a macro, followed by
999 @samp{(}, @samp{[}, @samp{,}, @samp{]}, and @samp{)} to form the
1000 argument list.  The macro expands to the empty string, but changes the
1001 quoting characters to something more useful for generating shell code
1002 (unbalanced @samp{`} and @samp{'} appear all the time in shell scripts,
1003 but unbalanced @samp{[]} tend to be rare).  Also in the first line,
1004 @code{m4} sees the token @samp{dnl}, which it recognizes as a builtin
1005 macro that consumes the rest of the line, resulting in no output for
1006 that line.
1008 The second line starts a macro definition.  @code{m4} sees the token
1009 @samp{define}, which it recognizes as a macro, followed by a @samp{(},
1010 @samp{[gl_STRING_MODULE_INDICATOR]}, and @samp{,}.  Because an unquoted
1011 comma was encountered, the first argument is known to be the expansion
1012 of the single-quoted string token, or @samp{gl_STRING_MODULE_INDICATOR}.
1013 Next, @code{m4} sees @samp{@key{NL}}, @samp{ }, and @samp{ }, but this
1014 whitespace is discarded as part of argument collection.  Then comes a
1015 rather lengthy single-quoted string token, @samp{[@key{NL}@ @ @ @ dnl
1016 comment@key{NL}@ @ @ @ GNULIB_]}.  This is followed by the token
1017 @samp{translit}, which @code{m4} recognizes as a macro name, so a nested
1018 macro expansion has started.
1020 The arguments to the @code{translit} are found by the tokens @samp{(},
1021 @samp{[$1]}, @samp{,}, @samp{[a-z]}, @samp{,}, @samp{[A-Z]}, and finally
1022 @samp{)}.  All three string arguments are expanded (or in other words,
1023 the quotes are stripped), and since neither @samp{$} nor @samp{1} need
1024 capitalization, the result of the macro is @samp{$1}.  This expansion is
1025 rescanned, resulting in the two literal characters @samp{$} and
1026 @samp{1}.
1028 Scanning of the outer macro resumes, and picks up with
1029 @samp{[=1@key{NL}@ @ ]}, and finally @samp{)}.  The collected pieces of
1030 expanded text are concatenated, with the end result that the macro
1031 @samp{gl_STRING_MODULE_INDICATOR} is now defined to be the sequence
1032 @samp{@key{NL}@ @ @ @ dnl comment@key{NL}@ @ @ @ GNULIB_$1=1@key{NL}@ @ }.
1033 Once again, @samp{dnl} is recognized and avoids a newline in the output.
1035 The final line is then parsed, beginning with @samp{ } and @samp{ }
1036 that are output literally.  Then @samp{gl_STRING_MODULE_INDICATOR} is
1037 recognized as a macro name, with an argument list of @samp{(},
1038 @samp{[strcase]}, and @samp{)}.  Since the definition of the macro
1039 contains the sequence @samp{$1}, that sequence is replaced with the
1040 argument @samp{strcase} prior to starting the rescan.  The rescan sees
1041 @samp{@key{NL}} and four spaces, which are output literally, then
1042 @samp{dnl}, which discards the text @samp{ comment@key{NL}}.  Next
1043 comes four more spaces, also output literally, and the token
1044 @samp{GNULIB_strcase}, which resulted from the earlier parameter
1045 substitution.  Since that is not a macro name, it is output literally,
1046 followed by the literal tokens @samp{=}, @samp{1}, @samp{@key{NL}}, and
1047 two more spaces.  Finally, the original @samp{@key{NL}} seen after the
1048 macro invocation is scanned and output literally.
1050 Now for a corrected approach.  This rearranges the use of newlines and
1051 whitespace so that less whitespace is output (which, although harmless
1052 to shell scripts, can be visually unappealing), and fixes the quoting
1053 issues so that the capitalization occurs when the macro
1054 @samp{gl_STRING_MODULE_INDICATOR} is invoked, rather then when it is
1055 defined.
1057 @example
1058 changequote([,])dnl
1059 define([gl_STRING_MODULE_INDICATOR],
1060   [dnl comment
1061   GNULIB_[]translit([$1], [a-z], [A-Z])=1dnl
1062 ])dnl
1063   gl_STRING_MODULE_INDICATOR([strcase])
1064 @result{}    GNULIB_STRCASE=1
1065 @end example
1067 The parsing of the first line is unchanged.  The second line sees the
1068 name of the macro to define, then sees the discarded @samp{@key{NL}}
1069 and two spaces, as before.  But this time, the next token is
1070 @samp{[dnl comment@key{NL}@ @ GNULIB_[]translit([$1], [a-z],
1071 [A-Z])=1dnl@key{NL}]}, which includes nested quotes, followed by
1072 @samp{)} to end the macro definition and @samp{dnl} to skip the
1073 newline.  No early expansion of @code{translit} occurs, so the entire
1074 string becomes the definition of the macro.
1076 The final line is then parsed, beginning with two spaces that are
1077 output literally, and an invocation of
1078 @code{gl_STRING_MODULE_INDICATOR} with the argument @samp{strcase}.
1079 Again, the @samp{$1} in the macro definition is substituted prior to
1080 rescanning.  Rescanning first encounters @samp{dnl}, and discards
1081 @samp{ comment@key{NL}}.  Then two spaces are output literally.  Next
1082 comes the token @samp{GNULIB_}, but that is not a macro, so it is
1083 output literally.  The token @samp{[]} is an empty string, so it does
1084 not affect output.  Then the token @samp{translit} is encountered.
1086 This time, the arguments to @code{translit} are parsed as @samp{(},
1087 @samp{[strcase]}, @samp{,}, @samp{ }, @samp{[a-z]}, @samp{,}, @samp{ },
1088 @samp{[A-Z]}, and @samp{)}.  The two spaces are discarded, and the
1089 translit results in the desired result @samp{STRCASE}.  This is
1090 rescanned, but since it is not a macro name, it is output literally.
1091 Then the scanner sees @samp{=} and @samp{1}, which are output
1092 literally, followed by @samp{dnl} which discards the rest of the
1093 definition of @code{gl_STRING_MODULE_INDICATOR}.  The newline at the
1094 end of output is the literal @samp{@key{NL}} that appeared after the
1095 invocation of the macro.
1097 The order in which @code{m4} expands the macros can be further explored
1098 using the trace facilities of @acronym{GNU} @code{m4} (@pxref{Trace}).
1100 @node Macros
1101 @chapter How to invoke macros
1103 This chapter covers macro invocation, macro arguments and how macro
1104 expansion is treated.
1106 @menu
1107 * Invocation::                  Macro invocation
1108 * Inhibiting Invocation::       Preventing macro invocation
1109 * Macro Arguments::             Macro arguments
1110 * Quoting Arguments::           On Quoting Arguments to macros
1111 * Macro expansion::             Expanding macros
1112 @end menu
1114 @node Invocation
1115 @section Macro invocation
1117 @cindex macro invocation
1118 Macro invocations has one of the forms
1120 @comment ignore
1121 @example
1122 name
1123 @end example
1125 @noindent
1126 which is a macro invocation without any arguments, or
1128 @comment ignore
1129 @example
1130 name(arg1, arg2, @dots{}, arg@var{n})
1131 @end example
1133 @noindent
1134 which is a macro invocation with @var{n} arguments.  Macros can have any
1135 number of arguments.  All arguments are strings, but different macros
1136 might interpret the arguments in different ways.
1138 The opening parenthesis @emph{must} follow the @var{name} directly, with
1139 no spaces in between.  If it does not, the macro is called with no
1140 arguments at all.
1142 For a macro call to have no arguments, the parentheses @emph{must} be
1143 left out.  The macro call
1145 @comment ignore
1146 @example
1147 name()
1148 @end example
1150 @noindent
1151 is a macro call with one argument, which is the empty string, not a call
1152 with no arguments.
1154 @node Inhibiting Invocation
1155 @section Preventing macro invocation
1157 An innovation of the @code{m4} language, compared to some of its
1158 predecessors (like Stratchey's @code{GPM}, for example), is the ability
1159 to recognize macro calls without resorting to any special, prefixed
1160 invocation character.  While generally useful, this feature might
1161 sometimes be the source of spurious, unwanted macro calls.  So, @acronym{GNU}
1162 @code{m4} offers several mechanisms or techniques for inhibiting the
1163 recognition of names as macro calls.
1165 @cindex @acronym{GNU} extensions
1166 @cindex blind macro
1167 @cindex macro, blind
1168 First of all, many builtin macros cannot meaningfully be called without
1169 arguments.  As a @acronym{GNU} extension, for any of these macros,
1170 whenever an opening parenthesis does not immediately follow their name,
1171 the builtin macro call is not triggered.  This solves the most usual
1172 cases, like for @samp{include} or @samp{eval}.  Later in this document,
1173 the sentence ``This macro is recognized only with parameters'' refers to
1174 this specific provision of @acronym{GNU} M4, also known as a blind
1175 builtin macro.  For the builtins defined by @acronym{POSIX} that bear
1176 this disclaimer, @acronym{POSIX} specifically states that invoking those
1177 builtins without arguments is unspecified, because many other
1178 implementations simply invoke the builtin as though it were given one
1179 empty argument instead.
1181 @example
1182 eval
1183 @result{}eval
1184 eval(`1')
1185 @result{}1
1186 @end example
1188 There is also a command line option (@option{--prefix-builtins}, or
1189 @option{-P}, @pxref{Operation modes, , Invoking m4}) that renames all
1190 builtin macros with a prefix of @samp{m4_} at startup.  The option has
1191 no effect whatsoever on user defined macros.  For example, with this option,
1192 one has to write @code{m4_dnl} and even @code{m4_m4exit}.  It also has
1193 no effect on whether a macro requires parameters.
1195 Another alternative is to redefine problematic macros to a name less
1196 likely to cause conflicts, @xref{Definitions}.
1198 If your version of @acronym{GNU} @code{m4} has the @code{changeword} feature
1199 compiled in, it offers far more flexibility in specifying the
1200 syntax of macro names, both builtin or user-defined.  @xref{Changeword},
1201 for more information on this experimental feature.
1203 Of course, the simplest way to prevent a name from being interpreted
1204 as a call to an existing macro is to quote it.  The remainder of
1205 this section studies a little more deeply how quoting affects macro
1206 invocation, and how quoting can be used to inhibit macro invocation.
1208 Even if quoting is usually done over the whole macro name, it can also
1209 be done over only a few characters of this name (provided, of course,
1210 that the unquoted portions are not also a macro).  It is also possible
1211 to quote the empty string, but this works only @emph{inside} the name.
1212 For example:
1214 @example
1215 `divert'
1216 @result{}divert
1217 `d'ivert
1218 @result{}divert
1219 di`ver't
1220 @result{}divert
1221 div`'ert
1222 @result{}divert
1223 @end example
1225 @noindent
1226 all yield the string @samp{divert}.  While in both:
1228 @example
1229 `'divert
1230 @result{}
1231 divert`'
1232 @result{}
1233 @end example
1235 @noindent
1236 the @code{divert} builtin macro will be called, which expands to the
1237 empty string.
1239 The output of macro evaluations is always rescanned.  The following
1240 example would yield the string @samp{de}, exactly as if @code{m4}
1241 has been given @w{@samp{substr(`abcde', `3', `2')}} as input:
1243 @example
1244 define(`x', `substr(ab')
1245 @result{}
1246 define(`y', `cde, `3', `2')')
1247 @result{}
1248 x`'y
1249 @result{}de
1250 @end example
1252 Unquoted strings on either side of a quoted string are subject to
1253 being recognized as macro names.  In the following example, quoting the
1254 empty string allows for the second @code{macro} to be recognized as such:
1256 @example
1257 define(`macro', `m')
1258 @result{}
1259 macro(`m')macro
1260 @result{}mmacro
1261 macro(`m')`'macro
1262 @result{}mm
1263 @end example
1265 Quoting may prevent recognizing as a macro name the concatenation of a
1266 macro expansion with the surrounding characters.  In this example:
1268 @example
1269 define(`macro', `di$1')
1270 @result{}
1271 macro(`v')`ert'
1272 @result{}divert
1273 macro(`v')ert
1274 @result{}
1275 @end example
1277 @noindent
1278 the input will produce the string @samp{divert}.  When the quotes were
1279 removed, the @code{divert} builtin was called instead.
1281 @node Macro Arguments
1282 @section Macro arguments
1284 @cindex macros, arguments to
1285 @cindex arguments to macros
1286 When a name is seen, and it has a macro definition, it will be expanded
1287 as a macro.
1289 If the name is followed by an opening parenthesis, the arguments will be
1290 collected before the macro is called.  If too few arguments are
1291 supplied, the missing arguments are taken to be the empty string.
1292 However, some builtins are documented to behave differently for a
1293 missing optional argument than for an explicit empty string.  If there
1294 are too many arguments, the excess arguments are ignored.  Unquoted
1295 leading whitespace is stripped off all arguments, but whitespace
1296 generated by a macro expansion or occurring after a macro that expanded
1297 to an empty string remains intact.  Whitespace includes space, tab,
1298 newline, carriage return, vertical tab, and formfeed.
1300 @example
1301 define(`macro', `$1')
1302 @result{}
1303 macro( unquoted leading space lost)
1304 @result{}unquoted leading space lost
1305 macro(` quoted leading space kept')
1306 @result{} quoted leading space kept
1307 macro(
1308  divert `unquoted space kept after expansion')
1309 @result{} unquoted space kept after expansion
1310 macro(macro(`
1311 ')`whitespace from expansion kept')
1312 @result{}
1313 @result{}whitespace from expansion kept
1314 macro(`unquoted trailing whitespace kept'
1316 @result{}unquoted trailing whitespace kept
1317 @result{}
1318 @end example
1320 Normally @code{m4} will issue warnings if a builtin macro is called
1321 with an inappropriate number of arguments, but it can be suppressed with
1322 the @option{--quiet} command line option (or @option{--silent}, or
1323 @option{-Q}, @pxref{Operation modes, , Invoking m4}).  For user
1324 defined macros, there is no check of the number of arguments given.
1326 Macros are expanded normally during argument collection, and whatever
1327 commas, quotes and parentheses that might show up in the resulting
1328 expanded text will serve to define the arguments as well.  Thus, if
1329 @var{foo} expands to @samp{, b, c}, the macro call
1331 @comment ignore
1332 @example
1333 bar(a foo, d)
1334 @end example
1336 @noindent
1337 is a macro call with four arguments, which are @samp{a }, @samp{b},
1338 @samp{c} and @samp{d}.  To understand why the first argument contains
1339 whitespace, remember that unquoted leading whitespace is never part
1340 of an argument, but trailing whitespace always is.
1342 It is possible for a macro's definition to change during argument
1343 collection, in which case the expansion uses the definition that was in
1344 effect at the time the opening @samp{(} was seen.
1346 @example
1347 define(`f', `1')
1348 @result{}
1349 f(define(`f', `2'))
1350 @result{}1
1352 @result{}2
1353 @end example
1355 It is an error if the end of file occurs while collecting arguments.
1357 @comment status: 1
1358 @example
1359 hello world
1360 @result{}hello world
1361 define(
1363 @error{}m4:stdin:2: ERROR: end of file in argument list
1364 @end example
1366 @node Quoting Arguments
1367 @section On Quoting Arguments to macros
1369 @cindex quoted macro arguments
1370 @cindex macros, quoted arguments to
1371 @cindex arguments, quoted macro
1372 Each argument has unquoted leading whitespace removed.  Within each
1373 argument, all unquoted parentheses must match.  For example, if
1374 @var{foo} is a macro,
1376 @comment ignore
1377 @example
1378 foo(() (`(') `(')
1379 @end example
1381 @noindent
1382 is a macro call, with one argument, whose value is @samp{() (() (}.
1383 Commas separate arguments, except when they occur inside quotes,
1384 comments, or unquoted parentheses.  @xref{Pseudo Arguments}, for
1385 examples.
1387 It is common practice to quote all arguments to macros, unless you are
1388 sure you want the arguments expanded.  Thus, in the above
1389 example with the parentheses, the `right' way to do it is like this:
1391 @comment ignore
1392 @example
1393 foo(`() (() (')
1394 @end example
1396 It is, however, in certain cases necessary (because nested expansion
1397 must occur to create the arguments for the outer macro) or convenient
1398 (because it uses fewer characters) to leave out quotes for some
1399 arguments, and there is nothing wrong in doing it.  It just makes life a
1400 bit harder, if you are not careful to follow a consistent quoting style.
1401 For consistency, this manual follows the rule of thumb that each layer
1402 of parentheses introduces another layer of single quoting, except when
1403 showing the consequences of quoting rules.  This is done even when the
1404 quoted string cannot be a macro, such as with integers when you have not
1405 changed the syntax via @code{changeword} (@pxref{Changeword}).
1407 The quoting rule of thumb of one level of quoting per parentheses has a
1408 nice property: when a macro name appears inside parentheses, you can
1409 determine when it will be expanded.  If it is not quoted, it will be
1410 expanded prior to the outer macro, so that its expansion becomes the
1411 argument.  If it is single-quoted, it will be expanded after the outer
1412 macro.  And if it is double-quoted, it will be used as literal text
1413 instead of a macro name.
1415 @example
1416 define(`active', `ACT, IVE')
1417 @result{}
1418 define(`show', `$1 $1')
1419 @result{}
1420 show(active)
1421 @result{}ACT ACT
1422 show(`active')
1423 @result{}ACT, IVE ACT, IVE
1424 show(``active'')
1425 @result{}active active
1426 @end example
1428 @node Macro expansion
1429 @section Macro expansion
1431 @cindex macros, expansion of
1432 @cindex expansion of macros
1433 When the arguments, if any, to a macro call have been collected, the
1434 macro is expanded, and the expansion text is pushed back onto the input
1435 (unquoted), and reread.  The expansion text from one macro call might
1436 therefore result in more macros being called, if the calls are included,
1437 completely or partially, in the first macro calls' expansion.
1439 Taking a very simple example, if @var{foo} expands to @samp{bar}, and
1440 @var{bar} expands to @samp{Hello world}, the input
1442 @comment ignore
1443 @example
1445 @end example
1447 @noindent
1448 will expand first to @samp{bar}, and when this is reread and
1449 expanded, into @samp{Hello world}.
1451 @node Definitions
1452 @chapter How to define new macros
1454 @cindex macros, how to define new
1455 @cindex defining new macros
1456 Macros can be defined, redefined and deleted in several different ways.
1457 Also, it is possible to redefine a macro without losing a previous
1458 value, and bring back the original value at a later time.
1460 @menu
1461 * Define::                      Defining a new macro
1462 * Arguments::                   Arguments to macros
1463 * Pseudo Arguments::            Special arguments to macros
1464 * Undefine::                    Deleting a macro
1465 * Defn::                        Renaming macros
1466 * Pushdef::                     Temporarily redefining macros
1468 * Indir::                       Indirect call of macros
1469 * Builtin::                     Indirect call of builtins
1470 @end menu
1472 @node Define
1473 @section Defining a macro
1475 The normal way to define or redefine macros is to use the builtin
1476 @code{define}:
1478 @deffn Builtin define (@var{name}, @ovar{expansion})
1479 Defines @var{name} to expand to @var{expansion}.  If
1480 @var{expansion} is not given, it is taken to be empty.
1482 The expansion of @code{define} is void.
1483 The macro @code{define} is recognized only with parameters.
1484 @end deffn
1486 The following example defines the macro @var{foo} to expand to the text
1487 @samp{Hello World.}.
1489 @example
1490 define(`foo', `Hello world.')
1491 @result{}
1493 @result{}Hello world.
1494 @end example
1496 The empty line in the output is there because the newline is not
1497 a part of the macro definition, and it is consequently copied to
1498 the output.  This can be avoided by use of the macro @code{dnl}.
1499 @xref{Dnl}, for details.
1501 The first argument to @code{define} should be quoted; otherwise, if the
1502 macro is already defined, you will be defining a different macro.  This
1503 example shows the problems with underquoting, since we did not want to
1504 redefine @code{one}:
1506 @example
1507 define(foo, one)
1508 @result{}
1509 define(foo, two)
1510 @result{}
1512 @result{}two
1513 @end example
1515 @cindex @acronym{GNU} extensions
1516 @acronym{GNU} @code{m4} normally replaces only the @emph{topmost}
1517 definition of a macro if it has several definitions from @code{pushdef}
1518 (@pxref{Pushdef}).  Some other implementations of @code{m4} replace all
1519 definitions of a macro with @code{define}.  @xref{Incompatibilities},
1520 for more details.
1522 As a @acronym{GNU} extension, the first argument to @code{define} does
1523 not have to be a simple word.
1524 It can be any text string, even the empty string.  A macro with a
1525 non-standard name cannot be invoked in the normal way, as the name is
1526 not recognized.  It can only be referenced by the builtins @code{indir}
1527 (@pxref{Indir}) and @code{defn} (@pxref{Defn}).
1529 @cindex arrays
1530 Arrays and associative arrays can be simulated by using this trick.
1532 @example
1533 define(`array', `defn(format(``array[%d]'', `$1'))')
1534 @result{}
1535 define(`array_set', `define(format(``array[%d]'', `$1'), `$2')')
1536 @result{}
1537 array_set(`4', `array element no. 4')
1538 @result{}
1539 array_set(`17', `array element no. 17')
1540 @result{}
1541 array(`4')
1542 @result{}array element no. 4
1543 array(eval(`10 + 7'))
1544 @result{}array element no. 17
1545 @end example
1547 Change the @samp{%d} to @samp{%s} and it is an associative array.
1549 @node Arguments
1550 @section Arguments to macros
1552 @cindex macros, arguments to
1553 @cindex Arguments to macros
1554 Macros can have arguments.  The @var{n}th argument is denoted by
1555 @code{$n} in the expansion text, and is replaced by the @var{n}th actual
1556 argument, when the macro is expanded.  Replacement of arguments happens
1557 before rescanning, regardless of how many nesting levels of quoting
1558 appear in the expansion.  Here is an example of a macro with
1559 two arguments.  It simply exchanges the order of the two arguments.
1561 @example
1562 define(`exch', `$2, $1')
1563 @result{}
1564 exch(`arg1', `arg2')
1565 @result{}arg2, arg1
1566 @end example
1568 This can be used, for example, if you like the arguments to
1569 @code{define} to be reversed.
1571 @example
1572 define(`exch', `$2, $1')
1573 @result{}
1574 define(exch(``expansion text'', ``macro''))
1575 @result{}
1576 macro
1577 @result{}expansion text
1578 @end example
1580 @xref{Quoting Arguments}, for an explanation of the double quotes.
1581 (You should try and improve this example so that clients of @code{exch}
1582 do not have to double quote; or @pxref{Improved exch, , Answers}).
1584 As a special case, the zeroth argument, @code{$0}, is always the name
1585 of the macro being expanded.
1587 @example
1588 define(`test', ``Macro name: $0'')
1589 @result{}
1590 test
1591 @result{}Macro name: test
1592 @end example
1594 If you want quoted text to appear as part of the expansion text,
1595 remember that quotes can be nested in quoted strings.  Thus, in
1597 @example
1598 define(`foo', `This is macro `foo'.')
1599 @result{}
1601 @result{}This is macro foo.
1602 @end example
1604 @noindent
1605 The @samp{foo} in the expansion text is @emph{not} expanded, since it is
1606 a quoted string, and not a name.
1608 @cindex @acronym{GNU} extensions
1609 @cindex nine arguments, more than
1610 @cindex more than nine arguments
1611 @cindex arguments, more than nine
1612 @cindex positional parameters, more than nine
1613 @acronym{GNU} @code{m4} allows the number following the @samp{$} to
1614 consist of one or more digits, allowing macros to have any number of
1615 arguments.  The extension of accepting multiple digits is incompatible
1616 with @acronym{POSIX}, and is different than traditional implementations
1617 of @code{m4}, which only recognize one digit.  Therefore, future
1618 versions of @acronym{GNU} M4 will phase out this feature.
1619 @xref{Extensions}, for an example of how to portably access the eleventh
1620 argument.
1622 @acronym{POSIX} also states that @samp{$} followed immediately by
1623 @samp{@{} in a macro definition is implementation-defined.  This version
1624 of M4 passes the literal characters @samp{$@{} through unchanged, but M4
1625 2.0 will implement an optional feature similar to @command{sh}, where
1626 @samp{$@{11@}} expands to the eleventh argument, to replace the current
1627 recognition of @samp{$11}.  Meanwhile, if you want to guarantee that you
1628 will get a literal @samp{$@{} in output when expanding a macro, even
1629 when you upgrade to M4 2.0, you can use nested quoting to your
1630 advantage:
1632 @example
1633 define(`foo', `single quoted $`'@{1@} output')
1634 @result{}
1635 define(`bar', ``double quoted $'`@{2@} output'')
1636 @result{}
1637 foo(`a', `b')
1638 @result{}single quoted $@{1@} output
1639 bar(`a', `b')
1640 @result{}double quoted $@{2@} output
1641 @end example
1643 To help you detect places in your M4 input files that might change in
1644 behavior due to the changed behavior of M4 2.0, you can use the
1645 @option{--warn-macro-sequence} command-line option (@pxref{Operation
1646 modes, , Invoking m4}) with the default regular expression.  This will
1647 add a warning any time a macro definition includes @samp{$} followed by
1648 multiple digits, or by @samp{@{} and a digit.  The warning is not
1649 enabled by default, because it triggers a number of warnings in Autoconf
1650 2.61 (and Autoconf uses @option{-E} to treat warnings as errors), and
1651 because it will still be possible to restore older behavior in M4 2.0.
1653 @comment ignore
1654 @example
1655 $ @kbd{m4 --warn-macro-sequence}
1656 define(`foo', `$001 $@{1@} $1')
1657 @error{}m4:stdin:1: Warning: definition of `foo' contains sequence `$001'
1658 @error{}m4:stdin:1: Warning: definition of `foo' contains sequence `$@{1@}'
1659 @result{}
1660 foo(`bar')
1661 @result{}bar $@{1@} bar
1662 @end example
1664 @node Pseudo Arguments
1665 @section Special arguments to macros
1667 @cindex special arguments to macros
1668 @cindex macros, special arguments to
1669 @cindex arguments to macros, special
1670 There is a special notation for the number of actual arguments supplied,
1671 and for all the actual arguments.
1673 The number of actual arguments in a macro call is denoted by @code{$#}
1674 in the expansion text.  Thus, a macro to display the number of arguments
1675 given can be
1677 @example
1678 define(`nargs', `$#')
1679 @result{}
1680 nargs
1681 @result{}0
1682 nargs()
1683 @result{}1
1684 nargs(`arg1', `arg2', `arg3')
1685 @result{}3
1686 nargs(`commas can be quoted, like this')
1687 @result{}1
1688 nargs(arg1#inside comments, commas do not separate arguments
1689 still arg1)
1690 @result{}1
1691 nargs((unquoted parentheses, like this, group arguments))
1692 @result{}1
1693 @end example
1695 The notation @code{$*} can be used in the expansion text to denote all
1696 the actual arguments, unquoted, with commas in between.  For example
1698 @example
1699 define(`echo', `$*')
1700 @result{}
1701 echo(arg1,    arg2, arg3 , arg4)
1702 @result{}arg1,arg2,arg3 ,arg4
1703 @end example
1705 Often each argument should be quoted, and the notation @code{$@@} handles
1706 that.  It is just like @code{$*}, except that it quotes each argument.
1707 A simple example of that is:
1709 @example
1710 define(`echo', `$@@')
1711 @result{}
1712 echo(arg1,    arg2, arg3 , arg4)
1713 @result{}arg1,arg2,arg3 ,arg4
1714 @end example
1716 Where did the quotes go?  Of course, they were eaten, when the expanded
1717 text were reread by @code{m4}.  To show the difference, try
1719 @example
1720 define(`echo1', `$*')
1721 @result{}
1722 define(`echo2', `$@@')
1723 @result{}
1724 define(`foo', `This is macro `foo'.')
1725 @result{}
1726 echo1(foo)
1727 @result{}This is macro This is macro foo..
1728 echo1(`foo')
1729 @result{}This is macro foo.
1730 echo2(foo)
1731 @result{}This is macro foo.
1732 echo2(`foo')
1733 @result{}foo
1734 @end example
1736 @noindent
1737 @xref{Trace}, if you do not understand this.  As another example of the
1738 difference, remember that comments encountered in arguments are passed
1739 untouched to the macro, and that quoting disables comments.
1741 @example
1742 define(`echo1', `$*')
1743 @result{}
1744 define(`echo2', `$@@')
1745 @result{}
1746 define(`foo', `bar')
1747 @result{}
1748 echo1(#foo'foo
1749 foo)
1750 @result{}#foo'foo
1751 @result{}bar
1752 echo2(#foo'foo
1753 foo)
1754 @result{}#foobar
1755 @result{}bar'
1756 @end example
1758 A @samp{$} sign in the expansion text, that is not followed by anything
1759 @code{m4} understands, is simply copied to the macro expansion, as any
1760 other text is.
1762 @example
1763 define(`foo', `$$$ hello $$$')
1764 @result{}
1766 @result{}$$$ hello $$$
1767 @end example
1769 If you want a macro to expand to something like @samp{$12}, the
1770 judicious use of nested quoting can put a safe character between the
1771 @code{$} and the next character, relying on the rescanning to remove the
1772 nested quote.  This will prevent @code{m4} from interpreting the
1773 @code{$} sign as a reference to an argument.
1775 @example
1776 define(`foo', `no nested quote: $1')
1777 @result{}
1778 foo(`arg')
1779 @result{}no nested quote: arg
1780 define(`foo', `nested quote around $: `$'1')
1781 @result{}
1782 foo(`arg')
1783 @result{}nested quote around $: $1
1784 define(`foo', `nested empty quote after $: $`'1')
1785 @result{}
1786 foo(`arg')
1787 @result{}nested empty quote after $: $1
1788 define(`foo', `nested quote around next character: $`1'')
1789 @result{}
1790 foo(`arg')
1791 @result{}nested quote around next character: $1
1792 define(`foo', `nested quote around both: `$1'')
1793 @result{}
1794 foo(`arg')
1795 @result{}nested quote around both: arg
1796 @end example
1798 @node Undefine
1799 @section Deleting a macro
1801 @cindex macros, how to delete
1802 @cindex deleting macros
1803 @cindex undefining macros
1804 A macro definition can be removed with @code{undefine}:
1806 @deffn Builtin undefine (@var{name}@dots{})
1807 For each argument, remove the macro @var{name}.  The macro names must
1808 necessarily be quoted, since they will be expanded otherwise.
1810 The expansion of @code{undefine} is void.
1811 The macro @code{undefine} is recognized only with parameters.
1812 @end deffn
1814 @example
1815 foo bar blah
1816 @result{}foo bar blah
1817 define(`foo', `some')define(`bar', `other')define(`blah', `text')
1818 @result{}
1819 foo bar blah
1820 @result{}some other text
1821 undefine(`foo')
1822 @result{}
1823 foo bar blah
1824 @result{}foo other text
1825 undefine(`bar', `blah')
1826 @result{}
1827 foo bar blah
1828 @result{}foo bar blah
1829 @end example
1831 Undefining a macro inside that macro's expansion is safe; the macro
1832 still expands to the definition that was in effect at the @samp{(}.
1834 @example
1835 define(`f', ``$0':$1')
1836 @result{}
1837 f(f(f(undefine(`f')`hello world')))
1838 @result{}f:f:f:hello world
1839 f(`bye')
1840 @result{}f(bye)
1841 @end example
1843 It is not an error for @var{name} to have no macro definition.  In that
1844 case, @code{undefine} does nothing.
1846 @node Defn
1847 @section Renaming macros
1849 @cindex macros, how to rename
1850 @cindex renaming macros
1851 It is possible to rename an already defined macro.  To do this, you need
1852 the builtin @code{defn}:
1854 @deffn Builtin defn (@var{name})
1855 Expands to the @emph{quoted definition} of @var{name}.  If the
1856 argument is not a defined macro, the expansion is void.
1858 If @var{name} is a user-defined macro, the quoted definition is simply
1859 the quoted expansion text.  If, instead, @var{name} is a builtin, the
1860 expansion is a special token, which points to the builtin's internal
1861 definition.  This token is only meaningful as the second argument to
1862 @code{define} (and @code{pushdef}), and is silently converted to an
1863 empty string in most other contexts.
1865 The macro @code{defn} is recognized only with parameters.
1866 @end deffn
1868 Its normal use is best understood through an example, which shows how to
1869 rename @code{undefine} to @code{zap}:
1871 @example
1872 define(`zap', defn(`undefine'))
1873 @result{}
1874 zap(`undefine')
1875 @result{}
1876 undefine(`zap')
1877 @result{}undefine(zap)
1878 @end example
1880 In this way, @code{defn} can be used to copy macro definitions, and also
1881 definitions of builtin macros.  Even if the original macro is removed,
1882 the other name can still be used to access the definition.
1884 The fact that macro definitions can be transferred also explains why you
1885 should use @code{$0}, rather than retyping a macro's name in its
1886 definition:
1888 @example
1889 define(`foo', `This is `$0'')
1890 @result{}
1891 define(`bar', defn(`foo'))
1892 @result{}
1894 @result{}This is bar
1895 @end example
1897 Macros used as string variables should be referred through @code{defn},
1898 to avoid unwanted expansion of the text:
1900 @example
1901 define(`string', `The macro dnl is very useful
1903 @result{}
1904 string
1905 @result{}The macro@w{ }
1906 defn(`string')
1907 @result{}The macro dnl is very useful
1908 @result{}
1909 @end example
1911 However, it is important to remember that @code{m4} rescanning is purely
1912 textual.  If an unbalanced end-quote string occurs in a macro
1913 definition, the rescan will see that embedded quote as the termination
1914 of the quoted string, and the remainder of the macro's definition will
1915 be rescanned unquoted.  Thus it is a good idea to avoid unbalanced
1916 end-quotes in macro definitions or arguments to macros.
1918 @example
1919 define(`foo', a'a)
1920 @result{}
1921 define(`a', `A')
1922 @result{}
1923 define(`echo', `$@@')
1924 @result{}
1926 @result{}A'A
1927 defn(`foo')
1928 @result{}aA'
1929 echo(foo)
1930 @result{}AA'
1931 @end example
1933 Using @code{defn} to generate special tokens for builtin macros outside
1934 of expected contexts can sometimes trigger warnings.  But most of the
1935 time, such tokens are silently converted to the empty string.
1937 @example
1938 defn(`defn')
1939 @result{}
1940 define(defn(`divnum'), `cannot redefine a builtin token')
1941 @error{}m4:stdin:2: Warning: define: invalid macro name ignored
1942 @result{}
1943 divnum
1944 @result{}0
1945 @end example
1947 @node Pushdef
1948 @section Temporarily redefining macros
1950 @cindex macros, temporary redefinition of
1951 @cindex temporary redefinition of macros
1952 @cindex redefinition of macros, temporary
1953 It is possible to redefine a macro temporarily, reverting to the
1954 previous definition at a later time.  This is done with the builtins
1955 @code{pushdef} and @code{popdef}:
1957 @deffn Builtin pushdef (@var{name}, @ovar{expansion})
1958 @deffnx Builtin popdef (@var{name}@dots{})
1959 Analogous to @code{define} and @code{undefine}.
1961 These macros work in a stack-like fashion.  A macro is temporarily
1962 redefined with @code{pushdef}, which replaces an existing definition of
1963 @var{name}, while saving the previous definition, before the new one is
1964 installed.  If there is no previous definition, @code{pushdef} behaves
1965 exactly like @code{define}.
1967 If a macro has several definitions (of which only one is accessible),
1968 the topmost definition can be removed with @code{popdef}.  If there is
1969 no previous definition, @code{popdef} behaves like @code{undefine}.
1971 The expansion of both @code{pushdef} and @code{popdef} is void.
1972 The macros @code{pushdef} and @code{popdef} are recognized only with
1973 parameters.
1974 @end deffn
1976 @example
1977 define(`foo', `Expansion one.')
1978 @result{}
1980 @result{}Expansion one.
1981 pushdef(`foo', `Expansion two.')
1982 @result{}
1984 @result{}Expansion two.
1985 pushdef(`foo', `Expansion three.')
1986 @result{}
1987 pushdef(`foo', `Expansion four.')
1988 @result{}
1989 popdef(`foo')
1990 @result{}
1992 @result{}Expansion three.
1993 popdef(`foo', `foo')
1994 @result{}
1996 @result{}Expansion one.
1997 popdef(`foo')
1998 @result{}
2000 @result{}foo
2001 @end example
2003 If a macro with several definitions is redefined with @code{define}, the
2004 topmost definition is @emph{replaced} with the new definition.  If it is
2005 removed with @code{undefine}, @emph{all} the definitions are removed,
2006 and not only the topmost one.
2008 @example
2009 define(`foo', `Expansion one.')
2010 @result{}
2012 @result{}Expansion one.
2013 pushdef(`foo', `Expansion two.')
2014 @result{}
2016 @result{}Expansion two.
2017 define(`foo', `Second expansion two.')
2018 @result{}
2020 @result{}Second expansion two.
2021 undefine(`foo')
2022 @result{}
2024 @result{}foo
2025 @end example
2027 @cindex local variables
2028 @cindex variables, local
2029 Local variables within macros are made with @code{pushdef} and
2030 @code{popdef}.  At the start of the macro a new definition is pushed,
2031 within the macro it is manipulated and at the end it is popped,
2032 revealing the former definition.
2034 It is possible to temporarily redefine a builtin with @code{pushdef}
2035 and @code{defn}.
2037 @node Indir
2038 @section Indirect call of macros
2040 @cindex indirect call of macros
2041 @cindex call of macros, indirect
2042 @cindex macros, indirect call of
2043 @cindex @acronym{GNU} extensions
2044 Any macro can be called indirectly with @code{indir}:
2046 @deffn Builtin indir (@var{name}, @ovar{args@dots{}})
2047 Results in a call to the macro @var{name}, which is passed the
2048 rest of the arguments @var{args}.  If @var{name} is not defined, an
2049 error message is printed, and the expansion is void.
2051 The macro @code{indir} is recognized only with parameters.
2052 @end deffn
2054 This can be used to call macros with computed or ``invalid''
2055 names (@code{define} allows such names to be defined):
2057 @example
2058 define(`$$internal$macro', `Internal macro (name `$0')')
2059 @result{}
2060 $$internal$macro
2061 @result{}$$internal$macro
2062 indir(`$$internal$macro')
2063 @result{}Internal macro (name $$internal$macro)
2064 @end example
2066 The point is, here, that larger macro packages can have private macros
2067 defined, that will not be called by accident.  They can @emph{only} be
2068 called through the builtin @code{indir}.
2070 One other point to observe is that argument collection occurs before
2071 @code{indir} invokes @var{name}, so if argument collection changes the
2072 value of @var{name}, that will be reflected in the final expansion.
2073 This is different than the behavior when invoking macros directly,
2074 where the definition that was in effect before argument collection is
2075 used.
2077 @example
2078 define(`f', `1')
2079 @result{}
2080 f(define(`f', `2'))
2081 @result{}1
2082 indir(`f', define(`f', `3'))
2083 @result{}3
2084 indir(`f', undefine(`f'))
2085 @error{}m4:stdin:4: undefined macro `f'
2086 @result{}
2087 @end example
2089 When handed the result of @code{defn} (@pxref{Defn}) as one of its
2090 arguments, @code{indir} defers to the invoked @var{name} for whether a
2091 token representing a builtin is recognized or flattened to the empty
2092 string.
2094 @example
2095 indir(defn(`defn'), `divnum')
2096 @error{}m4:stdin:1: Warning: indir: invalid macro name ignored
2097 @result{}
2098 indir(`define', defn(`defn'), `divnum')
2099 @error{}m4:stdin:2: Warning: define: invalid macro name ignored
2100 @result{}
2101 indir(`define', `foo', defn(`divnum'))
2102 @result{}
2104 @result{}0
2105 indir(`divert', defn(`foo'))
2106 @error{}m4:stdin:5: empty string treated as 0 in builtin `divert'
2107 @result{}
2108 @end example
2110 @node Builtin
2111 @section Indirect call of builtins
2113 @cindex indirect call of builtins
2114 @cindex call of builtins, indirect
2115 @cindex builtins, indirect call of
2116 @cindex @acronym{GNU} extensions
2117 Builtin macros can be called indirectly with @code{builtin}:
2119 @deffn Builtin builtin (@var{name}, @ovar{args@dots{}})
2120 Results in a call to the builtin @var{name}, which is passed the
2121 rest of the arguments @var{args}.  If @var{name} does not name a
2122 builtin, an error message is printed, and the expansion is void.
2124 The macro @code{builtin} is recognized only with parameters.
2125 @end deffn
2127 This can be used even if @var{name} has been given another definition
2128 that has covered the original, or been undefined so that no macro
2129 maps to the builtin.
2131 @example
2132 pushdef(`define', `hidden')
2133 @result{}
2134 undefine(`undefine')
2135 @result{}
2136 define(`foo', `bar')
2137 @result{}hidden
2139 @result{}foo
2140 builtin(`define', `foo', defn(`divnum'))
2141 @result{}
2143 @result{}0
2144 builtin(`define', `foo', `BAR')
2145 @result{}
2147 @result{}BAR
2148 undefine(`foo')
2149 @result{}undefine(foo)
2151 @result{}BAR
2152 builtin(`undefine', `foo')
2153 @result{}
2155 @result{}foo
2156 @end example
2158 The @var{name} argument only matches the original name of the builtin,
2159 even when the @option{--prefix-builtins} option (or @option{-P},
2160 @pxref{Operation modes, , Invoking m4}) is in effect.  This is different
2161 from @code{indir}, which only tracks current macro names.
2163 Note that @code{indir} and @code{builtin} can be used to invoke builtins
2164 without arguments, even when they normally require parameters to be
2165 recognized; but it will provoke a warning, and result in a void expansion.
2167 @example
2168 builtin
2169 @result{}builtin
2170 builtin()
2171 @error{}m4:stdin:2: undefined builtin `'
2172 @result{}
2173 builtin(`builtin')
2174 @error{}m4:stdin:3: Warning: too few arguments to builtin `builtin'
2175 @result{}
2176 builtin(`builtin',)
2177 @error{}m4:stdin:4: undefined builtin `'
2178 @result{}
2179 @end example
2181 @node Conditionals
2182 @chapter Conditionals, loops, and recursion
2184 Macros, expanding to plain text, perhaps with arguments, are not quite
2185 enough.  We would like to have macros expand to different things, based
2186 on decisions taken at run-time.  For that, we need some kind of conditionals.
2187 Also, we would like to have some kind of loop construct, so we could do
2188 something a number of times, or while some condition is true.
2190 @menu
2191 * Ifdef::                       Testing if a macro is defined
2192 * Ifelse::                      If-else construct, or multibranch
2193 * Shift::                       Recursion in @code{m4}
2194 * Forloop::                     Iteration by counting
2195 * Foreach::                     Iteration by list contents
2196 @end menu
2198 @node Ifdef
2199 @section Testing if a macro is defined
2201 @cindex conditionals
2202 There are two different builtin conditionals in @code{m4}.  The first is
2203 @code{ifdef}:
2205 @deffn Builtin ifdef (@var{name}, @var{string-1}, @ovar{string-2})
2206 If @var{name} is defined as a macro, @code{ifdef} expands to
2207 @var{string-1}, otherwise to @var{string-2}.  If @var{string-2} is
2208 omitted, it is taken to be the empty string (according to the normal
2209 rules).
2211 The macro @code{ifdef} is recognized only with parameters.
2212 @end deffn
2214 @example
2215 ifdef(`foo', ``foo' is defined', ``foo' is not defined')
2216 @result{}foo is not defined
2217 define(`foo', `')
2218 @result{}
2219 ifdef(`foo', ``foo' is defined', ``foo' is not defined')
2220 @result{}foo is defined
2221 ifdef(`no_such_macro', `yes', `no', `extra argument')
2222 @error{}m4:stdin:4: Warning: excess arguments to builtin `ifdef' ignored
2223 @result{}no
2224 @end example
2226 @node Ifelse
2227 @section If-else construct, or multibranch
2229 @cindex comparing strings
2230 The other conditional, @code{ifelse}, is much more powerful.  It can be
2231 used as a way to introduce a long comment, as an if-else construct, or
2232 as a multibranch, depending on the number of arguments supplied:
2234 @deffn Builtin ifelse (@var{comment})
2235 @deffnx Builtin ifelse (@var{string-1}, @var{string-2}, @var{equal}, @
2236   @ovar{not-equal})
2237 @deffnx Builtin ifelse (@var{string-1}, @var{string-2}, @var{equal-1}, @
2238   @var{string-3}, @var{string-4}, @var{equal-2}, @dots{})
2239 Used with only one argument, the @code{ifelse} simply discards it and
2240 produces no output.
2242 If called with three or four arguments, @code{ifelse} expands into
2243 @var{equal}, if @var{string-1} and @var{string-2} are equal (character
2244 for character), otherwise it expands to @var{not-equal}.  A final fifth
2245 argument is ignored, after triggering a warning.
2247 If called with six or more arguments, and @var{string-1} and
2248 @var{string-2} are equal, @code{ifelse} expands into @var{equal-1},
2249 otherwise the first three arguments are discarded and the processing
2250 starts again.
2252 The macro @code{ifelse} is recognized only with parameters.
2253 @end deffn
2255 Using only one argument is a common @code{m4} idiom for introducing a
2256 block comment, as an alternative to repeatedly using @code{dnl}.  This
2257 special usage is recognized by @acronym{GNU} @code{m4}, so that in this
2258 case, the warning about missing arguments is never triggered.
2260 @example
2261 ifelse(`some comments')
2262 @result{}
2263 ifelse(`foo', `bar')
2264 @error{}m4:stdin:2: Warning: too few arguments to builtin `ifelse'
2265 @result{}
2266 @end example
2268 Using three or four arguments provides decision points.
2270 @example
2271 ifelse(`foo', `bar', `true')
2272 @result{}
2273 ifelse(`foo', `foo', `true')
2274 @result{}true
2275 define(`foo', `bar')
2276 @result{}
2277 ifelse(foo, `bar', `true', `false')
2278 @result{}true
2279 ifelse(foo, `foo', `true', `false')
2280 @result{}false
2281 @end example
2283 @cindex macro, blind
2284 @cindex blind macro
2285 Notice how the first argument was used unquoted; it is common to compare
2286 the expansion of a macro with a string.  With this macro, you can now
2287 reproduce the behavior of blind builtins, where the macro is recognized
2288 only with arguments.
2290 @example
2291 define(`foo', `ifelse(`$#', `0', ``$0'', `arguments:$#')')
2292 @result{}
2294 @result{}foo
2295 foo()
2296 @result{}arguments:1
2297 foo(`a', `b', `c')
2298 @result{}arguments:3
2299 @end example
2301 @cindex multibranches
2302 However, @code{ifelse} can take more than four arguments.  If given more
2303 than four arguments, @code{ifelse} works like a @code{case} or @code{switch}
2304 statement in traditional programming languages.  If @var{string-1} and
2305 @var{string-2} are equal, @code{ifelse} expands into @var{equal-1}, otherwise
2306 the procedure is repeated with the first three arguments discarded.  This
2307 calls for an example:
2309 @example
2310 ifelse(`foo', `bar', `third', `gnu', `gnats')
2311 @error{}m4:stdin:1: Warning: excess arguments to builtin `ifelse' ignored
2312 @result{}gnu
2313 ifelse(`foo', `bar', `third', `gnu', `gnats', `sixth')
2314 @result{}
2315 ifelse(`foo', `bar', `third', `gnu', `gnats', `sixth', `seventh')
2316 @result{}seventh
2317 ifelse(`foo', `bar', `3', `gnu', `gnats', `6', `7', `8')
2318 @error{}m4:stdin:4: Warning: excess arguments to builtin `ifelse' ignored
2319 @result{}7
2320 @end example
2322 Naturally, the normal case will be slightly more advanced than these
2323 examples.  A common use of @code{ifelse} is in macros implementing loops
2324 of various kinds.
2326 @node Shift
2327 @section Recursion in @code{m4}
2329 @cindex recursive macros
2330 @cindex macros, recursive
2331 There is no direct support for loops in @code{m4}, but macros can be
2332 recursive.  There is no limit on the number of recursion levels, other
2333 than those enforced by your hardware and operating system.
2335 @cindex loops
2336 Loops can be programmed using recursion and the conditionals described
2337 previously.
2339 There is a builtin macro, @code{shift}, which can, among other things,
2340 be used for iterating through the actual arguments to a macro:
2342 @deffn Builtin shift (@var{arg1}, @dots{})
2343 Takes any number of arguments, and expands to all its arguments except
2344 @var{arg1}, separated by commas, with each argument quoted.
2346 The macro @code{shift} is recognized only with parameters.
2347 @end deffn
2349 @example
2350 shift
2351 @result{}shift
2352 shift(`bar')
2353 @result{}
2354 shift(`foo', `bar', `baz')
2355 @result{}bar,baz
2356 @end example
2358 An example of the use of @code{shift} is this macro:
2360 @deffn Composite reverse (@dots{})
2361 Takes any number of arguments, and reverses their order.
2362 @end deffn
2364 It is implemented as:
2366 @example
2367 define(`reverse', `ifelse(`$#', `0', , `$#', `1', ``$1'',
2368                           `reverse(shift($@@)), `$1'')')
2369 @result{}
2370 reverse
2371 @result{}
2372 reverse(`foo')
2373 @result{}foo
2374 reverse(`foo', `bar', `gnats', `and gnus')
2375 @result{}and gnus, gnats, bar, foo
2376 @end example
2378 While not a very interesting macro, it does show how simple loops can be
2379 made with @code{shift}, @code{ifelse} and recursion.  It also shows
2380 that @code{shift} is usually used with @samp{$@@}.  Sometimes, a
2381 recursive algorithm requires adding quotes to each element:
2383 @deffn Composite quote (@dots{})
2384 @deffnx Composite dquote (@dots{})
2385 @deffnx Composite dquote_elt (@dots{})
2386 Takes any number of arguments, and adds quoting.  With @code{quote},
2387 only one level of quoting is added, effectively removing whitespace
2388 after commas and turning multiple arguments into a single string.  With
2389 @code{dquote}, two levels of quoting are added, one around each element,
2390 and one around the list.  And with @code{dquote_elt}, two levels of
2391 quoting are added around each element.
2392 @end deffn
2394 An actual implementation of these three macros is distributed as
2395 @file{m4-@value{VERSION}/@/examples/@/quote.m4} in this package.  First,
2396 let's examine their usage:
2398 @example
2399 include(`quote.m4')
2400 @result{}
2401 -quote-dquote-dquote_elt-
2402 @result{}----
2403 -quote()-dquote()-dquote_elt()-
2404 @result{}--`'-`'-
2405 -quote(`1')-dquote(`1')-dquote_elt(`1')-
2406 @result{}-1-`1'-`1'-
2407 -quote(`1', `2')-dquote(`1', `2')-dquote_elt(`1', `2')-
2408 @result{}-1,2-`1',`2'-`1',`2'-
2409 define(`n', `$#')dnl
2410 -n(quote(`1', `2'))-n(dquote(`1', `2'))-n(dquote_elt(`1', `2'))-
2411 @result{}-1-1-2-
2412 dquote(dquote_elt(`1', `2'))
2413 @result{}``1'',``2''
2414 dquote_elt(dquote(`1', `2'))
2415 @result{}``1',`2''
2416 @end example
2418 The last two lines show that when given two arguments, @code{dquote}
2419 results in one string, while @code{dquote_elt} results in two.  Now,
2420 examine the implementation.  Note that @code{quote} and
2421 @code{dquote_elt} make decisions based on their number of arguments, so
2422 that when called without arguments, they result in nothing instead of a
2423 quoted empty string; this is so that it is possible to distinguish
2424 between no arguments and an empty first argument.  @code{dquote}, on the
2425 other hand, results in a string no matter what, since it is still
2426 possible to tell whether it was invoked without arguments based on the
2427 resulting string.
2429 @example
2430 undivert(`quote.m4')dnl
2431 @result{}divert(`-1')
2432 @result{}# quote(args) - convert args to single-quoted string
2433 @result{}define(`quote', `ifelse(`$#', `0', `', ``$*'')')
2434 @result{}# dquote(args) - convert args to quoted list of quoted strings
2435 @result{}define(`dquote', ``$@@'')
2436 @result{}# dquote_elt(args) - convert args to list of double-quoted strings
2437 @result{}define(`dquote_elt', `ifelse(`$#', `0', `', `$#', `1', ```$1''',
2438 @result{}                             ```$1'',$0(shift($@@))')')
2439 @result{}divert`'dnl
2440 @end example
2442 @node Forloop
2443 @section Iteration by counting
2445 @cindex for loops
2446 @cindex loops, counting
2447 @cindex counting loops
2448 Here is an example of a loop macro that implements a simple for loop.
2450 @deffn Composite forloop (@var{iterator}, @var{start}, @var{end}, @var{text})
2451 Takes the name in @var{iterator}, which must be a valid macro name, and
2452 successively assign it each integer value from @var{start} to @var{end},
2453 inclusive.  For each assignment to @var{iterator}, append @var{text} to
2454 the expansion of the @code{forloop}.  @var{text} may refer to
2455 @var{iterator}.  Any definition of @var{iterator} prior to this
2456 invocation is restored.
2457 @end deffn
2459 It can, for example, be used for simple counting:
2461 @example
2462 include(`forloop.m4')
2463 @result{}
2464 forloop(`i', `1', `8', `i ')
2465 @result{}1 2 3 4 5 6 7 8@w{ }
2466 @end example
2468 For-loops can be nested, like:
2470 @example
2471 include(`forloop.m4')
2472 @result{}
2473 forloop(`i', `1', `4', `forloop(`j', `1', `8', ` (i, j)')
2475 @result{} (1, 1) (1, 2) (1, 3) (1, 4) (1, 5) (1, 6) (1, 7) (1, 8)
2476 @result{} (2, 1) (2, 2) (2, 3) (2, 4) (2, 5) (2, 6) (2, 7) (2, 8)
2477 @result{} (3, 1) (3, 2) (3, 3) (3, 4) (3, 5) (3, 6) (3, 7) (3, 8)
2478 @result{} (4, 1) (4, 2) (4, 3) (4, 4) (4, 5) (4, 6) (4, 7) (4, 8)
2479 @result{}
2480 @end example
2482 The implementation of the @code{forloop} macro is fairly
2483 straightforward.  The @code{forloop} macro itself is simply a wrapper,
2484 which saves the previous definition of the first argument, calls the
2485 internal macro @code{@w{_forloop}}, and re-establishes the saved
2486 definition of the first argument.
2488 The macro @code{@w{_forloop}} expands the fourth argument once, and
2489 tests to see if the iterator has reached the final value.  If it has
2490 not finished, it increments the iterator (using the predefined macro
2491 @code{incr}, @pxref{Incr}), and recurses.
2493 Here is an actual implementation of @code{forloop}, distributed as
2494 @file{m4-@value{VERSION}/@/examples/@/forloop.m4} in this package:
2496 @example
2497 undivert(`forloop.m4')dnl
2498 @result{}divert(`-1')
2499 @result{}# forloop(var, from, to, stmt) - simple version
2500 @result{}define(`forloop', `pushdef(`$1', `$2')_forloop($@@)popdef(`$1')')
2501 @result{}define(`_forloop',
2502 @result{}       `$4`'ifelse($1, `$3', `', `define(`$1', incr($1))$0($@@)')')
2503 @result{}divert`'dnl
2504 @end example
2506 Notice the careful use of quotes.  Certain macro arguments are left
2507 unquoted, each for its own reason.  Try to find out @emph{why} these
2508 arguments are left unquoted, and see what happens if they are quoted.
2509 (As presented, these two macros are useful but not very robust for
2510 general use.  They lack even basic error handling for cases like
2511 @var{start} less than @var{end}, @var{end} not numeric, or
2512 @var{iterator} not being a macro name.  See if you can improve these
2513 macros; or @pxref{Improved forloop, , Answers}).
2515 @node Foreach
2516 @section Iteration by list contents
2518 @cindex for each loops
2519 @cindex loops, list iteration
2520 @cindex iterating over lists
2521 Here is an example of a loop macro that implements list iteration.
2523 @deffn Composite foreach (@var{iterator}, @var{paren-list}, @var{text})
2524 @deffnx Composite foreachq (@var{iterator}, @var{quote-list}, @var{text})
2525 Takes the name in @var{iterator}, which must be a valid macro name, and
2526 successively assign it each value from @var{paren-list} or
2527 @var{quote-list}.  In @code{foreach}, @var{paren-list} is a
2528 comma-separated list of elements contained in parentheses.  In
2529 @code{foreachq}, @var{quote-list} is a comma-separated list of elements
2530 contained in a quoted string.  For each assignment to @var{iterator},
2531 append @var{text} to the overall expansion.  @var{text} may refer to
2532 @var{iterator}.  Any definition of @var{iterator} prior to this
2533 invocation is restored.
2534 @end deffn
2536 As an example, this displays each word in a list inside of a sentence,
2537 using an implementation of @code{foreach} distributed as
2538 @file{m4-@value{VERSION}/@/examples/@/foreach.m4}, and @code{foreachq}
2539 in @file{m4-@value{VERSION}/@/examples/@/foreachq.m4}.
2541 @example
2542 include(`foreach.m4')
2543 @result{}
2544 foreach(`x', (foo, bar, foobar), `Word was: x
2545 ')dnl
2546 @result{}Word was: foo
2547 @result{}Word was: bar
2548 @result{}Word was: foobar
2549 include(`foreachq.m4')
2550 @result{}
2551 foreachq(`x', `foo, bar, foobar', `Word was: x
2552 ')dnl
2553 @result{}Word was: foo
2554 @result{}Word was: bar
2555 @result{}Word was: foobar
2556 @end example
2558 It is possible to be more complex; each element of the @var{paren-list}
2559 or @var{quote-list} can itself be a list, to pass as further arguments
2560 to a helper macro.  This example generates a shell case statement:
2562 @example
2563 include(`foreach.m4')
2564 @result{}
2565 define(`_case', `  $1)
2566     $2=" $1";;
2567 ')dnl
2568 define(`_cat', `$1$2')dnl
2569 case $`'1 in
2570 @result{}case $1 in
2571 foreach(`x', `(`(`a', `vara')', `(`b', `varb')', `(`c', `varc')')',
2572         `_cat(`_case', x)')dnl
2573 @result{}  a)
2574 @result{}    vara=" a";;
2575 @result{}  b)
2576 @result{}    varb=" b";;
2577 @result{}  c)
2578 @result{}    varc=" c";;
2579 esac
2580 @result{}esac
2581 @end example
2583 The implementation of the @code{foreach} macro is a bit more involved;
2584 it is a wrapper around two helper macros.  First, @code{@w{_arg1}} is
2585 needed to grab the first element of a list.  Second,
2586 @code{@w{_foreach}} implements the recursion, successively walking
2587 through the original list.  Here is a simple implementation of
2588 @code{foreach}:
2590 @example
2591 undivert(`foreach.m4')dnl
2592 @result{}divert(`-1')
2593 @result{}# foreach(x, (item_1, item_2, ..., item_n), stmt)
2594 @result{}#   parenthesized list, simple version
2595 @result{}define(`foreach', `pushdef(`$1')_foreach($@@)popdef(`$1')')
2596 @result{}define(`_arg1', `$1')
2597 @result{}define(`_foreach', `ifelse(`$2', `()', `',
2598 @result{}  `define(`$1', _arg1$2)$3`'$0(`$1', (shift$2), `$3')')')
2599 @result{}divert`'dnl
2600 @end example
2602 Unfortunately, that implementation is not robust to macro names as list
2603 elements.  Each iteration of @code{@w{_foreach}} is stripping another
2604 layer of quotes, leading to erratic results if list elements are not
2605 already fully expanded.  The first cut at implementing @code{foreachq}
2606 takes this into account.  Also, when using quoted elements in a
2607 @var{paren-list}, the overall list must be quoted.  A @var{quote-list}
2608 has the nice property of requiring fewer characters to create a list
2609 containing the same quoted elements.  To see the difference between the
2610 two macros, we attempt to pass double-quoted macro names in a list,
2611 expecting the macro name on output after one layer of quotes is removed
2612 during list iteration and the final layer removed during the final
2613 rescan:
2615 @example
2616 define(`a', `1')define(`b', `2')define(`c', `3')
2617 @result{}
2618 include(`foreach.m4')
2619 @result{}
2620 include(`foreachq.m4')
2621 @result{}
2622 foreach(`x', `(``a'', ``(b'', ``c)'')', `x
2624 @result{}1
2625 @result{}(2)1
2626 @result{}
2627 @result{}, x
2628 @result{})
2629 foreachq(`x', ```a'', ``(b'', ``c)''', `x
2630 ')dnl
2631 @result{}a
2632 @result{}(b
2633 @result{}c)
2634 @end example
2636 Obviously, @code{foreachq} did a better job; here is its implementation:
2638 @example
2639 undivert(`foreachq.m4')dnl
2640 @result{}include(`quote.m4')dnl
2641 @result{}divert(`-1')
2642 @result{}# foreachq(x, `item_1, item_2, ..., item_n', stmt)
2643 @result{}#   quoted list, simple version
2644 @result{}define(`foreachq', `pushdef(`$1')_foreachq($@@)popdef(`$1')')
2645 @result{}define(`_arg1', `$1')
2646 @result{}define(`_foreachq', `ifelse(quote($2), `', `',
2647 @result{}  `define(`$1', `_arg1($2)')$3`'$0(`$1', `shift($2)', `$3')')')
2648 @result{}divert`'dnl
2649 @end example
2651 Notice that @code{@w{_foreachq}} had to use the helper macro
2652 @code{quote} defined earlier (@pxref{Shift}), to ensure that the
2653 embedded @code{ifelse} call does not go haywire if a list element
2654 contains a comma.  Unfortunately, this implementation of @code{foreachq}
2655 has its own severe flaw.  Whereas the @code{foreach} implementation was
2656 linear, this macro is quadratic in the number of list elements, and is
2657 much more likely to trip up the limit set by the command line option
2658 @option{--nesting-limit} (or @option{-L}, @pxref{Limits control, ,
2659 Invoking m4}).  (It is possible to have robust iteration with linear
2660 behavior for either list style.  See if you can learn from the best
2661 elements of both of these implementations to create robust macros; or
2662 @pxref{Improved foreach, , Answers}).
2664 @node Debugging
2665 @chapter How to debug macros and input
2667 When writing macros for @code{m4}, they often do not work as intended on
2668 the first try (as is the case with most programming languages).
2669 Fortunately, there is support for macro debugging in @code{m4}.
2671 @menu
2672 * Dumpdef::                     Displaying macro definitions
2673 * Trace::                       Tracing macro calls
2674 * Debug Levels::                Controlling debugging output
2675 * Debug Output::                Saving debugging output
2676 @end menu
2678 @node Dumpdef
2679 @section Displaying macro definitions
2681 @cindex displaying macro definitions
2682 @cindex macros, displaying definitions
2683 @cindex definitions, displaying macro
2684 If you want to see what a name expands into, you can use the builtin
2685 @code{dumpdef}:
2687 @deffn Builtin dumpdef (@ovar{names@dots{}})
2688 Accepts any number of arguments.  If called without any arguments,
2689 it displays the definitions of all known names, otherwise it displays
2690 the definitions of the @var{names} given.  The output is printed to the
2691 current debug file (usually standard error), and is sorted by name.  If
2692 an unknown name is encountered, a warning is printed.
2694 The expansion of @code{dumpdef} is void.
2695 @end deffn
2697 @example
2698 define(`foo', `Hello world.')
2699 @result{}
2700 dumpdef(`foo')
2701 @error{}foo:@tabchar{}`Hello world.'
2702 @result{}
2703 dumpdef(`define')
2704 @error{}define:@tabchar{}<define>
2705 @result{}
2706 @end example
2708 The last example shows how builtin macros definitions are displayed.
2709 The definition that is dumped corresponds to what would occur if the
2710 macro were to be called at that point, even if other definitions are
2711 still live due to redefining a macro during argument collection.
2713 @example
2714 pushdef(`f', ``$0'1')pushdef(`f', ``$0'2')
2715 @result{}
2716 f(popdef(`f')dumpdef(`f'))
2717 @error{}f:@tabchar{}``$0'1'
2718 @result{}f2
2719 f(popdef(`f')dumpdef(`f'))
2720 @error{}m4:stdin:3: undefined macro `f'
2721 @result{}f1
2722 @end example
2724 @xref{Debug Levels}, for information on controlling the details of the
2725 display.
2727 @node Trace
2728 @section Tracing macro calls
2730 @cindex tracing macro expansion
2731 @cindex macro expansion, tracing
2732 @cindex expansion, tracing macro
2733 It is possible to trace macro calls and expansions through the builtins
2734 @code{traceon} and @code{traceoff}:
2736 @deffn Builtin traceon (@ovar{names@dots{}})
2737 @deffnx Builtin traceoff (@ovar{names@dots{}})
2738 When called without any arguments, @code{traceon} and @code{traceoff}
2739 will turn tracing on and off, respectively, for all currently defined
2740 macros.
2742 When called with arguments, only the macros listed in @var{names} are
2743 affected, whether or not they are currently defined.
2745 The expansion of @code{traceon} and @code{traceoff} is void.
2746 @end deffn
2748 Whenever a traced macro is called and the arguments have been collected,
2749 the call is displayed.  If the expansion of the macro call is not void,
2750 the expansion can be displayed after the call.  The output is printed
2751 to the current debug file (defaulting to standard error, @pxref{Debug
2752 Output}).
2754 @example
2755 define(`foo', `Hello World.')
2756 @result{}
2757 define(`echo', `$@@')
2758 @result{}
2759 traceon(`foo', `echo')
2760 @result{}
2762 @error{}m4trace: -1- foo -> `Hello World.'
2763 @result{}Hello World.
2764 echo(`gnus', `and gnats')
2765 @error{}m4trace: -1- echo(`gnus', `and gnats') -> ``gnus',`and gnats''
2766 @result{}gnus,and gnats
2767 @end example
2769 The number between dashes is the depth of the expansion.  It is one most
2770 of the time, signifying an expansion at the outermost level, but it
2771 increases when macro arguments contain unquoted macro calls.  The
2772 maximum number that will appear between dashes is controlled by the
2773 option @option{--nesting-limit} (@pxref{Limits control, , Invoking m4}).
2775 Tracing by name is an attribute that is preserved whether the macro is
2776 defined or not.  This allows the @option{-t} option to select macros to
2777 trace before those macros are defined.
2779 @example
2780 traceoff(`foo')
2781 @result{}
2782 traceon(`foo')
2783 @result{}
2785 @result{}foo
2786 define(`foo', `bar')
2787 @result{}
2789 @error{}m4trace: -1- foo -> `bar'
2790 @result{}bar
2791 undefine(`foo')
2792 @result{}
2793 ifdef(`foo', `yes', `no')
2794 @result{}no
2795 indir(`foo')
2796 @error{}m4:stdin:8: undefined macro `foo'
2797 @result{}
2798 define(`foo', `blah')
2799 @result{}
2801 @error{}m4trace: -1- foo -> `blah'
2802 @result{}blah
2803 traceoff
2804 @result{}
2806 @result{}blah
2807 @end example
2809 Tracing even works on builtins.  However, @code{defn} (@pxref{Defn})
2810 does not transfer tracing status.
2812 @example
2813 traceon(`eval', `m4_divnum')
2814 @result{}
2815 define(`m4_eval', defn(`eval'))
2816 @result{}
2817 define(`m4_divnum', defn(`divnum'))
2818 @result{}
2819 eval(divnum)
2820 @error{}m4trace: -1- eval(`0') -> `0'
2821 @result{}0
2822 m4_eval(m4_divnum)
2823 @error{}m4trace: -2- m4_divnum -> `0'
2824 @result{}0
2825 @end example
2827 @xref{Debug Levels}, for information on controlling the details of the
2828 display.
2830 @node Debug Levels
2831 @section Controlling debugging output
2833 @cindex controlling debugging output
2834 @cindex debugging output, controlling
2835 The @option{-d} option to @code{m4} (or @option{--debug},
2836 @pxref{Debugging options, , Invoking m4}) controls the amount of details
2837 presented in three
2838 categories of output.  Trace output is requested by @code{traceon}
2839 (@pxref{Trace}), and each line is prefixed by @samp{m4trace:} in
2840 relation to a macro invocation.  Debug output tracks useful events not
2841 associated with a macro invocation, and each line is prefixed by
2842 @samp{m4debug:}.  Finally, @code{dumpdef} (@pxref{Dumpdef}) output is
2843 affected, with no prefix added to the output lines.
2845 The @var{flags} following the option can be one or more of the
2846 following:
2848 @table @code
2849 @item a
2850 In trace output, show the actual arguments that were collected before
2851 invoking the macro.  This applies to all macro calls if the @samp{t}
2852 flag is used, otherwise only the macros covered by calls of
2853 @code{traceon}.
2855 @item c
2856 In trace output, show several trace lines for each macro call.  A line
2857 is shown when the macro is seen, but before the arguments are collected;
2858 a second line when the arguments have been collected and a third line
2859 after the call has completed.
2861 @item e
2862 In trace output, show the expansion of each macro call, if it is not
2863 void.  This applies to all macro calls if the @samp{t} flag is used,
2864 otherwise only the macros covered by calls of @code{traceon}.
2866 @item f
2867 In debug and trace output, include the name of the current input file in
2868 the output line.
2870 @item i
2871 In debug output, print a message each time the current input file is
2872 changed.
2874 @item l
2875 In debug and trace output, include the current input line number in the
2876 output line.
2878 @item p
2879 In debug output, print a message when a named file is found through the
2880 path search mechanism (@pxref{Search Path}), giving the actual file name
2881 used.
2883 @item q
2884 In trace and dumpdef output, quote actual arguments and macro expansions
2885 in the display with the current quotes.  This is useful in connection
2886 with the @samp{a} and @samp{e} flags above.
2888 @item t
2889 In trace output, trace all macro calls made in this invocation of
2890 @code{m4}, regardless of the settings of @code{traceon}.
2892 @item x
2893 In trace output, add a unique `macro call id' to each line of the trace
2894 output.  This is useful in connection with the @samp{c} flag above.
2896 @item V
2897 A shorthand for all of the above flags.
2898 @end table
2900 If no flags are specified with the @option{-d} option, the default is
2901 @samp{aeq}.  The examples throughout this manual assume the default
2902 flags.
2904 @cindex @acronym{GNU} extensions
2905 There is a builtin macro @code{debugmode}, which allows on-the-fly control of
2906 the debugging output format:
2908 @deffn Builtin debugmode (@ovar{flags})
2909 The argument @var{flags} should be a subset of the letters listed above.
2910 As special cases, if the argument starts with a @samp{+}, the flags are
2911 added to the current debug flags, and if it starts with a @samp{-}, they
2912 are removed.  If no argument is present, all debugging flags are cleared
2913 (as if no @option{-d} was given), and with an empty argument the flags
2914 are reset to the default of @samp{aeq}.
2916 The expansion of @code{debugmode} is void.
2917 @end deffn
2919 @example
2920 define(`foo', `FOO')
2921 @result{}
2922 traceon(`foo')
2923 @result{}
2924 debugmode()
2925 @result{}
2927 @error{}m4trace: -1- foo -> `FOO'
2928 @result{}FOO
2929 debugmode
2930 @result{}
2932 @error{}m4trace: -1- foo
2933 @result{}FOO
2934 debugmode(`+l')
2935 @result{}
2937 @error{}m4trace:8: -1- foo
2938 @result{}FOO
2939 @end example
2941 @node Debug Output
2942 @section Saving debugging output
2944 @cindex saving debugging output
2945 @cindex debugging output, saving
2946 @cindex output, saving debugging
2947 @cindex @acronym{GNU} extensions
2948 Debug and tracing output can be redirected to files using either the
2949 @option{--debugfile} option to @code{m4} (@pxref{Debugging options, ,
2950 Invoking m4}), or with the builtin macro @code{debugfile}:
2952 @deffn Builtin debugfile (@ovar{file})
2953 Sends all further debug and trace output to @var{file}, opened in append
2954 mode.  If @var{file} is the empty string, debug and trace output are
2955 discarded.  If @code{debugfile} is called without any arguments, debug
2956 and trace output are sent to standard error.  This does not affect
2957 warnings, error messages, or @code{errprint} output, which are
2958 always sent to standard error.  If @var{file} cannot be opened, the
2959 current debug file is unchanged, and an error is issued.
2961 The expansion of @code{debugfile} is void.
2962 @end deffn
2964 @example
2965 traceon(`divnum')
2966 @result{}
2967 divnum(`extra')
2968 @error{}m4:stdin:2: Warning: excess arguments to builtin `divnum' ignored
2969 @error{}m4trace: -1- divnum(`extra') -> `0'
2970 @result{}0
2971 debugfile()
2972 @result{}
2973 divnum(`extra')
2974 @error{}m4:stdin:4: Warning: excess arguments to builtin `divnum' ignored
2975 @result{}0
2976 debugfile
2977 @result{}
2978 divnum
2979 @error{}m4trace: -1- divnum -> `0'
2980 @result{}0
2981 @end example
2983 @node Input Control
2984 @chapter Input control
2986 This chapter describes various builtin macros for controlling the input
2987 to @code{m4}.
2989 @menu
2990 * Dnl::                         Deleting whitespace in input
2991 * Changequote::                 Changing the quote characters
2992 * Changecom::                   Changing the comment delimiters
2993 * Changeword::                  Changing the lexical structure of words
2994 * M4wrap::                      Saving text until end of input
2995 @end menu
2997 @node Dnl
2998 @section Deleting whitespace in input
3000 @cindex deleting whitespace in input
3001 The builtin @code{dnl} stands for ``Discard to Next Line'':
3003 @deffn Builtin dnl
3004 All characters, up to and including the next newline, are discarded
3005 without performing any macro expansion.  A warning is issued if the end
3006 of the file is encountered without a newline.
3008 The expansion of @code{dnl} is void.
3009 @end deffn
3011 It is often used in connection with @code{define}, to remove the
3012 newline that follows the call to @code{define}.  Thus
3014 @example
3015 define(`foo', `Macro `foo'.')dnl A very simple macro, indeed.
3017 @result{}Macro foo.
3018 @end example
3020 The input up to and including the next newline is discarded, as opposed
3021 to the way comments are treated (@pxref{Comments}).
3023 Usually, @code{dnl} is immediately followed by an end of line or some
3024 other whitespace.  @acronym{GNU} @code{m4} will produce a warning diagnostic if
3025 @code{dnl} is followed by an open parenthesis.  In this case, @code{dnl}
3026 will collect and process all arguments, looking for a matching close
3027 parenthesis.  All predictable side effects resulting from this
3028 collection will take place.  @code{dnl} will return no output.  The
3029 input following the matching close parenthesis up to and including the
3030 next newline, on whatever line containing it, will still be discarded.
3032 @example
3033 dnl(`args are ignored, but side effects occur',
3034 define(`foo', `like this')) while this text is ignored: undefine(`foo')
3035 @error{}m4:stdin:1: Warning: excess arguments to builtin `dnl' ignored
3036 See how `foo' was defined, foo?
3037 @result{}See how foo was defined, like this?
3038 @end example
3040 If the end of file is encountered without a newline character, a
3041 warning is issued and dnl stops consuming input.
3043 @example
3044 m4wrap(`m4wrap(`2 hi
3045 ')0 hi dnl 1 hi')
3046 @result{}
3047 define(`hi', `HI')
3048 @result{}
3050 @error{}m4:stdin:1: Warning: end of file treated as newline
3051 @result{}0 HI 2 HI
3052 @end example
3054 @node Changequote
3055 @section Changing the quote characters
3057 @cindex changing the quote delimiters
3058 @cindex quote delimiters, changing the
3059 The default quote delimiters can be changed with the builtin
3060 @code{changequote}:
3062 @deffn Builtin changequote (@dvar{start, `}, @dvar{end, '})
3063 This sets @var{start} as the new begin-quote delimiter and @var{end} as
3064 the new end-quote delimiter.  If both arguments are missing, the default
3065 quotes (@code{`} and @code{'}) are used.  If @var{start} is void, then
3066 quoting is disabled.  Otherwise, if @var{end} is missing or void, the
3067 default end-quote delimiter (@code{'}) is used.  The quote delimiters
3068 can be of any length.
3070 The expansion of @code{changequote} is void.
3071 @end deffn
3073 @example
3074 changequote(`[', `]')
3075 @result{}
3076 define([foo], [Macro [foo].])
3077 @result{}
3079 @result{}Macro foo.
3080 @end example
3082 The quotation strings can safely contain eight-bit characters.
3083 @ignore
3084 @comment Yuck.  I know of no clean way to render an 8-bit character in
3085 @comment both info and dvi.  This example uses the `open-guillemot' and
3086 @comment `close-guillemot' characters of the Latin-1 character set.
3088 @example
3089 define(`a', `b')
3090 @result{}
3091 «a»
3092 @result{}«b»
3093 changequote(`«', `»')
3094 @result{}
3095 «a»
3096 @result{}a
3097 @end example
3098 @end ignore
3099 If no single character is appropriate, @var{start} and @var{end} can be
3100 of any length.  Other implementations cap the delimiter length to five
3101 characters, but @acronym{GNU} has no inherent limit.
3103 @example
3104 changequote(`[[[', `]]]')
3105 @result{}
3106 define([[[foo]]], [[[Macro [[[[[foo]]]]].]]])
3107 @result{}
3109 @result{}Macro [[foo]].
3110 @end example
3112 Calling @code{changequote} with @var{start} as the empty string will
3113 effectively disable the quoting mechanism, leaving no way to quote text.
3114 However, using an empty string is not portable, as some other
3115 implementations of @code{m4} revert to the default quoting, while others
3116 preserve the prior non-empty delimiter.  If @var{start} is not empty,
3117 then an empty @var{end} will use the default end-quote delimiter of
3118 @samp{'}, as otherwise, it would be impossible to end a quoted string.
3119 Again, this is not portable, as some other @code{m4} implementations
3120 reuse @var{start} as the end-quote delimiter, while others preserve the
3121 previous non-empty value.  Omitting both arguments restores the default
3122 begin-quote and end-quote delimiters; fortunately this behavior is
3123 portable to all implementations of @code{m4}.
3125 @example
3126 define(`foo', `Macro `FOO'.')
3127 @result{}
3128 changequote(`', `')
3129 @result{}
3131 @result{}Macro `FOO'.
3132 `foo'
3133 @result{}`Macro `FOO'.'
3134 changequote(`,)
3135 @result{}
3137 @result{}Macro FOO.
3138 @end example
3140 There is no way in @code{m4} to quote a string containing an unmatched
3141 begin-quote, except using @code{changequote} to change the current
3142 quotes.
3144 If the quotes should be changed from, say, @samp{[} to @samp{[[},
3145 temporary quote characters have to be defined.  To achieve this, two
3146 calls of @code{changequote} must be made, one for the temporary quotes
3147 and one for the new quotes.
3149 Macros are recognized in preference to the begin-quote string, so if a
3150 prefix of @var{start} can be recognized as part of a potential macro
3151 name, the quoting mechanism is effectively disabled.  Unless you use
3152 @code{changeword} (@pxref{Changeword}), this means that @var{start}
3153 should not begin with a letter, digit, or @samp{_} (underscore).
3154 However, even though quoted strings are not recognized, the quote
3155 characters can still be discerned in macro expansion and in trace
3156 output.
3158 @example
3159 define(`echo', `$@@')
3160 @result{}
3161 define(`hi', `HI')
3162 @result{}
3163 changequote(`q', `Q')
3164 @result{}
3165 q hi Q hi
3166 @result{}q HI Q HI
3167 echo(hi)
3168 @result{}qHIQ
3169 changequote
3170 @result{}
3171 changequote(`-', `EOF')
3172 @result{}
3173 - hi EOF hi
3174 @result{} hi  HI
3175 changequote
3176 @result{}
3177 changequote(`1', `2')
3178 @result{}
3179 hi1hi2
3180 @result{}hi1hi2
3181 hi 1hi2
3182 @result{}HI hi
3183 @end example
3185 Quotes are recognized in preference to argument collection.  In
3186 particular, if @var{start} is a single @samp{(}, then argument
3187 collection is effectively disabled.  For portability with other
3188 implementations, it is a good idea to avoid @samp{(}, @samp{,}, and
3189 @samp{)} as the first character in @var{start}.
3191 @example
3192 define(`echo', `$#:$@@:')
3193 @result{}
3194 define(`hi', `HI')
3195 @result{}
3196 changequote(`(',`)')
3197 @result{}
3198 echo(hi)
3199 @result{}0::hi
3200 changequote
3201 @result{}
3202 changequote(`((', `))')
3203 @result{}
3204 echo(hi)
3205 @result{}1:HI:
3206 echo((hi))
3207 @result{}0::hi
3208 changequote
3209 @result{}
3210 changequote(`,', `)')
3211 @result{}
3212 echo(hi,hi)bye)
3213 @result{}1:HIhibye:
3214 @end example
3216 If @var{end} is a prefix of @var{start}, the end-quote will be
3217 recognized in preference to a nested begin-quote.  In particular,
3218 changing the quotes to have the same string for @var{start} and
3219 @var{end} disables nesting of quotes.  When quote nesting is disabled,
3220 it is impossible to double-quote strings across macro expansions, so
3221 using the same string is not done very often.
3223 @example
3224 define(`hi', `HI')
3225 @result{}
3226 changequote(`""', `"')
3227 @result{}
3228 ""hi"""hi"
3229 @result{}hihi
3230 ""hi" ""hi"
3231 @result{}hi hi
3232 ""hi"" "hi"
3233 @result{}hi" "HI"
3234 changequote
3235 @result{}
3236 `hi`hi'hi'
3237 @result{}hi`hi'hi
3238 changequote(`"', `"')
3239 @result{}
3240 "hi"hi"hi"
3241 @result{}hiHIhi
3242 @end example
3244 It is an error if the end of file occurs within a quoted string.
3246 @comment status: 1
3247 @example
3248 `hello world'
3249 @result{}hello world
3250 `dangling quote
3252 @error{}m4:stdin:2: ERROR: end of file in string
3253 @end example
3255 @node Changecom
3256 @section Changing the comment delimiters
3258 @cindex changing comment delimiters
3259 @cindex comment delimiters, changing
3260 The default comment delimiters can be changed with the builtin
3261 macro @code{changecom}:
3263 @deffn Builtin changecom (@ovar{start}, @dvar{end, @key{NL}})
3264 This sets @var{start} as the new begin-comment delimiter and @var{end}
3265 as the new end-comment delimiter.  If both arguments are missing, or
3266 @var{start} is void, then comments are disabled.  Otherwise, if
3267 @var{end} is missing or void, the default end-comment delimiter of
3268 newline is used.  The comment delimiters can be of any length.
3270 The expansion of @code{changecom} is void.
3271 @end deffn
3273 @example
3274 define(`comment', `COMMENT')
3275 @result{}
3276 # A normal comment
3277 @result{}# A normal comment
3278 changecom(`/*', `*/')
3279 @result{}
3280 # Not a comment anymore
3281 @result{}# Not a COMMENT anymore
3282 But: /* this is a comment now */ while this is not a comment
3283 @result{}But: /* this is a comment now */ while this is not a COMMENT
3284 @end example
3286 @cindex comments, copied to output
3287 Note how comments are copied to the output, much as if they were quoted
3288 strings.  If you want the text inside a comment expanded, quote the
3289 begin-comment delimiter.
3291 Calling @code{changecom} without any arguments, or with @var{start} as
3292 the empty string, will effectively disable the commenting mechanism.  To
3293 restore the original comment start of @samp{#}, you must explicitly ask
3294 for it.  If @var{start} is not empty, then an empty @var{end} will use
3295 the default end-comment delimiter of newline, as otherwise, it would be
3296 impossible to end a comment.  However, this is not portable, as some
3297 other @code{m4} implementations preserve the previous non-empty
3298 delimiters instead.
3300 @example
3301 define(`comment', `COMMENT')
3302 @result{}
3303 changecom
3304 @result{}
3305 # Not a comment anymore
3306 @result{}# Not a COMMENT anymore
3307 changecom(`#', `')
3308 @result{}
3309 # comment again
3310 @result{}# comment again
3311 @end example
3313 The comment strings can safely contain eight-bit characters.
3314 @ignore
3315 @comment Yuck.  I know of no clean way to render an 8-bit character in
3316 @comment both info and dvi.  This example uses the `open-guillemot' and
3317 @comment `close-guillemot' characters of the Latin-1 character set.
3319 @example
3320 define(`a', `b')
3321 @result{}
3322 «a»
3323 @result{}«b»
3324 changecom(`«', `»')
3325 @result{}
3326 «a»
3327 @result{}«a»
3328 @end example
3329 @end ignore
3330 If no single character is appropriate, @var{start} and @var{end} can be
3331 of any length.  Other implementations cap the delimiter length to five
3332 characters, but @acronym{GNU} has no inherent limit.
3334 Comments are recognized in preference to macros.  However, this is not
3335 compatible with other implementations, where macros and even quoting
3336 takes precedence over comments, so it may change in a future release.
3337 For portability, this means that @var{start} should not begin with a
3338 letter, digit, or @samp{_} (underscore), and that neither the
3339 start-quote nor the start-comment string should be a prefix of the
3340 other.
3342 @example
3343 define(`hi', `HI')
3344 @result{}
3345 define(`hi1hi2', `hello')
3346 @result{}
3347 changecom(`q', `Q')
3348 @result{}
3349 q hi Q hi
3350 @result{}q hi Q HI
3351 changecom(`1', `2')
3352 @result{}
3353 hi1hi2
3354 @result{}hello
3355 hi 1hi2
3356 @result{}HI 1hi2
3357 @end example
3359 Comments are recognized in preference to argument collection.  In
3360 particular, if @var{start} is a single @samp{(}, then argument
3361 collection is effectively disabled.  For portability with other
3362 implementations, it is a good idea to avoid @samp{(}, @samp{,}, and
3363 @samp{)} as the first character in @var{start}.
3365 @example
3366 define(`echo', `$#:$@@:')
3367 @result{}
3368 define(`hi', `HI')
3369 @result{}
3370 changecom(`(',`)')
3371 @result{}
3372 echo(hi)
3373 @result{}0::(hi)
3374 changecom
3375 @result{}
3376 changecom(`((', `))')
3377 @result{}
3378 echo(hi)
3379 @result{}1:HI:
3380 echo((hi))
3381 @result{}0::((hi))
3382 changecom(`,', `)')
3383 @result{}
3384 echo(hi,hi)bye)
3385 @result{}1:HI,hi)bye:
3386 @end example
3388 It is an error if the end of file occurs within a comment.
3390 @comment status: 1
3391 @example
3392 changecom(`/*', `*/')
3393 @result{}
3394 /*dangling comment
3396 @error{}m4:stdin:2: ERROR: end of file in comment
3397 @end example
3399 @node Changeword
3400 @section Changing the lexical structure of words
3402 @cindex lexical structure of words
3403 @cindex words, lexical structure of
3404 @quotation
3405 The macro @code{changeword} and all associated functionality is
3406 experimental.  It is only available if the @option{--enable-changeword}
3407 option was given to @code{configure}, at @acronym{GNU} @code{m4} installation
3408 time.  The functionality will go away in the future, to be replaced by
3409 other new features that are more efficient at providing the same
3410 capabilities.  @emph{Do not rely on it}.  Please direct your comments
3411 about it the same way you would do for bugs.
3412 @end quotation
3414 A file being processed by @code{m4} is split into quoted strings, words
3415 (potential macro names) and simple tokens (any other single character).
3416 Initially a word is defined by the following regular expression:
3418 @comment ignore
3419 @example
3420 [_a-zA-Z][_a-zA-Z0-9]*
3421 @end example
3423 Using @code{changeword}, you can change this regular expression:
3425 @deffn {Optional builtin} changeword (@var{regex})
3426 Changes the regular expression for recognizing macro names to be
3427 @var{regex}.  If @var{regex} is empty, use
3428 @samp{[_a-zA-Z][_a-zA-Z0-9]*}.  @var{regex} must obey the constraint
3429 that every prefix of the desired final pattern is also accepted by the
3430 regular expression.  If @var{regex} contains grouping parentheses, the
3431 macro invoked is the portion that matched the first group, rather than
3432 the entire matching string.
3434 The expansion of @code{changeword} is void.
3435 The macro @code{changeword} is recognized only with parameters.
3436 @end deffn
3438 Relaxing the lexical rules of @code{m4} might be useful (for example) if
3439 you wanted to apply translations to a file of numbers:
3441 @example
3442 ifdef(`changeword', `', `errprint(` skipping: no changeword support
3443 ')m4exit(`77')')dnl
3444 changeword(`[_a-zA-Z0-9]+')
3445 @result{}
3446 define(`1', `0')1
3447 @result{}0
3448 @end example
3450 Tightening the lexical rules is less useful, because it will generally
3451 make some of the builtins unavailable.  You could use it to prevent
3452 accidental call of builtins, for example:
3454 @example
3455 ifdef(`changeword', `', `errprint(` skipping: no changeword support
3456 ')m4exit(`77')')dnl
3457 define(`_indir', defn(`indir'))
3458 @result{}
3459 changeword(`_[_a-zA-Z0-9]*')
3460 @result{}
3461 esyscmd(`foo')
3462 @result{}esyscmd(foo)
3463 _indir(`esyscmd', `echo hi')
3464 @result{}hi
3465 @result{}
3466 @end example
3468 Because @code{m4} constructs its words a character at a time, there
3469 is a restriction on the regular expressions that may be passed to
3470 @code{changeword}.  This is that if your regular expression accepts
3471 @samp{foo}, it must also accept @samp{f} and @samp{fo}.
3473 @example
3474 ifdef(`changeword', `', `errprint(` skipping: no changeword support
3475 ')m4exit(`77')')dnl
3476 define(`foo
3477 ', `bar
3479 @result{}
3480 dnl This example wants to recognize changeword, dnl, and `foo\n'.
3481 dnl First, we check that our regexp will match.
3482 regexp(`changeword', `[cd][a-z]*\|foo[
3484 @result{}0
3485 regexp(`foo
3486 ', `[cd][a-z]*\|foo[
3488 @result{}0
3489 regexp(`f', `[cd][a-z]*\|foo[
3491 @result{}-1
3493 @result{}foo
3494 changeword(`[cd][a-z]*\|foo[
3496 @result{}
3497 dnl Even though `foo\n' matches, we forgot to allow `f'.
3499 @result{}foo
3500 changeword(`[cd][a-z]*\|fo*[
3501 ]?')
3502 @result{}
3503 dnl Now we can call `foo\n'.
3505 @result{}bar
3506 @end example
3508 @ignore
3509 @comment One more test of including newline in a macro name; but this
3510 @comment does not need to be displayed in the manual.  This ensures
3511 @comment that line numbering is correct when dnl cuts across include
3512 @comment file boundaries, and when __file__ or __line__ is the last
3513 @comment token in an include file.
3515 @example
3516 ifdef(`changeword', `', `errprint(` skipping: no changeword support
3517 ')m4exit(`77')')dnl
3518 define(`bar
3519 ', defn(`dnl'))dnl
3520 define(`baz', `dnl
3521 include(`foo') ignored
3522 dnl')dnl
3523 changeword(`\([_a-zA-Z][_a-zA-Z0-9]*\|bar
3524 \)')
3525 @result{}
3526 __file__:__line__
3527 @result{}stdin:10
3528 include(`foo') ignored
3529 __file__:__line__
3530 @result{}stdin:12
3531 baz ignored
3532 __file__:__line__
3533 @result{}stdin:14
3534 define(`bar
3535 ', defn(`__file__'))
3536 @result{}
3537 include(`foo')
3538 @result{}../examples/foo
3539 define(`bar
3540 ', defn(`__line__'))
3541 @result{}
3542 include(`foo')
3543 @result{}1
3544 __file__:__line__
3545 @result{}stdin:21
3546 @end example
3547 @end ignore
3549 @code{changeword} has another function.  If the regular expression
3550 supplied contains any grouped subexpressions, then text outside
3551 the first of these is discarded before symbol lookup.  So:
3553 @example
3554 ifdef(`changeword', `', `errprint(` skipping: no changeword support
3555 ')m4exit(`77')')dnl
3556 ifdef(`__unix__', ,
3557       `errprint(` skipping: syscmd does not have unix semantics
3558 ')m4exit(`77')')dnl
3559 changecom(`/*', `*/')dnl
3560 define(`foo', `bar')dnl
3561 changeword(`#\([_a-zA-Z0-9]*\)')
3562 @result{}
3563 #esyscmd(`echo foo \#foo')
3564 @result{}foo bar
3565 @result{}
3566 @end example
3568 @code{m4} now requires a @samp{#} mark at the beginning of every
3569 macro invocation, so one can use @code{m4} to preprocess plain
3570 text without losing various words like @samp{divert}.
3572 In @code{m4}, macro substitution is based on text, while in @TeX{}, it
3573 is based on tokens.  @code{changeword} can throw this difference into
3574 relief.  For example, here is the same idea represented in @TeX{} and
3575 @code{m4}.  First, the @TeX{} version:
3577 @comment ignore
3578 @example
3579 \def\a@{\message@{Hello@}@}
3580 \catcode`\@@=0
3581 \catcode`\\=12
3583 @@bye
3584 @result{}Hello
3585 @end example
3587 @noindent
3588 Then, the @code{m4} version:
3590 @example
3591 ifdef(`changeword', `', `errprint(` skipping: no changeword support
3592 ')m4exit(`77')')dnl
3593 define(`a', `errprint(`Hello')')dnl
3594 changeword(`@@\([_a-zA-Z0-9]*\)')
3595 @result{}
3597 @result{}errprint(Hello)
3598 @end example
3600 In the @TeX{} example, the first line defines a macro @code{a} to
3601 print the message @samp{Hello}.  The second line defines @key{@@} to
3602 be usable instead of @key{\} as an escape character.  The third line
3603 defines @key{\} to be a normal printing character, not an escape.
3604 The fourth line invokes the macro @code{a}.  So, when @TeX{} is run
3605 on this file, it displays the message @samp{Hello}.
3607 When the @code{m4} example is passed through @code{m4}, it outputs
3608 @samp{errprint(Hello)}.  The reason for this is that @TeX{} does
3609 lexical analysis of macro definition when the macro is @emph{defined}.
3610 @code{m4} just stores the text, postponing the lexical analysis until
3611 the macro is @emph{used}.
3613 You should note that using @code{changeword} will slow @code{m4} down
3614 by a factor of about seven, once it is changed to something other
3615 than the default regular expression.  You can invoke @code{changeword}
3616 with the empty string to restore the default word definition, and regain
3617 the parsing speed.
3619 @node M4wrap
3620 @section Saving text until end of input
3622 @cindex saving input
3623 @cindex input, saving
3624 It is possible to `save' some text until the end of the normal input has
3625 been seen.  Text can be saved, to be read again by @code{m4} when the
3626 normal input has been exhausted.  This feature is normally used to
3627 initiate cleanup actions before normal exit, e.g., deleting temporary
3628 files.
3630 To save input text, use the builtin @code{m4wrap}:
3632 @deffn Builtin m4wrap (@var{string}, @dots{})
3633 Stores @var{string} in a safe place, to be reread when end of input is
3634 reached.  As a @acronym{GNU} extension, additional arguments are
3635 concatenated with a space to the @var{string}.
3637 The expansion of @code{m4wrap} is void.
3638 The macro @code{m4wrap} is recognized only with parameters.
3639 @end deffn
3641 @example
3642 define(`cleanup', `This is the `cleanup' action.
3644 @result{}
3645 m4wrap(`cleanup')
3646 @result{}
3647 This is the first and last normal input line.
3648 @result{}This is the first and last normal input line.
3650 @result{}This is the cleanup action.
3651 @end example
3653 The saved input is only reread when the end of normal input is seen, and
3654 not if @code{m4exit} is used to exit @code{m4}.
3656 @comment FIXME: this contradicts POSIX, which requires that "If the
3657 @comment m4wrap macro is used multiple times, the arguments specified
3658 @comment shall be processed in the order in which the m4wrap macros were
3659 @comment processed."
3660 It is safe to call @code{m4wrap} from saved text, but then the order in
3661 which the saved text is reread is undefined.  If @code{m4wrap} is not used
3662 recursively, the saved pieces of text are reread in the opposite order
3663 in which they were saved (LIFO---last in, first out).  However, this
3664 behavior is likely to change in a future release, to match
3665 @acronym{POSIX}, so you should not depend on this order.
3667 Here is an example of implementing a factorial function using
3668 @code{m4wrap}:
3670 @example
3671 define(`f', `ifelse(`$1', `0', `Answer: 0!=1
3672 ', eval(`$1>1'), `0', `Answer: $2$1=eval(`$2$1')
3673 ', `m4wrap(`f(decr(`$1'), `$2$1*')')')')
3674 @result{}
3675 f(`10')
3676 @result{}
3678 @result{}Answer: 10*9*8*7*6*5*4*3*2*1=3628800
3679 @end example
3681 Invocations of @code{m4wrap} at the same recursion level are
3682 concatenated and rescanned as usual:
3684 @example
3685 define(`aa', `AA
3687 @result{}
3688 m4wrap(`a')m4wrap(`a')
3689 @result{}
3691 @result{}AA
3692 @end example
3694 @noindent
3695 however, the transition between recursion levels behaves like an end of
3696 file condition between two input files.
3698 @comment status: 1
3699 @example
3700 m4wrap(`m4wrap(`)')len(abc')
3701 @result{}
3703 @error{}m4:stdin:1: ERROR: end of file in argument list
3704 @end example
3706 @node File Inclusion
3707 @chapter File inclusion
3709 @cindex file inclusion
3710 @cindex inclusion, of files
3712 @code{m4} allows you to include named files at any point in the input.
3714 @menu
3715 * Include::                     Including named files
3716 * Search Path::                 Searching for include files
3717 @end menu
3719 @node Include
3720 @section Including named files
3722 There are two builtin macros in @code{m4} for including files:
3724 @deffn Builtin include (@var{file})
3725 @deffnx Builtin sinclude (@var{file})
3726 Both macros cause the file named @var{file} to be read by
3727 @code{m4}.  When the end of the file is reached, input is resumed from
3728 the previous input file.
3730 The expansion of @code{include} and @code{sinclude} is therefore the
3731 contents of @var{file}.
3733 If @var{file} does not exist (or cannot be read), the expansion is void,
3734 and @code{include} will fail with an error while @code{sinclude} is
3735 silent.  The empty string counts as a file that does not exist.
3737 The macros @code{include} and @code{sinclude} are recognized only with
3738 parameters.
3739 @end deffn
3741 @comment status: 1
3742 @example
3743 include(`none')
3744 @error{}m4:stdin:1: cannot open `none': No such file or directory
3745 @result{}
3746 include()
3747 @error{}m4:stdin:2: cannot open `': No such file or directory
3748 @result{}
3749 sinclude(`none')
3750 @result{}
3751 sinclude()
3752 @result{}
3753 @end example
3755 The rest of this section assumes that @code{m4} is invoked with the
3756 @option{-I} option (@pxref{Preprocessor features, , Invoking m4})
3757 pointing to the @file{m4-@value{VERSION}/@/examples}
3758 directory shipped as part of the @acronym{GNU} @code{m4} package.  The
3759 file @file{m4-@value{VERSION}/@/examples/@/incl.m4} in the distribution
3760 contains the lines:
3762 @comment ignore
3763 @example
3764 Include file start
3766 Include file end
3767 @end example
3769 Normally file inclusion is used to insert the contents of a file
3770 into the input stream.  The contents of the file will be read by
3771 @code{m4} and macro calls in the file will be expanded:
3773 @example
3774 define(`foo', `FOO')
3775 @result{}
3776 include(`incl.m4')
3777 @result{}Include file start
3778 @result{}FOO
3779 @result{}Include file end
3780 @result{}
3781 @end example
3783 The fact that @code{include} and @code{sinclude} expand to the contents
3784 of the file can be used to define macros that operate on entire files.
3785 Here is an example, which defines @samp{bar} to expand to the contents
3786 of @file{incl.m4}:
3788 @example
3789 define(`bar', include(`incl.m4'))
3790 @result{}
3791 This is `bar':  >>bar<<
3792 @result{}This is bar:  >>Include file start
3793 @result{}foo
3794 @result{}Include file end
3795 @result{}<<
3796 @end example
3798 This use of @code{include} is not trivial, though, as files can contain
3799 quotes, commas, and parentheses, which can interfere with the way the
3800 @code{m4} parser works.  @acronym{GNU} @code{m4} seamlessly concatenates
3801 the file contents with the next character, even if the included file
3802 ended in the middle of a comment, string, or macro call.  These
3803 conditions are only treated as end of file errors if specified as input
3804 files on the command line.
3806 In @acronym{GNU} @code{m4}, an alternative method of reading files is
3807 using @code{undivert} (@pxref{Undivert}) on a named file.
3809 @node Search Path
3810 @section Searching for include files
3812 @cindex search path for included files
3813 @cindex included files, search path for
3814 @cindex @acronym{GNU} extensions
3815 @acronym{GNU} @code{m4} allows included files to be found in other directories
3816 than the current working directory.
3818 If the @option{--prepend-include} or @option{-B} command-line option was
3819 provided (@pxref{Preprocessor features, , Invoking m4}), those
3820 directories are searched first, in reverse order that those options were
3821 listed on the command line.  Then @code{m4} looks in the current working
3822 directory.  Next comes the directories specified with the
3823 @option{--include} or @option{-I} option, in the order found on the
3824 command line.  Finally, if the @env{M4PATH} environment variable is set,
3825 it is expected to contain a colon-separated list of directories, which
3826 will be searched in order.
3828 If the automatic search for include-files causes trouble, the @samp{p}
3829 debug flag (@pxref{Debug Levels}) can help isolate the problem.
3831 @node Diversions
3832 @chapter Diverting and undiverting output
3834 Diversions are a way of temporarily saving output.  The output of
3835 @code{m4} can at any time be diverted to a temporary file, and be
3836 reinserted into the output stream, @dfn{undiverted}, again at a later
3837 time.
3839 Numbered diversions are counted from 0 upwards, diversion number 0
3840 being the normal output stream.  The number of simultaneous diversions
3841 is limited mainly by the memory used to describe them, because @acronym{GNU}
3842 @code{m4} tries to keep diversions in memory.  However, there is a
3843 limit to the overall memory usable by all diversions taken altogether
3844 (512K, currently).  When this maximum is about to be exceeded,
3845 a temporary file is opened to receive the contents of the biggest
3846 diversion still in memory, freeing this memory for other diversions.
3847 When creating the temporary file, @code{m4} honors the value of the
3848 environment variable @env{TMPDIR}, and falls back to @file{/tmp}.
3849 So, it is theoretically possible that the number and aggregate size of
3850 diversions is limited only by available disk space.
3852 @ignore
3853 @comment We need to test spilled diversions, but don't need to expose
3854 @comment this highly repetitive test in the manual.
3856 @example
3857 divert(`-1')define(`f', `.')
3858 define(`f', defn(`f')defn(`f'))
3859 define(`f', defn(`f')defn(`f'))
3860 define(`f', defn(`f')defn(`f'))
3861 define(`f', defn(`f')defn(`f'))
3862 define(`f', defn(`f')defn(`f'))
3863 define(`f', defn(`f')defn(`f'))
3864 define(`f', defn(`f')defn(`f'))
3865 define(`f', defn(`f')defn(`f'))
3866 define(`f', defn(`f')defn(`f'))
3867 define(`f', defn(`f')defn(`f'))
3868 define(`f', defn(`f')defn(`f'))
3869 define(`f', defn(`f')defn(`f'))
3870 define(`f', defn(`f')defn(`f'))
3871 define(`f', defn(`f')defn(`f'))
3872 define(`f', defn(`f')defn(`f'))
3873 define(`f', defn(`f')defn(`f'))
3874 define(`f', defn(`f')defn(`f'))
3875 define(`f', defn(`f')defn(`f'))
3876 define(`f', defn(`f')defn(`f'))
3877 define(`f', defn(`f')defn(`f'))
3878 divert`'dnl
3879 len(f)
3880 @result{}1048576
3881 divert(`1')
3883 divert(`-1')undivert
3884 @end example
3886 @comment Another test of spilled diversions.
3888 @example
3889 divert(`-1')define(`f', `.')
3890 define(`f', defn(`f')defn(`f'))
3891 define(`f', defn(`f')defn(`f'))
3892 define(`f', defn(`f')defn(`f'))
3893 define(`f', defn(`f')defn(`f'))
3894 define(`f', defn(`f')defn(`f'))
3895 define(`f', defn(`f')defn(`f'))
3896 define(`f', defn(`f')defn(`f'))
3897 define(`f', defn(`f')defn(`f'))
3898 define(`f', defn(`f')defn(`f'))
3899 define(`f', defn(`f')defn(`f'))
3900 define(`f', defn(`f')defn(`f'))
3901 define(`f', defn(`f')defn(`f'))
3902 define(`f', defn(`f')defn(`f'))
3903 define(`f', defn(`f')defn(`f'))
3904 define(`f', defn(`f')defn(`f'))
3905 define(`f', defn(`f')defn(`f'))
3906 define(`f', defn(`f')defn(`f'))
3907 define(`f', defn(`f')defn(`f'))
3908 define(`f', defn(`f')defn(`f'))
3909 define(`f', defn(`f')defn(`f'))
3910 divert`'dnl
3911 len(f)
3912 @result{}1048576
3913 divert(`1')
3915 m4exit
3916 @end example
3917 @end ignore
3919 Diversions make it possible to generate output in a different order than
3920 the input was read.  It is possible to implement topological sorting
3921 dependencies.  For example, @acronym{GNU} Autoconf makes use of
3922 diversions under the hood to ensure that the expansion of a prerequisite
3923 macro appears in the output prior to the expansion of a dependent macro,
3924 regardless of which order the two macros were invoked in the user's
3925 input file.
3927 @menu
3928 * Divert::                      Diverting output
3929 * Undivert::                    Undiverting output
3930 * Divnum::                      Diversion numbers
3931 * Cleardivert::                 Discarding diverted text
3932 @end menu
3934 @node Divert
3935 @section Diverting output
3937 @cindex diverting output to files
3938 @cindex output, diverting to files
3939 @cindex files, diverting output to
3940 Output is diverted using @code{divert}:
3942 @deffn Builtin divert (@dvar{number, 0})
3943 The current diversion is changed to @var{number}.  If @var{number} is left
3944 out or empty, it is assumed to be zero.  If @var{number} cannot be
3945 parsed, the diversion is unchanged.
3947 The expansion of @code{divert} is void.
3948 @end deffn
3950 When all the @code{m4} input will have been processed, all existing
3951 diversions are automatically undiverted, in numerical order.
3953 @example
3954 divert(`1')
3955 This text is diverted.
3956 divert
3957 @result{}
3958 This text is not diverted.
3959 @result{}This text is not diverted.
3961 @result{}
3962 @result{}This text is diverted.
3963 @end example
3965 Several calls of @code{divert} with the same argument do not overwrite
3966 the previous diverted text, but append to it.  Diversions are printed
3967 after any wrapped text is expanded.
3969 @example
3970 define(`text', `TEXT')
3971 @result{}
3972 divert(`1')`diverted text.'
3973 divert
3974 @result{}
3975 m4wrap(`Wrapped text precedes ')
3976 @result{}
3978 @result{}Wrapped TEXT precedes diverted text.
3979 @end example
3981 If output is diverted to a negative diversion, it is simply discarded.
3982 This can be used to suppress unwanted output.  A common example of
3983 unwanted output is the trailing newlines after macro definitions.  Here
3984 is a common programming idiom in @code{m4} for avoiding them.
3986 @example
3987 divert(`-1')
3988 define(`foo', `Macro `foo'.')
3989 define(`bar', `Macro `bar'.')
3990 divert
3991 @result{}
3992 @end example
3994 @cindex @acronym{GNU} extensions
3995 Traditional implementations only supported ten diversions.  But as a
3996 @acronym{GNU} extension, diversion numbers can be as large as positive
3997 integers will allow, rather than treating a multi-digit diversion number
3998 as a request to discard text.
4000 @example
4001 divert(eval(`1<<28'))world
4002 divert(`2')hello
4004 @result{}hello
4005 @result{}world
4006 @end example
4008 Note that @code{divert} is an English word, but also an active macro
4009 without arguments.  When processing plain text, the word might appear in
4010 normal text and be unintentionally swallowed as a macro invocation.  One
4011 way to avoid this is to use the @option{-P} option to rename all
4012 builtins (@pxref{Operation modes, , Invoking m4}).  Another is to write
4013 a wrapper that requires a parameter to be recognized.
4015 @example
4016 We decided to divert the stream for irrigation.
4017 @result{}We decided to  the stream for irrigation.
4018 define(`divert', `ifelse(`$#', `0', ``$0'', `builtin(`$0', $@@)')')
4019 @result{}
4020 divert(`-1')
4021 Ignored text.
4022 divert(`0')
4023 @result{}
4024 We decided to divert the stream for irrigation.
4025 @result{}We decided to divert the stream for irrigation.
4026 @end example
4028 @node Undivert
4029 @section Undiverting output
4031 Diverted text can be undiverted explicitly using the builtin
4032 @code{undivert}:
4034 @deffn Builtin undivert (@ovar{diversions@dots{}})
4035 Undiverts the numeric @var{diversions} given by the arguments, in the
4036 order given.  If no arguments are supplied, all diversions are
4037 undiverted, in numerical order.
4039 As a @acronym{GNU} extension, @var{diversions} may contain non-numeric
4040 strings, which are treated as the names of files to copy into the output
4041 without expansion.  A warning is issued if a file could not be opened.
4043 The expansion of @code{undivert} is void.
4044 @end deffn
4046 @example
4047 divert(`1')
4048 This text is diverted.
4049 divert
4050 @result{}
4051 This text is not diverted.
4052 @result{}This text is not diverted.
4053 undivert(`1')
4054 @result{}
4055 @result{}This text is diverted.
4056 @result{}
4057 @end example
4059 Notice the last two blank lines.  One of them comes from the newline
4060 following @code{undivert}, the other from the newline that followed the
4061 @code{divert}!  A diversion often starts with a blank line like this.
4063 When diverted text is undiverted, it is @emph{not} reread by @code{m4},
4064 but rather copied directly to the current output, and it is therefore
4065 not an error to undivert into a diversion.  Undiverting the empty string
4066 is the same as specifying diversion 0; in either case nothing happens
4067 since the output has already been flushed.
4069 @example
4070 divert(`1')diverted text
4071 divert
4072 @result{}
4073 undivert()
4074 @result{}
4075 undivert(`0')
4076 @result{}
4077 undivert
4078 @result{}diverted text
4079 @result{}
4080 @end example
4082 When a diversion has been undiverted, the diverted text is discarded,
4083 and it is not possible to bring back diverted text more than once.
4085 @example
4086 divert(`1')
4087 This text is diverted first.
4088 divert(`0')undivert(`1')dnl
4089 @result{}
4090 @result{}This text is diverted first.
4091 undivert(`1')
4092 @result{}
4093 divert(`1')
4094 This text is also diverted but not appended.
4095 divert(`0')undivert(`1')dnl
4096 @result{}
4097 @result{}This text is also diverted but not appended.
4098 @end example
4100 Attempts to undivert the current diversion are silently ignored.  Thus,
4101 when the current diversion is not 0, the current diversion does not get
4102 rearranged among the other diversions.
4104 @example
4105 divert(`1')one
4106 divert(`2')two
4107 divert(`3')three
4108 divert(`2')undivert`'dnl
4109 divert`'undivert`'dnl
4110 @result{}two
4111 @result{}one
4112 @result{}three
4113 @end example
4115 @cindex @acronym{GNU} extensions
4116 @cindex file inclusion
4117 @cindex inclusion, of files
4118 @acronym{GNU} @code{m4} allows named files to be undiverted.  Given a
4119 non-numeric
4120 argument, the contents of the file named will be copied, uninterpreted, to
4121 the current output.  This complements the builtin @code{include}
4122 (@pxref{Include}).  To illustrate the difference, the file
4123 @file{m4-@value{VERSION}/@/examples/@/foo} contains the word @samp{bar}:
4125 @example
4126 define(`bar', `BAR')
4127 @result{}
4128 undivert(`foo')
4129 @result{}bar
4130 @result{}
4131 include(`foo')
4132 @result{}BAR
4133 @result{}
4134 @end example
4136 If the file is not found (or cannot be read), an error message is
4137 issued, and the expansion is void.
4139 @node Divnum
4140 @section Diversion numbers
4142 @cindex diversion numbers
4143 The current diversion is tracked by the builtin @code{divnum}:
4145 @deffn Builtin divnum
4146 Expands to the number of the current diversion.
4147 @end deffn
4149 @example
4150 Initial divnum
4151 @result{}Initial 0
4152 divert(`1')
4153 Diversion one: divnum
4154 divert(`2')
4155 Diversion two: divnum
4157 @result{}
4158 @result{}Diversion one: 1
4159 @result{}
4160 @result{}Diversion two: 2
4161 @end example
4163 @node Cleardivert
4164 @section Discarding diverted text
4166 @cindex discarding diverted text
4167 @cindex diverted text, discarding
4168 Often it is not known, when output is diverted, whether the diverted
4169 text is actually needed.  Since all non-empty diversion are brought back
4170 on the main output stream when the end of input is seen, a method of
4171 discarding a diversion is needed.  If all diversions should be
4172 discarded, the easiest is to end the input to @code{m4} with
4173 @samp{divert(`-1')} followed by an explicit @samp{undivert}:
4175 @example
4176 divert(`1')
4177 Diversion one: divnum
4178 divert(`2')
4179 Diversion two: divnum
4180 divert(`-1')
4181 undivert
4183 @end example
4185 @noindent
4186 No output is produced at all.
4188 Clearing selected diversions can be done with the following macro:
4190 @deffn Composite cleardivert (@ovar{diversions@dots{}})
4191 Discard the contents of each of the listed numeric @var{diversions}.
4192 @end deffn
4194 @example
4195 define(`cleardivert',
4196 `pushdef(`_n', divnum)divert(`-1')undivert($@@)divert(_n)popdef(`_n')')
4197 @result{}
4198 @end example
4200 It is called just like @code{undivert}, but the effect is to clear the
4201 diversions, given by the arguments.  (This macro has a nasty bug!  You
4202 should try to see if you can find it and correct it; or @pxref{Improved
4203 cleardivert, , Answers}).
4205 @node Text handling
4206 @chapter Macros for text handling
4208 There are a number of builtins in @code{m4} for manipulating text in
4209 various ways, extracting substrings, searching, substituting, and so on.
4211 @menu
4212 * Len::                         Calculating length of strings
4213 * Index macro::                 Searching for substrings
4214 * Regexp::                      Searching for regular expressions
4215 * Substr::                      Extracting substrings
4216 * Translit::                    Translating characters
4217 * Patsubst::                    Substituting text by regular expression
4218 * Format::                      Formatting strings (printf-like)
4219 @end menu
4221 @node Len
4222 @section Calculating length of strings
4224 @cindex length of strings
4225 @cindex strings, length of
4226 The length of a string can be calculated by @code{len}:
4228 @deffn Builtin len (@var{string})
4229 Expands to the length of @var{string}, as a decimal number.
4231 The macro @code{len} is recognized only with parameters.
4232 @end deffn
4234 @example
4235 len()
4236 @result{}0
4237 len(`abcdef')
4238 @result{}6
4239 @end example
4241 @node Index macro
4242 @section Searching for substrings
4244 Searching for substrings is done with @code{index}:
4246 @deffn Builtin index (@var{string}, @var{substring})
4247 Expands to the index of the first occurrence of @var{substring} in
4248 @var{string}.  The first character in @var{string} has index 0.  If
4249 @var{substring} does not occur in @var{string}, @code{index} expands to
4250 @samp{-1}.
4252 The macro @code{index} is recognized only with parameters.
4253 @end deffn
4255 @example
4256 index(`gnus, gnats, and armadillos', `nat')
4257 @result{}7
4258 index(`gnus, gnats, and armadillos', `dag')
4259 @result{}-1
4260 @end example
4262 Omitting @var{substring} evokes a warning, but still produces output.
4264 @example
4265 index(`abc')
4266 @error{}m4:stdin:1: Warning: too few arguments to builtin `index'
4267 @result{}0
4268 @end example
4270 @node Regexp
4271 @section Searching for regular expressions
4273 @cindex regular expressions
4274 @cindex @acronym{GNU} extensions
4275 Searching for regular expressions is done with the builtin
4276 @code{regexp}:
4278 @deffn Builtin regexp (@var{string}, @var{regexp}, @ovar{replacement})
4279 Searches for @var{regexp} in @var{string}.  The syntax for regular
4280 expressions is the same as in @acronym{GNU} Emacs.
4281 @ifnothtml
4282 @xref{Regexps, , Syntax of Regular Expressions, emacs, The GNU Emacs
4283 Manual}.
4284 @end ifnothtml
4285 @ifhtml
4287 @uref{http://www.gnu.org/@/software/@/emacs/@/manual/@/emacs.html#Regexps,
4288 Syntax of Regular Expressions} in the @acronym{GNU} Emacs Manual.
4289 @end ifhtml
4291 If @var{replacement} is omitted, @code{regexp} expands to the index of
4292 the first match of @var{regexp} in @var{string}.  If @var{regexp} does
4293 not match anywhere in @var{string}, it expands to -1.
4295 If @var{replacement} is supplied, and there was a match, @code{regexp}
4296 changes the expansion to this argument, with @samp{\@var{n}} substituted
4297 by the text matched by the @var{n}th parenthesized sub-expression of
4298 @var{regexp}, up to nine sub-expressions.  The escape @samp{\&} is
4299 replaced by the text of the entire regular expression matched.  For
4300 all other characters, @samp{\} treats the next character literally.  A
4301 warning is issued if there were fewer sub-expressions than the
4302 @samp{\@var{n}} requested, or if there is a trailing @samp{\}.  If there
4303 was no match, @code{regexp} expands to the empty string.
4305 The macro @code{regexp} is recognized only with parameters.
4306 @end deffn
4308 @example
4309 regexp(`GNUs not Unix', `\<[a-z]\w+')
4310 @result{}5
4311 regexp(`GNUs not Unix', `\<Q\w*')
4312 @result{}-1
4313 regexp(`GNUs not Unix', `\w\(\w+\)$', `*** \& *** \1 ***')
4314 @result{}*** Unix *** nix ***
4315 regexp(`GNUs not Unix', `\<Q\w*', `*** \& *** \1 ***')
4316 @result{}
4317 @end example
4319 Here are some more examples on the handling of backslash:
4321 @example
4322 regexp(`abc', `\(b\)', `\\\10\a')
4323 @result{}\b0a
4324 regexp(`abc', `b', `\1\')
4325 @error{}m4:stdin:2: Warning: sub-expression 1 not present
4326 @error{}m4:stdin:2: Warning: trailing \ ignored in replacement
4327 @result{}
4328 regexp(`abc', `\(\(d\)?\)\(c\)', `\1\2\3\4\5\6')
4329 @error{}m4:stdin:3: Warning: sub-expression 4 not present
4330 @error{}m4:stdin:3: Warning: sub-expression 5 not present
4331 @error{}m4:stdin:3: Warning: sub-expression 6 not present
4332 @result{}c
4333 @end example
4335 Omitting @var{regexp} evokes a warning, but still produces output.
4337 @example
4338 regexp(`abc')
4339 @error{}m4:stdin:1: Warning: too few arguments to builtin `regexp'
4340 @result{}0
4341 @end example
4343 @node Substr
4344 @section Extracting substrings
4346 @cindex extracting substrings
4347 @cindex substrings, extracting
4348 Substrings are extracted with @code{substr}:
4350 @deffn Builtin substr (@var{string}, @var{from}, @ovar{length})
4351 Expands to the substring of @var{string}, which starts at index
4352 @var{from}, and extends for @var{length} characters, or to the end of
4353 @var{string}, if @var{length} is omitted.  The starting index of a string
4354 is always 0.  The expansion is empty if there is an error parsing
4355 @var{from} or @var{length}, if @var{from} is beyond the end of
4356 @var{string}, or if @var{length} is negative.
4358 The macro @code{substr} is recognized only with parameters.
4359 @end deffn
4361 @example
4362 substr(`gnus, gnats, and armadillos', `6')
4363 @result{}gnats, and armadillos
4364 substr(`gnus, gnats, and armadillos', `6', `5')
4365 @result{}gnats
4366 @end example
4368 Omitting @var{from} evokes a warning, but still produces output.
4370 @example
4371 substr(`abc')
4372 @error{}m4:stdin:1: Warning: too few arguments to builtin `substr'
4373 @result{}abc
4374 substr(`abc',)
4375 @error{}m4:stdin:2: empty string treated as 0 in builtin `substr'
4376 @result{}abc
4377 @end example
4379 @node Translit
4380 @section Translating characters
4382 @cindex translating characters
4383 @cindex characters, translating
4384 Character translation is done with @code{translit}:
4386 @deffn Builtin translit (@var{string}, @var{chars}, @ovar{replacement})
4387 Expands to @var{string}, with each character that occurs in
4388 @var{chars} translated into the character from @var{replacement} with
4389 the same index.
4391 If @var{replacement} is shorter than @var{chars}, the excess characters
4392 of @var{chars} are deleted from the expansion; if @var{chars} is
4393 shorter, the excess characters in @var{replacement} are silently
4394 ignored.  If @var{replacement} is omitted, all characters in
4395 @var{string} that are present in @var{chars} are deleted from the
4396 expansion.  If a character appears more than once in @var{chars}, only
4397 the first instance is used in making the translation.  Only a single
4398 translation pass is made, even if characters in @var{replacement} also
4399 appear in @var{chars}.
4401 As a @acronym{GNU} extension, both @var{chars} and @var{replacement} can
4402 contain character-ranges, e.g., @samp{a-z} (meaning all lowercase
4403 letters) or @samp{0-9} (meaning all digits).  To include a dash @samp{-}
4404 in @var{chars} or @var{replacement}, place it first or last in the
4405 entire string, or as the last character of a range.  Back-to-back ranges
4406 can share a common endpoint.  It is not an error for the last character
4407 in the range to be `larger' than the first.  In that case, the range
4408 runs backwards, i.e., @samp{9-0} means the string @samp{9876543210}.
4409 The expansion of a range is dependent on the underlying encoding of
4410 characters, so using ranges is not always portable between machines.
4412 The macro @code{translit} is recognized only with parameters.
4413 @end deffn
4415 @example
4416 translit(`GNUs not Unix', `A-Z')
4417 @result{}s not nix
4418 translit(`GNUs not Unix', `a-z', `A-Z')
4419 @result{}GNUS NOT UNIX
4420 translit(`GNUs not Unix', `A-Z', `z-a')
4421 @result{}tmfs not fnix
4422 translit(`+,-12345', `+--1-5', `<;>a-c-a')
4423 @result{}<;>abcba
4424 translit(`abcdef', `aabdef', `bcged')
4425 @result{}bgced
4426 @end example
4428 In the @sc{ascii} encoding, the first example deletes all uppercase
4429 letters, the second converts lowercase to uppercase, and the third
4430 `mirrors' all uppercase letters, while converting them to lowercase.
4431 The two first cases are by far the most common, even though they are not
4432 portable to @sc{ebcdic} or other encodings.  The fourth example shows a
4433 range ending in @samp{-}, as well as back-to-back ranges.  The final
4434 example shows that @samp{a} is mapped to @samp{b}, not @samp{c}; the
4435 resulting @samp{b} is not further remapped to @samp{g}; the @samp{d} and
4436 @samp{e} are swapped, and the @samp{f} is discarded.
4438 @ignore
4439 @comment No need to fight 8-bit characters, as it is difficult to get
4440 @comment rendering right in both info and dvi.
4442 @example
4443 translit(`«abc~', `~-»')
4444 @result{}abc
4445 @end example
4446 @end ignore
4448 Omitting @var{chars} evokes a warning, but still produces output.
4450 @example
4451 translit(`abc')
4452 @error{}m4:stdin:1: Warning: too few arguments to builtin `translit'
4453 @result{}abc
4454 @end example
4456 @node Patsubst
4457 @section Substituting text by regular expression
4459 @cindex regular expressions
4460 @cindex pattern substitution
4461 @cindex substitution by regular expression
4462 @cindex @acronym{GNU} extensions
4463 Global substitution in a string is done by @code{patsubst}:
4465 @deffn Builtin patsubst (@var{string}, @var{regexp}, @ovar{replacement})
4466 Searches @var{string} for matches of @var{regexp}, and substitutes
4467 @var{replacement} for each match.  The syntax for regular expressions
4468 is the same as in @acronym{GNU} Emacs (@pxref{Regexp}).
4470 The parts of @var{string} that are not covered by any match of
4471 @var{regexp} are copied to the expansion.  Whenever a match is found, the
4472 search proceeds from the end of the match, so a character from
4473 @var{string} will never be substituted twice.  If @var{regexp} matches a
4474 string of zero length, the start position for the search is incremented,
4475 to avoid infinite loops.
4477 When a replacement is to be made, @var{replacement} is inserted into
4478 the expansion, with @samp{\@var{n}} substituted by the text matched by
4479 the @var{n}th parenthesized sub-expression of @var{patsubst}, for up to
4480 nine sub-expressions.  The escape @samp{\&} is replaced by the text of
4481 the entire regular expression matched.  For all other characters,
4482 @samp{\} treats the next character literally.  A warning is issued if
4483 there were fewer sub-expressions than the @samp{\@var{n}} requested, or
4484 if there is a trailing @samp{\}.
4486 The @var{replacement} argument can be omitted, in which case the text
4487 matched by @var{regexp} is deleted.
4489 The macro @code{patsubst} is recognized only with parameters.
4490 @end deffn
4492 @example
4493 patsubst(`GNUs not Unix', `^', `OBS: ')
4494 @result{}OBS: GNUs not Unix
4495 patsubst(`GNUs not Unix', `\<', `OBS: ')
4496 @result{}OBS: GNUs OBS: not OBS: Unix
4497 patsubst(`GNUs not Unix', `\w*', `(\&)')
4498 @result{}(GNUs)() (not)() (Unix)()
4499 patsubst(`GNUs not Unix', `\w+', `(\&)')
4500 @result{}(GNUs) (not) (Unix)
4501 patsubst(`GNUs not Unix', `[A-Z][a-z]+')
4502 @result{}GN not@w{ }
4503 patsubst(`GNUs not Unix', `not', `NOT\')
4504 @error{}m4:stdin:6: Warning: trailing \ ignored in replacement
4505 @result{}GNUs NOT Unix
4506 @end example
4508 Here is a slightly more realistic example, which capitalizes individual
4509 words or whole sentences, by substituting calls of the macros
4510 @code{upcase} and @code{downcase} into the strings.
4512 @deffn Composite upcase (@var{text})
4513 @deffnx Composite downcase (@var{text})
4514 @deffnx Composite capitalize (@var{text})
4515 Expand to @var{text}, but with capitalization changed: @code{upcase}
4516 changes all letters to upper case, @code{downcase} changes all letters
4517 to lower case, and @code{capitalize} changes the first character of each
4518 word to upper case and the remaining characters to lower case.
4519 @end deffn
4521 @example
4522 define(`upcase', `translit(`$*', `a-z', `A-Z')')dnl
4523 define(`downcase', `translit(`$*', `A-Z', `a-z')')dnl
4524 define(`capitalize1',
4525        `regexp(`$1', `^\(\w\)\(\w*\)',
4526                `upcase(`\1')`'downcase(`\2')')')dnl
4527 define(`capitalize',
4528        `patsubst(`$1', `\w+', `capitalize1(`\&')')')dnl
4529 capitalize(`GNUs not Unix')
4530 @result{}Gnus Not Unix
4531 @end example
4533 While @code{regexp} replaces the whole input with the replacement as
4534 soon as there is a match, @code{patsubst} replaces each
4535 @emph{occurrence} of a match and preserves non-matching pieces:
4537 @example
4538 define(`patreg',
4539 `patsubst($@@)
4540 regexp($@@)')dnl
4541 patreg(`bar foo baz Foo', `foo\|Foo', `FOO')
4542 @result{}bar FOO baz FOO
4543 @result{}FOO
4544 patreg(`aba abb 121', `\(.\)\(.\)\1', `\2\1\2')
4545 @result{}bab abb 212
4546 @result{}bab
4547 @end example
4549 Omitting @var{regexp} evokes a warning, but still produces output.
4551 @example
4552 patsubst(`abc')
4553 @error{}m4:stdin:1: Warning: too few arguments to builtin `patsubst'
4554 @result{}abc
4555 @end example
4557 @node Format
4558 @section Formatting strings (printf-like)
4560 @cindex formatted output
4561 @cindex output, formatted
4562 @cindex @acronym{GNU} extensions
4563 Formatted output can be made with @code{format}:
4565 @deffn Builtin format (@var{format-string}, @dots{})
4566 Works much like the C function @code{printf}.  The first argument
4567 @var{format-string} can contain @samp{%} specifications which are
4568 satisfied by additional arguments, and the expansion of @code{format} is
4569 the formatted string.
4571 The macro @code{format} is recognized only with parameters.
4572 @end deffn
4574 Its use is best described by a few examples:
4576 @example
4577 define(`foo', `The brown fox jumped over the lazy dog')
4578 @result{}
4579 format(`The string "%s" uses %d characters', foo, len(foo))
4580 @result{}The string "The brown fox jumped over the lazy dog" uses 38 characters
4581 format(`%.0f', `56789.9876')
4582 @result{}56790
4583 len(format(`%-*X', `300', `1'))
4584 @result{}300
4585 @end example
4587 Using the @code{forloop} macro defined earlier (@pxref{Forloop}), this
4588 example shows how @code{format} can be used to produce tabular output.
4590 @example
4591 include(`forloop.m4')
4592 @result{}
4593 forloop(`i', `1', `10', `format(`%6d squared is %10d
4594 ', i, eval(i**2))')
4595 @result{}     1 squared is          1
4596 @result{}     2 squared is          4
4597 @result{}     3 squared is          9
4598 @result{}     4 squared is         16
4599 @result{}     5 squared is         25
4600 @result{}     6 squared is         36
4601 @result{}     7 squared is         49
4602 @result{}     8 squared is         64
4603 @result{}     9 squared is         81
4604 @result{}    10 squared is        100
4605 @result{}
4606 @end example
4608 The builtin @code{format} is modeled after the ANSI C @samp{printf}
4609 function, and supports these @samp{%} specifiers: @samp{c},
4610 @samp{s}, @samp{d}, @samp{o}, @samp{x}, @samp{X}, @samp{u}, @samp{e},
4611 @samp{E}, @samp{f}, @samp{F}, @samp{g}, @samp{G}, and @samp{%}; it
4612 supports field widths and precisions, and the
4613 modifiers @samp{+}, @samp{-}, @samp{@w{ }}, @samp{0}, @samp{#}, @samp{h} and
4614 @samp{l}.  For more details on the functioning of @code{printf}, see the
4615 C Library Manual.
4617 For now, unrecognized specifiers are silently ignored, but it is
4618 anticipated that a future release of @acronym{GNU} @code{m4} will support more
4619 specifiers, and give warnings when problems are encountered.  Likewise,
4620 escape sequences are not yet recognized.
4622 @node Arithmetic
4623 @chapter Macros for doing arithmetic
4625 @cindex arithmetic
4626 @cindex integer arithmetic
4627 Integer arithmetic is included in @code{m4}, with a C-like syntax.  As
4628 convenient shorthands, there are builtins for simple increment and
4629 decrement operations.
4631 @menu
4632 * Incr::                        Decrement and increment operators
4633 * Eval::                        Evaluating integer expressions
4634 @end menu
4636 @node Incr
4637 @section Decrement and increment operators
4639 @cindex decrement operator
4640 @cindex increment operator
4641 Increment and decrement of integers are supported using the builtins
4642 @code{incr} and @code{decr}:
4644 @deffn Builtin incr (@var{number})
4645 @deffnx Builtin decr (@var{number})
4646 Expand to the numerical value of @var{number}, incremented
4647 or decremented, respectively, by one.  Except for the empty string, the
4648 expansion is empty if @var{number} could not be parsed.
4650 The macros @code{incr} and @code{decr} are recognized only with
4651 parameters.
4652 @end deffn
4654 @example
4655 incr(`4')
4656 @result{}5
4657 decr(`7')
4658 @result{}6
4659 incr()
4660 @error{}m4:stdin:3: empty string treated as 0 in builtin `incr'
4661 @result{}1
4662 decr()
4663 @error{}m4:stdin:4: empty string treated as 0 in builtin `decr'
4664 @result{}-1
4665 @end example
4667 @node Eval
4668 @section Evaluating integer expressions
4670 @cindex integer expression evaluation
4671 @cindex evaluation, of integer expressions
4672 @cindex expressions, evaluation of integer
4673 Integer expressions are evaluated with @code{eval}:
4675 @deffn Builtin eval (@var{expression}, @dvar{radix, 10}, @ovar{width})
4676 Expands to the value of @var{expression}.  The expansion is empty
4677 if a problem is encountered while parsing the arguments.  If specified,
4678 @var{radix} and @var{width} control the format of the output.
4680 Calculations are done with 32-bit signed numbers.  Overflow silently
4681 results in wraparound.  A warning is issued if division by zero is
4682 attempted, or if @var{expression} could not be parsed.
4684 Expressions can contain the following operators, listed in order of
4685 decreasing precedence.
4687 @table @samp
4688 @item ()
4689 Parentheses
4690 @item +  -  ~  !
4691 Unary plus and minus, and bitwise and logical negation
4692 @item **
4693 Exponentiation
4694 @item *  /  %
4695 Multiplication, division, and modulo
4696 @item +  -
4697 Addition and subtraction
4698 @item <<  >>
4699 Shift left or right
4700 @item >  >=  <  <=
4701 Relational operators
4702 @item ==  !=
4703 Equality operators
4704 @item &
4705 Bitwise and
4706 @item ^
4707 Bitwise exclusive-or
4708 @item |
4709 Bitwise or
4710 @item &&
4711 Logical and
4712 @item ||
4713 Logical or
4714 @end table
4716 The macro @code{eval} is recognized only with parameters.
4717 @end deffn
4719 All binary operators, except exponentiation, are left associative.  C
4720 operators that perform variable assignment, such as @samp{+=} or
4721 @samp{--}, are forbidden by @acronym{POSIX}, since @code{eval} only
4722 operates on constants, not variables.  Attempting to use them results
4723 in an error.  However, since traditional implementations treated
4724 @samp{=} as an undocumented alias for @samp{==} as opposed to an
4725 assignment operator, this usage is supported as a special case.  Be
4726 aware that a future version of @acronym{GNU} M4 may support assignment
4727 semantics as an extension when @acronym{POSIX} mode is not requested,
4728 and that using @samp{=} to check equality is not portable.
4730 @comment status: 1
4731 @example
4732 eval(`2 = 2')
4733 @error{}m4:stdin:1: Warning: recommend ==, not =, for equality operator
4734 @result{}1
4735 eval(`++0')
4736 @error{}m4:stdin:2: invalid operator in eval: ++0
4737 @result{}
4738 eval(`0 |= 1')
4739 @error{}m4:stdin:3: invalid operator in eval: 0 |= 1
4740 @result{}
4741 @end example
4743 Note that some older @code{m4} implementations use @samp{^} as an
4744 alternate operator for the exponentiation, although @acronym{POSIX}
4745 requires the C behavior of bitwise exclusive-or.  The precedence of the
4746 negation operators, @samp{~} and @samp{!}, was traditionally lower than
4747 equality.  The unary operators could not be used reliably more than once
4748 on the same term without intervening parentheses.  The traditional
4749 precedence of the equality operators @samp{==} and @samp{!=} was
4750 identical instead of lower than the relational operators such as
4751 @samp{<}, even through @acronym{GNU} M4 1.4.8.  Starting with version
4752 1.4.9, @acronym{GNU} M4 correctly follows @acronym{POSIX} precedence
4753 rules.  M4 scripts designed to be portable between releases must be
4754 aware that parentheses may be required to enforce C precedence rules.
4755 Likewise, division by zero, even in the unused branch of a
4756 short-circuiting operator, is not always well-defined in other
4757 implementations.
4759 Following are some examples where the current version of M4 follows C
4760 precedence rules, but where older versions and some other
4761 implementations of @code{m4} require explicit parentheses to get the
4762 correct result:
4764 @example
4765 eval(`1 == 2 > 0')
4766 @result{}1
4767 eval(`(1 == 2) > 0')
4768 @result{}0
4769 eval(`! 0 * 2')
4770 @result{}2
4771 eval(`! (0 * 2)')
4772 @result{}1
4773 eval(`1 | 1 ^ 1')
4774 @result{}1
4775 eval(`(1 | 1) ^ 1')
4776 @result{}0
4777 eval(`+ + - ~ ! ~ 0')
4778 @result{}1
4779 eval(`2 || 1 / 0')
4780 @result{}1
4781 eval(`0 || 1 / 0')
4782 @error{}m4:stdin:9: divide by zero in eval: 0 || 1 / 0
4783 @result{}
4784 eval(`0 && 1 % 0')
4785 @result{}0
4786 eval(`2 && 1 % 0')
4787 @error{}m4:stdin:11: modulo by zero in eval: 2 && 1 % 0
4788 @result{}
4789 @end example
4791 @cindex @acronym{GNU} extensions
4792 As a @acronym{GNU} extension, the operator @samp{**} performs integral
4793 exponentiation.  The operator is right-associative, and if evaluated,
4794 the exponent must be non-negative, and at least one of the arguments
4795 must be non-zero, or a warning is issued.
4797 @example
4798 eval(`2 ** 3 ** 2')
4799 @result{}512
4800 eval(`(2 ** 3) ** 2')
4801 @result{}64
4802 eval(`0 ** 1')
4803 @result{}0
4804 eval(`2 ** 0')
4805 @result{}1
4806 eval(`0 ** 0')
4807 @result{}
4808 @error{}m4:stdin:5: divide by zero in eval: 0 ** 0
4809 eval(`4 ** -2')
4810 @error{}m4:stdin:6: negative exponent in eval: 4 ** -2
4811 @result{}
4812 @end example
4814 Within @var{expression}, (but not @var{radix} or @var{width}), numbers
4815 without a special prefix are decimal.  A simple @samp{0} prefix
4816 introduces an octal number.  @samp{0x} introduces a hexadecimal number.
4817 As @acronym{GNU} extensions, @samp{0b} introduces a binary number.
4818 @samp{0r} introduces a number expressed in any radix between 1 and 36:
4819 the prefix should be immediately followed by the decimal expression of
4820 the radix, a colon, then the digits making the number.  For radix 1,
4821 leading zeros are ignored, and all remaining digits must be @samp{1};
4822 for all other radices, the digits are @samp{0}, @samp{1}, @samp{2},
4823 @dots{}.  Beyond @samp{9}, the digits are @samp{a}, @samp{b} @dots{} up
4824 to @samp{z}.  Lower and upper case letters can be used interchangeably
4825 in numbers prefixes and as number digits.
4827 Parentheses may be used to group subexpressions whenever needed.  For the
4828 relational operators, a true relation returns @code{1}, and a false
4829 relation return @code{0}.
4831 Here are a few examples of use of @code{eval}.
4833 @example
4834 eval(`-3 * 5')
4835 @result{}-15
4836 eval(index(`Hello world', `llo') >= 0)
4837 @result{}1
4838 eval(`0r1:0111 + 0b100 + 0r3:12')
4839 @result{}12
4840 define(`square', `eval(`($1) ** 2')')
4841 @result{}
4842 square(`9')
4843 @result{}81
4844 square(square(`5')` + 1')
4845 @result{}676
4846 define(`foo', `666')
4847 @result{}
4848 eval(`foo / 6')
4849 @error{}m4:stdin:8: bad expression in eval: foo / 6
4850 @result{}
4851 eval(foo / 6)
4852 @result{}111
4853 @end example
4855 As the last two lines show, @code{eval} does not handle macro
4856 names, even if they expand to a valid expression (or part of a valid
4857 expression).  Therefore all macros must be expanded before they are
4858 passed to @code{eval}.
4860 Some calculations are not portable to other implementations, since they
4861 have undefined semantics in C, but @acronym{GNU} @code{m4} has
4862 well-defined behavior on overflow.  When shifting, an out-of-range shift
4863 amount is implicitly brought into the range of 32-bit signed integers
4864 using an implicit bit-wise and with 0x1f).
4866 @example
4867 define(`max_int', eval(`0x7fffffff'))
4868 @result{}
4869 define(`min_int', incr(max_int))
4870 @result{}
4871 eval(min_int` < 0')
4872 @result{}1
4873 eval(max_int` > 0')
4874 @result{}1
4875 ifelse(eval(min_int` / -1'), min_int, `overflow occurred')
4876 @result{}overflow occurred
4877 min_int
4878 @result{}-2147483648
4879 eval(`0x80000000 % -1')
4880 @result{}0
4881 eval(`-4 >> 1')
4882 @result{}-2
4883 eval(`-4 >> 33')
4884 @result{}-2
4885 @end example
4887 If @var{radix} is specified, it specifies the radix to be used in the
4888 expansion.  The default radix is 10; this is also the case if
4889 @var{radix} is the empty string.  A warning results if the radix is
4890 outside the range of 1 through 36, inclusive.  The result of @code{eval}
4891 is always taken to be signed.  No radix prefix is output, and for
4892 radices greater than 10, the digits are lower case.  The @var{width}
4893 argument specifies the minimum output width, excluding any negative
4894 sign.  The result is zero-padded to extend the expansion to the
4895 requested width.  A warning results if the width is negative.  If
4896 @var{radix} or @var{width} is out of bounds, the expansion of
4897 @code{eval} is empty.
4899 @example
4900 eval(`666', `10')
4901 @result{}666
4902 eval(`666', `11')
4903 @result{}556
4904 eval(`666', `6')
4905 @result{}3030
4906 eval(`666', `6', `10')
4907 @result{}0000003030
4908 eval(`-666', `6', `10')
4909 @result{}-0000003030
4910 eval(`10', `', `0')
4911 @result{}10
4912 `0r1:'eval(`10', `1', `11')
4913 @result{}0r1:01111111111
4914 eval(`10', `16')
4915 @result{}a
4916 eval(`1', `37')
4917 @error{}m4:stdin:9: radix 37 in builtin `eval' out of range
4918 @result{}
4919 eval(`1', , `-1')
4920 @error{}m4:stdin:10: negative width to builtin `eval'
4921 @result{}
4922 eval()
4923 @error{}m4:stdin:11: empty string treated as 0 in builtin `eval'
4924 @result{}0
4925 @end example
4927 @node Shell commands
4928 @chapter Macros for running shell commands
4930 @cindex executing UNIX commands
4931 @cindex running UNIX commands
4932 @cindex UNIX commands, running
4933 @cindex commands, running UNIX
4934 @cindex executing shell commands
4935 @cindex running shell commands
4936 @cindex shell commands, running
4937 @cindex commands, running shell
4938 There are a few builtin macros in @code{m4} that allow you to run shell
4939 commands from within @code{m4}.
4941 Note that the definition of a valid shell command is system dependent.
4942 On UNIX systems, this is the typical @command{/bin/sh}.  But on other
4943 systems, such as native Windows, the shell has a different syntax of
4944 commands that it understands.  Some examples in this chapter assume
4945 @command{/bin/sh}, and also demonstrate how to quit early with a known
4946 exit value if this is not the case.
4948 @menu
4949 * Platform macros::             Determining the platform
4950 * Syscmd::                      Executing simple commands
4951 * Esyscmd::                     Reading the output of commands
4952 * Sysval::                      Exit status
4953 * Mkstemp::                     Making temporary files
4954 @end menu
4956 @node Platform macros
4957 @section Determining the platform
4959 @cindex platform macros
4960 Sometimes it is desirable for an input file to know which platform
4961 @code{m4} is running on.  @acronym{GNU} @code{m4} provides several
4962 macros that are predefined to expand to the empty string; checking for
4963 their existence will confirm platform details.
4965 @deffn {Optional builtin} __gnu__
4966 @deffnx {Optional builtin} __os2__
4967 @deffnx {Optional builtin} os2
4968 @deffnx {Optional builtin} __unix__
4969 @deffnx {Optional builtin} unix
4970 @deffnx {Optional builtin} __windows__
4971 @deffnx {Optional builtin} windows
4972 Each of these macros is conditionally defined as needed to describe the
4973 environment of @code{m4}.  If defined, each macro expands to the empty
4974 string.
4975 @end deffn
4977 When @acronym{GNU} extensions are in effect (that is, when you did not
4978 use the @option{-G} option, @pxref{Limits control, , Invoking m4}),
4979 @acronym{GNU} @code{m4} will define the macro @code{@w{__gnu__}} to
4980 expand to the empty string.
4982 @example
4983 __gnu__
4984 @result{}
4985 ifdef(`__gnu__', `Extensions are active')
4986 @result{}Extensions are active
4987 @end example
4989 @cindex platform macro
4990 On UNIX systems, @acronym{GNU} @code{m4} will define @code{@w{__unix__}}
4991 by default, or @code{unix} when the @option{-G} option is specified.
4993 On native Windows systems, @acronym{GNU} @code{m4} will define
4994 @code{@w{__windows__}} by default, or @code{windows} when the
4995 @option{-G} option is specified.
4997 On OS/2 systems, @acronym{GNU} @code{m4} will define @code{@w{__os2__}}
4998 by default, or @code{os2} when the @option{-G} option is specified.
5000 If @acronym{GNU} @code{m4} does not provide a platform macro for your system,
5001 please report that as a bug.
5003 @example
5004 define(`provided', `0')
5005 @result{}
5006 ifdef(`__unix__', `define(`provided', incr(provided))')
5007 @result{}
5008 ifdef(`__windows__', `define(`provided', incr(provided))')
5009 @result{}
5010 ifdef(`__os2__', `define(`provided', incr(provided))')
5011 @result{}
5012 provided
5013 @result{}1
5014 @end example
5016 @node Syscmd
5017 @section Executing simple commands
5019 Any shell command can be executed, using @code{syscmd}:
5021 @deffn Builtin syscmd (@var{shell-command})
5022 Executes @var{shell-command} as a shell command.
5024 The expansion of @code{syscmd} is void, @emph{not} the output from
5025 @var{shell-command}!  Output or error messages from @var{shell-command}
5026 are not read by @code{m4}.  @xref{Esyscmd}, if you need to process the
5027 command output.
5029 Prior to executing the command, @code{m4} flushes its buffers.
5030 The default standard input, output and error of @var{shell-command} are
5031 the same as those of @code{m4}.
5033 The macro @code{syscmd} is recognized only with parameters.
5034 @end deffn
5036 @example
5037 define(`foo', `FOO')
5038 @result{}
5039 syscmd(`echo foo')
5040 @result{}foo
5041 @result{}
5042 @end example
5044 Note how the expansion of @code{syscmd} keeps the trailing newline of
5045 the command, as well as using the newline that appeared after the macro.
5047 As an example of @var{shell-command} using the same standard input as
5048 @code{m4}, the command line @kbd{echo "m4wrap(\`syscmd(\`cat')')" | m4}
5049 will tell @code{m4} to read all of its input before executing the
5050 wrapped text, then hand a valid (albeit emptied) pipe as standard input
5051 for the @code{cat} subcommand.  Therefore, you should be careful when
5052 using standard input (either by specifying no files, or by passing
5053 @samp{-} as a file name on the command line, @pxref{Command line files,
5054 , Invoking m4}), and
5055 also invoking subcommands via @code{syscmd} or @code{esyscmd} that
5056 consume data from standard input.  When standard input is a seekable
5057 file, the subprocess will pick up with the next character not yet
5058 processed by @code{m4}; when it is a pipe or other non-seekable file,
5059 there is no guarantee how much data will already be buffered by
5060 @code{m4} and thus unavailable to the child.
5062 @ignore
5063 @comment If the user types the example below with stdin being an
5064 @comment interactive terminal, then cat will hang waiting for additional
5065 @comment input after m4 has exited.  But the testsuite is using a pipe
5066 @comment for stdin.  Hence, we have two versions - the one we feed the
5067 @comment testsuite below, and the one we display to the user above that
5068 @comment more accurately shows what the testsuite is really doing but
5069 @comment which the testsuite cannot parse.
5071 @example
5072 m4wrap(`syscmd(`cat')')
5073 @result{}
5075 @end example
5076 @end ignore
5078 @node Esyscmd
5079 @section Reading the output of commands
5081 @cindex @acronym{GNU} extensions
5082 If you want @code{m4} to read the output of a shell command, use
5083 @code{esyscmd}:
5085 @deffn Builtin esyscmd (@var{shell-command})
5086 Expands to the standard output of the shell command
5087 @var{shell-command}.
5089 Prior to executing the command, @code{m4} flushes its buffers.
5090 The default standard input and standard error of @var{shell-command} are
5091 the same as those of @code{m4}.  The error output of @var{shell-command}
5092 is not a part of the expansion: it will appear along with the error
5093 output of @code{m4}.
5095 The macro @code{esyscmd} is recognized only with parameters.
5096 @end deffn
5098 @example
5099 define(`foo', `FOO')
5100 @result{}
5101 esyscmd(`echo foo')
5102 @result{}FOO
5103 @result{}
5104 @end example
5106 Note how the expansion of @code{esyscmd} keeps the trailing newline of
5107 the command, as well as using the newline that appeared after the macro.
5109 Just as with @code{syscmd}, care must be exercised when sharing standard
5110 input between @code{m4} and the child process of @code{esyscmd}.
5112 @node Sysval
5113 @section Exit status
5115 @cindex UNIX commands, exit status from
5116 @cindex exit status from shell commands
5117 @cindex shell commands, exit status from
5118 @cindex commands, exit status from shell
5119 @cindex status of shell commands
5120 To see whether a shell command succeeded, use @code{sysval}:
5122 @deffn Builtin sysval
5123 Expands to the exit status of the last shell command run with
5124 @code{syscmd} or @code{esyscmd}.  Expands to 0 if no command has been
5125 run yet.
5126 @end deffn
5128 @example
5129 syscmd(`false')
5130 @result{}
5131 ifelse(sysval, `0', `zero', `non-zero')
5132 @result{}non-zero
5133 syscmd(`exit 2')
5134 @result{}
5135 sysval
5136 @result{}2
5137 syscmd(`true')
5138 @result{}
5139 sysval
5140 @result{}0
5141 esyscmd(`false')
5142 @result{}
5143 ifelse(sysval, `0', `zero', `non-zero')
5144 @result{}non-zero
5145 esyscmd(`exit 2')
5146 @result{}
5147 sysval
5148 @result{}2
5149 esyscmd(`true')
5150 @result{}
5151 sysval
5152 @result{}0
5153 @end example
5155 @code{sysval} results in 127 if there was a problem executing the
5156 command, for example, if the system-imposed argument length is exceeded,
5157 or if there were not enough resources to fork.  It is not possible to
5158 distinguish between failed execution and successful execution that had
5159 an exit status of 127.
5161 On UNIX platforms, where it is possible to detect when command execution
5162 is terminated by a signal, rather than a normal exit, the result is the
5163 signal number shifted left by eight bits.
5165 @comment This test has difficulties being portable, even on platforms
5166 @comment where syscmd invokes /bin/sh.  Kill is not portable with signal
5167 @comment names.  According to autoconf, the only portable signal numbers
5168 @comment are 1 (HUP), 2 (INT), 9 (KILL), 13 (PIPE) and 15 (TERM).  But
5169 @comment all shells handle SIGINT, and ksh handles HUP (as in, the shell
5170 @comment exits normally rather than letting the signal terminate it).
5171 @comment Also, TERM is flaky, as it can also kill the running m4 on
5172 @comment systems where /bin/sh does not create its own process group.
5173 @comment And PIPE is unreliable, since people tend to run with it
5174 @comment ignored, with m4 inheriting that choice.  That leaves KILL as
5175 @comment the only signal we can reliably test.
5176 @example
5177 dnl This test assumes kill is a shell builtin, and that signals are
5178 dnl recognizable.
5179 ifdef(`__unix__', ,
5180       `errprint(` skipping: syscmd does not have unix semantics
5181 ')m4exit(`77')')dnl
5182 syscmd(`kill -9 $$')
5183 @result{}
5184 sysval
5185 @result{}2304
5186 esyscmd(`kill -9 $$')
5187 @result{}
5188 sysval
5189 @result{}2304
5190 @end example
5192 @node Mkstemp
5193 @section Making temporary files
5195 @cindex temporary file names
5196 @cindex files, names of temporary
5197 Commands specified to @code{syscmd} or @code{esyscmd} might need a
5198 temporary file, for output or for some other purpose.  There is a
5199 builtin macro, @code{mkstemp}, for making a temporary file:
5201 @deffn Builtin mkstemp (@var{template})
5202 @deffnx Builtin maketemp (@var{template})
5203 Expands to a name of a new, empty file, made from the string
5204 @var{template}, which should end with the string @samp{XXXXXX}.  The six
5205 @samp{X} characters are then replaced with random characters matching
5206 the regular expression @samp{[a-zA-Z0-9._-]}, in order to make the file
5207 name unique.  If fewer than six @samp{X} characters are found at the end
5208 of @code{template}, the result will be longer than the template.  The
5209 created file will have access permissions as if by @kbd{chmod =rw,go=},
5210 meaning that the current umask of the @code{m4} process is taken into
5211 account, and at most only the current user can read and write the file.
5213 The traditional behavior, standardized by @acronym{POSIX}, is that
5214 @code{maketemp} merely replaces the trailing @samp{X} with the process
5215 id, without creating a file, and without ensuring that the resulting
5216 string is a unique file name.  In part, this means that using the same
5217 @var{template} twice in the same input file will result in the same
5218 expansion.  This behavior is a security hole, as it is very easy for
5219 another process to guess the name that will be generated, and thus
5220 interfere with a subsequent use of @code{syscmd} trying to manipulate
5221 that file name.  Hence, @acronym{POSIX} has recommended that all new
5222 implementations of @code{m4} provide the secure @code{mkstemp} builtin,
5223 and that users of @code{m4} check for its existence.
5225 The macros @code{mkstemp} and @code{maketemp} are recognized only with
5226 parameters.
5227 @end deffn
5229 If you try this next example, you will most likely get different output
5230 for the two file names, since the replacement characters are randomly
5231 chosen:
5233 @comment ignore
5234 @example
5235 maketemp(`/tmp/fooXXXXXX')
5236 @result{}/tmp/fooa07346
5237 ifdef(`mkstemp', `define(`maketemp', defn(`mkstemp'))',
5238       `define(`mkstemp', defn(`maketemp'))dnl
5239 errprint(`warning: potentially insecure maketemp implementation
5240 ')')
5241 @result{}
5242 mkstemp(`doc')
5243 @result{}docQv83Uw
5244 @end example
5246 @cindex @acronym{GNU} extensions
5247 Unless you use the @option{--traditional} command line option (or
5248 @option{-G}, @pxref{Limits control, , Invoking m4}), the @acronym{GNU}
5249 version of @code{maketemp} is secure.  This means that using the same
5250 template to multiple calls will generate multiple files.  However, we
5251 recommend that you use the new @code{mkstemp} macro, introduced in
5252 @acronym{GNU} M4 1.4.8, which is secure even in traditional mode.
5254 @example
5255 syscmd(`echo foo??????')dnl
5256 @result{}foo??????
5257 define(`file1', maketemp(`fooXXXXXX'))dnl
5258 ifelse(esyscmd(`echo foo??????'), `foo??????', `no file', `created')
5259 @result{}created
5260 define(`file2', maketemp(`fooXX'))dnl
5261 define(`file3', mkstemp(`fooXXXXXX'))dnl
5262 ifelse(len(file1), len(file2), `same length', `different')
5263 @result{}same length
5264 ifelse(file1, file2, `same', `different file')
5265 @result{}different file
5266 ifelse(file2, file3, `same', `different file')
5267 @result{}different file
5268 ifelse(file1, file3, `same', `different file')
5269 @result{}different file
5270 syscmd(`rm 'file1 file2 file3)
5271 @result{}
5272 sysval
5273 @result{}0
5274 @end example
5276 @node Miscellaneous
5277 @chapter Miscellaneous builtin macros
5279 This chapter describes various builtins, that do not really belong in
5280 any of the previous chapters.
5282 @menu
5283 * Errprint::                    Printing error messages
5284 * Location::                    Printing current location
5285 * M4exit::                      Exiting from @code{m4}
5286 @end menu
5288 @node Errprint
5289 @section Printing error messages
5291 @cindex printing error messages
5292 @cindex error messages, printing
5293 @cindex messages, printing error
5294 You can print error messages using @code{errprint}:
5296 @deffn Builtin errprint (@var{message}, @dots{})
5297 Prints @var{message} and the rest of the arguments to standard error,
5298 separated by spaces.  Standard error is used, regardless of the
5299 @option{--debugfile} option (@pxref{Debugging options, , Invoking m4}).
5301 The expansion of @code{errprint} is void.
5302 The macro @code{errprint} is recognized only with parameters.
5303 @end deffn
5305 @example
5306 errprint(`Invalid arguments to forloop
5308 @error{}Invalid arguments to forloop
5309 @result{}
5310 errprint(`1')errprint(`2',`3
5312 @error{}12 3
5313 @result{}
5314 @end example
5316 A trailing newline is @emph{not} printed automatically, so it should be
5317 supplied as part of the argument, as in the example.  Unfortunately, the
5318 exact output of @code{errprint} is not very portable to other @code{m4}
5319 implementations: @acronym{POSIX} requires that all arguments be printed,
5320 but some implementations of @code{m4} only print the first.
5321 Furthermore, some BSD implementations always append a newline for each
5322 @code{errprint} call, regardless of whether the last argument already
5323 had one, and @acronym{POSIX} is silent on whether this is acceptable.
5325 @node Location
5326 @section Printing current location
5328 To make it possible to specify the location of an error, three
5329 utility builtins exist:
5331 @deffn Builtin __file__
5332 @deffnx Builtin __line__
5333 @deffnx Builtin __program__
5334 Expand to the quoted name of the current input file, the
5335 current input line number in that file, and the quoted name of the
5336 current invocation of @code{m4}.
5337 @end deffn
5339 @example
5340 errprint(__program__:__file__:__line__: `input error
5342 @error{}m4:stdin:1: input error
5343 @result{}
5344 @end example
5346 Line numbers start at 1 for each file.  If the file was found due to the
5347 @option{-I} option or @env{M4PATH} environment variable, that is
5348 reflected in the file name.  The syncline option (@option{-s},
5349 @pxref{Preprocessor features, , Invoking m4}), and the
5350 @samp{f} and @samp{l} flags of @code{debugmode} (@pxref{Debug Levels}),
5351 also use this notion of current file and line.  Redefining the three
5352 location macros has no effect on syncline, debug, or warning message
5353 output.  Assume this example is run in the
5354 @file{m4-@value{VERSION}/@/checks} directory of the @acronym{GNU} M4
5355 package, using @samp{--include=../examples} in the command line to find
5356 the file @file{incl.m4} mentioned earlier:
5358 @example
5359 define(`foo', ``$0' called at __file__:__line__')
5360 @result{}
5362 @result{}foo called at stdin:2
5363 include(`incl.m4')
5364 @result{}Include file start
5365 @result{}foo called at ../examples/incl.m4:2
5366 @result{}Include file end
5367 @result{}
5368 @end example
5370 The location of macros invoked during the rescanning of macro expansion
5371 text corresponds to the location in the file where the expansion was
5372 triggered, regardless of how many newline characters the expansion text
5373 contains.  As of @acronym{GNU} M4 1.4.8, the location of text wrapped
5374 with @code{m4wrap} (@pxref{M4wrap}) is the point at which the
5375 @code{m4wrap} was invoked.  Previous versions, however, behaved as
5376 though wrapped text came from line 0 of the file ``''.
5378 @example
5379 define(`echo', `$@@')
5380 @result{}
5381 define(`foo', `echo(__line__
5382 __line__)')
5383 @result{}
5384 echo(__line__
5385 __line__)
5386 @result{}4
5387 @result{}5
5388 m4wrap(`foo
5390 @result{}
5391 foo(errprint(__line__
5392 __line__
5394 @error{}8
5395 @error{}9
5396 @result{}8
5397 @result{}8
5398 __line__
5399 @result{}11
5401 @result{}6
5402 @result{}6
5403 @end example
5405 The @code{@w{__program__}} macro behaves like @samp{$0} in shell
5406 terminology.  If you invoke @code{m4} through an absolute path or a link
5407 with a different spelling, rather than by relying on a @env{PATH} search
5408 for plain @samp{m4}, it will affect how @code{@w{__program__}} expands.
5409 The intent is that you can use it to produce error messages with the
5410 same formatting that @code{m4} produces internally.  It can also be used
5411 within @code{syscmd} (@pxref{Syscmd}) to pick the same version of
5412 @code{m4} that is currently running, rather than whatever version of
5413 @code{m4} happens to be first in @env{PATH}.  It was first introduced in
5414 @acronym{GNU} M4 1.4.6.
5416 @node M4exit
5417 @section Exiting from @code{m4}
5419 @cindex exiting from @code{m4}
5420 @cindex status, setting @code{m4} exit
5421 If you need to exit from @code{m4} before the entire input has been
5422 read, you can use @code{m4exit}:
5424 @deffn Builtin m4exit (@dvar{code, 0})
5425 Causes @code{m4} to exit, with exit status @var{code}.  If @var{code} is
5426 left out, the exit status is zero.  If @var{code} cannot be parsed, or
5427 is outside the range of 0 to 255, the exit status is one.  No further
5428 input is read, and all wrapped and diverted text is discarded.
5429 @end deffn
5431 @example
5432 m4wrap(`This text is lost due to `m4exit'.')
5433 @result{}
5434 divert(`1') So is this.
5435 divert
5436 @result{}
5437 m4exit And this is never read.
5438 @end example
5440 A common use of this is to abort processing:
5442 @deffn Composite fatal_error (@var{message})
5443 Abort processing with an error message and non-zero status.  Prefix
5444 @var{message} with details about where the error occurred, and print the
5445 resulting string to standard error.
5446 @end deffn
5448 @comment status: 1
5449 @example
5450 define(`fatal_error',
5451        `errprint(__program__:__file__:__line__`: fatal error: $*
5452 ')m4exit(`1')')
5453 @result{}
5454 fatal_error(`this is a BAD one, buster')
5455 @error{}m4:stdin:4: fatal error: this is a BAD one, buster
5456 @end example
5458 After this macro call, @code{m4} will exit with exit status 1.  This macro
5459 is only intended for error exits, since the normal exit procedures are
5460 not followed, e.g., diverted text is not undiverted, and saved text
5461 (@pxref{M4wrap}) is not reread.  (This macro could be made more robust
5462 to earlier versions of @code{m4}.  You should try to see if you can find
5463 weaknesses and correct them; or @pxref{Improved fatal_error, , Answers}).
5465 Note that it is still possible for the exit status to be different than
5466 what was requested by @code{m4exit}.  If @code{m4} detects some other
5467 error, such as a write error on standard output, the exit status will be
5468 non-zero even if @code{m4exit} requested zero.
5470 If standard input is seekable, then the file will be positioned at the
5471 next unread character.  If it is a pipe or other non-seekable file,
5472 then there are no guarantees how much data @code{m4} might have read
5473 into buffers, and thus discarded.
5475 @node Frozen files
5476 @chapter Fast loading of frozen state
5478 Some bigger @code{m4} applications may be built over a common base
5479 containing hundreds of definitions and other costly initializations.
5480 Usually, the common base is kept in one or more declarative files,
5481 which files are listed on each @code{m4} invocation prior to the
5482 user's input file, or else each input file uses @code{include}.
5484 Reading the common base of a big application, over and over again, may
5485 be time consuming.  @acronym{GNU} @code{m4} offers some machinery to
5486 speed up the start of an application using lengthy common bases.
5488 @menu
5489 * Using frozen files::          Using frozen files
5490 * Frozen file format::          Frozen file format
5491 @end menu
5493 @node Using frozen files
5494 @section Using frozen files
5495 @cindex fast loading of frozen files
5496 @cindex frozen files for fast loading
5497 @cindex initialization, frozen states
5498 @cindex dumping into frozen file
5499 @cindex reloading a frozen file
5500 @cindex @acronym{GNU} extensions
5501 Suppose a user has a library of @code{m4} initializations in
5502 @file{base.m4}, which is then used with multiple input files:
5504 @comment ignore
5505 @example
5506 m4 base.m4 input1.m4
5507 m4 base.m4 input2.m4
5508 m4 base.m4 input3.m4
5509 @end example
5511 Rather than spending time parsing the fixed contents of @file{base.m4}
5512 every time, the user might rather execute:
5514 @comment ignore
5515 @example
5516 m4 -F base.m4f base.m4
5517 @end example
5519 @noindent
5520 once, and further execute, as often as needed:
5522 @comment ignore
5523 @example
5524 m4 -R base.m4f input1.m4
5525 m4 -R base.m4f input2.m4
5526 m4 -R base.m4f input3.m4
5527 @end example
5529 @noindent
5530 with the varying input.  The first call, containing the @option{-F}
5531 option, only reads and executes file @file{base.m4}, defining
5532 various application macros and computing other initializations.
5533 Once the input file @file{base.m4} has been completely processed, @acronym{GNU}
5534 @code{m4} produces in @file{base.m4f} a @dfn{frozen} file, that is, a
5535 file which contains a kind of snapshot of the @code{m4} internal state.
5537 Later calls, containing the @option{-R} option, are able to reload
5538 the internal state of @code{m4}, from @file{base.m4f},
5539 @emph{prior} to reading any other input files.  This means
5540 instead of starting with a virgin copy of @code{m4}, input will be
5541 read after having effectively recovered the effect of a prior run.
5542 In our example, the effect is the same as if file @file{base.m4} has
5543 been read anew.  However, this effect is achieved a lot faster.
5545 Only one frozen file may be created or read in any one @code{m4}
5546 invocation.  It is not possible to recover two frozen files at once.
5547 However, frozen files may be updated incrementally, through using
5548 @option{-R} and @option{-F} options simultaneously.  For example, if
5549 some care is taken, the command:
5551 @comment ignore
5552 @example
5553 m4 file1.m4 file2.m4 file3.m4 file4.m4
5554 @end example
5556 @noindent
5557 could be broken down in the following sequence, accumulating the same
5558 output:
5560 @comment ignore
5561 @example
5562 m4 -F file1.m4f file1.m4
5563 m4 -R file1.m4f -F file2.m4f file2.m4
5564 m4 -R file2.m4f -F file3.m4f file3.m4
5565 m4 -R file3.m4f file4.m4
5566 @end example
5568 Some care is necessary because not every effort has been made for
5569 this to work in all cases.  In particular, the trace attribute of
5570 macros is not handled, nor the current setting of @code{changeword}.
5571 Currently, @code{m4wrap} and @code{sysval} also have problems.
5572 Also, interactions for some options of @code{m4}, being used in one call
5573 and not in the next, have not been fully analyzed yet.  On the other
5574 end, you may be confident that stacks of @code{pushdef} definitions
5575 are handled correctly, as well as undefined or renamed builtins, and
5576 changed strings for quotes or comments.  And future releases of
5577 @acronym{GNU} M4 will improve on the utility of frozen files.
5579 When an @code{m4} run is to be frozen, the automatic undiversion
5580 which takes place at end of execution is inhibited.  Instead, all
5581 positively numbered diversions are saved into the frozen file.
5582 The active diversion number is also transmitted.
5584 A frozen file to be reloaded need not reside in the current directory.
5585 It is looked up the same way as an @code{include} file (@pxref{Search
5586 Path}).
5588 If the frozen file was generated with a newer version of @code{m4}, and
5589 contains directives that an older @code{m4} cannot parse, attempting to
5590 load the frozen file with option @option{-R} will cause @code{m4} to
5591 exit with status 63 to indicate version mismatch.
5593 @node Frozen file format
5594 @section Frozen file format
5595 @cindex frozen file format
5596 @cindex file format, frozen file
5597 Frozen files are sharable across architectures.  It is safe to write
5598 a frozen file on one machine and read it on another, given that the
5599 second machine uses the same or newer version of @acronym{GNU} @code{m4}.
5600 It is conventional, but not required, to give a frozen file the suffix
5601 of @code{.m4f}.
5603 These are simple (editable) text files, made up of directives,
5604 each starting with a capital letter and ending with a newline
5605 (@key{NL}).  Wherever a directive is expected, the character
5606 @samp{#} introduces a comment line; empty lines are also ignored if they
5607 are not part of an embedded string.
5608 In the following descriptions, each @var{len} refers to the length of
5609 the corresponding strings @var{str} in the next line of input.  Numbers
5610 are always expressed in decimal.  There are no escape characters.  The
5611 directives are:
5613 @table @code
5614 @item C @var{len1} , @var{len2} @key{NL} @var{str1} @var{str2} @key{NL}
5615 Uses @var{str1} and @var{str2} as the begin-comment and
5616 end-comment strings.  If omitted, then @samp{#} and @key{NL} are the
5617 comment delimiters.
5619 @item D @var{number}, @var{len} @key{NL} @var{str} @key{NL}
5620 Selects diversion @var{number}, making it current, then copy
5621 @var{str} in the current diversion.  @var{number} may be a negative
5622 number for a non-existing diversion.  To merely specify an active
5623 selection, use this command with an empty @var{str}.  With 0 as the
5624 diversion @var{number}, @var{str} will be issued on standard output
5625 at reload time.  @acronym{GNU} @code{m4} will not produce the @samp{D}
5626 directive with non-zero length for diversion 0, but this can be done
5627 with manual edits.  This directive may
5628 appear more than once for the same diversion, in which case the
5629 diversion is the concatenation of the various uses.  If omitted, then
5630 diversion 0 is current.
5632 @item F @var{len1} , @var{len2} @key{NL} @var{str1} @var{str2} @key{NL}
5633 Defines, through @code{pushdef}, a definition for @var{str1}
5634 expanding to the function whose builtin name is @var{str2}.  If the
5635 builtin does not exist (for example, if the frozen file was produced by
5636 a copy of @code{m4} compiled with changeword support, but the version
5637 of @code{m4} reloading was compiled without it), the reload is silent,
5638 but any subsequent use of the definition of @var{str1} will result in
5639 a warning.  This directive may appear more than once for the same name,
5640 and its order, along with @samp{T}, is important.  If omitted, you will
5641 have no access to any builtins.
5643 @item Q @var{len1} , @var{len2} @key{NL} @var{str1} @var{str2} @key{NL}
5644 Uses @var{str1} and @var{str2} as the begin-quote and end-quote
5645 strings.  If omitted, then @samp{`} and @samp{'} are the quote
5646 delimiters.
5648 @item T @var{len1} , @var{len2} @key{NL} @var{str1} @var{str2} @key{NL}
5649 Defines, though @code{pushdef}, a definition for @var{str1}
5650 expanding to the text given by @var{str2}.  This directive may appear
5651 more than once for the same name, and its order, along with @samp{F}, is
5652 important.
5654 @item V @var{number} @key{NL}
5655 Confirms the format of the file.  @code{m4} @value{VERSION} only creates
5656 and understands frozen files where @var{number} is 1.  This directive
5657 must be the first non-comment in the file, and may not appear more than
5658 once.
5659 @end table
5661 @node Compatibility
5662 @chapter Compatibility with other versions of @code{m4}
5664 @cindex compatibility
5665 This chapter describes the differences between this implementation of
5666 @code{m4}, and the implementation found under UNIX, notably System V,
5667 Release 3.
5669 There are also differences in BSD flavors of @code{m4}.  No attempt
5670 is made to summarize these here.
5672 @menu
5673 * Extensions::                  Extensions in @acronym{GNU} M4
5674 * Incompatibilities::           Facilities in System V m4 not in GNU M4
5675 * Other Incompatibilities::     Other incompatibilities
5676 @end menu
5678 @node Extensions
5679 @section Extensions in @acronym{GNU} @code{m4}
5681 @cindex @acronym{GNU} extensions
5682 This version of @code{m4} contains a few facilities that do not exist
5683 in System V @code{m4}.  These extra facilities are all suppressed by
5684 using the @option{-G} command line option (@pxref{Limits control, ,
5685 Invoking m4}), unless overridden by other command line options.
5687 @itemize @bullet
5688 @item
5689 In the @code{$@var{n}} notation for macro arguments, @var{n} can contain
5690 several digits, while the System V @code{m4} only accepts one digit.
5691 This allows macros in @acronym{GNU} @code{m4} to take any number of
5692 arguments, and not only nine (@pxref{Arguments}).
5694 This means that @code{define(`foo', `$11')} is ambiguous between
5695 implementations.  To portably choose between grabbing the first
5696 parameter and appending 1 to the expansion, or grabbing the eleventh
5697 parameter, you can do the following:
5699 @example
5700 define(`a1', `A1')
5701 @result{}
5702 dnl First argument, concatenated with 1
5703 define(`_1', `$1')define(`first1', `_1($@@)1')
5704 @result{}
5705 dnl Eleventh argument, portable
5706 define(`_9', `$9')define(`eleventh', `_9(shift(shift($@@)))')
5707 @result{}
5708 dnl Eleventh argument, GNU style
5709 define(`Eleventh', `$11')
5710 @result{}
5711 first1(`a', `b', `c', `d', `e', `f', `g', `h', `i', `j', `k')
5712 @result{}A1
5713 eleventh(`a', `b', `c', `d', `e', `f', `g', `h', `i', `j', `k')
5714 @result{}k
5715 Eleventh(`a', `b', `c', `d', `e', `f', `g', `h', `i', `j', `k')
5716 @result{}k
5717 @end example
5719 @item
5720 The @code{divert} (@pxref{Divert}) macro can manage more than 9
5721 diversions.  @acronym{GNU} @code{m4} treats all positive numbers as valid
5722 diversions, rather than discarding diversions greater than 9.
5724 @item
5725 Files included with @code{include} and @code{sinclude} are sought in a
5726 user specified search path, if they are not found in the working
5727 directory.  The search path is specified by the @option{-I} option and the
5728 @env{M4PATH} environment variable (@pxref{Search Path}).
5730 @item
5731 Arguments to @code{undivert} can be non-numeric, in which case the named
5732 file will be included uninterpreted in the output (@pxref{Undivert}).
5734 @item
5735 Formatted output is supported through the @code{format} builtin, which
5736 is modeled after the C library function @code{printf} (@pxref{Format}).
5738 @item
5739 Searches and text substitution through regular expressions are
5740 supported by the @code{regexp} (@pxref{Regexp}) and @code{patsubst}
5741 (@pxref{Patsubst}) builtins.
5743 @item
5744 The output of shell commands can be read into @code{m4} with
5745 @code{esyscmd} (@pxref{Esyscmd}).
5747 @item
5748 There is indirect access to any builtin macro with @code{builtin}
5749 (@pxref{Builtin}).
5751 @item
5752 Macros can be called indirectly through @code{indir} (@pxref{Indir}).
5754 @item
5755 The name of the program, the current input file, and the current input
5756 line number are accessible through the builtins @code{@w{__program__}},
5757 @code{@w{__file__}}, and @code{@w{__line__}} (@pxref{Location}).
5759 @item
5760 The format of the output from @code{dumpdef} and macro tracing can be
5761 controlled with @code{debugmode} (@pxref{Debug Levels}).
5763 @item
5764 The destination of trace and debug output can be controlled with
5765 @code{debugfile} (@pxref{Debug Output}).
5767 @item
5768 The @code{maketemp} (@pxref{Mkstemp}) macro behaves like @code{mkstemp},
5769 creating a new file with a unique name on every invocation, rather than
5770 following the insecure behavior of replacing the trailing @samp{X}
5771 characters with the @code{m4} process id.
5772 @end itemize
5774 In addition to the above extensions, @acronym{GNU} @code{m4} implements the
5775 following command line options: @option{-F}, @option{-G}, @option{-I},
5776 @option{-L}, @option{-R}, @option{-V}, @option{-W}, @option{-d}, @option{-i},
5777 @option{-l}, @option{--debugfile} and @option{-t}.  @xref{Invoking m4}, for a
5778 description of these options.
5780 Also, the debugging and tracing facilities in @acronym{GNU} @code{m4} are much
5781 more extensive than in most other versions of @code{m4}.
5783 @node Incompatibilities
5784 @section Facilities in System V @code{m4} not in @acronym{GNU} @code{m4}
5786 The version of @code{m4} from System V contains a few facilities that
5787 have not been implemented in @acronym{GNU} @code{m4} yet.  Additionally,
5788 @acronym{POSIX} requires some behaviors that @acronym{GNU} @code{m4} has not
5789 implemented yet.  Relying on these behaviors is non-portable, as a
5790 future release of @acronym{GNU} @code{m4} may change.
5792 @itemize @bullet
5793 @item
5794 System V @code{m4} supports multiple arguments to @code{defn}, and
5795 @acronym{POSIX} requires it.  This is not yet implemented in @acronym{GNU}
5796 @code{m4}.  Unfortunately, this means it is not possible to mix builtins
5797 and other text into a single macro; a helper macro is required.
5799 @item
5800 @acronym{POSIX} requires an application to exit with non-zero status if
5801 it wrote an error message to stderr.  This has not yet been consistently
5802 implemented for the various builtins that are required to issue an error
5803 (such as @code{include} (@pxref{Include}) when a file is unreadable,
5804 @code{eval} (@pxref{Eval}) when an argument cannot be parsed, or using
5805 @code{m4exit} (@pxref{M4exit}) with a non-numeric argument).
5807 @item
5808 Some traditional implementations only allow reading standard input
5809 once, but @acronym{GNU} @code{m4} correctly handles multiple instances
5810 of @samp{-} on the command line.
5812 @item
5813 @acronym{POSIX} requires @code{m4wrap} (@pxref{M4wrap}) to act in FIFO
5814 (first-in, first-out) order, but @acronym{GNU} @code{m4} currently uses
5815 LIFO order.  Furthermore, @acronym{POSIX} states that only the first
5816 argument to @code{m4wrap} is saved for later evaluation, bug
5817 @acronym{GNU} @code{m4} saves and processes all arguments, with output
5818 separated by spaces.
5820 However, it is possible to emulate @acronym{POSIX} behavior by
5821 including the file @file{m4-@value{VERSION}/@/examples/@/wrapfifo.m4}
5822 from the distribution:
5824 @example
5825 undivert(`wrapfifo.m4')dnl
5826 @result{}dnl Redefine m4wrap to have FIFO semantics.
5827 @result{}define(`_m4wrap_level', `0')dnl
5828 @result{}define(`m4wrap',
5829 @result{}`ifdef(`m4wrap'_m4wrap_level,
5830 @result{}       `define(`m4wrap'_m4wrap_level,
5831 @result{}               defn(`m4wrap'_m4wrap_level)`$1')',
5832 @result{}       `builtin(`m4wrap', `define(`_m4wrap_level',
5833 @result{}                                  incr(_m4wrap_level))dnl
5834 @result{}m4wrap'_m4wrap_level)dnl
5835 @result{}define(`m4wrap'_m4wrap_level, `$1')')')dnl
5836 include(`wrapfifo.m4')
5837 @result{}
5838 m4wrap(`a`'m4wrap(`c
5839 ', `d')')m4wrap(`b')
5840 @result{}
5842 @result{}abc
5843 @end example
5845 @item
5846 @acronym{POSIX} states that builtins that require arguments, but are
5847 called without arguments, have undefined behavior.  Traditional
5848 implementations simply behave as though empty strings had been passed.
5849 For example, @code{a`'define`'b} would expand to @code{ab}.  But
5850 @acronym{GNU} @code{m4} ignores certain builtins if they have missing
5851 arguments, giving @code{adefineb} for the above example.
5853 @item
5854 Traditional implementations handle @code{define(`f',`1')} (@pxref{Define})
5855 by undefining the entire stack of previous definitions, and if doing
5856 @code{undefine(`f')} first.  @acronym{GNU} @code{m4} replaces just the top
5857 definition on the stack, as if doing @code{popdef(`f')} followed by
5858 @code{pushdef(`f',`1')}.
5860 @item
5861 @acronym{POSIX} requires @code{syscmd} (@pxref{Syscmd}) to evaluate
5862 command output for macro expansion, but this appears to be a mistake
5863 in @acronym{POSIX} since traditional implementations did not do this.
5864 @acronym{GNU} @code{m4} follows traditional behavior in @code{syscmd}, and
5865 provides the extension @code{esyscmd} that provides the @acronym{POSIX}
5866 semantics.
5868 @item
5869 At one point, @acronym{POSIX} required @code{changequote(@var{arg})}
5870 (@pxref{Changequote}) to use newline as the close quote, but this was a
5871 bug, and the next version of @acronym{POSIX} is anticipated to state
5872 that using empty strings or just one argument is unspecified.
5873 Meanwhile, the @acronym{GNU} @code{m4} behavior of treating an empty
5874 end-quote delimiter as @samp{'} is not portable, as Solaris treats it as
5875 repeating the start-quote delimiter, and BSD treats it as leaving the
5876 previous end-quote delimiter unchanged.  For predictable results, never
5877 call changequote with just one argument, or with empty strings for
5878 arguments.
5880 @item
5881 At one point, @acronym{POSIX} required @code{changecom(@var{arg},)}
5882 (@pxref{Changecom}) to make it impossible to end a comment, but this is
5883 a bug, and the next version of @acronym{POSIX} is anticipated to state
5884 that using empty strings is unspecified.  Meanwhile, the @acronym{GNU}
5885 @code{m4} behavior of treating an empty end-comment delimiter as newline
5886 is not portable, as BSD treats it as leaving the previous end-comment
5887 delimiter unchanged.  It is also impossible in BSD implementations to
5888 disable comments, even though that is required by @acronym{POSIX}.  For
5889 predictable results, never call changecom with empty strings for
5890 arguments.
5892 @item
5893 Most implementations of @code{m4} give macros a higher precedence than
5894 comments when parsing, meaning that if the start delimiter given to
5895 @code{changecom} (@pxref{Changecom}) starts with a macro name, comments
5896 are effectively disabled.  @acronym{POSIX} does not specify what the
5897 precedence is, so the @acronym{GNU} @code{m4} parser recognizes
5898 comments, then macros, then quoted strings.
5900 @item
5901 Traditional implementations allow argument collection, but not string
5902 and comment processing, to span file boundaries.  Thus, if @file{a.m4}
5903 contains @samp{len(}, and @file{b.m4} contains @samp{abc)},
5904 @kbd{m4 a.m4 b.m4} outputs @samp{3} with traditional @code{m4}, but
5905 gives an error message that the end of file was encountered inside a
5906 macro with @acronym{GNU} @code{m4}.  On the other hand, traditional
5907 implementations do end of file processing for files included with
5908 @code{include} or @code{sinclude} (@pxref{Include}), while @acronym{GNU}
5909 @code{m4} seamlessly integrates the content of those files.  Thus
5910 @code{include(`a.m4')include(`b.m4')} will output @samp{3} instead of
5911 giving an error.
5913 @item
5914 Traditional @code{m4} treats @code{traceon} (@pxref{Trace}) without
5915 arguments as a global variable, independent of named macro tracing.
5916 Also, once a macro is undefined, named tracing of that macro is lost.
5917 On the other hand, when @acronym{GNU} @code{m4} encounters
5918 @code{traceon} without
5919 arguments, it turns tracing on for all existing definitions at the time,
5920 but does not trace future definitions; @code{traceoff} without arguments
5921 turns tracing off for all definitions regardless of whether they were
5922 also traced by name; and tracing by name, such as with @option{-tfoo} at
5923 the command line or @code{traceon(`foo')} in the input, is an attribute
5924 that is preserved even if the macro is currently undefined.
5926 @item
5927 @acronym{POSIX} requires @code{eval} (@pxref{Eval}) to treat all
5928 operators with the same precedence as C.  However, earlier versions of
5929 @acronym{GNU} @code{m4} followed the traditional behavior of other
5930 @code{m4} implementations, where bitwise and logical negation (@samp{~}
5931 and @samp{!}) have lower precedence than equality operators; and where
5932 equality operators (@samp{==} and @samp{!=}) had the same precedence as
5933 relational operators (such as @samp{<}).  Use explicit parentheses to
5934 ensure proper precedence.  As extensions to @acronym{POSIX},
5935 @acronym{GNU} @code{m4} gives well-defined semantics to operations that
5936 C leaves undefined, such as when overflow occurs, when shifting negative
5937 numbers, or when performing division by zero.  @acronym{POSIX} also
5938 requires @samp{=} to cause an error, but many traditional
5939 implementations allowed it as an alias for @samp{==}.
5941 @item
5942 @acronym{POSIX} requires @code{translit} (@pxref{Translit}) to treat
5943 each character of the second and third arguments literally, but @acronym{GNU}
5944 @code{m4} treats @samp{-} as a range operator.
5946 @item
5947 @acronym{POSIX} requires @code{m4} to honor the locale environment
5948 variables of @env{LANG}, @env{LC_ALL}, @env{LC_CTYPE},
5949 @env{LC_MESSAGES}, and @env{NLSPATH}, but this has not yet been
5950 implemented in @acronym{GNU} @code{m4}.
5952 @item
5953 @acronym{POSIX} states that only unquoted leading newlines and blanks
5954 (that is, space and tab) are ignored when collecting macro arguments.
5955 However, this appears to be a bug in @acronym{POSIX}, since most
5956 traditional implementations also ignore all whitespace (formfeed,
5957 carriage return, and vertical tab).  @acronym{GNU} @code{m4} follows
5958 tradition and ignores all leading unquoted whitespace.
5959 @end itemize
5961 @node Other Incompatibilities
5962 @section Other incompatibilities
5964 There are a few other incompatibilities between this implementation of
5965 @code{m4}, and the System V version.
5967 @itemize @bullet
5968 @item
5969 @acronym{GNU} @code{m4} implements sync lines differently from System V
5970 @code{m4}, when text is being diverted.  @acronym{GNU} @code{m4} outputs
5971 the sync lines when the text is being diverted, and System V @code{m4}
5972 when the diverted text is being brought back.
5974 The problem is which lines and file names should be attached to text that
5975 is being, or has been, diverted.  System V @code{m4} regards all the
5976 diverted text as being generated by the source line containing the
5977 @code{undivert} call, whereas @acronym{GNU} @code{m4} regards the
5978 diverted text as being generated at the time it is diverted.
5980 The sync line option is used mostly when using @code{m4} as
5981 a front end to a compiler.  If a diverted line causes a compiler error,
5982 the error messages should most probably refer to the place where the
5983 diversion were made, and not where it was inserted again.
5985 @item
5986 @acronym{GNU} @code{m4} makes no attempt at prohibiting self-referential
5987 definitions like:
5989 @comment ignore
5990 @example
5991 define(`x', `x')
5992 @result{}
5993 define(`x', `x ')
5994 @result{}
5995 @end example
5997 There is nothing inherently wrong with defining @samp{x} to
5998 return @samp{x}.  The wrong thing is to expand @samp{x} unquoted.
5999 In @code{m4}, one might use macros to hold strings, as we do for
6000 variables in other programming languages, further checking them with:
6002 @comment ignore
6003 @example
6004 ifelse(defn(`@var{holder}'), `@var{value}', @dots{})
6005 @end example
6007 @noindent
6008 In cases like this one, an interdiction for a macro to hold its own
6009 name would be a useless limitation.  Of course, this leaves more rope
6010 for the @acronym{GNU} @code{m4} user to hang himself!  Rescanning hangs may be
6011 avoided through careful programming, a little like for endless loops
6012 in traditional programming languages.
6013 @end itemize
6015 @node Answers
6016 @chapter Correct version of some examples
6018 Some of the examples in this manuals are buggy or not very robust, for
6019 demonstration purposes.  Improved versions of these composite macros are
6020 presented here.
6022 @menu
6023 * Improved exch::               Solution for @code{exch}
6024 * Improved forloop::            Solution for @code{forloop}
6025 * Improved foreach::            Solution for @code{foreach}
6026 * Improved cleardivert::        Solution for @code{cleardivert}
6027 * Improved fatal_error::        Solution for @code{fatal_error}
6028 @end menu
6030 @node Improved exch
6031 @section Solution for @code{exch}
6033 The @code{exch} macro (@pxref{Arguments}) as presented requires clients
6034 to double quote their arguments.  A nicer definition, which lets
6035 clients follow the rule of thumb of one level of quoting per level of
6036 parentheses, involves adding quotes in the definition of @code{exch}, as
6037 follows:
6039 @example
6040 define(`exch', ``$2', `$1'')
6041 @result{}
6042 define(exch(`expansion text', `macro'))
6043 @result{}
6044 macro
6045 @result{}expansion text
6046 @end example
6048 @node Improved forloop
6049 @section Solution for @code{forloop}
6051 The @code{forloop} macro (@pxref{Forloop}) as presented earlier can go
6052 into an infinite loop if given an iterator that is not parsed as a macro
6053 name.  It does not do any sanity checking on its numeric bounds, and
6054 only permits decimal numbers for bounds.  Here is an improved version,
6055 shipped as @file{m4-@value{VERSION}/@/examples/@/forloop2.m4}; this
6056 version also optimizes based on the fact that the starting bound does
6057 not need to be passed to the helper @code{@w{_forloop}}.
6059 @example
6060 undivert(`forloop2.m4')dnl
6061 @result{}divert(`-1')
6062 @result{}# forloop(var, from, to, stmt) - improved version:
6063 @result{}#   works even if VAR is not a strict macro name
6064 @result{}#   performs sanity check that FROM is larger than TO
6065 @result{}#   allows complex numerical expressions in TO and FROM
6066 @result{}define(`forloop', `ifelse(eval(`($3) >= ($2)'), `1',
6067 @result{}  `pushdef(`$1', eval(`$2'))_forloop(`$1',
6068 @result{}    eval(`$3'), `$4')popdef(`$1')')')
6069 @result{}define(`_forloop',
6070 @result{}  `$3`'ifelse(indir(`$1'), `$2', `',
6071 @result{}    `define(`$1', incr(indir(`$1')))$0($@@)')')
6072 @result{}divert`'dnl
6073 include(`forloop2.m4')
6074 @result{}
6075 forloop(`i', `2', `1', `no iteration occurs')
6076 @result{}
6077 forloop(`', `1', `2', ` odd iterator name')
6078 @result{} odd iterator name odd iterator name
6079 forloop(`i', `5 + 5', `0xc', ` 0x`'eval(i, `16')')
6080 @result{} 0xa 0xb 0xc
6081 forloop(`i', `a', `b', `non-numeric bounds')
6082 @error{}m4:stdin:6: bad expression in eval (bad input): (b) >= (a)
6083 @result{}
6084 @end example
6086 Of course, it is possible to make even more improvements, such as
6087 adding an optional step argument, or allowing iteration through
6088 descending sequences.  @acronym{GNU} Autoconf provides some of these
6089 additional bells and whistles in its @code{m4_for} macro.
6091 @node Improved foreach
6092 @section Solution for @code{foreach}
6094 The @code{foreach} and @code{foreachq} macros (@pxref{Foreach}) as
6095 presented earlier each have flaws.  First, we will examine and fix the
6096 quadratic behavior of @code{foreachq}:
6098 @example
6099 include(`foreachq.m4')
6100 @result{}
6101 traceon(`shift')debugmode(`aq')
6102 @result{}
6103 foreachq(`x', ``1', `2', `3', `4'', `x
6104 ')dnl
6105 @result{}1
6106 @error{}m4trace: -3- shift(`1', `2', `3', `4')
6107 @error{}m4trace: -2- shift(`1', `2', `3', `4')
6108 @result{}2
6109 @error{}m4trace: -4- shift(`1', `2', `3', `4')
6110 @error{}m4trace: -3- shift(`2', `3', `4')
6111 @error{}m4trace: -3- shift(`1', `2', `3', `4')
6112 @error{}m4trace: -2- shift(`2', `3', `4')
6113 @result{}3
6114 @error{}m4trace: -5- shift(`1', `2', `3', `4')
6115 @error{}m4trace: -4- shift(`2', `3', `4')
6116 @error{}m4trace: -3- shift(`3', `4')
6117 @error{}m4trace: -4- shift(`1', `2', `3', `4')
6118 @error{}m4trace: -3- shift(`2', `3', `4')
6119 @error{}m4trace: -2- shift(`3', `4')
6120 @result{}4
6121 @error{}m4trace: -6- shift(`1', `2', `3', `4')
6122 @error{}m4trace: -5- shift(`2', `3', `4')
6123 @error{}m4trace: -4- shift(`3', `4')
6124 @error{}m4trace: -3- shift(`4')
6125 @end example
6127 Each successive iteration was adding more quoted @code{shift}
6128 invocations, and the entire list contents were passing through every
6129 iteration.  In general, when recursing, it is a good idea to make the
6130 recursion use fewer arguments, rather than adding additional quoted
6131 uses of @code{shift}.  By doing so, @code{m4} uses less memory, invokes
6132 fewer macros, is less likely to run into machine limits, and most
6133 importantly, performs faster.  The fixed version of @code{foreachq} can
6134 be found in @file{m4-@value{VERSION}/@/examples/@/foreachq2.m4}:
6136 @example
6137 include(`foreachq2.m4')
6138 @result{}
6139 undivert(`foreachq2.m4')dnl
6140 @result{}include(`quote.m4')dnl
6141 @result{}divert(`-1')
6142 @result{}# foreachq(x, `item_1, item_2, ..., item_n', stmt)
6143 @result{}#   quoted list, improved version
6144 @result{}define(`foreachq', `pushdef(`$1')_foreachq($@@)popdef(`$1')')
6145 @result{}define(`_arg1q', ``$1'')
6146 @result{}define(`_rest', `ifelse(`$#', `1', `', `dquote(shift($@@))')')
6147 @result{}define(`_foreachq', `ifelse(`$2', `', `',
6148 @result{}  `define(`$1', _arg1q($2))$3`'$0(`$1', _rest($2), `$3')')')
6149 @result{}divert`'dnl
6150 traceon(`shift')debugmode(`aq')
6151 @result{}
6152 foreachq(`x', ``1', `2', `3', `4'', `x
6153 ')dnl
6154 @result{}1
6155 @error{}m4trace: -3- shift(`1', `2', `3', `4')
6156 @result{}2
6157 @error{}m4trace: -3- shift(`2', `3', `4')
6158 @result{}3
6159 @error{}m4trace: -3- shift(`3', `4')
6160 @result{}4
6161 @end example
6163 Note that the fixed version calls unquoted helper macros in
6164 @code{@w{_foreachq}} to trim elements immediately; those helper macros
6165 in turn must re-supply the layer of quotes lost in the macro invocation.
6166 Contrast the use of @code{@w{_arg1q}}, which quotes the first list
6167 element, with @code{@w{_arg1}} of the earlier implementation that
6168 returned the first list element directly.
6170 For a different approach, the improved version of @code{foreach},
6171 available in @file{m4-@value{VERSION}/@/examples/@/foreach2.m4}, simply
6172 overquotes the arguments to @code{@w{_foreach}} to begin with, using
6173 @code{dquote_elt}.  Then @code{@w{_foreach}} can just use
6174 @code{@w{_arg1}} to remove the extra layer of quoting that was added up
6175 front:
6177 @example
6178 include(`foreach2.m4')
6179 @result{}
6180 undivert(`foreach2.m4')dnl
6181 @result{}include(`quote.m4')dnl
6182 @result{}divert(`-1')
6183 @result{}# foreach(x, (item_1, item_2, ..., item_n), stmt)
6184 @result{}#   parenthesized list, improved version
6185 @result{}define(`foreach', `pushdef(`$1')_foreach(`$1',
6186 @result{}  (dquote(dquote_elt$2)), `$3')popdef(`$1')')
6187 @result{}define(`_arg1', `$1')
6188 @result{}define(`_foreach', `ifelse(`$2', `(`')', `',
6189 @result{}  `define(`$1', _arg1$2)$3`'$0(`$1', (dquote(shift$2)), `$3')')')
6190 @result{}divert`'dnl
6191 traceon(`shift')debugmode(`aq')
6192 @result{}
6193 foreach(`x', `(`1', `2', `3', `4')', `x
6194 ')dnl
6195 @error{}m4trace: -4- shift(`1', `2', `3', `4')
6196 @error{}m4trace: -4- shift(`2', `3', `4')
6197 @error{}m4trace: -4- shift(`3', `4')
6198 @result{}1
6199 @error{}m4trace: -3- shift(``1'', ``2'', ``3'', ``4'')
6200 @result{}2
6201 @error{}m4trace: -3- shift(``2'', ``3'', ``4'')
6202 @result{}3
6203 @error{}m4trace: -3- shift(``3'', ``4'')
6204 @result{}4
6205 @error{}m4trace: -3- shift(``4'')
6206 @end example
6208 In summary, recursion over list elements is trickier than it appeared at
6209 first glance, but provides a powerful idiom within @code{m4} processing.
6210 As a final demonstration, both list styles are now able to handle
6211 several scenarios that would wreak havoc on the original
6212 implementations.  This points out one other difference between the two
6213 list styles.  @code{foreach} evaluates unquoted list elements only once,
6214 in preparation for calling @code{@w{_foreach}}.  But @code{foreachq}
6215 evaluates unquoted list elements twice while visiting the first list
6216 element, once in @code{@w{_arg1q}} and once in @code{@w{_rest}}.  When
6217 deciding which list style to use, one must take into account whether
6218 repeating the side effects of unquoted list elements will have any
6219 detrimental effects.
6221 @example
6222 include(`foreach2.m4')
6223 @result{}
6224 include(`foreachq2.m4')
6225 @result{}
6226 dnl 0-element list:
6227 foreach(`x', `', `<x>') / foreachq(`x', `', `<x>')
6228 @result{} /@w{ }
6229 dnl 1-element list of empty element
6230 foreach(`x', `()', `<x>') / foreachq(`x', ``'', `<x>')
6231 @result{}<> / <>
6232 dnl 2-element list of empty elements
6233 foreach(`x', `(`',`')', `<x>') / foreachq(`x', ``',`'', `<x>')
6234 @result{}<><> / <><>
6235 dnl 1-element list of a comma
6236 foreach(`x', `(`,')', `<x>') / foreachq(`x', ``,'', `<x>')
6237 @result{}<,> / <,>
6238 dnl 2-element list of unbalanced parentheses
6239 foreach(`x', `(`(', `)')', `<x>') / foreachq(`x', ``(', `)'', `<x>')
6240 @result{}<(><)> / <(><)>
6241 define(`active', `ACT, IVE')
6242 @result{}
6243 traceon(`active')
6244 @result{}
6245 dnl list of unquoted macros; expansion occurs before recursion
6246 foreach(`x', `(active, active)', `<x>
6247 ')dnl
6248 @error{}m4trace: -4- active -> `ACT, IVE'
6249 @error{}m4trace: -4- active -> `ACT, IVE'
6250 @result{}<ACT>
6251 @result{}<IVE>
6252 @result{}<ACT>
6253 @result{}<IVE>
6254 foreachq(`x', `active, active', `<x>
6255 ')dnl
6256 @error{}m4trace: -3- active -> `ACT, IVE'
6257 @error{}m4trace: -3- active -> `ACT, IVE'
6258 @result{}<ACT>
6259 @error{}m4trace: -3- active -> `ACT, IVE'
6260 @error{}m4trace: -3- active -> `ACT, IVE'
6261 @result{}<IVE>
6262 @result{}<ACT>
6263 @result{}<IVE>
6264 dnl list of quoted macros; expansion occurs during recursion
6265 foreach(`x', `(`active', `active')', `<x>
6266 ')dnl
6267 @error{}m4trace: -1- active -> `ACT, IVE'
6268 @result{}<ACT, IVE>
6269 @error{}m4trace: -1- active -> `ACT, IVE'
6270 @result{}<ACT, IVE>
6271 foreachq(`x', ``active', `active'', `<x>
6272 ')dnl
6273 @error{}m4trace: -1- active -> `ACT, IVE'
6274 @result{}<ACT, IVE>
6275 @error{}m4trace: -1- active -> `ACT, IVE'
6276 @result{}<ACT, IVE>
6277 dnl list of double-quoted macro names; no expansion
6278 foreach(`x', `(``active'', ``active'')', `<x>
6279 ')dnl
6280 @result{}<active>
6281 @result{}<active>
6282 foreachq(`x', ```active'', ``active''', `<x>
6283 ')dnl
6284 @result{}<active>
6285 @result{}<active>
6286 @end example
6288 @node Improved cleardivert
6289 @section Solution for @code{cleardivert}
6291 The @code{cleardivert} macro (@pxref{Cleardivert}) cannot, as it stands, be
6292 called without arguments to clear all pending diversions.  That is
6293 because using undivert with an empty string for an argument is different
6294 than using it with no arguments at all.  Compare the earlier definition
6295 with one that takes the number of arguments into account:
6297 @example
6298 define(`cleardivert',
6299   `pushdef(`_n', divnum)divert(`-1')undivert($@@)divert(_n)popdef(`_n')')
6300 @result{}
6301 divert(`1')one
6302 divert
6303 @result{}
6304 cleardivert
6305 @result{}
6306 undivert
6307 @result{}one
6308 @result{}
6309 define(`cleardivert',
6310   `pushdef(`_num', divnum)divert(`-1')ifelse(`$#', `0',
6311     `undivert`'', `undivert($@@)')divert(_num)popdef(`_num')')
6312 @result{}
6313 divert(`2')two
6314 divert
6315 @result{}
6316 cleardivert
6317 @result{}
6318 undivert
6319 @result{}
6320 @end example
6322 @node Improved fatal_error
6323 @section Solution for @code{fatal_error}
6325 The @code{fatal_error} macro (@pxref{M4exit}) is not robust to versions
6326 of @acronym{GNU} M4 earlier than 1.4.8, where invoking
6327 @code{@w{__file__}} (@pxref{Location}) inside @code{m4wrap} would result
6328 in an empty string, and @code{@w{__line__}} resulted in @samp{0} even
6329 though all files start at line 1.  Furthermore, versions earlier than
6330 1.4.6 did not support the @code{@w{__program__}} macro.  If you want
6331 @code{fatal_error} to work across the entire 1.4.x release series, a
6332 better implementation would be:
6334 @comment status: 1
6335 @example
6336 define(`fatal_error',
6337   `errprint(ifdef(`__program__', `__program__', ``m4'')'dnl
6338 `:ifelse(__line__, `0', `',
6339     `__file__:__line__:')` fatal error: $*
6340 ')m4exit(`1')')
6341 @result{}
6342 m4wrap(`divnum(`demo of internal message')
6343 fatal_error(`inside wrapped text')')
6344 @result{}
6346 @error{}m4:stdin:6: Warning: excess arguments to builtin `divnum' ignored
6347 @result{}0
6348 @error{}m4:stdin:6: fatal error: inside wrapped text
6349 @end example
6351 @c ========================================================== Appendices
6353 @node Copying This Manual
6354 @appendix How to make copies of this manual
6355 @cindex License
6357 @menu
6358 * GNU Free Documentation License::  License for copying this manual
6359 @end menu
6361 @include fdl.texi
6363 @node Indices
6364 @appendix Indices of concepts and macros
6366 @menu
6367 * Concept index::               Index for many concepts
6368 * Macro index::                 Index for all @code{m4} macros
6369 @end menu
6371 @node Concept index
6372 @appendixsec Index for many concepts
6374 @printindex cp
6376 @node Macro index
6377 @appendixsec Index for all @code{m4} macros
6379 References are exclusively to the places where a builtin is introduced
6380 the first time.
6382 @iftex
6383 @sp 1
6384 @end iftex
6386 @printindex fn
6388 @bye
6390 @c Local Variables:
6391 @c coding: iso-8859-1
6392 @c fill-column: 72
6393 @c ispell-local-dictionary: "american"
6394 @c indent-tabs-mode: nil
6395 @c whitespace-check-buffer-indent: nil
6396 @c End: