POSIX requires defn(`a',`b') to concatenate definitions.
[m4/ericb.git] / doc / m4.texinfo
blob2564c675ac5242daff6f9513a2ca26d28cdb88ec
1 \input texinfo @c -*- texinfo -*-
2 @comment ========================================================
3 @comment %**start of header
4 @setfilename m4.info
5 @include version.texi
6 @settitle GNU M4 @value{VERSION} macro processor
7 @setchapternewpage odd
8 @ifnothtml
9 @setcontentsaftertitlepage
10 @end ifnothtml
11 @finalout
13 @c @tabchar{}
14 @c ----------
15 @c The testsuite expects literal tab output in some examples, but
16 @c literal tabs in texinfo lead to formatting issues.
17 @macro tabchar
18 @       @c
19 @end macro
21 @c @ovar{ARG}
22 @c -------------------
23 @c The ARG is an optional argument.  To be used for macro arguments in
24 @c their documentation.
25 @macro ovar{varname}
26 @r{[}@var{\varname\}@r{]}
27 @end macro
29 @c @dvar{ARG, DEFAULT}
30 @c -------------------
31 @c The ARG is an optional argument, defaulting to DEFAULT.  To be used
32 @c for macro arguments in their documentation.
33 @macro dvar{varname, default}
34 @r{[}@var{\varname\} = @samp{\default\}@r{]}
35 @end macro
37 @comment %**end of header
38 @comment ========================================================
40 @copying
42 This manual is for @acronym{GNU} M4 (version @value{VERSION}, @value{UPDATED}),
43 a package containing an implementation of the m4 macro language.
45 Copyright @copyright{} 1989, 1990, 1991, 1992, 1993, 1994, 2004, 2005,
46 2006, 2007 Free Software Foundation, Inc.
48 @quotation
49 Permission is granted to copy, distribute and/or modify this document
50 under the terms of the @acronym{GNU} Free Documentation License,
51 Version 1.2 or any later version published by the Free Software
52 Foundation; with no Invariant Sections, no Front-Cover Texts, and no
53 Back-Cover Texts.  A copy of the license is included in the section
54 entitled ``@acronym{GNU} Free Documentation License.''
55 @end quotation
56 @end copying
58 @dircategory Text creation and manipulation
59 @direntry
60 * M4: (m4).                     A powerful macro processor.
61 @end direntry
63 @titlepage
64 @title GNU M4, version @value{VERSION}
65 @subtitle A powerful macro processor
66 @subtitle Edition @value{EDITION}, @value{UPDATED}
67 @author by Ren@'e Seindal, Fran@,{c}ois Pinard,
68 @author Gary V. Vaughan, and Eric Blake
69 @author (@email{bug-m4@@gnu.org})
71 @page
72 @vskip 0pt plus 1filll
73 @insertcopying
74 @end titlepage
76 @contents
78 @ifnottex
79 @node Top
80 @top GNU M4
81 @insertcopying
82 @end ifnottex
84 @acronym{GNU} @code{m4} is an implementation of the traditional UNIX macro
85 processor.  It is mostly SVR4 compatible, although it has some
86 extensions (for example, handling more than 9 positional parameters
87 to macros).  @code{m4} also has builtin functions for including
88 files, running shell commands, doing arithmetic, etc.  Autoconf needs
89 @acronym{GNU} @code{m4} for generating @file{configure} scripts, but not for
90 running them.
92 @acronym{GNU} @code{m4} was originally written by Ren@'e Seindal, with
93 subsequent changes by Fran@,{c}ois Pinard and other volunteers
94 on the Internet.  All names and email addresses can be found in the
95 files @file{m4-@value{VERSION}/@/AUTHORS} and
96 @file{m4-@value{VERSION}/@/THANKS} from the @acronym{GNU} M4
97 distribution.
99 This is release @value{VERSION}.  It is now considered stable:  future
100 releases in the 1.4.x series are only meant to fix bugs, increase speed,
101 or improve documentation.  However@dots{}
103 An experimental feature, which would improve @code{m4} usefulness,
104 allows for changing the syntax for what is a @dfn{word} in @code{m4}.
105 You should use:
106 @comment ignore
107 @example
108 ./configure --enable-changeword
109 @end example
110 @noindent
111 if you want this feature compiled in.  The current implementation
112 slows down @code{m4} considerably and is hardly acceptable.  In the
113 future, @code{m4} 2.0 will come with a different set of new features
114 that provide similar capabilities, but without the inefficiencies, so
115 changeword will go away and @emph{you should not count on it}.
117 @menu
118 * Preliminaries::               Introduction and preliminaries
119 * Invoking m4::                 Invoking @code{m4}
120 * Syntax::                      Lexical and syntactic conventions
122 * Macros::                      How to invoke macros
123 * Definitions::                 How to define new macros
124 * Conditionals::                Conditionals, loops, and recursion
126 * Debugging::                   How to debug macros and input
128 * Input Control::               Input control
129 * File Inclusion::              File inclusion
130 * Diversions::                  Diverting and undiverting output
132 * Text handling::               Macros for text handling
133 * Arithmetic::                  Macros for doing arithmetic
134 * Shell commands::              Macros for running shell commands
135 * Miscellaneous::               Miscellaneous builtin macros
136 * Frozen files::                Fast loading of frozen state
138 * Compatibility::               Compatibility with other versions of @code{m4}
139 * Answers::                     Correct version of some examples
141 * Copying This Package::        How to make copies of the overall M4 package
142 * Copying This Manual::         How to make copies of this manual
143 * Indices::                     Indices of concepts and macros
145 @detailmenu
146  --- The Detailed Node Listing ---
148 Introduction and preliminaries
150 * Intro::                       Introduction to @code{m4}
151 * History::                     Historical references
152 * Bugs::                        Problems and bugs
153 * Manual::                      Using this manual
155 Invoking @code{m4}
157 * Operation modes::             Command line options for operation modes
158 * Preprocessor features::       Command line options for preprocessor features
159 * Limits control::              Command line options for limits control
160 * Frozen state::                Command line options for frozen state
161 * Debugging options::           Command line options for debugging
162 * Command line files::          Specifying input files on the command line
164 Lexical and syntactic conventions
166 * Names::                       Macro names
167 * Quoted strings::              Quoting input to @code{m4}
168 * Comments::                    Comments in @code{m4} input
169 * Other tokens::                Other kinds of input tokens
170 * Input processing::            How @code{m4} copies input to output
172 How to invoke macros
174 * Invocation::                  Macro invocation
175 * Inhibiting Invocation::       Preventing macro invocation
176 * Macro Arguments::             Macro arguments
177 * Quoting Arguments::           On Quoting Arguments to macros
178 * Macro expansion::             Expanding macros
180 How to define new macros
182 * Define::                      Defining a new macro
183 * Arguments::                   Arguments to macros
184 * Pseudo Arguments::            Special arguments to macros
185 * Undefine::                    Deleting a macro
186 * Defn::                        Renaming macros
187 * Pushdef::                     Temporarily redefining macros
189 * Indir::                       Indirect call of macros
190 * Builtin::                     Indirect call of builtins
192 Conditionals, loops, and recursion
194 * Ifdef::                       Testing if a macro is defined
195 * Ifelse::                      If-else construct, or multibranch
196 * Shift::                       Recursion in @code{m4}
197 * Forloop::                     Iteration by counting
198 * Foreach::                     Iteration by list contents
200 How to debug macros and input
202 * Dumpdef::                     Displaying macro definitions
203 * Trace::                       Tracing macro calls
204 * Debug Levels::                Controlling debugging output
205 * Debug Output::                Saving debugging output
207 Input control
209 * Dnl::                         Deleting whitespace in input
210 * Changequote::                 Changing the quote characters
211 * Changecom::                   Changing the comment delimiters
212 * Changeword::                  Changing the lexical structure of words
213 * M4wrap::                      Saving text until end of input
215 File inclusion
217 * Include::                     Including named files
218 * Search Path::                 Searching for include files
220 Diverting and undiverting output
222 * Divert::                      Diverting output
223 * Undivert::                    Undiverting output
224 * Divnum::                      Diversion numbers
225 * Cleardivert::                 Discarding diverted text
227 Macros for text handling
229 * Len::                         Calculating length of strings
230 * Index macro::                 Searching for substrings
231 * Regexp::                      Searching for regular expressions
232 * Substr::                      Extracting substrings
233 * Translit::                    Translating characters
234 * Patsubst::                    Substituting text by regular expression
235 * Format::                      Formatting strings (printf-like)
237 Macros for doing arithmetic
239 * Incr::                        Decrement and increment operators
240 * Eval::                        Evaluating integer expressions
242 Macros for running shell commands
244 * Platform macros::             Determining the platform
245 * Syscmd::                      Executing simple commands
246 * Esyscmd::                     Reading the output of commands
247 * Sysval::                      Exit status
248 * Mkstemp::                     Making temporary files
250 Miscellaneous builtin macros
252 * Errprint::                    Printing error messages
253 * Location::                    Printing current location
254 * M4exit::                      Exiting from @code{m4}
256 Fast loading of frozen state
258 * Using frozen files::          Using frozen files
259 * Frozen file format::          Frozen file format
261 Compatibility with other versions of @code{m4}
263 * Extensions::                  Extensions in @acronym{GNU} M4
264 * Incompatibilities::           Facilities in System V m4 not in GNU M4
265 * Other Incompatibilities::     Other incompatibilities
267 Correct version of some examples
269 * Improved exch::               Solution for @code{exch}
270 * Improved forloop::            Solution for @code{forloop}
271 * Improved foreach::            Solution for @code{foreach}
272 * Improved cleardivert::        Solution for @code{cleardivert}
273 * Improved fatal_error::        Solution for @code{fatal_error}
275 How to make copies of the overall M4 package
277 * GNU General Public License::  License for copying the M4 package
279 How to make copies of this manual
281 * GNU Free Documentation License::  License for copying this manual
283 Indices of concepts and macros
285 * Macro index::                 Index for all @code{m4} macros
286 * Concept index::               Index for many concepts
288 @end detailmenu
289 @end menu
291 @node Preliminaries
292 @chapter Introduction and preliminaries
294 This first chapter explains what @acronym{GNU} @code{m4} is, where @code{m4}
295 comes from, how to read and use this documentation, how to call the
296 @code{m4} program, and how to report bugs about it.  It concludes by
297 giving tips for reading the remainder of the manual.
299 The following chapters then detail all the features of the @code{m4}
300 language.
302 @menu
303 * Intro::                       Introduction to @code{m4}
304 * History::                     Historical references
305 * Bugs::                        Problems and bugs
306 * Manual::                      Using this manual
307 @end menu
309 @node Intro
310 @section Introduction to @code{m4}
312 @cindex overview of @code{m4}
313 @code{m4} is a macro processor, in the sense that it copies its
314 input to the output, expanding macros as it goes.  Macros are either
315 builtin or user-defined, and can take any number of arguments.
316 Besides just doing macro expansion, @code{m4} has builtin functions
317 for including named files, running shell commands, doing integer
318 arithmetic, manipulating text in various ways, performing recursion,
319 etc.@dots{}  @code{m4} can be used either as a front-end to a compiler,
320 or as a macro processor in its own right.
322 The @code{m4} macro processor is widely available on all UNIXes, and has
323 been standardized by @acronym{POSIX}.
324 Usually, only a small percentage of users are aware of its existence.
325 However, those who find it often become committed users.  The
326 popularity of @acronym{GNU} Autoconf, which requires @acronym{GNU}
327 @code{m4} for @emph{generating} @file{configure} scripts, is an incentive
328 for many to install it, while these people will not themselves
329 program in @code{m4}.  @acronym{GNU} @code{m4} is mostly compatible with the
330 System V, Release 3 version, except for some minor differences.
331 @xref{Compatibility}, for more details.
333 Some people find @code{m4} to be fairly addictive.  They first use
334 @code{m4} for simple problems, then take bigger and bigger challenges,
335 learning how to write complex sets of @code{m4} macros along the way.
336 Once really addicted, users pursue writing of sophisticated @code{m4}
337 applications even to solve simple problems, devoting more time
338 debugging their @code{m4} scripts than doing real work.  Beware that
339 @code{m4} may be dangerous for the health of compulsive programmers.
341 @node History
342 @section Historical references
344 @cindex history of @code{m4}
345 @cindex @acronym{GNU} M4, history of
346 @code{GPM} was an important ancestor of @code{m4}.  See
347 C. Stratchey: ``A General Purpose Macro generator'', Computer Journal
348 8,3 (1965), pp. 225 ff.  @code{GPM} is also succinctly described into
349 David Gries classic ``Compiler Construction for Digital Computers''.
351 The classic B. Kernighan and P.J. Plauger: ``Software Tools'',
352 Addison-Wesley, Inc. (1976) describes and implements a Unix
353 macro-processor language, which inspired Dennis Ritchie to write
354 @code{m3}, a macro processor for the AP-3 minicomputer.
356 Kernighan and Ritchie then joined forces to develop the original
357 @code{m4}, as described in ``The M4 Macro Processor'', Bell
358 Laboratories (1977).  It had only 21 builtin macros.
360 While @code{GPM} was more @emph{pure}, @code{m4} is meant to deal with
361 the true intricacies of real life: macros can be recognized without
362 being pre-announced, skipping whitespace or end-of-lines is easier,
363 more constructs are builtin instead of derived, etc.
365 Originally, the Kernighan and Plauger macro-processor, and then
366 @code{m3}, formed the engine for the Rational FORTRAN preprocessor,
367 that is, the @code{Ratfor} equivalent of @code{cpp}.  Later, @code{m4}
368 was used as a front-end for @code{Ratfor}, @code{C} and @code{Cobol}.
370 Ren@'e Seindal released his implementation of @code{m4}, @acronym{GNU}
371 @code{m4},
372 in 1990, with the aim of removing the artificial limitations in many
373 of the traditional @code{m4} implementations, such as maximum line
374 length, macro size, or number of macros.
376 The late Professor A. Dain Samples described and implemented a further
377 evolution in the form of @code{M5}: ``User's Guide to the M5 Macro
378 Language: 2nd edition'', Electronic Announcement on comp.compilers
379 newsgroup (1992).
381 Fran@,{c}ois Pinard took over maintenance of @acronym{GNU} @code{m4} in
382 1992, until 1994 when he released @acronym{GNU} @code{m4} 1.4, which was
383 the stable release for 10 years.  It was at this time that @acronym{GNU}
384 Autoconf decided to require @acronym{GNU} @code{m4} as its underlying
385 engine, since all other implementations of @code{m4} had too many
386 limitations.
388 More recently, in 2004, Paul Eggert released 1.4.1 and 1.4.2 which
389 addressed some long standing bugs in the venerable 1.4 release.  Then in
390 2005, Gary V. Vaughan collected together the many patches to
391 @acronym{GNU} @code{m4} 1.4 that were floating around the net and
392 released 1.4.3 and 1.4.4.  And in 2006, Eric Blake joined the team and
393 prepared patches for the release of 1.4.5, 1.4.6, 1.4.7, and 1.4.8.  The
394 1.4.x series remains open for bug fixes, including releases 1.4.9,
395 1.4.10, and 1.4.11 in 2007.
397 Meanwhile, development has continued on new features for @code{m4}, such
398 as dynamic module loading and additional builtins.  When complete,
399 @acronym{GNU} @code{m4} 2.0 will start a new series of releases.
401 @node Bugs
402 @section Problems and bugs
404 @cindex reporting bugs
405 @cindex bug reports
406 @cindex suggestions, reporting
407 If you have problems with @acronym{GNU} M4 or think you've found a bug,
408 please report it.  Before reporting a bug, make sure you've actually
409 found a real bug.  Carefully reread the documentation and see if it
410 really says you can do what you're trying to do.  If it's not clear
411 whether you should be able to do something or not, report that too; it's
412 a bug in the documentation!
414 Before reporting a bug or trying to fix it yourself, try to isolate it
415 to the smallest possible input file that reproduces the problem.  Then
416 send us the input file and the exact results @code{m4} gave you.  Also
417 say what you expected to occur; this will help us decide whether the
418 problem was really in the documentation.
420 Once you've got a precise problem, send e-mail to
421 @email{bug-m4@@gnu.org}.  Please include the version number of @code{m4}
422 you are using.  You can get this information with the command
423 @kbd{m4 --version}.  Also provide details about the platform you are
424 executing on.
426 Non-bug suggestions are always welcome as well.  If you have questions
427 about things that are unclear in the documentation or are just obscure
428 features, please report them too.
430 @node Manual
431 @section Using this manual
433 @cindex examples, understanding
434 This manual contains a number of examples of @code{m4} input and output,
435 and a simple notation is used to distinguish input, output and error
436 messages from @code{m4}.  Examples are set out from the normal text, and
437 shown in a fixed width font, like this
439 @comment ignore
440 @example
441 This is an example of an example!
442 @end example
444 To distinguish input from output, all output from @code{m4} is prefixed
445 by the string @samp{@result{}}, and all error messages by the string
446 @samp{@error{}}.  When showing how command line options affect matters,
447 the command line is shown with a prompt @samp{$ @kbd{like this}},
448 otherwise, you can assume that a simple @kbd{m4} invocation will work.
449 Thus:
451 @comment ignore
452 @example
453 $ @kbd{command line to invoke m4}
454 Example of input line
455 @result{}Output line from m4
456 @error{}and an error message
457 @end example
459 The sequence @samp{^D} in an example indicates the end of the input
460 file.  The sequence @samp{@key{NL}} refers to the newline character.
461 The majority of these examples are self-contained, and you can run them
462 with similar results by invoking @kbd{m4 -d}.  In fact, the testsuite
463 that is bundled in the @acronym{GNU} M4 package consists of the examples
464 in this document!  Some of the examples assume that your current
465 directory is located where you unpacked the installation, so if you plan
466 on following along, you may find it helpful to do this now:
468 @comment ignore
469 @example
470 $ @kbd{cd m4-@value{VERSION}}
471 @end example
473 As each of the predefined macros in @code{m4} is described, a prototype
474 call of the macro will be shown, giving descriptive names to the
475 arguments, e.g.,
477 @deffn Composite example (@var{string}, @dvar{count, 1}, @
478   @ovar{argument}@dots{})
479 This is a sample prototype.  There is not really a macro named
480 @code{example}, but this documents that if there were, it would be a
481 Composite macro, rather than a Builtin.  It requires at least one
482 argument, @var{string}.  Remember that in @code{m4}, there must not be a
483 space between the macro name and the opening parenthesis, unless it was
484 intended to call the macro without any arguments.  The brackets around
485 @var{count} and @var{argument} show that these arguments are optional.
486 If @var{count} is omitted, the macro behaves as if count were @samp{1},
487 whereas if @var{argument} is omitted, the macro behaves as if it were
488 the empty string.  A blank argument is not the same as an omitted
489 argument.  For example, @samp{example(`a')}, @samp{example(`a',`1')},
490 and @samp{example(`a',`1',)} would behave identically with @var{count}
491 set to @samp{1}; while @samp{example(`a',)} and @samp{example(`a',`')}
492 would explicitly pass the empty string for @var{count}.  The ellipses
493 (@samp{@dots{}}) show that the macro processes additional arguments
494 after @var{argument}, rather than ignoring them.
495 @end deffn
497 @cindex numbers
498 All macro arguments in @code{m4} are strings, but some are given
499 special interpretation, e.g., as numbers, file names, regular
500 expressions, etc.  The documentation for each macro will state how the
501 parameters are interpreted, and what happens if the argument cannot be
502 parsed according to the desired interpretation.  Unless specified
503 otherwise, a parameter specified to be a number is parsed as a decimal,
504 even if the argument has leading zeros; and parsing the empty string as
505 a number results in 0 rather than an error, although a warning will be
506 issued.
508 This document consistently writes and uses @dfn{builtin}, without a
509 hyphen, as if it were an English word.  This is how the @code{builtin}
510 primitive is spelled within @code{m4}.
512 @node Invoking m4
513 @chapter Invoking @code{m4}
515 @cindex command line
516 @cindex invoking @code{m4}
517 The format of the @code{m4} command is:
519 @comment ignore
520 @example
521 @code{m4} @r{[}@var{option}@dots{}@r{]} @r{[}@var{file}@dots{}@r{]}
522 @end example
524 @cindex command line, options
525 @cindex options, command line
526 @cindex @env{POSIXLY_CORRECT}
527 All options begin with @samp{-}, or if long option names are used, with
528 @samp{--}.  A long option name need not be written completely, any
529 unambiguous prefix is sufficient.  @acronym{POSIX} requires @code{m4} to
530 recognize arguments intermixed with files, even when
531 @env{POSIXLY_CORRECT} is set in the environment.  Most options take
532 effect at startup regardless of their position, but some are documented
533 below as taking effect after any files that occurred earlier in the
534 command line.  The argument @option{--} is a marker to denote the end of
535 options.
537 With short options, options that do not take arguments may be combined
538 into a single command line argument with subsequent options, options
539 with mandatory arguments may be provided either as a single command line
540 argument or as two arguments, and options with optional arguments must
541 be provided as a single argument.  In other words,
542 @kbd{m4 -QPDfoo -d a -d+f} is equivalent to
543 @kbd{m4 -Q -P -D foo -d -d+f -- ./a}, although the latter form is
544 considered canonical.
546 With long options, options with mandatory arguments may be provided with
547 an equal sign (@samp{=}) in a single argument, or as two arguments, and
548 options with optional arguments must be provided as a single argument.
549 In other words, @kbd{m4 --def foo --debug a} is equivalent to
550 @kbd{m4 --define=foo --debug= -- ./a}, although the latter form is
551 considered canonical (not to mention more robust, in case a future
552 version of @code{m4} introduces an option named @option{--default}).
554 @code{m4} understands the following options, grouped by functionality.
556 @menu
557 * Operation modes::             Command line options for operation modes
558 * Preprocessor features::       Command line options for preprocessor features
559 * Limits control::              Command line options for limits control
560 * Frozen state::                Command line options for frozen state
561 * Debugging options::           Command line options for debugging
562 * Command line files::          Specifying input files on the command line
563 @end menu
565 @node Operation modes
566 @section Command line options for operation modes
568 Several options control the overall operation of @code{m4}:
570 @table @code
571 @item --help
572 Print a help summary on standard output, then immediately exit
573 @code{m4} without reading any input files or performing any other
574 actions.
576 @item --version
577 Print the version number of the program on standard output, then
578 immediately exit @code{m4} without reading any input files or
579 performing any other actions.
581 @item -E
582 @itemx --fatal-warnings
583 @cindex errors, fatal
584 @cindex fatal errors
585 Controls the effect of warnings.  If unspecified, then execution
586 continues and exit status is unaffected when a warning is printed.  If
587 specified exactly once, warnings become fatal; when one is issued,
588 execution continues, but the exit status will be non-zero.  If specified
589 multiple times, then execution halts with non-zero status the first time
590 a warning is issued.  The introduction of behavior levels is new to M4
591 1.4.9; for behavior consistent with earlier versions, you should specify
592 @option{-E} twice.
594 @item -i
595 @itemx --interactive
596 @itemx -e
597 Makes this invocation of @code{m4} interactive.  This means that all
598 output will be unbuffered, and interrupts will be ignored.  The
599 spelling @option{-e} exists for compatibility with other @code{m4}
600 implementations, and issues a warning because it may be withdrawn in a
601 future version of @acronym{GNU} M4.
603 @item -P
604 @itemx --prefix-builtins
605 Internally modify @emph{all} builtin macro names so they all start with
606 the prefix @samp{m4_}.  For example, using this option, one should write
607 @samp{m4_define} instead of @samp{define}, and @samp{m4___file__}
608 instead of @samp{__file__}.  This option has no effect if @option{-R}
609 is also specified.
611 @item -Q
612 @itemx --quiet
613 @itemx --silent
614 Suppress warnings, such as missing or superfluous arguments in macro
615 calls, or treating the empty string as zero.
617 @item --warn-macro-sequence@r{[}=@var{REGEXP}@r{]}
618 Issue a warning if the regular expression @var{REGEXP} has a non-empty
619 match in any macro definition (either by @code{define} or
620 @code{pushdef}).  Empty matches are ignored; therefore, supplying the
621 empty string as @var{REGEXP} disables any warning.  If the optional
622 @var{REGEXP} is not supplied, then the default regular expression is
623 @samp{\$\(@{[^@}]*@}\|[0-9][0-9]+\)} (a literal @samp{$} followed by
624 multiple digits or by an open brace), since these sequences will
625 change semantics in the default operation of @acronym{GNU} M4 2.0 (due
626 to a change in how more than 9 arguments in a macro definition will be
627 handled, @pxref{Arguments}).  Providing an alternate regular
628 expression can provide a useful reverse lookup feature of finding
629 where a macro is defined to have a given definition.
631 @item -W @var{REGEXP}
632 @itemx --word-regexp=@var{REGEXP}
633 Use @var{REGEXP} as an alternative syntax for macro names.  This
634 experimental option will not be present in all @acronym{GNU} @code{m4}
635 implementations (@pxref{Changeword}).
636 @end table
638 @node Preprocessor features
639 @section Command line options for preprocessor features
641 @cindex macro definitions, on the command line
642 @cindex command line, macro definitions on the
643 @cindex preprocessor features
644 Several options allow @code{m4} to behave more like a preprocessor.
645 Macro definitions and deletions can be made on the command line, the
646 search path can be altered, and the output file can track where the
647 input came from.  These features occur with the following options:
649 @table @code
650 @item -D @var{NAME}@r{[}=@var{VALUE}@r{]}
651 @itemx --define=@var{NAME}@r{[}=@var{VALUE}@r{]}
652 This enters @var{NAME} into the symbol table.  If @samp{=@var{VALUE}} is
653 missing, the value is taken to be the empty string.  The @var{VALUE} can
654 be any string, and the macro can be defined to take arguments, just as
655 if it was defined from within the input.  This option may be given more
656 than once; order with respect to file names is significant, and
657 redefining the same @var{NAME} loses the previous value.
659 @item -I @var{DIRECTORY}
660 @itemx --include=@var{DIRECTORY}
661 Make @code{m4} search @var{DIRECTORY} for included files that are not
662 found in the current working directory.  @xref{Search Path}, for more
663 details.  This option may be given more than once.
665 @item -s
666 @itemx --synclines
667 @cindex synchronization lines
668 @cindex location, input
669 @cindex input location
670 Generate synchronization lines, for use by the C preprocessor or other
671 similar tools.  Order is significant with respect to file names.  This
672 option is useful, for example, when @code{m4} is used as a
673 front end to a compiler.  Source file name and line number information
674 is conveyed by directives of the form @samp{#line @var{linenum}
675 "@var{file}"}, which are inserted as needed into the middle of the
676 output.  Such directives mean that the following line originated or was
677 expanded from the contents of input file @var{file} at line
678 @var{linenum}.  The @samp{"@var{file}"} part is often omitted when
679 the file name did not change from the previous directive.
681 Synchronization directives are always given on complete lines by
682 themselves.  When a synchronization discrepancy occurs in the middle of
683 an output line, the associated synchronization directive is delayed
684 until the next newline that does not occur in the middle of a quoted
685 string or comment.
687 @comment options: -s
688 @example
689 define(`twoline', `1
691 @result{}#line 2 "stdin"
692 @result{}
693 changecom(`/*', `*/')
694 @result{}
695 define(`comment', `/*1
696 2*/')
697 @result{}#line 5
698 @result{}
699 dnl no line
700 hello
701 @result{}#line 7
702 @result{}hello
703 twoline
704 @result{}1
705 @result{}#line 8
706 @result{}2
707 comment
708 @result{}/*1
709 @result{}2*/
710 one comment `two
711 three'
712 @result{}#line 10
713 @result{}one /*1
714 @result{}2*/ two
715 @result{}three
716 goodbye
717 @result{}#line 12
718 @result{}goodbye
719 @end example
721 @item -U @var{NAME}
722 @itemx --undefine=@var{NAME}
723 This deletes any predefined meaning @var{NAME} might have.  Obviously,
724 only predefined macros can be deleted in this way.  This option may be
725 given more than once; undefining a @var{NAME} that does not have a
726 definition is silently ignored.  Order is significant with respect to
727 file names.
728 @end table
730 @node Limits control
731 @section Command line options for limits control
733 There are some limits within @code{m4} that can be tuned.  For
734 compatibility, @code{m4} also accepts some options that control limits
735 in other implementations, but which are automatically unbounded (limited
736 only by your hardware and operating system constraints) in @acronym{GNU}
737 @code{m4}.
739 @table @code
740 @item -G
741 @itemx --traditional
742 Suppress all the extensions made in this implementation, compared to the
743 System V version.  @xref{Compatibility}, for a list of these.
745 @item -H @var{NUM}
746 @itemx --hashsize=@var{NUM}
747 Make the internal hash table for symbol lookup be @var{NUM} entries big.
748 For better performance, the number should be prime, but this is not
749 checked.  The default is 509 entries.  It should not be necessary to
750 increase this value, unless you define an excessive number of macros.
752 @item -L @var{NUM}
753 @itemx --nesting-limit=@var{NUM}
754 @cindex nesting limit
755 @cindex limit, nesting
756 Artificially limit the nesting of macro calls to @var{NUM} levels,
757 stopping program execution if this limit is ever exceeded.  When not
758 specified, nesting is limited to 1024 levels.  A value of zero means
759 unlimited; but then heavily nested code could potentially cause a stack
760 overflow.
762 The precise effect of this option might be more correctly associated
763 with textual nesting than dynamic recursion.  It has been useful
764 when some complex @code{m4} input was generated by mechanical means.
765 Most users would never need this option.  If shown to be obtrusive,
766 this option (which is still experimental) might well disappear.
768 @cindex rescanning
769 This option does @emph{not} have the ability to break endless
770 rescanning loops, since these do not necessarily consume much memory
771 or stack space.  Through clever usage of rescanning loops, one can
772 request complex, time-consuming computations from @code{m4} with useful
773 results.  Putting limitations in this area would break @code{m4} power.
774 There are many pathological cases: @w{@samp{define(`a', `a')a}} is
775 only the simplest example (but @pxref{Compatibility}).  Expecting @acronym{GNU}
776 @code{m4} to detect these would be a little like expecting a compiler
777 system to detect and diagnose endless loops: it is a quite @emph{hard}
778 problem in general, if not undecidable!
780 @item -B @var{NUM}
781 @itemx -S @var{NUM}
782 @itemx -T @var{NUM}
783 These options are present for compatibility with System V @code{m4}, but
784 do nothing in this implementation.  They may disappear in future
785 releases, and issue a warning to that effect.
787 @item -N @var{NUM}
788 @itemx --diversions=@var{NUM}
789 These options are present only for compatibility with previous
790 versions of @acronym{GNU} @code{m4}, and were controlling the number of
791 possible diversions which could be used at the same time.  They do nothing,
792 because there is no fixed limit anymore.  They may disappear in future
793 releases, and issue a warning to that effect.
794 @end table
796 @node Frozen state
797 @section Command line options for frozen state
799 @acronym{GNU} @code{m4} comes with a feature of freezing internal state
800 (@pxref{Frozen files}).  This can be used to speed up @code{m4}
801 execution when reusing a common initialization script.
803 @table @code
804 @item -F @var{FILE}
805 @itemx --freeze-state=@var{FILE}
806 Once execution is finished, write out the frozen state on the specified
807 @var{FILE}.  It is conventional, but not required, for @var{FILE} to end
808 in @samp{.m4f}.
810 @item -R @var{FILE}
811 @itemx --reload-state=@var{FILE}
812 Before execution starts, recover the internal state from the specified
813 frozen @var{FILE}.  The options @option{-D}, @option{-U}, and
814 @option{-t} take effect after state is reloaded, but before the input
815 files are read.
816 @end table
818 @node Debugging options
819 @section Command line options for debugging
821 Finally, there are several options for aiding in debugging @code{m4}
822 scripts.
824 @table @code
825 @item -d@r{[}@var{FLAGS}@r{]}
826 @itemx --debug@r{[}=@var{FLAGS}@r{]}
827 Set the debug-level according to the flags @var{FLAGS}.  The debug-level
828 controls the format and amount of information presented by the debugging
829 functions.  @xref{Debug Levels}, for more details on the format and
830 meaning of @var{FLAGS}.  If omitted, @var{FLAGS} defaults to @samp{aeq}.
832 @item --debugfile=@var{FILE}
833 @itemx -o @var{FILE}
834 @itemx --error-output=@var{FILE}
835 Redirect @code{dumpdef} output, debug messages, and trace output to the
836 named @var{FILE}.  Warnings, error messages, and @code{errprint} output
837 are still printed to standard error.  If unspecified, debug output goes
838 to standard error; if empty, debug output is discarded.  @xref{Debug
839 Output}, for more details.  The spellings @option{-o} and
840 @option{--error-output} are misleading and inconsistent with other
841 @acronym{GNU} tools; for now they are silently accepted as synonyms of
842 @option{--debugfile}, but in a future version of M4, using them will
843 cause a warning to be issued.
845 @item -l @var{NUM}
846 @itemx --arglength=@var{NUM}
847 Restrict the size of the output generated by macro tracing to @var{NUM}
848 characters per trace line.  If unspecified or zero, output is
849 unlimited.  @xref{Debug Levels}, for more details.
851 @item -t @var{NAME}
852 @itemx --trace=@var{NAME}
853 This enables tracing for the macro @var{NAME}, at any point where it is
854 defined.  @var{NAME} need not be defined when this option is given.
855 This option may be given more than once, and order is significant with
856 respect to file names.  @xref{Trace}, for more details.
857 @end table
859 @node Command line files
860 @section Specifying input files on the command line
862 @cindex command line, file names on the
863 @cindex file names, on the command line
864 The remaining arguments on the command line are taken to be input file
865 names.  If no names are present, standard input is read.  A file
866 name of @file{-} is taken to mean standard input.  It is
867 conventional, but not required, for input files to end in @samp{.m4}.
869 The input files are read in the sequence given.  Standard input can be
870 read more than once, so the file name @file{-} may appear multiple times
871 on the command line; this makes a difference when input is from a
872 terminal or other special file type.  It is an error if an input file
873 ends in the middle of argument collection, a comment, or a quoted
874 string.
876 The options @option{--define} (@option{-D}), @option{--undefine}
877 (@option{-U}), @option{--synclines} (@option{-s}), and @option{--trace}
878 (@option{-t}) only take effect after processing input from any file
879 names that occur earlier on the command line.  For example, assume the
880 file @file{foo} contains:
882 @comment ignore
883 @example
884 $ @kbd{cat foo}
886 @end example
888 The text @samp{bar} can then be redefined over multiple uses of
889 @file{foo}:
891 @comment options: -Dbar=hello foo -Dbar=world foo
892 @example
893 $ @kbd{m4 -Dbar=hello foo -Dbar=world foo}
894 @result{}hello
895 @result{}world
896 @end example
898 If none of the input files invoked @code{m4exit} (@pxref{M4exit}), the
899 exit status of @code{m4} will be 0 for success, 1 for general failure
900 (such as problems with reading an input file), and 63 for version
901 mismatch (@pxref{Using frozen files}).
903 If you need to read a file whose name starts with a @file{-}, you can
904 specify it as @samp{./-file}, or use @option{--} to mark the end of
905 options.
907 @node Syntax
908 @chapter Lexical and syntactic conventions
910 @cindex input tokens
911 @cindex tokens
912 As @code{m4} reads its input, it separates it into @dfn{tokens}.  A
913 token is either a name, a quoted string, or any single character, that
914 is not a part of either a name or a string.  Input to @code{m4} can also
915 contain comments.  @acronym{GNU} @code{m4} does not yet understand
916 multibyte locales; all operations are byte-oriented rather than
917 character-oriented (although if your locale uses a single byte
918 encoding, such as @sc{ISO-8859-1}, you will not notice a difference).
919 However, @code{m4} is eight-bit clean, so you can
920 use non-@sc{ascii} characters in quoted strings (@pxref{Changequote}),
921 comments (@pxref{Changecom}), and macro names (@pxref{Indir}), with the
922 exception of the @sc{nul} character (the zero byte @samp{'\0'}).
924 @menu
925 * Names::                       Macro names
926 * Quoted strings::              Quoting input to @code{m4}
927 * Comments::                    Comments in @code{m4} input
928 * Other tokens::                Other kinds of input tokens
929 * Input processing::            How @code{m4} copies input to output
930 @end menu
932 @node Names
933 @section Macro names
935 @cindex names
936 @cindex words
937 A name is any sequence of letters, digits, and the character @samp{_}
938 (underscore), where the first character is not a digit.  @code{m4} will
939 use the longest such sequence found in the input.  If a name has a
940 macro definition, it will be subject to macro expansion
941 (@pxref{Macros}).  Names are case-sensitive.
943 Examples of legal names are: @samp{foo}, @samp{_tmp}, and @samp{name01}.
945 @node Quoted strings
946 @section Quoting input to @code{m4}
948 @cindex quoted string
949 @cindex string, quoted
950 A quoted string is a sequence of characters surrounded by quote
951 strings, defaulting to
952 @samp{`} and @samp{'}, where the nested begin and end quotes within the
953 string are balanced.  The value of a string token is the text, with one
954 level of quotes stripped off.  Thus
956 @comment ignore
957 @example
959 @result{}
960 @end example
962 @noindent
963 is the empty string, and double-quoting turns into single-quoting.
965 @comment ignore
966 @example
967 ``quoted''
968 @result{}`quoted'
969 @end example
971 The quote characters can be changed at any time, using the builtin macro
972 @code{changequote}.  @xref{Changequote}, for more information.
974 @node Comments
975 @section Comments in @code{m4} input
977 @cindex comments
978 Comments in @code{m4} are normally delimited by the characters @samp{#}
979 and newline.  All characters between the comment delimiters are ignored,
980 but the entire comment (including the delimiters) is passed through to
981 the output---comments are @emph{not} discarded by @code{m4}.
983 Comments cannot be nested, so the first newline after a @samp{#} ends
984 the comment.  The commenting effect of the begin-comment string
985 can be inhibited by quoting it.
987 @example
988 $ @kbd{m4}
989 `quoted text' # `commented text'
990 @result{}quoted text # `commented text'
991 `quoting inhibits' `#' `comments'
992 @result{}quoting inhibits # comments
993 @end example
995 The comment delimiters can be changed to any string at any time, using
996 the builtin macro @code{changecom}.  @xref{Changecom}, for more
997 information.
999 @node Other tokens
1000 @section Other kinds of input tokens
1002 @cindex tokens, special
1003 Any character, that is neither a part of a name, nor of a quoted string,
1004 nor a comment, is a token by itself.  When not in the context of macro
1005 expansion, all of these tokens are just copied to output.  However,
1006 during macro expansion, whitespace characters (space, tab, newline,
1007 formfeed, carriage return, vertical tab), parentheses (@samp{(} and
1008 @samp{)}), comma (@samp{,}), and dollar (@samp{$}) have additional
1009 roles, explained later.
1011 @node Input processing
1012 @section How @code{m4} copies input to output
1014 As @code{m4} reads the input token by token, it will copy each token
1015 directly to the output immediately.
1017 The exception is when it finds a word with a macro definition.  In that
1018 case @code{m4} will calculate the macro's expansion, possibly reading
1019 more input to get the arguments.  It then inserts the expansion in front
1020 of the remaining input.  In other words, the resulting text from a macro
1021 call will be read and parsed into tokens again.
1023 @code{m4} expands a macro as soon as possible.  If it finds a macro call
1024 when collecting the arguments to another, it will expand the second call
1025 first.  This process continues until there are no more macro calls to
1026 expand and all the input has been consumed.
1028 For a running example, examine how @code{m4} handles this input:
1030 @comment ignore
1031 @example
1032 format(`Result is %d', eval(`2**15'))
1033 @end example
1035 @noindent
1036 First, @code{m4} sees that the token @samp{format} is a macro name, so
1037 it collects the tokens @samp{(}, @samp{`Result is %d'}, @samp{,},
1038 and @samp{@w{ }}, before encountering another potential macro.  Sure
1039 enough, @samp{eval} is a macro name, so the nested argument collection
1040 picks up @samp{(}, @samp{`2**15'}, and @samp{)}, invoking the eval macro
1041 with the lone argument of @samp{2**15}.  The expansion of
1042 @samp{eval(2**15)} is @samp{32768}, which is then rescanned as the five
1043 tokens @samp{3}, @samp{2}, @samp{7}, @samp{6}, and @samp{8}; and
1044 combined with the next @samp{)}, the format macro now has all its
1045 arguments, as if the user had typed:
1047 @comment ignore
1048 @example
1049 format(`Result is %d', 32768)
1050 @end example
1052 @noindent
1053 The format macro expands to @samp{Result is 32768}, and we have another
1054 round of scanning for the tokens @samp{Result}, @samp{@w{ }},
1055 @samp{is}, @samp{@w{ }}, @samp{3}, @samp{2}, @samp{7}, @samp{6}, and
1056 @samp{8}.  None of these are macros, so the final output is
1058 @comment ignore
1059 @example
1060 @result{}Result is 32768
1061 @end example
1063 As a more complicated example, we will contrast an actual code
1064 example from the Gnulib project@footnote{Derived from a patch in
1065 @uref{http://lists.gnu.org/archive/html/bug-gnulib/@/2007-01/@/msg00389.html},
1066 and a followup patch in
1067 @uref{http://lists.gnu.org/archive/html/bug-gnulib/@/2007-02/@/msg00000.html}},
1068 showing both a buggy approach and the desired results.  The user desires
1069 to output a shell assignment statement that takes its argument and turns
1070 it into a shell variable by converting it to uppercase and prepending a
1071 prefix.  The original attempt looks like this:
1073 @example
1074 changequote([,])dnl
1075 define([gl_STRING_MODULE_INDICATOR],
1076   [
1077     dnl comment
1078     GNULIB_]translit([$1],[a-z],[A-Z])[=1
1079   ])dnl
1080   gl_STRING_MODULE_INDICATOR([strcase])
1081 @result{} @w{ }
1082 @result{}        GNULIB_strcase=1
1083 @result{} @w{ }
1084 @end example
1086 Oops -- the argument did not get capitalized.  And although the manual
1087 is not able to easily show it, both lines that appear empty actually
1088 contain two trailing spaces.  By stepping through the parse, it is easy
1089 to see what happened.  First, @code{m4} sees the token
1090 @samp{changequote}, which it recognizes as a macro, followed by
1091 @samp{(}, @samp{[}, @samp{,}, @samp{]}, and @samp{)} to form the
1092 argument list.  The macro expands to the empty string, but changes the
1093 quoting characters to something more useful for generating shell code
1094 (unbalanced @samp{`} and @samp{'} appear all the time in shell scripts,
1095 but unbalanced @samp{[]} tend to be rare).  Also in the first line,
1096 @code{m4} sees the token @samp{dnl}, which it recognizes as a builtin
1097 macro that consumes the rest of the line, resulting in no output for
1098 that line.
1100 The second line starts a macro definition.  @code{m4} sees the token
1101 @samp{define}, which it recognizes as a macro, followed by a @samp{(},
1102 @samp{[gl_STRING_MODULE_INDICATOR]}, and @samp{,}.  Because an unquoted
1103 comma was encountered, the first argument is known to be the expansion
1104 of the single-quoted string token, or @samp{gl_STRING_MODULE_INDICATOR}.
1105 Next, @code{m4} sees @samp{@key{NL}}, @samp{ }, and @samp{ }, but this
1106 whitespace is discarded as part of argument collection.  Then comes a
1107 rather lengthy single-quoted string token, @samp{[@key{NL}@ @ @ @ dnl
1108 comment@key{NL}@ @ @ @ GNULIB_]}.  This is followed by the token
1109 @samp{translit}, which @code{m4} recognizes as a macro name, so a nested
1110 macro expansion has started.
1112 The arguments to the @code{translit} are found by the tokens @samp{(},
1113 @samp{[$1]}, @samp{,}, @samp{[a-z]}, @samp{,}, @samp{[A-Z]}, and finally
1114 @samp{)}.  All three string arguments are expanded (or in other words,
1115 the quotes are stripped), and since neither @samp{$} nor @samp{1} need
1116 capitalization, the result of the macro is @samp{$1}.  This expansion is
1117 rescanned, resulting in the two literal characters @samp{$} and
1118 @samp{1}.
1120 Scanning of the outer macro resumes, and picks up with
1121 @samp{[=1@key{NL}@ @ ]}, and finally @samp{)}.  The collected pieces of
1122 expanded text are concatenated, with the end result that the macro
1123 @samp{gl_STRING_MODULE_INDICATOR} is now defined to be the sequence
1124 @samp{@key{NL}@ @ @ @ dnl comment@key{NL}@ @ @ @ GNULIB_$1=1@key{NL}@ @ }.
1125 Once again, @samp{dnl} is recognized and avoids a newline in the output.
1127 The final line is then parsed, beginning with @samp{ } and @samp{ }
1128 that are output literally.  Then @samp{gl_STRING_MODULE_INDICATOR} is
1129 recognized as a macro name, with an argument list of @samp{(},
1130 @samp{[strcase]}, and @samp{)}.  Since the definition of the macro
1131 contains the sequence @samp{$1}, that sequence is replaced with the
1132 argument @samp{strcase} prior to starting the rescan.  The rescan sees
1133 @samp{@key{NL}} and four spaces, which are output literally, then
1134 @samp{dnl}, which discards the text @samp{ comment@key{NL}}.  Next
1135 comes four more spaces, also output literally, and the token
1136 @samp{GNULIB_strcase}, which resulted from the earlier parameter
1137 substitution.  Since that is not a macro name, it is output literally,
1138 followed by the literal tokens @samp{=}, @samp{1}, @samp{@key{NL}}, and
1139 two more spaces.  Finally, the original @samp{@key{NL}} seen after the
1140 macro invocation is scanned and output literally.
1142 Now for a corrected approach.  This rearranges the use of newlines and
1143 whitespace so that less whitespace is output (which, although harmless
1144 to shell scripts, can be visually unappealing), and fixes the quoting
1145 issues so that the capitalization occurs when the macro
1146 @samp{gl_STRING_MODULE_INDICATOR} is invoked, rather then when it is
1147 defined.
1149 @example
1150 changequote([,])dnl
1151 define([gl_STRING_MODULE_INDICATOR],
1152   [dnl comment
1153   GNULIB_[]translit([$1], [a-z], [A-Z])=1dnl
1154 ])dnl
1155   gl_STRING_MODULE_INDICATOR([strcase])
1156 @result{}    GNULIB_STRCASE=1
1157 @end example
1159 The parsing of the first line is unchanged.  The second line sees the
1160 name of the macro to define, then sees the discarded @samp{@key{NL}}
1161 and two spaces, as before.  But this time, the next token is
1162 @samp{[dnl comment@key{NL}@ @ GNULIB_[]translit([$1], [a-z],
1163 [A-Z])=1dnl@key{NL}]}, which includes nested quotes, followed by
1164 @samp{)} to end the macro definition and @samp{dnl} to skip the
1165 newline.  No early expansion of @code{translit} occurs, so the entire
1166 string becomes the definition of the macro.
1168 The final line is then parsed, beginning with two spaces that are
1169 output literally, and an invocation of
1170 @code{gl_STRING_MODULE_INDICATOR} with the argument @samp{strcase}.
1171 Again, the @samp{$1} in the macro definition is substituted prior to
1172 rescanning.  Rescanning first encounters @samp{dnl}, and discards
1173 @samp{ comment@key{NL}}.  Then two spaces are output literally.  Next
1174 comes the token @samp{GNULIB_}, but that is not a macro, so it is
1175 output literally.  The token @samp{[]} is an empty string, so it does
1176 not affect output.  Then the token @samp{translit} is encountered.
1178 This time, the arguments to @code{translit} are parsed as @samp{(},
1179 @samp{[strcase]}, @samp{,}, @samp{ }, @samp{[a-z]}, @samp{,}, @samp{ },
1180 @samp{[A-Z]}, and @samp{)}.  The two spaces are discarded, and the
1181 translit results in the desired result @samp{STRCASE}.  This is
1182 rescanned, but since it is not a macro name, it is output literally.
1183 Then the scanner sees @samp{=} and @samp{1}, which are output
1184 literally, followed by @samp{dnl} which discards the rest of the
1185 definition of @code{gl_STRING_MODULE_INDICATOR}.  The newline at the
1186 end of output is the literal @samp{@key{NL}} that appeared after the
1187 invocation of the macro.
1189 The order in which @code{m4} expands the macros can be further explored
1190 using the trace facilities of @acronym{GNU} @code{m4} (@pxref{Trace}).
1192 @node Macros
1193 @chapter How to invoke macros
1195 This chapter covers macro invocation, macro arguments and how macro
1196 expansion is treated.
1198 @menu
1199 * Invocation::                  Macro invocation
1200 * Inhibiting Invocation::       Preventing macro invocation
1201 * Macro Arguments::             Macro arguments
1202 * Quoting Arguments::           On Quoting Arguments to macros
1203 * Macro expansion::             Expanding macros
1204 @end menu
1206 @node Invocation
1207 @section Macro invocation
1209 @cindex macro invocation
1210 @cindex invoking macros
1211 Macro invocations has one of the forms
1213 @comment ignore
1214 @example
1215 name
1216 @end example
1218 @noindent
1219 which is a macro invocation without any arguments, or
1221 @comment ignore
1222 @example
1223 name(arg1, arg2, @dots{}, arg@var{n})
1224 @end example
1226 @noindent
1227 which is a macro invocation with @var{n} arguments.  Macros can have any
1228 number of arguments.  All arguments are strings, but different macros
1229 might interpret the arguments in different ways.
1231 The opening parenthesis @emph{must} follow the @var{name} directly, with
1232 no spaces in between.  If it does not, the macro is called with no
1233 arguments at all.
1235 For a macro call to have no arguments, the parentheses @emph{must} be
1236 left out.  The macro call
1238 @comment ignore
1239 @example
1240 name()
1241 @end example
1243 @noindent
1244 is a macro call with one argument, which is the empty string, not a call
1245 with no arguments.
1247 @node Inhibiting Invocation
1248 @section Preventing macro invocation
1250 An innovation of the @code{m4} language, compared to some of its
1251 predecessors (like Stratchey's @code{GPM}, for example), is the ability
1252 to recognize macro calls without resorting to any special, prefixed
1253 invocation character.  While generally useful, this feature might
1254 sometimes be the source of spurious, unwanted macro calls.  So, @acronym{GNU}
1255 @code{m4} offers several mechanisms or techniques for inhibiting the
1256 recognition of names as macro calls.
1258 @cindex @acronym{GNU} extensions
1259 @cindex blind macro
1260 @cindex macro, blind
1261 First of all, many builtin macros cannot meaningfully be called without
1262 arguments.  As a @acronym{GNU} extension, for any of these macros,
1263 whenever an opening parenthesis does not immediately follow their name,
1264 the builtin macro call is not triggered.  This solves the most usual
1265 cases, like for @samp{include} or @samp{eval}.  Later in this document,
1266 the sentence ``This macro is recognized only with parameters'' refers to
1267 this specific provision of @acronym{GNU} M4, also known as a blind
1268 builtin macro.  For the builtins defined by @acronym{POSIX} that bear
1269 this disclaimer, @acronym{POSIX} specifically states that invoking those
1270 builtins without arguments is unspecified, because many other
1271 implementations simply invoke the builtin as though it were given one
1272 empty argument instead.
1274 @example
1275 $ @kbd{m4}
1276 eval
1277 @result{}eval
1278 eval(`1')
1279 @result{}1
1280 @end example
1282 There is also a command line option (@option{--prefix-builtins}, or
1283 @option{-P}, @pxref{Operation modes, , Invoking m4}) that renames all
1284 builtin macros with a prefix of @samp{m4_} at startup.  The option has
1285 no effect whatsoever on user defined macros.  For example, with this option,
1286 one has to write @code{m4_dnl} and even @code{m4_m4exit}.  It also has
1287 no effect on whether a macro requires parameters.
1289 @comment options: -P
1290 @example
1291 $ @kbd{m4 -P}
1292 eval
1293 @result{}eval
1294 eval(`1')
1295 @result{}eval(1)
1296 m4_eval
1297 @result{}m4_eval
1298 m4_eval(`1')
1299 @result{}1
1300 @end example
1302 Another alternative is to redefine problematic macros to a name less
1303 likely to cause conflicts, @xref{Definitions}.
1305 If your version of @acronym{GNU} @code{m4} has the @code{changeword} feature
1306 compiled in, it offers far more flexibility in specifying the
1307 syntax of macro names, both builtin or user-defined.  @xref{Changeword},
1308 for more information on this experimental feature.
1310 Of course, the simplest way to prevent a name from being interpreted
1311 as a call to an existing macro is to quote it.  The remainder of
1312 this section studies a little more deeply how quoting affects macro
1313 invocation, and how quoting can be used to inhibit macro invocation.
1315 Even if quoting is usually done over the whole macro name, it can also
1316 be done over only a few characters of this name (provided, of course,
1317 that the unquoted portions are not also a macro).  It is also possible
1318 to quote the empty string, but this works only @emph{inside} the name.
1319 For example:
1321 @example
1322 `divert'
1323 @result{}divert
1324 `d'ivert
1325 @result{}divert
1326 di`ver't
1327 @result{}divert
1328 div`'ert
1329 @result{}divert
1330 @end example
1332 @noindent
1333 all yield the string @samp{divert}.  While in both:
1335 @example
1336 `'divert
1337 @result{}
1338 divert`'
1339 @result{}
1340 @end example
1342 @noindent
1343 the @code{divert} builtin macro will be called, which expands to the
1344 empty string.
1346 @cindex rescanning
1347 The output of macro evaluations is always rescanned.  The following
1348 example would yield the string @samp{de}, exactly as if @code{m4}
1349 has been given @w{@samp{substr(`abcde', `3', `2')}} as input:
1351 @example
1352 define(`x', `substr(ab')
1353 @result{}
1354 define(`y', `cde, `3', `2')')
1355 @result{}
1356 x`'y
1357 @result{}de
1358 @end example
1360 Unquoted strings on either side of a quoted string are subject to
1361 being recognized as macro names.  In the following example, quoting the
1362 empty string allows for the second @code{macro} to be recognized as such:
1364 @example
1365 define(`macro', `m')
1366 @result{}
1367 macro(`m')macro
1368 @result{}mmacro
1369 macro(`m')`'macro
1370 @result{}mm
1371 @end example
1373 Quoting may prevent recognizing as a macro name the concatenation of a
1374 macro expansion with the surrounding characters.  In this example:
1376 @example
1377 define(`macro', `di$1')
1378 @result{}
1379 macro(`v')`ert'
1380 @result{}divert
1381 macro(`v')ert
1382 @result{}
1383 @end example
1385 @noindent
1386 the input will produce the string @samp{divert}.  When the quotes were
1387 removed, the @code{divert} builtin was called instead.
1389 @node Macro Arguments
1390 @section Macro arguments
1392 @cindex macros, arguments to
1393 @cindex arguments to macros
1394 When a name is seen, and it has a macro definition, it will be expanded
1395 as a macro.
1397 If the name is followed by an opening parenthesis, the arguments will be
1398 collected before the macro is called.  If too few arguments are
1399 supplied, the missing arguments are taken to be the empty string.
1400 However, some builtins are documented to behave differently for a
1401 missing optional argument than for an explicit empty string.  If there
1402 are too many arguments, the excess arguments are ignored.  Unquoted
1403 leading whitespace is stripped off all arguments, but whitespace
1404 generated by a macro expansion or occurring after a macro that expanded
1405 to an empty string remains intact.  Whitespace includes space, tab,
1406 newline, carriage return, vertical tab, and formfeed.
1408 @example
1409 define(`macro', `$1')
1410 @result{}
1411 macro( unquoted leading space lost)
1412 @result{}unquoted leading space lost
1413 macro(` quoted leading space kept')
1414 @result{} quoted leading space kept
1415 macro(
1416  divert `unquoted space kept after expansion')
1417 @result{} unquoted space kept after expansion
1418 macro(macro(`
1419 ')`whitespace from expansion kept')
1420 @result{}
1421 @result{}whitespace from expansion kept
1422 macro(`unquoted trailing whitespace kept'
1424 @result{}unquoted trailing whitespace kept
1425 @result{}
1426 @end example
1428 @cindex warnings, suppressing
1429 @cindex suppressing warnings
1430 Normally @code{m4} will issue warnings if a builtin macro is called
1431 with an inappropriate number of arguments, but it can be suppressed with
1432 the @option{--quiet} command line option (or @option{--silent}, or
1433 @option{-Q}, @pxref{Operation modes, , Invoking m4}).  For user
1434 defined macros, there is no check of the number of arguments given.
1436 @example
1437 $ @kbd{m4}
1438 index(`abc')
1439 @error{}m4:stdin:1: Warning: too few arguments to builtin `index'
1440 @result{}0
1441 index(`abc',)
1442 @result{}0
1443 index(`abc', `b', `ignored')
1444 @error{}m4:stdin:3: Warning: excess arguments to builtin `index' ignored
1445 @result{}1
1446 @end example
1448 @comment options: -Q
1449 @example
1450 $ @kbd{m4 -Q}
1451 index(`abc')
1452 @result{}0
1453 index(`abc',)
1454 @result{}0
1455 index(`abc', `b', `ignored')
1456 @result{}1
1457 @end example
1459 Macros are expanded normally during argument collection, and whatever
1460 commas, quotes and parentheses that might show up in the resulting
1461 expanded text will serve to define the arguments as well.  Thus, if
1462 @var{foo} expands to @samp{, b, c}, the macro call
1464 @comment ignore
1465 @example
1466 bar(a foo, d)
1467 @end example
1469 @noindent
1470 is a macro call with four arguments, which are @samp{a }, @samp{b},
1471 @samp{c} and @samp{d}.  To understand why the first argument contains
1472 whitespace, remember that unquoted leading whitespace is never part
1473 of an argument, but trailing whitespace always is.
1475 It is possible for a macro's definition to change during argument
1476 collection, in which case the expansion uses the definition that was in
1477 effect at the time the opening @samp{(} was seen.
1479 @example
1480 define(`f', `1')
1481 @result{}
1482 f(define(`f', `2'))
1483 @result{}1
1485 @result{}2
1486 @end example
1488 It is an error if the end of file occurs while collecting arguments.
1490 @comment status: 1
1491 @example
1492 hello world
1493 @result{}hello world
1494 define(
1496 @error{}m4:stdin:2: ERROR: end of file in argument list
1497 @end example
1499 @node Quoting Arguments
1500 @section On Quoting Arguments to macros
1502 @cindex quoted macro arguments
1503 @cindex macros, quoted arguments to
1504 @cindex arguments, quoted macro
1505 Each argument has unquoted leading whitespace removed.  Within each
1506 argument, all unquoted parentheses must match.  For example, if
1507 @var{foo} is a macro,
1509 @comment ignore
1510 @example
1511 foo(() (`(') `(')
1512 @end example
1514 @noindent
1515 is a macro call, with one argument, whose value is @samp{() (() (}.
1516 Commas separate arguments, except when they occur inside quotes,
1517 comments, or unquoted parentheses.  @xref{Pseudo Arguments}, for
1518 examples.
1520 It is common practice to quote all arguments to macros, unless you are
1521 sure you want the arguments expanded.  Thus, in the above
1522 example with the parentheses, the `right' way to do it is like this:
1524 @comment ignore
1525 @example
1526 foo(`() (() (')
1527 @end example
1529 @cindex quoting rule of thumb
1530 @cindex rule of thumb, quoting
1531 It is, however, in certain cases necessary (because nested expansion
1532 must occur to create the arguments for the outer macro) or convenient
1533 (because it uses fewer characters) to leave out quotes for some
1534 arguments, and there is nothing wrong in doing it.  It just makes life a
1535 bit harder, if you are not careful to follow a consistent quoting style.
1536 For consistency, this manual follows the rule of thumb that each layer
1537 of parentheses introduces another layer of single quoting, except when
1538 showing the consequences of quoting rules.  This is done even when the
1539 quoted string cannot be a macro, such as with integers when you have not
1540 changed the syntax via @code{changeword} (@pxref{Changeword}).
1542 The quoting rule of thumb of one level of quoting per parentheses has a
1543 nice property: when a macro name appears inside parentheses, you can
1544 determine when it will be expanded.  If it is not quoted, it will be
1545 expanded prior to the outer macro, so that its expansion becomes the
1546 argument.  If it is single-quoted, it will be expanded after the outer
1547 macro.  And if it is double-quoted, it will be used as literal text
1548 instead of a macro name.
1550 @example
1551 define(`active', `ACT, IVE')
1552 @result{}
1553 define(`show', `$1 $1')
1554 @result{}
1555 show(active)
1556 @result{}ACT ACT
1557 show(`active')
1558 @result{}ACT, IVE ACT, IVE
1559 show(``active'')
1560 @result{}active active
1561 @end example
1563 @node Macro expansion
1564 @section Macro expansion
1566 @cindex macros, expansion of
1567 @cindex expansion of macros
1568 When the arguments, if any, to a macro call have been collected, the
1569 macro is expanded, and the expansion text is pushed back onto the input
1570 (unquoted), and reread.  The expansion text from one macro call might
1571 therefore result in more macros being called, if the calls are included,
1572 completely or partially, in the first macro calls' expansion.
1574 Taking a very simple example, if @var{foo} expands to @samp{bar}, and
1575 @var{bar} expands to @samp{Hello}, the input
1577 @comment options: -Dbar=Hello -Dfoo=bar
1578 @example
1579 $ @kbd{m4 -Dbar=Hello -Dfoo=bar}
1581 @result{}Hello
1582 @end example
1584 @noindent
1585 will expand first to @samp{bar}, and when this is reread and
1586 expanded, into @samp{Hello}.
1588 @node Definitions
1589 @chapter How to define new macros
1591 @cindex macros, how to define new
1592 @cindex defining new macros
1593 Macros can be defined, redefined and deleted in several different ways.
1594 Also, it is possible to redefine a macro without losing a previous
1595 value, and bring back the original value at a later time.
1597 @menu
1598 * Define::                      Defining a new macro
1599 * Arguments::                   Arguments to macros
1600 * Pseudo Arguments::            Special arguments to macros
1601 * Undefine::                    Deleting a macro
1602 * Defn::                        Renaming macros
1603 * Pushdef::                     Temporarily redefining macros
1605 * Indir::                       Indirect call of macros
1606 * Builtin::                     Indirect call of builtins
1607 @end menu
1609 @node Define
1610 @section Defining a macro
1612 The normal way to define or redefine macros is to use the builtin
1613 @code{define}:
1615 @deffn Builtin define (@var{name}, @ovar{expansion})
1616 Defines @var{name} to expand to @var{expansion}.  If
1617 @var{expansion} is not given, it is taken to be empty.
1619 The expansion of @code{define} is void.
1620 The macro @code{define} is recognized only with parameters.
1621 @end deffn
1623 The following example defines the macro @var{foo} to expand to the text
1624 @samp{Hello World.}.
1626 @example
1627 define(`foo', `Hello world.')
1628 @result{}
1630 @result{}Hello world.
1631 @end example
1633 The empty line in the output is there because the newline is not
1634 a part of the macro definition, and it is consequently copied to
1635 the output.  This can be avoided by use of the macro @code{dnl}.
1636 @xref{Dnl}, for details.
1638 The first argument to @code{define} should be quoted; otherwise, if the
1639 macro is already defined, you will be defining a different macro.  This
1640 example shows the problems with underquoting, since we did not want to
1641 redefine @code{one}:
1643 @example
1644 define(foo, one)
1645 @result{}
1646 define(foo, two)
1647 @result{}
1649 @result{}two
1650 @end example
1652 @cindex @acronym{GNU} extensions
1653 @acronym{GNU} @code{m4} normally replaces only the @emph{topmost}
1654 definition of a macro if it has several definitions from @code{pushdef}
1655 (@pxref{Pushdef}).  Some other implementations of @code{m4} replace all
1656 definitions of a macro with @code{define}.  @xref{Incompatibilities},
1657 for more details.
1659 As a @acronym{GNU} extension, the first argument to @code{define} does
1660 not have to be a simple word.
1661 It can be any text string, even the empty string.  A macro with a
1662 non-standard name cannot be invoked in the normal way, as the name is
1663 not recognized.  It can only be referenced by the builtins @code{indir}
1664 (@pxref{Indir}) and @code{defn} (@pxref{Defn}).
1666 @cindex arrays
1667 Arrays and associative arrays can be simulated by using non-standard
1668 macro names.
1670 @deffn Composite array (@var{index})
1671 @deffnx Composite array_set (@var{index}, @ovar{value})
1672 Provide access to entries within an array.  @code{array} reads the entry
1673 at location @var{index}, and @code{array_set} assigns @var{value} to
1674 location @var{index}.
1675 @end deffn
1677 @example
1678 define(`array', `defn(format(``array[%d]'', `$1'))')
1679 @result{}
1680 define(`array_set', `define(format(``array[%d]'', `$1'), `$2')')
1681 @result{}
1682 array_set(`4', `array element no. 4')
1683 @result{}
1684 array_set(`17', `array element no. 17')
1685 @result{}
1686 array(`4')
1687 @result{}array element no. 4
1688 array(eval(`10 + 7'))
1689 @result{}array element no. 17
1690 @end example
1692 Change the @samp{%d} to @samp{%s} and it is an associative array.
1694 @node Arguments
1695 @section Arguments to macros
1697 @cindex macros, arguments to
1698 @cindex arguments to macros
1699 Macros can have arguments.  The @var{n}th argument is denoted by
1700 @code{$n} in the expansion text, and is replaced by the @var{n}th actual
1701 argument, when the macro is expanded.  Replacement of arguments happens
1702 before rescanning, regardless of how many nesting levels of quoting
1703 appear in the expansion.  Here is an example of a macro with
1704 two arguments.
1706 @deffn Composite exch (@var{arg1}, @var{arg2})
1707 Expands to @var{arg2} followed by @var{arg1}, effectively exchanging
1708 their order.
1709 @end deffn
1711 @example
1712 define(`exch', `$2, $1')
1713 @result{}
1714 exch(`arg1', `arg2')
1715 @result{}arg2, arg1
1716 @end example
1718 This can be used, for example, if you like the arguments to
1719 @code{define} to be reversed.
1721 @example
1722 define(`exch', `$2, $1')
1723 @result{}
1724 define(exch(``expansion text'', ``macro''))
1725 @result{}
1726 macro
1727 @result{}expansion text
1728 @end example
1730 @xref{Quoting Arguments}, for an explanation of the double quotes.
1731 (You should try and improve this example so that clients of @code{exch}
1732 do not have to double quote; or @pxref{Improved exch, , Answers}).
1734 As a special case, the zeroth argument, @code{$0}, is always the name
1735 of the macro being expanded.
1737 @example
1738 define(`test', ``Macro name: $0'')
1739 @result{}
1740 test
1741 @result{}Macro name: test
1742 @end example
1744 If you want quoted text to appear as part of the expansion text,
1745 remember that quotes can be nested in quoted strings.  Thus, in
1747 @example
1748 define(`foo', `This is macro `foo'.')
1749 @result{}
1751 @result{}This is macro foo.
1752 @end example
1754 @noindent
1755 The @samp{foo} in the expansion text is @emph{not} expanded, since it is
1756 a quoted string, and not a name.
1758 @cindex @acronym{GNU} extensions
1759 @cindex nine arguments, more than
1760 @cindex more than nine arguments
1761 @cindex arguments, more than nine
1762 @cindex positional parameters, more than nine
1763 @acronym{GNU} @code{m4} allows the number following the @samp{$} to
1764 consist of one or more digits, allowing macros to have any number of
1765 arguments.  The extension of accepting multiple digits is incompatible
1766 with @acronym{POSIX}, and is different than traditional implementations
1767 of @code{m4}, which only recognize one digit.  Therefore, future
1768 versions of @acronym{GNU} M4 will phase out this feature.  To portably
1769 access beyond the ninth argument, you can use the @code{argn} macro
1770 documented later (@pxref{Shift}).
1772 @acronym{POSIX} also states that @samp{$} followed immediately by
1773 @samp{@{} in a macro definition is implementation-defined.  This version
1774 of M4 passes the literal characters @samp{$@{} through unchanged, but M4
1775 2.0 will implement an optional feature similar to @command{sh}, where
1776 @samp{$@{11@}} expands to the eleventh argument, to replace the current
1777 recognition of @samp{$11}.  Meanwhile, if you want to guarantee that you
1778 will get a literal @samp{$@{} in output when expanding a macro, even
1779 when you upgrade to M4 2.0, you can use nested quoting to your
1780 advantage:
1782 @example
1783 define(`foo', `single quoted $`'@{1@} output')
1784 @result{}
1785 define(`bar', ``double quoted $'`@{2@} output'')
1786 @result{}
1787 foo(`a', `b')
1788 @result{}single quoted $@{1@} output
1789 bar(`a', `b')
1790 @result{}double quoted $@{2@} output
1791 @end example
1793 To help you detect places in your M4 input files that might change in
1794 behavior due to the changed behavior of M4 2.0, you can use the
1795 @option{--warn-macro-sequence} command-line option (@pxref{Operation
1796 modes, , Invoking m4}) with the default regular expression.  This will
1797 add a warning any time a macro definition includes @samp{$} followed by
1798 multiple digits, or by @samp{@{}.  The warning is not enabled by
1799 default, because it triggers a number of warnings in Autoconf 2.61 (and
1800 Autoconf uses @option{-E} to treat warnings as errors), and because it
1801 will still be possible to restore older behavior in M4 2.0.
1803 @comment ignore
1804 @example
1805 $ @kbd{m4 --warn-macro-sequence}
1806 define(`foo', `$001 $@{1@} $1')
1807 @error{}m4:stdin:1: Warning: definition of `foo' contains sequence `$001'
1808 @error{}m4:stdin:1: Warning: definition of `foo' contains sequence `$@{1@}'
1809 @result{}
1810 foo(`bar')
1811 @result{}bar $@{1@} bar
1812 @end example
1814 @node Pseudo Arguments
1815 @section Special arguments to macros
1817 @cindex special arguments to macros
1818 @cindex macros, special arguments to
1819 @cindex arguments to macros, special
1820 There is a special notation for the number of actual arguments supplied,
1821 and for all the actual arguments.
1823 The number of actual arguments in a macro call is denoted by @code{$#}
1824 in the expansion text.
1826 @deffn Composite nargs (@dots{})
1827 Expands to a count of the number of arguments supplied.
1828 @end deffn
1830 @example
1831 define(`nargs', `$#')
1832 @result{}
1833 nargs
1834 @result{}0
1835 nargs()
1836 @result{}1
1837 nargs(`arg1', `arg2', `arg3')
1838 @result{}3
1839 nargs(`commas can be quoted, like this')
1840 @result{}1
1841 nargs(arg1#inside comments, commas do not separate arguments
1842 still arg1)
1843 @result{}1
1844 nargs((unquoted parentheses, like this, group arguments))
1845 @result{}1
1846 @end example
1848 Remember that @samp{#} defaults to the comment character; if you forget
1849 quotes to inhibit the comment behavior, your macro definition may not
1850 end where you expected.
1852 @example
1853 dnl Attempt to define a macro to just `$#'
1854 define(underquoted, $#)
1855 oops)
1856 @result{}
1857 underquoted
1858 @result{}0)
1859 @result{}oops
1860 @end example
1862 The notation @code{$*} can be used in the expansion text to denote all
1863 the actual arguments, unquoted, with commas in between.  For example
1865 @example
1866 define(`echo', `$*')
1867 @result{}
1868 echo(arg1,    arg2, arg3 , arg4)
1869 @result{}arg1,arg2,arg3 ,arg4
1870 @end example
1872 Often each argument should be quoted, and the notation @code{$@@} handles
1873 that.  It is just like @code{$*}, except that it quotes each argument.
1874 A simple example of that is:
1876 @example
1877 define(`echo', `$@@')
1878 @result{}
1879 echo(arg1,    arg2, arg3 , arg4)
1880 @result{}arg1,arg2,arg3 ,arg4
1881 @end example
1883 Where did the quotes go?  Of course, they were eaten, when the expanded
1884 text were reread by @code{m4}.  To show the difference, try
1886 @example
1887 define(`echo1', `$*')
1888 @result{}
1889 define(`echo2', `$@@')
1890 @result{}
1891 define(`foo', `This is macro `foo'.')
1892 @result{}
1893 echo1(foo)
1894 @result{}This is macro This is macro foo..
1895 echo1(`foo')
1896 @result{}This is macro foo.
1897 echo2(foo)
1898 @result{}This is macro foo.
1899 echo2(`foo')
1900 @result{}foo
1901 @end example
1903 @noindent
1904 @xref{Trace}, if you do not understand this.  As another example of the
1905 difference, remember that comments encountered in arguments are passed
1906 untouched to the macro, and that quoting disables comments.
1908 @example
1909 define(`echo1', `$*')
1910 @result{}
1911 define(`echo2', `$@@')
1912 @result{}
1913 define(`foo', `bar')
1914 @result{}
1915 echo1(#foo'foo
1916 foo)
1917 @result{}#foo'foo
1918 @result{}bar
1919 echo2(#foo'foo
1920 foo)
1921 @result{}#foobar
1922 @result{}bar'
1923 @end example
1925 A @samp{$} sign in the expansion text, that is not followed by anything
1926 @code{m4} understands, is simply copied to the macro expansion, as any
1927 other text is.
1929 @example
1930 define(`foo', `$$$ hello $$$')
1931 @result{}
1933 @result{}$$$ hello $$$
1934 @end example
1936 @cindex rescanning
1937 @cindex literal output
1938 @cindex output, literal
1939 If you want a macro to expand to something like @samp{$12}, the
1940 judicious use of nested quoting can put a safe character between the
1941 @code{$} and the next character, relying on the rescanning to remove the
1942 nested quote.  This will prevent @code{m4} from interpreting the
1943 @code{$} sign as a reference to an argument.
1945 @example
1946 define(`foo', `no nested quote: $1')
1947 @result{}
1948 foo(`arg')
1949 @result{}no nested quote: arg
1950 define(`foo', `nested quote around $: `$'1')
1951 @result{}
1952 foo(`arg')
1953 @result{}nested quote around $: $1
1954 define(`foo', `nested empty quote after $: $`'1')
1955 @result{}
1956 foo(`arg')
1957 @result{}nested empty quote after $: $1
1958 define(`foo', `nested quote around next character: $`1'')
1959 @result{}
1960 foo(`arg')
1961 @result{}nested quote around next character: $1
1962 define(`foo', `nested quote around both: `$1'')
1963 @result{}
1964 foo(`arg')
1965 @result{}nested quote around both: arg
1966 @end example
1968 @node Undefine
1969 @section Deleting a macro
1971 @cindex macros, how to delete
1972 @cindex deleting macros
1973 @cindex undefining macros
1974 A macro definition can be removed with @code{undefine}:
1976 @deffn Builtin undefine (@var{name}@dots{})
1977 For each argument, remove the macro @var{name}.  The macro names must
1978 necessarily be quoted, since they will be expanded otherwise.
1980 The expansion of @code{undefine} is void.
1981 The macro @code{undefine} is recognized only with parameters.
1982 @end deffn
1984 @example
1985 foo bar blah
1986 @result{}foo bar blah
1987 define(`foo', `some')define(`bar', `other')define(`blah', `text')
1988 @result{}
1989 foo bar blah
1990 @result{}some other text
1991 undefine(`foo')
1992 @result{}
1993 foo bar blah
1994 @result{}foo other text
1995 undefine(`bar', `blah')
1996 @result{}
1997 foo bar blah
1998 @result{}foo bar blah
1999 @end example
2001 Undefining a macro inside that macro's expansion is safe; the macro
2002 still expands to the definition that was in effect at the @samp{(}.
2004 @example
2005 define(`f', ``$0':$1')
2006 @result{}
2007 f(f(f(undefine(`f')`hello world')))
2008 @result{}f:f:f:hello world
2009 f(`bye')
2010 @result{}f(bye)
2011 @end example
2013 It is not an error for @var{name} to have no macro definition.  In that
2014 case, @code{undefine} does nothing.
2016 @node Defn
2017 @section Renaming macros
2019 @cindex macros, how to rename
2020 @cindex renaming macros
2021 @cindex macros, displaying definitions
2022 @cindex definitions, displaying macro
2023 It is possible to rename an already defined macro.  To do this, you need
2024 the builtin @code{defn}:
2026 @deffn Builtin defn (@var{name}@dots{})
2027 Expands to the @emph{quoted definition} of each @var{name}.  If an
2028 argument is not a defined macro, the expansion for that argument is
2029 empty.
2031 If @var{name} is a user-defined macro, the quoted definition is simply
2032 the quoted expansion text.  If, instead, there is only one @var{name}
2033 and it is a builtin, the
2034 expansion is a special token, which points to the builtin's internal
2035 definition.  This token is only meaningful as the second argument to
2036 @code{define} (and @code{pushdef}), and is silently converted to an
2037 empty string in most other contexts.  Combining a builtin with anything
2038 else is not supported; a warning is issued and the builtin is omitted
2039 from the final expansion.
2041 The macro @code{defn} is recognized only with parameters.
2042 @end deffn
2044 Its normal use is best understood through an example, which shows how to
2045 rename @code{undefine} to @code{zap}:
2047 @example
2048 define(`zap', defn(`undefine'))
2049 @result{}
2050 zap(`undefine')
2051 @result{}
2052 undefine(`zap')
2053 @result{}undefine(zap)
2054 @end example
2056 In this way, @code{defn} can be used to copy macro definitions, and also
2057 definitions of builtin macros.  Even if the original macro is removed,
2058 the other name can still be used to access the definition.
2060 The fact that macro definitions can be transferred also explains why you
2061 should use @code{$0}, rather than retyping a macro's name in its
2062 definition:
2064 @example
2065 define(`foo', `This is `$0'')
2066 @result{}
2067 define(`bar', defn(`foo'))
2068 @result{}
2070 @result{}This is bar
2071 @end example
2073 Macros used as string variables should be referred through @code{defn},
2074 to avoid unwanted expansion of the text:
2076 @example
2077 define(`string', `The macro dnl is very useful
2079 @result{}
2080 string
2081 @result{}The macro@w{ }
2082 defn(`string')
2083 @result{}The macro dnl is very useful
2084 @result{}
2085 @end example
2087 @cindex rescanning
2088 However, it is important to remember that @code{m4} rescanning is purely
2089 textual.  If an unbalanced end-quote string occurs in a macro
2090 definition, the rescan will see that embedded quote as the termination
2091 of the quoted string, and the remainder of the macro's definition will
2092 be rescanned unquoted.  Thus it is a good idea to avoid unbalanced
2093 end-quotes in macro definitions or arguments to macros.
2095 @example
2096 define(`foo', a'a)
2097 @result{}
2098 define(`a', `A')
2099 @result{}
2100 define(`echo', `$@@')
2101 @result{}
2103 @result{}A'A
2104 defn(`foo')
2105 @result{}aA'
2106 echo(foo)
2107 @result{}AA'
2108 @end example
2110 On the other hand, it is possible to exploit the fact that @code{defn}
2111 can concatenate multiple macros prior to the rescanning phase, in order
2112 to join the definitions of macros that, in isolation, have unbalanced
2113 quotes.  In the example below, note how the use of @code{defn} on
2114 @code{l} in isolation opens a string, which is not closed until the next
2115 line; but used on @code{l} and @code{r} together results in nested
2116 quoting.  Also note that @code{defn} with multiple arguments can only
2117 join text macros, not builtins, although a future version of
2118 @acronym{GNU} M4 may lift this restriction.
2120 @example
2121 define(`l', `<[>')define(`r', `<]>')
2122 @result{}
2123 changequote(`[', `]')
2124 @result{}
2125 defn([l])defn([r])
2127 @result{}<[>]defn([r])
2128 @result{})
2129 defn([l], [r])
2130 @result{}<[>][<]>
2131 define([a], [A])
2132 @result{}
2133 defn([a], [defn], [a])
2134 @error{}m4:stdin:7: Warning: cannot concatenate builtin `defn'
2135 @result{}AA
2136 @end example
2138 @cindex builtins, special tokens
2139 @cindex tokens, builtin macro
2140 Using @code{defn} to generate special tokens for builtin macros outside
2141 of expected contexts can sometimes trigger warnings.  But most of the
2142 time, such tokens are silently converted to the empty string.
2144 @example
2145 defn(`defn')
2146 @result{}
2147 define(defn(`divnum'), `cannot redefine a builtin token')
2148 @error{}m4:stdin:2: Warning: define: invalid macro name ignored
2149 @result{}
2150 divnum
2151 @result{}0
2152 @end example
2154 @node Pushdef
2155 @section Temporarily redefining macros
2157 @cindex macros, temporary redefinition of
2158 @cindex temporary redefinition of macros
2159 @cindex redefinition of macros, temporary
2160 @cindex definition stack
2161 @cindex stack, macro definition
2162 It is possible to redefine a macro temporarily, reverting to the
2163 previous definition at a later time.  This is done with the builtins
2164 @code{pushdef} and @code{popdef}:
2166 @deffn Builtin pushdef (@var{name}, @ovar{expansion})
2167 @deffnx Builtin popdef (@var{name}@dots{})
2168 Analogous to @code{define} and @code{undefine}.
2170 These macros work in a stack-like fashion.  A macro is temporarily
2171 redefined with @code{pushdef}, which replaces an existing definition of
2172 @var{name}, while saving the previous definition, before the new one is
2173 installed.  If there is no previous definition, @code{pushdef} behaves
2174 exactly like @code{define}.
2176 If a macro has several definitions (of which only one is accessible),
2177 the topmost definition can be removed with @code{popdef}.  If there is
2178 no previous definition, @code{popdef} behaves like @code{undefine}.
2180 The expansion of both @code{pushdef} and @code{popdef} is void.
2181 The macros @code{pushdef} and @code{popdef} are recognized only with
2182 parameters.
2183 @end deffn
2185 @example
2186 define(`foo', `Expansion one.')
2187 @result{}
2189 @result{}Expansion one.
2190 pushdef(`foo', `Expansion two.')
2191 @result{}
2193 @result{}Expansion two.
2194 pushdef(`foo', `Expansion three.')
2195 @result{}
2196 pushdef(`foo', `Expansion four.')
2197 @result{}
2198 popdef(`foo')
2199 @result{}
2201 @result{}Expansion three.
2202 popdef(`foo', `foo')
2203 @result{}
2205 @result{}Expansion one.
2206 popdef(`foo')
2207 @result{}
2209 @result{}foo
2210 @end example
2212 If a macro with several definitions is redefined with @code{define}, the
2213 topmost definition is @emph{replaced} with the new definition.  If it is
2214 removed with @code{undefine}, @emph{all} the definitions are removed,
2215 and not only the topmost one.  However, @acronym{POSIX} allows other
2216 implementations that treat @code{define} as replacing an entire stack
2217 of definitions with a single new definition, so to be portable to other
2218 implementations, it may be worth explicitly using @code{popdef} and
2219 @code{pushdef} rather than relying on the @acronym{GNU} behavior of
2220 @code{define}.
2222 @example
2223 define(`foo', `Expansion one.')
2224 @result{}
2226 @result{}Expansion one.
2227 pushdef(`foo', `Expansion two.')
2228 @result{}
2230 @result{}Expansion two.
2231 define(`foo', `Second expansion two.')
2232 @result{}
2234 @result{}Second expansion two.
2235 undefine(`foo')
2236 @result{}
2238 @result{}foo
2239 @end example
2241 @cindex local variables
2242 @cindex variables, local
2243 Local variables within macros are made with @code{pushdef} and
2244 @code{popdef}.  At the start of the macro a new definition is pushed,
2245 within the macro it is manipulated and at the end it is popped,
2246 revealing the former definition.
2248 It is possible to temporarily redefine a builtin with @code{pushdef}
2249 and @code{defn}.
2251 @node Indir
2252 @section Indirect call of macros
2254 @cindex indirect call of macros
2255 @cindex call of macros, indirect
2256 @cindex macros, indirect call of
2257 @cindex @acronym{GNU} extensions
2258 Any macro can be called indirectly with @code{indir}:
2260 @deffn Builtin indir (@var{name}, @ovar{args@dots{}})
2261 Results in a call to the macro @var{name}, which is passed the
2262 rest of the arguments @var{args}.  If @var{name} is not defined, an
2263 error message is printed, and the expansion is void.
2265 The macro @code{indir} is recognized only with parameters.
2266 @end deffn
2268 This can be used to call macros with computed or ``invalid''
2269 names (@code{define} allows such names to be defined):
2271 @example
2272 define(`$$internal$macro', `Internal macro (name `$0')')
2273 @result{}
2274 $$internal$macro
2275 @result{}$$internal$macro
2276 indir(`$$internal$macro')
2277 @result{}Internal macro (name $$internal$macro)
2278 @end example
2280 The point is, here, that larger macro packages can have private macros
2281 defined, that will not be called by accident.  They can @emph{only} be
2282 called through the builtin @code{indir}.
2284 One other point to observe is that argument collection occurs before
2285 @code{indir} invokes @var{name}, so if argument collection changes the
2286 value of @var{name}, that will be reflected in the final expansion.
2287 This is different than the behavior when invoking macros directly,
2288 where the definition that was in effect before argument collection is
2289 used.
2291 @example
2292 $ @kbd{m4 -d}
2293 define(`f', `1')
2294 @result{}
2295 f(define(`f', `2'))
2296 @result{}1
2297 indir(`f', define(`f', `3'))
2298 @result{}3
2299 indir(`f', undefine(`f'))
2300 @error{}m4:stdin:4: undefined macro `f'
2301 @result{}
2302 @end example
2304 When handed the result of @code{defn} (@pxref{Defn}) as one of its
2305 arguments, @code{indir} defers to the invoked @var{name} for whether a
2306 token representing a builtin is recognized or flattened to the empty
2307 string.
2309 @example
2310 $ @kbd{m4 -d}
2311 indir(defn(`defn'), `divnum')
2312 @error{}m4:stdin:1: Warning: indir: invalid macro name ignored
2313 @result{}
2314 indir(`define', defn(`defn'), `divnum')
2315 @error{}m4:stdin:2: Warning: define: invalid macro name ignored
2316 @result{}
2317 indir(`define', `foo', defn(`divnum'))
2318 @result{}
2320 @result{}0
2321 indir(`divert', defn(`foo'))
2322 @error{}m4:stdin:5: empty string treated as 0 in builtin `divert'
2323 @result{}
2324 @end example
2326 @node Builtin
2327 @section Indirect call of builtins
2329 @cindex indirect call of builtins
2330 @cindex call of builtins, indirect
2331 @cindex builtins, indirect call of
2332 @cindex @acronym{GNU} extensions
2333 Builtin macros can be called indirectly with @code{builtin}:
2335 @deffn Builtin builtin (@var{name}, @ovar{args@dots{}})
2336 Results in a call to the builtin @var{name}, which is passed the
2337 rest of the arguments @var{args}.  If @var{name} does not name a
2338 builtin, an error message is printed, and the expansion is void.
2340 The macro @code{builtin} is recognized only with parameters.
2341 @end deffn
2343 This can be used even if @var{name} has been given another definition
2344 that has covered the original, or been undefined so that no macro
2345 maps to the builtin.
2347 @example
2348 pushdef(`define', `hidden')
2349 @result{}
2350 undefine(`undefine')
2351 @result{}
2352 define(`foo', `bar')
2353 @result{}hidden
2355 @result{}foo
2356 builtin(`define', `foo', defn(`divnum'))
2357 @result{}
2359 @result{}0
2360 builtin(`define', `foo', `BAR')
2361 @result{}
2363 @result{}BAR
2364 undefine(`foo')
2365 @result{}undefine(foo)
2367 @result{}BAR
2368 builtin(`undefine', `foo')
2369 @result{}
2371 @result{}foo
2372 @end example
2374 The @var{name} argument only matches the original name of the builtin,
2375 even when the @option{--prefix-builtins} option (or @option{-P},
2376 @pxref{Operation modes, , Invoking m4}) is in effect.  This is different
2377 from @code{indir}, which only tracks current macro names.
2379 @comment options: -P
2380 @example
2381 $ @kbd{m4 -P}
2382 m4_builtin(`divnum')
2383 @result{}0
2384 m4_builtin(`m4_divnum')
2385 @error{}m4:stdin:2: undefined builtin `m4_divnum'
2386 @result{}
2387 m4_indir(`divnum')
2388 @error{}m4:stdin:3: undefined macro `divnum'
2389 @result{}
2390 m4_indir(`m4_divnum')
2391 @result{}0
2392 @end example
2394 Note that @code{indir} and @code{builtin} can be used to invoke builtins
2395 without arguments, even when they normally require parameters to be
2396 recognized; but it will provoke a warning, and result in a void expansion.
2398 @example
2399 builtin
2400 @result{}builtin
2401 builtin()
2402 @error{}m4:stdin:2: undefined builtin `'
2403 @result{}
2404 builtin(`builtin')
2405 @error{}m4:stdin:3: Warning: too few arguments to builtin `builtin'
2406 @result{}
2407 builtin(`builtin',)
2408 @error{}m4:stdin:4: undefined builtin `'
2409 @result{}
2410 @end example
2412 @node Conditionals
2413 @chapter Conditionals, loops, and recursion
2415 Macros, expanding to plain text, perhaps with arguments, are not quite
2416 enough.  We would like to have macros expand to different things, based
2417 on decisions taken at run-time.  For that, we need some kind of conditionals.
2418 Also, we would like to have some kind of loop construct, so we could do
2419 something a number of times, or while some condition is true.
2421 @menu
2422 * Ifdef::                       Testing if a macro is defined
2423 * Ifelse::                      If-else construct, or multibranch
2424 * Shift::                       Recursion in @code{m4}
2425 * Forloop::                     Iteration by counting
2426 * Foreach::                     Iteration by list contents
2427 @end menu
2429 @node Ifdef
2430 @section Testing if a macro is defined
2432 @cindex conditionals
2433 There are two different builtin conditionals in @code{m4}.  The first is
2434 @code{ifdef}:
2436 @deffn Builtin ifdef (@var{name}, @var{string-1}, @ovar{string-2})
2437 If @var{name} is defined as a macro, @code{ifdef} expands to
2438 @var{string-1}, otherwise to @var{string-2}.  If @var{string-2} is
2439 omitted, it is taken to be the empty string (according to the normal
2440 rules).
2442 The macro @code{ifdef} is recognized only with parameters.
2443 @end deffn
2445 @example
2446 ifdef(`foo', ``foo' is defined', ``foo' is not defined')
2447 @result{}foo is not defined
2448 define(`foo', `')
2449 @result{}
2450 ifdef(`foo', ``foo' is defined', ``foo' is not defined')
2451 @result{}foo is defined
2452 ifdef(`no_such_macro', `yes', `no', `extra argument')
2453 @error{}m4:stdin:4: Warning: excess arguments to builtin `ifdef' ignored
2454 @result{}no
2455 @end example
2457 @node Ifelse
2458 @section If-else construct, or multibranch
2460 @cindex comparing strings
2461 @cindex discarding input
2462 @cindex input, discarding
2463 The other conditional, @code{ifelse}, is much more powerful.  It can be
2464 used as a way to introduce a long comment, as an if-else construct, or
2465 as a multibranch, depending on the number of arguments supplied:
2467 @deffn Builtin ifelse (@var{comment})
2468 @deffnx Builtin ifelse (@var{string-1}, @var{string-2}, @var{equal}, @
2469   @ovar{not-equal})
2470 @deffnx Builtin ifelse (@var{string-1}, @var{string-2}, @var{equal-1}, @
2471   @var{string-3}, @var{string-4}, @var{equal-2}, @dots{})
2472 Used with only one argument, the @code{ifelse} simply discards it and
2473 produces no output.
2475 If called with three or four arguments, @code{ifelse} expands into
2476 @var{equal}, if @var{string-1} and @var{string-2} are equal (character
2477 for character), otherwise it expands to @var{not-equal}.  A final fifth
2478 argument is ignored, after triggering a warning.
2480 If called with six or more arguments, and @var{string-1} and
2481 @var{string-2} are equal, @code{ifelse} expands into @var{equal-1},
2482 otherwise the first three arguments are discarded and the processing
2483 starts again.
2485 The macro @code{ifelse} is recognized only with parameters.
2486 @end deffn
2488 Using only one argument is a common @code{m4} idiom for introducing a
2489 block comment, as an alternative to repeatedly using @code{dnl}.  This
2490 special usage is recognized by @acronym{GNU} @code{m4}, so that in this
2491 case, the warning about missing arguments is never triggered.
2493 @example
2494 ifelse(`some comments')
2495 @result{}
2496 ifelse(`foo', `bar')
2497 @error{}m4:stdin:2: Warning: too few arguments to builtin `ifelse'
2498 @result{}
2499 @end example
2501 Using three or four arguments provides decision points.
2503 @example
2504 ifelse(`foo', `bar', `true')
2505 @result{}
2506 ifelse(`foo', `foo', `true')
2507 @result{}true
2508 define(`foo', `bar')
2509 @result{}
2510 ifelse(foo, `bar', `true', `false')
2511 @result{}true
2512 ifelse(foo, `foo', `true', `false')
2513 @result{}false
2514 @end example
2516 @cindex macro, blind
2517 @cindex blind macro
2518 Notice how the first argument was used unquoted; it is common to compare
2519 the expansion of a macro with a string.  With this macro, you can now
2520 reproduce the behavior of blind builtins, where the macro is recognized
2521 only with arguments.
2523 @example
2524 define(`foo', `ifelse(`$#', `0', ``$0'', `arguments:$#')')
2525 @result{}
2527 @result{}foo
2528 foo()
2529 @result{}arguments:1
2530 foo(`a', `b', `c')
2531 @result{}arguments:3
2532 @end example
2534 @cindex multibranches
2535 @cindex switch statement
2536 @cindex case statement
2537 However, @code{ifelse} can take more than four arguments.  If given more
2538 than four arguments, @code{ifelse} works like a @code{case} or @code{switch}
2539 statement in traditional programming languages.  If @var{string-1} and
2540 @var{string-2} are equal, @code{ifelse} expands into @var{equal-1}, otherwise
2541 the procedure is repeated with the first three arguments discarded.  This
2542 calls for an example:
2544 @example
2545 ifelse(`foo', `bar', `third', `gnu', `gnats')
2546 @error{}m4:stdin:1: Warning: excess arguments to builtin `ifelse' ignored
2547 @result{}gnu
2548 ifelse(`foo', `bar', `third', `gnu', `gnats', `sixth')
2549 @result{}
2550 ifelse(`foo', `bar', `third', `gnu', `gnats', `sixth', `seventh')
2551 @result{}seventh
2552 ifelse(`foo', `bar', `3', `gnu', `gnats', `6', `7', `8')
2553 @error{}m4:stdin:4: Warning: excess arguments to builtin `ifelse' ignored
2554 @result{}7
2555 @end example
2557 Naturally, the normal case will be slightly more advanced than these
2558 examples.  A common use of @code{ifelse} is in macros implementing loops
2559 of various kinds.
2561 @node Shift
2562 @section Recursion in @code{m4}
2564 @cindex recursive macros
2565 @cindex macros, recursive
2566 There is no direct support for loops in @code{m4}, but macros can be
2567 recursive.  There is no limit on the number of recursion levels, other
2568 than those enforced by your hardware and operating system.
2570 @cindex loops
2571 Loops can be programmed using recursion and the conditionals described
2572 previously.
2574 There is a builtin macro, @code{shift}, which can, among other things,
2575 be used for iterating through the actual arguments to a macro:
2577 @deffn Builtin shift (@var{arg1}, @dots{})
2578 Takes any number of arguments, and expands to all its arguments except
2579 @var{arg1}, separated by commas, with each argument quoted.
2581 The macro @code{shift} is recognized only with parameters.
2582 @end deffn
2584 @example
2585 shift
2586 @result{}shift
2587 shift(`bar')
2588 @result{}
2589 shift(`foo', `bar', `baz')
2590 @result{}bar,baz
2591 @end example
2593 An example of the use of @code{shift} is this macro:
2595 @deffn Composite reverse (@dots{})
2596 Takes any number of arguments, and reverses their order.
2597 @end deffn
2599 It is implemented as:
2601 @example
2602 define(`reverse', `ifelse(`$#', `0', , `$#', `1', ``$1'',
2603                           `reverse(shift($@@)), `$1'')')
2604 @result{}
2605 reverse
2606 @result{}
2607 reverse(`foo')
2608 @result{}foo
2609 reverse(`foo', `bar', `gnats', `and gnus')
2610 @result{}and gnus, gnats, bar, foo
2611 @end example
2613 While not a very interesting macro, it does show how simple loops can be
2614 made with @code{shift}, @code{ifelse} and recursion.  It also shows
2615 that @code{shift} is usually used with @samp{$@@}.  Sometimes, a
2616 recursive algorithm requires adding quotes to each element:
2618 @deffn Composite quote (@dots{})
2619 @deffnx Composite dquote (@dots{})
2620 @deffnx Composite dquote_elt (@dots{})
2621 Takes any number of arguments, and adds quoting.  With @code{quote},
2622 only one level of quoting is added, effectively removing whitespace
2623 after commas and turning multiple arguments into a single string.  With
2624 @code{dquote}, two levels of quoting are added, one around each element,
2625 and one around the list.  And with @code{dquote_elt}, two levels of
2626 quoting are added around each element.
2627 @end deffn
2629 An actual implementation of these three macros is distributed as
2630 @file{m4-@value{VERSION}/@/examples/@/quote.m4} in this package.  First,
2631 let's examine their usage:
2633 @example
2634 $ @kbd{m4 -I examples}
2635 include(`quote.m4')
2636 @result{}
2637 -quote-dquote-dquote_elt-
2638 @result{}----
2639 -quote()-dquote()-dquote_elt()-
2640 @result{}--`'-`'-
2641 -quote(`1')-dquote(`1')-dquote_elt(`1')-
2642 @result{}-1-`1'-`1'-
2643 -quote(`1', `2')-dquote(`1', `2')-dquote_elt(`1', `2')-
2644 @result{}-1,2-`1',`2'-`1',`2'-
2645 define(`n', `$#')dnl
2646 -n(quote(`1', `2'))-n(dquote(`1', `2'))-n(dquote_elt(`1', `2'))-
2647 @result{}-1-1-2-
2648 dquote(dquote_elt(`1', `2'))
2649 @result{}``1'',``2''
2650 dquote_elt(dquote(`1', `2'))
2651 @result{}``1',`2''
2652 @end example
2654 The last two lines show that when given two arguments, @code{dquote}
2655 results in one string, while @code{dquote_elt} results in two.  Now,
2656 examine the implementation.  Note that @code{quote} and
2657 @code{dquote_elt} make decisions based on their number of arguments, so
2658 that when called without arguments, they result in nothing instead of a
2659 quoted empty string; this is so that it is possible to distinguish
2660 between no arguments and an empty first argument.  @code{dquote}, on the
2661 other hand, results in a string no matter what, since it is still
2662 possible to tell whether it was invoked without arguments based on the
2663 resulting string.
2665 @example
2666 $ @kbd{m4 -I examples}
2667 undivert(`quote.m4')dnl
2668 @result{}divert(`-1')
2669 @result{}# quote(args) - convert args to single-quoted string
2670 @result{}define(`quote', `ifelse(`$#', `0', `', ``$*'')')
2671 @result{}# dquote(args) - convert args to quoted list of quoted strings
2672 @result{}define(`dquote', ``$@@'')
2673 @result{}# dquote_elt(args) - convert args to list of double-quoted strings
2674 @result{}define(`dquote_elt', `ifelse(`$#', `0', `', `$#', `1', ```$1''',
2675 @result{}                             ```$1'',$0(shift($@@))')')
2676 @result{}divert`'dnl
2677 @end example
2679 @cindex nine arguments, more than
2680 @cindex more than nine arguments
2681 @cindex arguments, more than nine
2682 One more useful macro based on @code{shift} allows portably selecting
2683 an arbitrary argument (usually greater than the ninth argument), without
2684 relying on the @acronym{GNU} extension of multi-digit arguments
2685 (@pxref{Arguments}).
2687 @deffn Composite argn (@var{n}, @dots{})
2688 Expands to argument @var{n} out of the remaining arguments.  @var{n}
2689 must be a positive number.  Usually invoked as
2690 @samp{argn(`@var{n}',$@@)}.
2691 @end deffn
2693 It is implemented as:
2695 @example
2696 define(`argn', `ifelse(`$1', 1, ``$2'',
2697   `argn(decr(`$1'), shift(shift($@@)))')')
2698 @result{}
2699 argn(`1', `a')
2700 @result{}a
2701 define(`foo', `argn(`11', $@@)')
2702 @result{}
2703 foo(`a', `b', `c', `d', `e', `f', `g', `h', `i', `j', `k', `l')
2704 @result{}k
2705 @end example
2707 @node Forloop
2708 @section Iteration by counting
2710 @cindex for loops
2711 @cindex loops, counting
2712 @cindex counting loops
2713 Here is an example of a loop macro that implements a simple for loop.
2715 @deffn Composite forloop (@var{iterator}, @var{start}, @var{end}, @var{text})
2716 Takes the name in @var{iterator}, which must be a valid macro name, and
2717 successively assign it each integer value from @var{start} to @var{end},
2718 inclusive.  For each assignment to @var{iterator}, append @var{text} to
2719 the expansion of the @code{forloop}.  @var{text} may refer to
2720 @var{iterator}.  Any definition of @var{iterator} prior to this
2721 invocation is restored.
2722 @end deffn
2724 It can, for example, be used for simple counting:
2726 @example
2727 $ @kbd{m4 -I examples}
2728 include(`forloop.m4')
2729 @result{}
2730 forloop(`i', `1', `8', `i ')
2731 @result{}1 2 3 4 5 6 7 8@w{ }
2732 @end example
2734 For-loops can be nested, like:
2736 @example
2737 $ @kbd{m4 -I examples}
2738 include(`forloop.m4')
2739 @result{}
2740 forloop(`i', `1', `4', `forloop(`j', `1', `8', ` (i, j)')
2742 @result{} (1, 1) (1, 2) (1, 3) (1, 4) (1, 5) (1, 6) (1, 7) (1, 8)
2743 @result{} (2, 1) (2, 2) (2, 3) (2, 4) (2, 5) (2, 6) (2, 7) (2, 8)
2744 @result{} (3, 1) (3, 2) (3, 3) (3, 4) (3, 5) (3, 6) (3, 7) (3, 8)
2745 @result{} (4, 1) (4, 2) (4, 3) (4, 4) (4, 5) (4, 6) (4, 7) (4, 8)
2746 @result{}
2747 @end example
2749 The implementation of the @code{forloop} macro is fairly
2750 straightforward.  The @code{forloop} macro itself is simply a wrapper,
2751 which saves the previous definition of the first argument, calls the
2752 internal macro @code{@w{_forloop}}, and re-establishes the saved
2753 definition of the first argument.
2755 The macro @code{@w{_forloop}} expands the fourth argument once, and
2756 tests to see if the iterator has reached the final value.  If it has
2757 not finished, it increments the iterator (using the predefined macro
2758 @code{incr}, @pxref{Incr}), and recurses.
2760 Here is an actual implementation of @code{forloop}, distributed as
2761 @file{m4-@value{VERSION}/@/examples/@/forloop.m4} in this package:
2763 @example
2764 $ @kbd{m4 -I examples}
2765 undivert(`forloop.m4')dnl
2766 @result{}divert(`-1')
2767 @result{}# forloop(var, from, to, stmt) - simple version
2768 @result{}define(`forloop', `pushdef(`$1', `$2')_forloop($@@)popdef(`$1')')
2769 @result{}define(`_forloop',
2770 @result{}       `$4`'ifelse($1, `$3', `', `define(`$1', incr($1))$0($@@)')')
2771 @result{}divert`'dnl
2772 @end example
2774 Notice the careful use of quotes.  Certain macro arguments are left
2775 unquoted, each for its own reason.  Try to find out @emph{why} these
2776 arguments are left unquoted, and see what happens if they are quoted.
2777 (As presented, these two macros are useful but not very robust for
2778 general use.  They lack even basic error handling for cases like
2779 @var{start} less than @var{end}, @var{end} not numeric, or
2780 @var{iterator} not being a macro name.  See if you can improve these
2781 macros; or @pxref{Improved forloop, , Answers}).
2783 @node Foreach
2784 @section Iteration by list contents
2786 @cindex for each loops
2787 @cindex loops, list iteration
2788 @cindex iterating over lists
2789 Here is an example of a loop macro that implements list iteration.
2791 @deffn Composite foreach (@var{iterator}, @var{paren-list}, @var{text})
2792 @deffnx Composite foreachq (@var{iterator}, @var{quote-list}, @var{text})
2793 Takes the name in @var{iterator}, which must be a valid macro name, and
2794 successively assign it each value from @var{paren-list} or
2795 @var{quote-list}.  In @code{foreach}, @var{paren-list} is a
2796 comma-separated list of elements contained in parentheses.  In
2797 @code{foreachq}, @var{quote-list} is a comma-separated list of elements
2798 contained in a quoted string.  For each assignment to @var{iterator},
2799 append @var{text} to the overall expansion.  @var{text} may refer to
2800 @var{iterator}.  Any definition of @var{iterator} prior to this
2801 invocation is restored.
2802 @end deffn
2804 As an example, this displays each word in a list inside of a sentence,
2805 using an implementation of @code{foreach} distributed as
2806 @file{m4-@value{VERSION}/@/examples/@/foreach.m4}, and @code{foreachq}
2807 in @file{m4-@value{VERSION}/@/examples/@/foreachq.m4}.
2809 @example
2810 $ @kbd{m4 -I examples}
2811 include(`foreach.m4')
2812 @result{}
2813 foreach(`x', (foo, bar, foobar), `Word was: x
2814 ')dnl
2815 @result{}Word was: foo
2816 @result{}Word was: bar
2817 @result{}Word was: foobar
2818 include(`foreachq.m4')
2819 @result{}
2820 foreachq(`x', `foo, bar, foobar', `Word was: x
2821 ')dnl
2822 @result{}Word was: foo
2823 @result{}Word was: bar
2824 @result{}Word was: foobar
2825 @end example
2827 It is possible to be more complex; each element of the @var{paren-list}
2828 or @var{quote-list} can itself be a list, to pass as further arguments
2829 to a helper macro.  This example generates a shell case statement:
2831 @example
2832 $ @kbd{m4 -I examples}
2833 include(`foreach.m4')
2834 @result{}
2835 define(`_case', `  $1)
2836     $2=" $1";;
2837 ')dnl
2838 define(`_cat', `$1$2')dnl
2839 case $`'1 in
2840 @result{}case $1 in
2841 foreach(`x', `(`(`a', `vara')', `(`b', `varb')', `(`c', `varc')')',
2842         `_cat(`_case', x)')dnl
2843 @result{}  a)
2844 @result{}    vara=" a";;
2845 @result{}  b)
2846 @result{}    varb=" b";;
2847 @result{}  c)
2848 @result{}    varc=" c";;
2849 esac
2850 @result{}esac
2851 @end example
2853 The implementation of the @code{foreach} macro is a bit more involved;
2854 it is a wrapper around two helper macros.  First, @code{@w{_arg1}} is
2855 needed to grab the first element of a list.  Second,
2856 @code{@w{_foreach}} implements the recursion, successively walking
2857 through the original list.  Here is a simple implementation of
2858 @code{foreach}:
2860 @example
2861 $ @kbd{m4 -I examples}
2862 undivert(`foreach.m4')dnl
2863 @result{}divert(`-1')
2864 @result{}# foreach(x, (item_1, item_2, ..., item_n), stmt)
2865 @result{}#   parenthesized list, simple version
2866 @result{}define(`foreach', `pushdef(`$1')_foreach($@@)popdef(`$1')')
2867 @result{}define(`_arg1', `$1')
2868 @result{}define(`_foreach', `ifelse(`$2', `()', `',
2869 @result{}  `define(`$1', _arg1$2)$3`'$0(`$1', (shift$2), `$3')')')
2870 @result{}divert`'dnl
2871 @end example
2873 Unfortunately, that implementation is not robust to macro names as list
2874 elements.  Each iteration of @code{@w{_foreach}} is stripping another
2875 layer of quotes, leading to erratic results if list elements are not
2876 already fully expanded.  The first cut at implementing @code{foreachq}
2877 takes this into account.  Also, when using quoted elements in a
2878 @var{paren-list}, the overall list must be quoted.  A @var{quote-list}
2879 has the nice property of requiring fewer characters to create a list
2880 containing the same quoted elements.  To see the difference between the
2881 two macros, we attempt to pass double-quoted macro names in a list,
2882 expecting the macro name on output after one layer of quotes is removed
2883 during list iteration and the final layer removed during the final
2884 rescan:
2886 @example
2887 $ @kbd{m4 -I examples}
2888 define(`a', `1')define(`b', `2')define(`c', `3')
2889 @result{}
2890 include(`foreach.m4')
2891 @result{}
2892 include(`foreachq.m4')
2893 @result{}
2894 foreach(`x', `(``a'', ``(b'', ``c)'')', `x
2896 @result{}1
2897 @result{}(2)1
2898 @result{}
2899 @result{}, x
2900 @result{})
2901 foreachq(`x', ```a'', ``(b'', ``c)''', `x
2902 ')dnl
2903 @result{}a
2904 @result{}(b
2905 @result{}c)
2906 @end example
2908 Obviously, @code{foreachq} did a better job; here is its implementation:
2910 @example
2911 $ @kbd{m4 -I examples}
2912 undivert(`foreachq.m4')dnl
2913 @result{}include(`quote.m4')dnl
2914 @result{}divert(`-1')
2915 @result{}# foreachq(x, `item_1, item_2, ..., item_n', stmt)
2916 @result{}#   quoted list, simple version
2917 @result{}define(`foreachq', `pushdef(`$1')_foreachq($@@)popdef(`$1')')
2918 @result{}define(`_arg1', `$1')
2919 @result{}define(`_foreachq', `ifelse(quote($2), `', `',
2920 @result{}  `define(`$1', `_arg1($2)')$3`'$0(`$1', `shift($2)', `$3')')')
2921 @result{}divert`'dnl
2922 @end example
2924 Notice that @code{@w{_foreachq}} had to use the helper macro
2925 @code{quote} defined earlier (@pxref{Shift}), to ensure that the
2926 embedded @code{ifelse} call does not go haywire if a list element
2927 contains a comma.  Unfortunately, this implementation of @code{foreachq}
2928 has its own severe flaw.  Whereas the @code{foreach} implementation was
2929 linear, this macro is quadratic in the number of list elements, and is
2930 much more likely to trip up the limit set by the command line option
2931 @option{--nesting-limit} (or @option{-L}, @pxref{Limits control, ,
2932 Invoking m4}).  (It is possible to have robust iteration with linear
2933 behavior for either list style.  See if you can learn from the best
2934 elements of both of these implementations to create robust macros; or
2935 @pxref{Improved foreach, , Answers}).
2937 @node Debugging
2938 @chapter How to debug macros and input
2940 @cindex debugging macros
2941 @cindex macros, debugging
2942 When writing macros for @code{m4}, they often do not work as intended on
2943 the first try (as is the case with most programming languages).
2944 Fortunately, there is support for macro debugging in @code{m4}.
2946 @menu
2947 * Dumpdef::                     Displaying macro definitions
2948 * Trace::                       Tracing macro calls
2949 * Debug Levels::                Controlling debugging output
2950 * Debug Output::                Saving debugging output
2951 @end menu
2953 @node Dumpdef
2954 @section Displaying macro definitions
2956 @cindex displaying macro definitions
2957 @cindex macros, displaying definitions
2958 @cindex definitions, displaying macro
2959 @cindex standard error, output to
2960 If you want to see what a name expands into, you can use the builtin
2961 @code{dumpdef}:
2963 @deffn Builtin dumpdef (@ovar{names@dots{}})
2964 Accepts any number of arguments.  If called without any arguments,
2965 it displays the definitions of all known names, otherwise it displays
2966 the definitions of the @var{names} given.  The output is printed to the
2967 current debug file (usually standard error), and is sorted by name.  If
2968 an unknown name is encountered, a warning is printed.
2970 The expansion of @code{dumpdef} is void.
2971 @end deffn
2973 @example
2974 $ @kbd{m4 -d}
2975 define(`foo', `Hello world.')
2976 @result{}
2977 dumpdef(`foo')
2978 @error{}foo:@tabchar{}`Hello world.'
2979 @result{}
2980 dumpdef(`define')
2981 @error{}define:@tabchar{}<define>
2982 @result{}
2983 @end example
2985 The last example shows how builtin macros definitions are displayed.
2986 The definition that is dumped corresponds to what would occur if the
2987 macro were to be called at that point, even if other definitions are
2988 still live due to redefining a macro during argument collection.
2990 @example
2991 $ @kbd{m4 -d}
2992 pushdef(`f', ``$0'1')pushdef(`f', ``$0'2')
2993 @result{}
2994 f(popdef(`f')dumpdef(`f'))
2995 @error{}f:@tabchar{}``$0'1'
2996 @result{}f2
2997 f(popdef(`f')dumpdef(`f'))
2998 @error{}m4:stdin:3: undefined macro `f'
2999 @result{}f1
3000 @end example
3002 @xref{Debug Levels}, for information on controlling the details of the
3003 display.
3005 @node Trace
3006 @section Tracing macro calls
3008 @cindex tracing macro expansion
3009 @cindex macro expansion, tracing
3010 @cindex expansion, tracing macro
3011 @cindex standard error, output to
3012 It is possible to trace macro calls and expansions through the builtins
3013 @code{traceon} and @code{traceoff}:
3015 @deffn Builtin traceon (@ovar{names@dots{}})
3016 @deffnx Builtin traceoff (@ovar{names@dots{}})
3017 When called without any arguments, @code{traceon} and @code{traceoff}
3018 will turn tracing on and off, respectively, for all currently defined
3019 macros.
3021 When called with arguments, only the macros listed in @var{names} are
3022 affected, whether or not they are currently defined.
3024 The expansion of @code{traceon} and @code{traceoff} is void.
3025 @end deffn
3027 Whenever a traced macro is called and the arguments have been collected,
3028 the call is displayed.  If the expansion of the macro call is not void,
3029 the expansion can be displayed after the call.  The output is printed
3030 to the current debug file (defaulting to standard error, @pxref{Debug
3031 Output}).
3033 @example
3034 $ @kbd{m4 -d}
3035 define(`foo', `Hello World.')
3036 @result{}
3037 define(`echo', `$@@')
3038 @result{}
3039 traceon(`foo', `echo')
3040 @result{}
3042 @error{}m4trace: -1- foo -> `Hello World.'
3043 @result{}Hello World.
3044 echo(`gnus', `and gnats')
3045 @error{}m4trace: -1- echo(`gnus', `and gnats') -> ``gnus',`and gnats''
3046 @result{}gnus,and gnats
3047 @end example
3049 The number between dashes is the depth of the expansion.  It is one most
3050 of the time, signifying an expansion at the outermost level, but it
3051 increases when macro arguments contain unquoted macro calls.  The
3052 maximum number that will appear between dashes is controlled by the
3053 option @option{--nesting-limit} (or @option{-L}, @pxref{Limits control,
3054 , Invoking m4}).  Additionally, the option @option{--trace} (or
3055 @option{-t}) can be used to invoke @code{traceon(@var{name})} before
3056 parsing input.
3058 @comment options: -dp -L3 -tifelse
3059 @comment status: 1
3060 @example
3061 $ @kbd{m4 -L 3 -t ifelse}
3062 ifelse(`one level')
3063 @error{}m4trace: -1- ifelse
3064 @result{}
3065 ifelse(ifelse(ifelse(`three levels')))
3066 @error{}m4trace: -3- ifelse
3067 @error{}m4trace: -2- ifelse
3068 @error{}m4trace: -1- ifelse
3069 @result{}
3070 ifelse(ifelse(ifelse(ifelse(`four levels'))))
3071 @error{}m4:stdin:3: recursion limit of 3 exceeded, use -L<N> to change it
3072 @end example
3074 Tracing by name is an attribute that is preserved whether the macro is
3075 defined or not.  This allows the selection of macros to trace before
3076 those macros are defined.
3078 @example
3079 $ @kbd{m4 -d}
3080 traceoff(`foo')
3081 @result{}
3082 traceon(`foo')
3083 @result{}
3085 @result{}foo
3086 define(`foo', `bar')
3087 @result{}
3089 @error{}m4trace: -1- foo -> `bar'
3090 @result{}bar
3091 undefine(`foo')
3092 @result{}
3093 ifdef(`foo', `yes', `no')
3094 @result{}no
3095 indir(`foo')
3096 @error{}m4:stdin:8: undefined macro `foo'
3097 @result{}
3098 define(`foo', `blah')
3099 @result{}
3101 @error{}m4trace: -1- foo -> `blah'
3102 @result{}blah
3103 traceoff
3104 @result{}
3106 @result{}blah
3107 @end example
3109 Tracing even works on builtins.  However, @code{defn} (@pxref{Defn})
3110 does not transfer tracing status.
3112 @example
3113 $ @kbd{m4 -d}
3114 traceon(`eval', `m4_divnum')
3115 @result{}
3116 define(`m4_eval', defn(`eval'))
3117 @result{}
3118 define(`m4_divnum', defn(`divnum'))
3119 @result{}
3120 eval(divnum)
3121 @error{}m4trace: -1- eval(`0') -> `0'
3122 @result{}0
3123 m4_eval(m4_divnum)
3124 @error{}m4trace: -2- m4_divnum -> `0'
3125 @result{}0
3126 @end example
3128 @xref{Debug Levels}, for information on controlling the details of the
3129 display.
3131 @node Debug Levels
3132 @section Controlling debugging output
3134 @cindex controlling debugging output
3135 @cindex debugging output, controlling
3136 The @option{-d} option to @code{m4} (or @option{--debug},
3137 @pxref{Debugging options, , Invoking m4}) controls the amount of details
3138 presented in three
3139 categories of output.  Trace output is requested by @code{traceon}
3140 (@pxref{Trace}), and each line is prefixed by @samp{m4trace:} in
3141 relation to a macro invocation.  Debug output tracks useful events not
3142 associated with a macro invocation, and each line is prefixed by
3143 @samp{m4debug:}.  Finally, @code{dumpdef} (@pxref{Dumpdef}) output is
3144 affected, with no prefix added to the output lines.
3146 The @var{flags} following the option can be one or more of the
3147 following:
3149 @table @code
3150 @item a
3151 In trace output, show the actual arguments that were collected before
3152 invoking the macro.  This applies to all macro calls if the @samp{t}
3153 flag is used, otherwise only the macros covered by calls of
3154 @code{traceon}.
3156 @item c
3157 In trace output, show several trace lines for each macro call.  A line
3158 is shown when the macro is seen, but before the arguments are collected;
3159 a second line when the arguments have been collected and a third line
3160 after the call has completed.
3162 @item e
3163 In trace output, show the expansion of each macro call, if it is not
3164 void.  This applies to all macro calls if the @samp{t} flag is used,
3165 otherwise only the macros covered by calls of @code{traceon}.
3167 @item f
3168 In debug and trace output, include the name of the current input file in
3169 the output line.
3171 @item i
3172 In debug output, print a message each time the current input file is
3173 changed.
3175 @item l
3176 In debug and trace output, include the current input line number in the
3177 output line.
3179 @item p
3180 In debug output, print a message when a named file is found through the
3181 path search mechanism (@pxref{Search Path}), giving the actual file name
3182 used.
3184 @item q
3185 In trace and dumpdef output, quote actual arguments and macro expansions
3186 in the display with the current quotes.  This is useful in connection
3187 with the @samp{a} and @samp{e} flags above.
3189 @item t
3190 In trace output, trace all macro calls made in this invocation of
3191 @code{m4}, regardless of the settings of @code{traceon}.
3193 @item x
3194 In trace output, add a unique `macro call id' to each line of the trace
3195 output.  This is useful in connection with the @samp{c} flag above.
3197 @item V
3198 A shorthand for all of the above flags.
3199 @end table
3201 If no flags are specified with the @option{-d} option, the default is
3202 @samp{aeq}.  The examples throughout this manual assume the default
3203 flags.
3205 @cindex @acronym{GNU} extensions
3206 There is a builtin macro @code{debugmode}, which allows on-the-fly control of
3207 the debugging output format:
3209 @deffn Builtin debugmode (@ovar{flags})
3210 The argument @var{flags} should be a subset of the letters listed above.
3211 As special cases, if the argument starts with a @samp{+}, the flags are
3212 added to the current debug flags, and if it starts with a @samp{-}, they
3213 are removed.  If no argument is present, all debugging flags are cleared
3214 (as if no @option{-d} was given), and with an empty argument the flags
3215 are reset to the default of @samp{aeq}.
3217 The expansion of @code{debugmode} is void.
3218 @end deffn
3220 @comment options: -dp
3221 @example
3222 $ @kbd{m4}
3223 define(`foo', `FOO')
3224 @result{}
3225 traceon(`foo')
3226 @result{}
3227 debugmode()
3228 @result{}
3230 @error{}m4trace: -1- foo -> `FOO'
3231 @result{}FOO
3232 debugmode
3233 @result{}
3235 @error{}m4trace: -1- foo
3236 @result{}FOO
3237 debugmode(`+l')
3238 @result{}
3240 @error{}m4trace:8: -1- foo
3241 @result{}FOO
3242 @end example
3244 @node Debug Output
3245 @section Saving debugging output
3247 @cindex saving debugging output
3248 @cindex debugging output, saving
3249 @cindex output, saving debugging
3250 @cindex @acronym{GNU} extensions
3251 Debug and tracing output can be redirected to files using either the
3252 @option{--debugfile} option to @code{m4} (@pxref{Debugging options, ,
3253 Invoking m4}), or with the builtin macro @code{debugfile}:
3255 @deffn Builtin debugfile (@ovar{file})
3256 Sends all further debug and trace output to @var{file}, opened in append
3257 mode.  If @var{file} is the empty string, debug and trace output are
3258 discarded.  If @code{debugfile} is called without any arguments, debug
3259 and trace output are sent to standard error.  This does not affect
3260 warnings, error messages, or @code{errprint} output, which are
3261 always sent to standard error.  If @var{file} cannot be opened, the
3262 current debug file is unchanged, and an error is issued.
3264 The expansion of @code{debugfile} is void.
3265 @end deffn
3267 @example
3268 $ @kbd{m4}
3269 traceon(`divnum')
3270 @result{}
3271 divnum(`extra')
3272 @error{}m4:stdin:2: Warning: excess arguments to builtin `divnum' ignored
3273 @error{}m4trace: -1- divnum(`extra') -> `0'
3274 @result{}0
3275 debugfile()
3276 @result{}
3277 divnum(`extra')
3278 @error{}m4:stdin:4: Warning: excess arguments to builtin `divnum' ignored
3279 @result{}0
3280 debugfile
3281 @result{}
3282 divnum
3283 @error{}m4trace: -1- divnum -> `0'
3284 @result{}0
3285 @end example
3287 @node Input Control
3288 @chapter Input control
3290 This chapter describes various builtin macros for controlling the input
3291 to @code{m4}.
3293 @menu
3294 * Dnl::                         Deleting whitespace in input
3295 * Changequote::                 Changing the quote characters
3296 * Changecom::                   Changing the comment delimiters
3297 * Changeword::                  Changing the lexical structure of words
3298 * M4wrap::                      Saving text until end of input
3299 @end menu
3301 @node Dnl
3302 @section Deleting whitespace in input
3304 @cindex deleting whitespace in input
3305 @cindex discarding input
3306 @cindex input, discarding
3307 The builtin @code{dnl} stands for ``Discard to Next Line'':
3309 @deffn Builtin dnl
3310 All characters, up to and including the next newline, are discarded
3311 without performing any macro expansion.  A warning is issued if the end
3312 of the file is encountered without a newline.
3314 The expansion of @code{dnl} is void.
3315 @end deffn
3317 It is often used in connection with @code{define}, to remove the
3318 newline that follows the call to @code{define}.  Thus
3320 @example
3321 define(`foo', `Macro `foo'.')dnl A very simple macro, indeed.
3323 @result{}Macro foo.
3324 @end example
3326 The input up to and including the next newline is discarded, as opposed
3327 to the way comments are treated (@pxref{Comments}).
3329 Usually, @code{dnl} is immediately followed by an end of line or some
3330 other whitespace.  @acronym{GNU} @code{m4} will produce a warning diagnostic if
3331 @code{dnl} is followed by an open parenthesis.  In this case, @code{dnl}
3332 will collect and process all arguments, looking for a matching close
3333 parenthesis.  All predictable side effects resulting from this
3334 collection will take place.  @code{dnl} will return no output.  The
3335 input following the matching close parenthesis up to and including the
3336 next newline, on whatever line containing it, will still be discarded.
3338 @example
3339 dnl(`args are ignored, but side effects occur',
3340 define(`foo', `like this')) while this text is ignored: undefine(`foo')
3341 @error{}m4:stdin:1: Warning: excess arguments to builtin `dnl' ignored
3342 See how `foo' was defined, foo?
3343 @result{}See how foo was defined, like this?
3344 @end example
3346 If the end of file is encountered without a newline character, a
3347 warning is issued and dnl stops consuming input.
3349 @example
3350 m4wrap(`m4wrap(`2 hi
3351 ')0 hi dnl 1 hi')
3352 @result{}
3353 define(`hi', `HI')
3354 @result{}
3356 @error{}m4:stdin:1: Warning: end of file treated as newline
3357 @result{}0 HI 2 HI
3358 @end example
3360 @node Changequote
3361 @section Changing the quote characters
3363 @cindex changing quote delimiters
3364 @cindex quote delimiters, changing
3365 @cindex delimiters, changing
3366 The default quote delimiters can be changed with the builtin
3367 @code{changequote}:
3369 @deffn Builtin changequote (@dvar{start, `}, @dvar{end, '})
3370 This sets @var{start} as the new begin-quote delimiter and @var{end} as
3371 the new end-quote delimiter.  If both arguments are missing, the default
3372 quotes (@code{`} and @code{'}) are used.  If @var{start} is void, then
3373 quoting is disabled.  Otherwise, if @var{end} is missing or void, the
3374 default end-quote delimiter (@code{'}) is used.  The quote delimiters
3375 can be of any length.
3377 The expansion of @code{changequote} is void.
3378 @end deffn
3380 @example
3381 changequote(`[', `]')
3382 @result{}
3383 define([foo], [Macro [foo].])
3384 @result{}
3386 @result{}Macro foo.
3387 @end example
3389 The quotation strings can safely contain eight-bit characters.
3390 @ignore
3391 @comment Yuck.  I know of no clean way to render an 8-bit character in
3392 @comment both info and dvi.  This example uses the `open-guillemot' and
3393 @comment `close-guillemot' characters of the Latin-1 character set.
3395 @example
3396 define(`a', `b')
3397 @result{}
3398 «a»
3399 @result{}«b»
3400 changequote(`«', `»')
3401 @result{}
3402 «a»
3403 @result{}a
3404 @end example
3405 @end ignore
3406 If no single character is appropriate, @var{start} and @var{end} can be
3407 of any length.  Other implementations cap the delimiter length to five
3408 characters, but @acronym{GNU} has no inherent limit.
3410 @example
3411 changequote(`[[[', `]]]')
3412 @result{}
3413 define([[[foo]]], [[[Macro [[[[[foo]]]]].]]])
3414 @result{}
3416 @result{}Macro [[foo]].
3417 @end example
3419 Calling @code{changequote} with @var{start} as the empty string will
3420 effectively disable the quoting mechanism, leaving no way to quote text.
3421 However, using an empty string is not portable, as some other
3422 implementations of @code{m4} revert to the default quoting, while others
3423 preserve the prior non-empty delimiter.  If @var{start} is not empty,
3424 then an empty @var{end} will use the default end-quote delimiter of
3425 @samp{'}, as otherwise, it would be impossible to end a quoted string.
3426 Again, this is not portable, as some other @code{m4} implementations
3427 reuse @var{start} as the end-quote delimiter, while others preserve the
3428 previous non-empty value.  Omitting both arguments restores the default
3429 begin-quote and end-quote delimiters; fortunately this behavior is
3430 portable to all implementations of @code{m4}.
3432 @example
3433 define(`foo', `Macro `FOO'.')
3434 @result{}
3435 changequote(`', `')
3436 @result{}
3438 @result{}Macro `FOO'.
3439 `foo'
3440 @result{}`Macro `FOO'.'
3441 changequote(`,)
3442 @result{}
3444 @result{}Macro FOO.
3445 @end example
3447 There is no way in @code{m4} to quote a string containing an unmatched
3448 begin-quote, except using @code{changequote} to change the current
3449 quotes.
3451 If the quotes should be changed from, say, @samp{[} to @samp{[[},
3452 temporary quote characters have to be defined.  To achieve this, two
3453 calls of @code{changequote} must be made, one for the temporary quotes
3454 and one for the new quotes.
3456 Macros are recognized in preference to the begin-quote string, so if a
3457 prefix of @var{start} can be recognized as part of a potential macro
3458 name, the quoting mechanism is effectively disabled.  Unless you use
3459 @code{changeword} (@pxref{Changeword}), this means that @var{start}
3460 should not begin with a letter, digit, or @samp{_} (underscore).
3461 However, even though quoted strings are not recognized, the quote
3462 characters can still be discerned in macro expansion and in trace
3463 output.
3465 @example
3466 define(`echo', `$@@')
3467 @result{}
3468 define(`hi', `HI')
3469 @result{}
3470 changequote(`q', `Q')
3471 @result{}
3472 q hi Q hi
3473 @result{}q HI Q HI
3474 echo(hi)
3475 @result{}qHIQ
3476 changequote
3477 @result{}
3478 changequote(`-', `EOF')
3479 @result{}
3480 - hi EOF hi
3481 @result{} hi  HI
3482 changequote
3483 @result{}
3484 changequote(`1', `2')
3485 @result{}
3486 hi1hi2
3487 @result{}hi1hi2
3488 hi 1hi2
3489 @result{}HI hi
3490 @end example
3492 Quotes are recognized in preference to argument collection.  In
3493 particular, if @var{start} is a single @samp{(}, then argument
3494 collection is effectively disabled.  For portability with other
3495 implementations, it is a good idea to avoid @samp{(}, @samp{,}, and
3496 @samp{)} as the first character in @var{start}.
3498 @example
3499 define(`echo', `$#:$@@:')
3500 @result{}
3501 define(`hi', `HI')
3502 @result{}
3503 changequote(`(',`)')
3504 @result{}
3505 echo(hi)
3506 @result{}0::hi
3507 changequote
3508 @result{}
3509 changequote(`((', `))')
3510 @result{}
3511 echo(hi)
3512 @result{}1:HI:
3513 echo((hi))
3514 @result{}0::hi
3515 changequote
3516 @result{}
3517 changequote(`,', `)')
3518 @result{}
3519 echo(hi,hi)bye)
3520 @result{}1:HIhibye:
3521 @end example
3523 If @var{end} is a prefix of @var{start}, the end-quote will be
3524 recognized in preference to a nested begin-quote.  In particular,
3525 changing the quotes to have the same string for @var{start} and
3526 @var{end} disables nesting of quotes.  When quote nesting is disabled,
3527 it is impossible to double-quote strings across macro expansions, so
3528 using the same string is not done very often.
3530 @example
3531 define(`hi', `HI')
3532 @result{}
3533 changequote(`""', `"')
3534 @result{}
3535 ""hi"""hi"
3536 @result{}hihi
3537 ""hi" ""hi"
3538 @result{}hi hi
3539 ""hi"" "hi"
3540 @result{}hi" "HI"
3541 changequote
3542 @result{}
3543 `hi`hi'hi'
3544 @result{}hi`hi'hi
3545 changequote(`"', `"')
3546 @result{}
3547 "hi"hi"hi"
3548 @result{}hiHIhi
3549 @end example
3551 It is an error if the end of file occurs within a quoted string.
3553 @comment status: 1
3554 @example
3555 `hello world'
3556 @result{}hello world
3557 `dangling quote
3559 @error{}m4:stdin:2: ERROR: end of file in string
3560 @end example
3562 @node Changecom
3563 @section Changing the comment delimiters
3565 @cindex changing comment delimiters
3566 @cindex comment delimiters, changing
3567 @cindex delimiters, changing
3568 The default comment delimiters can be changed with the builtin
3569 macro @code{changecom}:
3571 @deffn Builtin changecom (@ovar{start}, @dvar{end, @key{NL}})
3572 This sets @var{start} as the new begin-comment delimiter and @var{end}
3573 as the new end-comment delimiter.  If both arguments are missing, or
3574 @var{start} is void, then comments are disabled.  Otherwise, if
3575 @var{end} is missing or void, the default end-comment delimiter of
3576 newline is used.  The comment delimiters can be of any length.
3578 The expansion of @code{changecom} is void.
3579 @end deffn
3581 @example
3582 define(`comment', `COMMENT')
3583 @result{}
3584 # A normal comment
3585 @result{}# A normal comment
3586 changecom(`/*', `*/')
3587 @result{}
3588 # Not a comment anymore
3589 @result{}# Not a COMMENT anymore
3590 But: /* this is a comment now */ while this is not a comment
3591 @result{}But: /* this is a comment now */ while this is not a COMMENT
3592 @end example
3594 @cindex comments, copied to output
3595 Note how comments are copied to the output, much as if they were quoted
3596 strings.  If you want the text inside a comment expanded, quote the
3597 begin-comment delimiter.
3599 Calling @code{changecom} without any arguments, or with @var{start} as
3600 the empty string, will effectively disable the commenting mechanism.  To
3601 restore the original comment start of @samp{#}, you must explicitly ask
3602 for it.  If @var{start} is not empty, then an empty @var{end} will use
3603 the default end-comment delimiter of newline, as otherwise, it would be
3604 impossible to end a comment.  However, this is not portable, as some
3605 other @code{m4} implementations preserve the previous non-empty
3606 delimiters instead.
3608 @example
3609 define(`comment', `COMMENT')
3610 @result{}
3611 changecom
3612 @result{}
3613 # Not a comment anymore
3614 @result{}# Not a COMMENT anymore
3615 changecom(`#', `')
3616 @result{}
3617 # comment again
3618 @result{}# comment again
3619 @end example
3621 The comment strings can safely contain eight-bit characters.
3622 @ignore
3623 @comment Yuck.  I know of no clean way to render an 8-bit character in
3624 @comment both info and dvi.  This example uses the `open-guillemot' and
3625 @comment `close-guillemot' characters of the Latin-1 character set.
3627 @example
3628 define(`a', `b')
3629 @result{}
3630 «a»
3631 @result{}«b»
3632 changecom(`«', `»')
3633 @result{}
3634 «a»
3635 @result{}«a»
3636 @end example
3637 @end ignore
3638 If no single character is appropriate, @var{start} and @var{end} can be
3639 of any length.  Other implementations cap the delimiter length to five
3640 characters, but @acronym{GNU} has no inherent limit.
3642 Comments are recognized in preference to macros.  However, this is not
3643 compatible with other implementations, where macros and even quoting
3644 takes precedence over comments, so it may change in a future release.
3645 For portability, this means that @var{start} should not begin with a
3646 letter, digit, or @samp{_} (underscore), and that neither the
3647 start-quote nor the start-comment string should be a prefix of the
3648 other.
3650 @example
3651 define(`hi', `HI')
3652 @result{}
3653 define(`hi1hi2', `hello')
3654 @result{}
3655 changecom(`q', `Q')
3656 @result{}
3657 q hi Q hi
3658 @result{}q hi Q HI
3659 changecom(`1', `2')
3660 @result{}
3661 hi1hi2
3662 @result{}hello
3663 hi 1hi2
3664 @result{}HI 1hi2
3665 @end example
3667 Comments are recognized in preference to argument collection.  In
3668 particular, if @var{start} is a single @samp{(}, then argument
3669 collection is effectively disabled.  For portability with other
3670 implementations, it is a good idea to avoid @samp{(}, @samp{,}, and
3671 @samp{)} as the first character in @var{start}.
3673 @example
3674 define(`echo', `$#:$@@:')
3675 @result{}
3676 define(`hi', `HI')
3677 @result{}
3678 changecom(`(',`)')
3679 @result{}
3680 echo(hi)
3681 @result{}0::(hi)
3682 changecom
3683 @result{}
3684 changecom(`((', `))')
3685 @result{}
3686 echo(hi)
3687 @result{}1:HI:
3688 echo((hi))
3689 @result{}0::((hi))
3690 changecom(`,', `)')
3691 @result{}
3692 echo(hi,hi)bye)
3693 @result{}1:HI,hi)bye:
3694 @end example
3696 It is an error if the end of file occurs within a comment.
3698 @comment status: 1
3699 @example
3700 changecom(`/*', `*/')
3701 @result{}
3702 /*dangling comment
3704 @error{}m4:stdin:2: ERROR: end of file in comment
3705 @end example
3707 @node Changeword
3708 @section Changing the lexical structure of words
3710 @cindex lexical structure of words
3711 @cindex words, lexical structure of
3712 @cindex syntax, changing
3713 @cindex changing syntax
3714 @cindex regular expressions
3715 @quotation
3716 The macro @code{changeword} and all associated functionality is
3717 experimental.  It is only available if the @option{--enable-changeword}
3718 option was given to @code{configure}, at @acronym{GNU} @code{m4} installation
3719 time.  The functionality will go away in the future, to be replaced by
3720 other new features that are more efficient at providing the same
3721 capabilities.  @emph{Do not rely on it}.  Please direct your comments
3722 about it the same way you would do for bugs.
3723 @end quotation
3725 A file being processed by @code{m4} is split into quoted strings, words
3726 (potential macro names) and simple tokens (any other single character).
3727 Initially a word is defined by the following regular expression:
3729 @comment ignore
3730 @example
3731 [_a-zA-Z][_a-zA-Z0-9]*
3732 @end example
3734 Using @code{changeword}, you can change this regular expression:
3736 @deffn {Optional builtin} changeword (@var{regex})
3737 Changes the regular expression for recognizing macro names to be
3738 @var{regex}.  If @var{regex} is empty, use
3739 @samp{[_a-zA-Z][_a-zA-Z0-9]*}.  @var{regex} must obey the constraint
3740 that every prefix of the desired final pattern is also accepted by the
3741 regular expression.  If @var{regex} contains grouping parentheses, the
3742 macro invoked is the portion that matched the first group, rather than
3743 the entire matching string.
3745 The expansion of @code{changeword} is void.
3746 The macro @code{changeword} is recognized only with parameters.
3747 @end deffn
3749 Relaxing the lexical rules of @code{m4} might be useful (for example) if
3750 you wanted to apply translations to a file of numbers:
3752 @example
3753 ifdef(`changeword', `', `errprint(` skipping: no changeword support
3754 ')m4exit(`77')')dnl
3755 changeword(`[_a-zA-Z0-9]+')
3756 @result{}
3757 define(`1', `0')1
3758 @result{}0
3759 @end example
3761 Tightening the lexical rules is less useful, because it will generally
3762 make some of the builtins unavailable.  You could use it to prevent
3763 accidental call of builtins, for example:
3765 @example
3766 ifdef(`changeword', `', `errprint(` skipping: no changeword support
3767 ')m4exit(`77')')dnl
3768 define(`_indir', defn(`indir'))
3769 @result{}
3770 changeword(`_[_a-zA-Z0-9]*')
3771 @result{}
3772 esyscmd(`foo')
3773 @result{}esyscmd(foo)
3774 _indir(`esyscmd', `echo hi')
3775 @result{}hi
3776 @result{}
3777 @end example
3779 Because @code{m4} constructs its words a character at a time, there
3780 is a restriction on the regular expressions that may be passed to
3781 @code{changeword}.  This is that if your regular expression accepts
3782 @samp{foo}, it must also accept @samp{f} and @samp{fo}.
3784 @example
3785 ifdef(`changeword', `', `errprint(` skipping: no changeword support
3786 ')m4exit(`77')')dnl
3787 define(`foo
3788 ', `bar
3790 @result{}
3791 dnl This example wants to recognize changeword, dnl, and `foo\n'.
3792 dnl First, we check that our regexp will match.
3793 regexp(`changeword', `[cd][a-z]*\|foo[
3795 @result{}0
3796 regexp(`foo
3797 ', `[cd][a-z]*\|foo[
3799 @result{}0
3800 regexp(`f', `[cd][a-z]*\|foo[
3802 @result{}-1
3804 @result{}foo
3805 changeword(`[cd][a-z]*\|foo[
3807 @result{}
3808 dnl Even though `foo\n' matches, we forgot to allow `f'.
3810 @result{}foo
3811 changeword(`[cd][a-z]*\|fo*[
3812 ]?')
3813 @result{}
3814 dnl Now we can call `foo\n'.
3816 @result{}bar
3817 @end example
3819 @ignore
3820 @comment One more test of including newline in a macro name; but this
3821 @comment does not need to be displayed in the manual.  This ensures
3822 @comment that line numbering is correct when dnl cuts across include
3823 @comment file boundaries, and when __file__ or __line__ is the last
3824 @comment token in an include file.
3826 @example
3827 ifdef(`changeword', `', `errprint(` skipping: no changeword support
3828 ')m4exit(`77')')dnl
3829 define(`bar
3830 ', defn(`dnl'))dnl
3831 define(`baz', `dnl
3832 include(`foo') ignored
3833 dnl')dnl
3834 changeword(`\([_a-zA-Z][_a-zA-Z0-9]*\|bar
3835 \)')
3836 @result{}
3837 __file__:__line__
3838 @result{}stdin:10
3839 include(`foo') ignored
3840 __file__:__line__
3841 @result{}stdin:12
3842 baz ignored
3843 __file__:__line__
3844 @result{}stdin:14
3845 define(`bar
3846 ', defn(`__file__'))
3847 @result{}
3848 include(`foo')
3849 @result{}../examples/foo
3850 define(`bar
3851 ', defn(`__line__'))
3852 @result{}
3853 include(`foo')
3854 @result{}1
3855 __file__:__line__
3856 @result{}stdin:21
3857 @end example
3858 @end ignore
3860 @code{changeword} has another function.  If the regular expression
3861 supplied contains any grouped subexpressions, then text outside
3862 the first of these is discarded before symbol lookup.  So:
3864 @example
3865 ifdef(`changeword', `', `errprint(` skipping: no changeword support
3866 ')m4exit(`77')')dnl
3867 ifdef(`__unix__', ,
3868       `errprint(` skipping: syscmd does not have unix semantics
3869 ')m4exit(`77')')dnl
3870 changecom(`/*', `*/')dnl
3871 define(`foo', `bar')dnl
3872 changeword(`#\([_a-zA-Z0-9]*\)')
3873 @result{}
3874 #esyscmd(`echo foo \#foo')
3875 @result{}foo bar
3876 @result{}
3877 @end example
3879 @code{m4} now requires a @samp{#} mark at the beginning of every
3880 macro invocation, so one can use @code{m4} to preprocess plain
3881 text without losing various words like @samp{divert}.
3883 In @code{m4}, macro substitution is based on text, while in @TeX{}, it
3884 is based on tokens.  @code{changeword} can throw this difference into
3885 relief.  For example, here is the same idea represented in @TeX{} and
3886 @code{m4}.  First, the @TeX{} version:
3888 @comment ignore
3889 @example
3890 \def\a@{\message@{Hello@}@}
3891 \catcode`\@@=0
3892 \catcode`\\=12
3894 @@bye
3895 @result{}Hello
3896 @end example
3898 @noindent
3899 Then, the @code{m4} version:
3901 @example
3902 ifdef(`changeword', `', `errprint(` skipping: no changeword support
3903 ')m4exit(`77')')dnl
3904 define(`a', `errprint(`Hello')')dnl
3905 changeword(`@@\([_a-zA-Z0-9]*\)')
3906 @result{}
3908 @result{}errprint(Hello)
3909 @end example
3911 In the @TeX{} example, the first line defines a macro @code{a} to
3912 print the message @samp{Hello}.  The second line defines @key{@@} to
3913 be usable instead of @key{\} as an escape character.  The third line
3914 defines @key{\} to be a normal printing character, not an escape.
3915 The fourth line invokes the macro @code{a}.  So, when @TeX{} is run
3916 on this file, it displays the message @samp{Hello}.
3918 When the @code{m4} example is passed through @code{m4}, it outputs
3919 @samp{errprint(Hello)}.  The reason for this is that @TeX{} does
3920 lexical analysis of macro definition when the macro is @emph{defined}.
3921 @code{m4} just stores the text, postponing the lexical analysis until
3922 the macro is @emph{used}.
3924 You should note that using @code{changeword} will slow @code{m4} down
3925 by a factor of about seven, once it is changed to something other
3926 than the default regular expression.  You can invoke @code{changeword}
3927 with the empty string to restore the default word definition, and regain
3928 the parsing speed.
3930 @node M4wrap
3931 @section Saving text until end of input
3933 @cindex saving input
3934 @cindex input, saving
3935 @cindex deferring expansion
3936 @cindex expansion, deferring
3937 It is possible to `save' some text until the end of the normal input has
3938 been seen.  Text can be saved, to be read again by @code{m4} when the
3939 normal input has been exhausted.  This feature is normally used to
3940 initiate cleanup actions before normal exit, e.g., deleting temporary
3941 files.
3943 To save input text, use the builtin @code{m4wrap}:
3945 @deffn Builtin m4wrap (@var{string}, @dots{})
3946 Stores @var{string} in a safe place, to be reread when end of input is
3947 reached.  As a @acronym{GNU} extension, additional arguments are
3948 concatenated with a space to the @var{string}.
3950 The expansion of @code{m4wrap} is void.
3951 The macro @code{m4wrap} is recognized only with parameters.
3952 @end deffn
3954 @example
3955 define(`cleanup', `This is the `cleanup' action.
3957 @result{}
3958 m4wrap(`cleanup')
3959 @result{}
3960 This is the first and last normal input line.
3961 @result{}This is the first and last normal input line.
3963 @result{}This is the cleanup action.
3964 @end example
3966 The saved input is only reread when the end of normal input is seen, and
3967 not if @code{m4exit} is used to exit @code{m4}.
3969 @comment FIXME: this contradicts POSIX, which requires that "If the
3970 @comment m4wrap macro is used multiple times, the arguments specified
3971 @comment shall be processed in the order in which the m4wrap macros were
3972 @comment processed."
3973 It is safe to call @code{m4wrap} from saved text, but then the order in
3974 which the saved text is reread is undefined.  If @code{m4wrap} is not used
3975 recursively, the saved pieces of text are reread in the opposite order
3976 in which they were saved (LIFO---last in, first out).  However, this
3977 behavior is likely to change in a future release, to match
3978 @acronym{POSIX}, so you should not depend on this order.
3980 Here is an example of implementing a factorial function using
3981 @code{m4wrap}:
3983 @example
3984 define(`f', `ifelse(`$1', `0', `Answer: 0!=1
3985 ', eval(`$1>1'), `0', `Answer: $2$1=eval(`$2$1')
3986 ', `m4wrap(`f(decr(`$1'), `$2$1*')')')')
3987 @result{}
3988 f(`10')
3989 @result{}
3991 @result{}Answer: 10*9*8*7*6*5*4*3*2*1=3628800
3992 @end example
3994 Invocations of @code{m4wrap} at the same recursion level are
3995 concatenated and rescanned as usual:
3997 @example
3998 define(`aa', `AA
4000 @result{}
4001 m4wrap(`a')m4wrap(`a')
4002 @result{}
4004 @result{}AA
4005 @end example
4007 @noindent
4008 however, the transition between recursion levels behaves like an end of
4009 file condition between two input files.
4011 @comment status: 1
4012 @example
4013 m4wrap(`m4wrap(`)')len(abc')
4014 @result{}
4016 @error{}m4:stdin:1: ERROR: end of file in argument list
4017 @end example
4019 @node File Inclusion
4020 @chapter File inclusion
4022 @cindex file inclusion
4023 @cindex inclusion, of files
4024 @code{m4} allows you to include named files at any point in the input.
4026 @menu
4027 * Include::                     Including named files
4028 * Search Path::                 Searching for include files
4029 @end menu
4031 @node Include
4032 @section Including named files
4034 There are two builtin macros in @code{m4} for including files:
4036 @deffn Builtin include (@var{file})
4037 @deffnx Builtin sinclude (@var{file})
4038 Both macros cause the file named @var{file} to be read by
4039 @code{m4}.  When the end of the file is reached, input is resumed from
4040 the previous input file.
4042 The expansion of @code{include} and @code{sinclude} is therefore the
4043 contents of @var{file}.
4045 If @var{file} does not exist (or cannot be read), the expansion is void,
4046 and @code{include} will fail with an error while @code{sinclude} is
4047 silent.  The empty string counts as a file that does not exist.
4049 The macros @code{include} and @code{sinclude} are recognized only with
4050 parameters.
4051 @end deffn
4053 @comment status: 1
4054 @example
4055 include(`none')
4056 @error{}m4:stdin:1: cannot open `none': No such file or directory
4057 @result{}
4058 include()
4059 @error{}m4:stdin:2: cannot open `': No such file or directory
4060 @result{}
4061 sinclude(`none')
4062 @result{}
4063 sinclude()
4064 @result{}
4065 @end example
4067 The rest of this section assumes that @code{m4} is invoked with the
4068 @option{-I} option (@pxref{Preprocessor features, , Invoking m4})
4069 pointing to the @file{m4-@value{VERSION}/@/examples}
4070 directory shipped as part of the @acronym{GNU} @code{m4} package.  The
4071 file @file{m4-@value{VERSION}/@/examples/@/incl.m4} in the distribution
4072 contains the lines:
4074 @comment ignore
4075 @example
4076 $ @kbd{cat examples/incl.m4}
4077 @result{}Include file start
4078 @result{}foo
4079 @result{}Include file end
4080 @end example
4082 Normally file inclusion is used to insert the contents of a file
4083 into the input stream.  The contents of the file will be read by
4084 @code{m4} and macro calls in the file will be expanded:
4086 @example
4087 $ @kbd{m4 -I examples}
4088 define(`foo', `FOO')
4089 @result{}
4090 include(`incl.m4')
4091 @result{}Include file start
4092 @result{}FOO
4093 @result{}Include file end
4094 @result{}
4095 @end example
4097 The fact that @code{include} and @code{sinclude} expand to the contents
4098 of the file can be used to define macros that operate on entire files.
4099 Here is an example, which defines @samp{bar} to expand to the contents
4100 of @file{incl.m4}:
4102 @example
4103 $ @kbd{m4 -I examples}
4104 define(`bar', include(`incl.m4'))
4105 @result{}
4106 This is `bar':  >>bar<<
4107 @result{}This is bar:  >>Include file start
4108 @result{}foo
4109 @result{}Include file end
4110 @result{}<<
4111 @end example
4113 This use of @code{include} is not trivial, though, as files can contain
4114 quotes, commas, and parentheses, which can interfere with the way the
4115 @code{m4} parser works.  @acronym{GNU} @code{m4} seamlessly concatenates
4116 the file contents with the next character, even if the included file
4117 ended in the middle of a comment, string, or macro call.  These
4118 conditions are only treated as end of file errors if specified as input
4119 files on the command line.
4121 In @acronym{GNU} @code{m4}, an alternative method of reading files is
4122 using @code{undivert} (@pxref{Undivert}) on a named file.
4124 @node Search Path
4125 @section Searching for include files
4127 @cindex search path for included files
4128 @cindex included files, search path for
4129 @cindex @acronym{GNU} extensions
4130 @acronym{GNU} @code{m4} allows included files to be found in other directories
4131 than the current working directory.
4133 @cindex @env{M4PATH}
4134 If the @option{--prepend-include} or @option{-B} command-line option was
4135 provided (@pxref{Preprocessor features, , Invoking m4}), those
4136 directories are searched first, in reverse order that those options were
4137 listed on the command line.  Then @code{m4} looks in the current working
4138 directory.  Next comes the directories specified with the
4139 @option{--include} or @option{-I} option, in the order found on the
4140 command line.  Finally, if the @env{M4PATH} environment variable is set,
4141 it is expected to contain a colon-separated list of directories, which
4142 will be searched in order.
4144 If the automatic search for include-files causes trouble, the @samp{p}
4145 debug flag (@pxref{Debug Levels}) can help isolate the problem.
4147 @node Diversions
4148 @chapter Diverting and undiverting output
4150 @cindex deferring output
4151 Diversions are a way of temporarily saving output.  The output of
4152 @code{m4} can at any time be diverted to a temporary file, and be
4153 reinserted into the output stream, @dfn{undiverted}, again at a later
4154 time.
4156 @cindex @env{TMPDIR}
4157 Numbered diversions are counted from 0 upwards, diversion number 0
4158 being the normal output stream.  The number of simultaneous diversions
4159 is limited mainly by the memory used to describe them, because @acronym{GNU}
4160 @code{m4} tries to keep diversions in memory.  However, there is a
4161 limit to the overall memory usable by all diversions taken altogether
4162 (512K, currently).  When this maximum is about to be exceeded,
4163 a temporary file is opened to receive the contents of the biggest
4164 diversion still in memory, freeing this memory for other diversions.
4165 When creating the temporary file, @code{m4} honors the value of the
4166 environment variable @env{TMPDIR}, and falls back to @file{/tmp}.
4167 So, it is theoretically possible that the number and aggregate size of
4168 diversions is limited only by available disk space.
4170 @ignore
4171 @comment We need to test spilled diversions, but don't need to expose
4172 @comment this highly repetitive test in the manual.
4174 @example
4175 divert(`-1')define(`f', `.')
4176 define(`f', defn(`f')defn(`f'))
4177 define(`f', defn(`f')defn(`f'))
4178 define(`f', defn(`f')defn(`f'))
4179 define(`f', defn(`f')defn(`f'))
4180 define(`f', defn(`f')defn(`f'))
4181 define(`f', defn(`f')defn(`f'))
4182 define(`f', defn(`f')defn(`f'))
4183 define(`f', defn(`f')defn(`f'))
4184 define(`f', defn(`f')defn(`f'))
4185 define(`f', defn(`f')defn(`f'))
4186 define(`f', defn(`f')defn(`f'))
4187 define(`f', defn(`f')defn(`f'))
4188 define(`f', defn(`f')defn(`f'))
4189 define(`f', defn(`f')defn(`f'))
4190 define(`f', defn(`f')defn(`f'))
4191 define(`f', defn(`f')defn(`f'))
4192 define(`f', defn(`f')defn(`f'))
4193 define(`f', defn(`f')defn(`f'))
4194 define(`f', defn(`f')defn(`f'))
4195 define(`f', defn(`f')defn(`f'))
4196 divert`'dnl
4197 len(f)
4198 @result{}1048576
4199 divert(`1')
4201 divert(`-1')undivert
4202 @end example
4204 @comment Another test of spilled diversions.
4206 @example
4207 divert(`-1')define(`f', `.')
4208 define(`f', defn(`f')defn(`f'))
4209 define(`f', defn(`f')defn(`f'))
4210 define(`f', defn(`f')defn(`f'))
4211 define(`f', defn(`f')defn(`f'))
4212 define(`f', defn(`f')defn(`f'))
4213 define(`f', defn(`f')defn(`f'))
4214 define(`f', defn(`f')defn(`f'))
4215 define(`f', defn(`f')defn(`f'))
4216 define(`f', defn(`f')defn(`f'))
4217 define(`f', defn(`f')defn(`f'))
4218 define(`f', defn(`f')defn(`f'))
4219 define(`f', defn(`f')defn(`f'))
4220 define(`f', defn(`f')defn(`f'))
4221 define(`f', defn(`f')defn(`f'))
4222 define(`f', defn(`f')defn(`f'))
4223 define(`f', defn(`f')defn(`f'))
4224 define(`f', defn(`f')defn(`f'))
4225 define(`f', defn(`f')defn(`f'))
4226 define(`f', defn(`f')defn(`f'))
4227 define(`f', defn(`f')defn(`f'))
4228 divert`'dnl
4229 len(f)
4230 @result{}1048576
4231 divert(`1')
4233 m4exit
4234 @end example
4235 @end ignore
4237 Diversions make it possible to generate output in a different order than
4238 the input was read.  It is possible to implement topological sorting
4239 dependencies.  For example, @acronym{GNU} Autoconf makes use of
4240 diversions under the hood to ensure that the expansion of a prerequisite
4241 macro appears in the output prior to the expansion of a dependent macro,
4242 regardless of which order the two macros were invoked in the user's
4243 input file.
4245 @menu
4246 * Divert::                      Diverting output
4247 * Undivert::                    Undiverting output
4248 * Divnum::                      Diversion numbers
4249 * Cleardivert::                 Discarding diverted text
4250 @end menu
4252 @node Divert
4253 @section Diverting output
4255 @cindex diverting output to files
4256 @cindex output, diverting to files
4257 @cindex files, diverting output to
4258 Output is diverted using @code{divert}:
4260 @deffn Builtin divert (@dvar{number, 0})
4261 The current diversion is changed to @var{number}.  If @var{number} is left
4262 out or empty, it is assumed to be zero.  If @var{number} cannot be
4263 parsed, the diversion is unchanged.
4265 The expansion of @code{divert} is void.
4266 @end deffn
4268 When all the @code{m4} input will have been processed, all existing
4269 diversions are automatically undiverted, in numerical order.
4271 @example
4272 divert(`1')
4273 This text is diverted.
4274 divert
4275 @result{}
4276 This text is not diverted.
4277 @result{}This text is not diverted.
4279 @result{}
4280 @result{}This text is diverted.
4281 @end example
4283 Several calls of @code{divert} with the same argument do not overwrite
4284 the previous diverted text, but append to it.  Diversions are printed
4285 after any wrapped text is expanded.
4287 @example
4288 define(`text', `TEXT')
4289 @result{}
4290 divert(`1')`diverted text.'
4291 divert
4292 @result{}
4293 m4wrap(`Wrapped text precedes ')
4294 @result{}
4296 @result{}Wrapped TEXT precedes diverted text.
4297 @end example
4299 @cindex discarding input
4300 @cindex input, discarding
4301 If output is diverted to a negative diversion, it is simply discarded.
4302 This can be used to suppress unwanted output.  A common example of
4303 unwanted output is the trailing newlines after macro definitions.  Here
4304 is a common programming idiom in @code{m4} for avoiding them.
4306 @example
4307 divert(`-1')
4308 define(`foo', `Macro `foo'.')
4309 define(`bar', `Macro `bar'.')
4310 divert
4311 @result{}
4312 @end example
4314 @cindex @acronym{GNU} extensions
4315 Traditional implementations only supported ten diversions.  But as a
4316 @acronym{GNU} extension, diversion numbers can be as large as positive
4317 integers will allow, rather than treating a multi-digit diversion number
4318 as a request to discard text.
4320 @example
4321 divert(eval(`1<<28'))world
4322 divert(`2')hello
4324 @result{}hello
4325 @result{}world
4326 @end example
4328 Note that @code{divert} is an English word, but also an active macro
4329 without arguments.  When processing plain text, the word might appear in
4330 normal text and be unintentionally swallowed as a macro invocation.  One
4331 way to avoid this is to use the @option{-P} option to rename all
4332 builtins (@pxref{Operation modes, , Invoking m4}).  Another is to write
4333 a wrapper that requires a parameter to be recognized.
4335 @example
4336 We decided to divert the stream for irrigation.
4337 @result{}We decided to  the stream for irrigation.
4338 define(`divert', `ifelse(`$#', `0', ``$0'', `builtin(`$0', $@@)')')
4339 @result{}
4340 divert(`-1')
4341 Ignored text.
4342 divert(`0')
4343 @result{}
4344 We decided to divert the stream for irrigation.
4345 @result{}We decided to divert the stream for irrigation.
4346 @end example
4348 @node Undivert
4349 @section Undiverting output
4351 Diverted text can be undiverted explicitly using the builtin
4352 @code{undivert}:
4354 @deffn Builtin undivert (@ovar{diversions@dots{}})
4355 Undiverts the numeric @var{diversions} given by the arguments, in the
4356 order given.  If no arguments are supplied, all diversions are
4357 undiverted, in numerical order.
4359 @cindex file inclusion
4360 @cindex inclusion, of files
4361 @cindex @acronym{GNU} extensions
4362 As a @acronym{GNU} extension, @var{diversions} may contain non-numeric
4363 strings, which are treated as the names of files to copy into the output
4364 without expansion.  A warning is issued if a file could not be opened.
4366 The expansion of @code{undivert} is void.
4367 @end deffn
4369 @example
4370 divert(`1')
4371 This text is diverted.
4372 divert
4373 @result{}
4374 This text is not diverted.
4375 @result{}This text is not diverted.
4376 undivert(`1')
4377 @result{}
4378 @result{}This text is diverted.
4379 @result{}
4380 @end example
4382 Notice the last two blank lines.  One of them comes from the newline
4383 following @code{undivert}, the other from the newline that followed the
4384 @code{divert}!  A diversion often starts with a blank line like this.
4386 When diverted text is undiverted, it is @emph{not} reread by @code{m4},
4387 but rather copied directly to the current output, and it is therefore
4388 not an error to undivert into a diversion.  Undiverting the empty string
4389 is the same as specifying diversion 0; in either case nothing happens
4390 since the output has already been flushed.
4392 @example
4393 divert(`1')diverted text
4394 divert
4395 @result{}
4396 undivert()
4397 @result{}
4398 undivert(`0')
4399 @result{}
4400 undivert
4401 @result{}diverted text
4402 @result{}
4403 @end example
4405 When a diversion has been undiverted, the diverted text is discarded,
4406 and it is not possible to bring back diverted text more than once.
4408 @example
4409 divert(`1')
4410 This text is diverted first.
4411 divert(`0')undivert(`1')dnl
4412 @result{}
4413 @result{}This text is diverted first.
4414 undivert(`1')
4415 @result{}
4416 divert(`1')
4417 This text is also diverted but not appended.
4418 divert(`0')undivert(`1')dnl
4419 @result{}
4420 @result{}This text is also diverted but not appended.
4421 @end example
4423 Attempts to undivert the current diversion are silently ignored.  Thus,
4424 when the current diversion is not 0, the current diversion does not get
4425 rearranged among the other diversions.
4427 @example
4428 divert(`1')one
4429 divert(`2')two
4430 divert(`3')three
4431 divert(`2')undivert`'dnl
4432 divert`'undivert`'dnl
4433 @result{}two
4434 @result{}one
4435 @result{}three
4436 @end example
4438 @cindex @acronym{GNU} extensions
4439 @cindex file inclusion
4440 @cindex inclusion, of files
4441 @acronym{GNU} @code{m4} allows named files to be undiverted.  Given a
4442 non-numeric argument, the contents of the file named will be copied,
4443 uninterpreted, to the current output.  This complements the builtin
4444 @code{include} (@pxref{Include}).  To illustrate the difference, assume
4445 the file @file{foo} contains:
4447 @comment ignore
4448 @example
4449 $ @kbd{cat foo}
4451 @end example
4453 @noindent
4454 then
4456 @example
4457 define(`bar', `BAR')
4458 @result{}
4459 undivert(`foo')
4460 @result{}bar
4461 @result{}
4462 include(`foo')
4463 @result{}BAR
4464 @result{}
4465 @end example
4467 If the file is not found (or cannot be read), an error message is
4468 issued, and the expansion is void.  It is possible to intermix files
4469 and diversion numbers.
4471 @example
4472 divert(`1')diversion one
4473 divert(`2')undivert(`foo')dnl
4474 divert(`3')diversion three
4475 divert`'dnl
4476 undivert(`1', `2', `foo', `3')dnl
4477 @result{}diversion one
4478 @result{}bar
4479 @result{}bar
4480 @result{}diversion three
4481 @end example
4483 @node Divnum
4484 @section Diversion numbers
4486 @cindex diversion numbers
4487 The current diversion is tracked by the builtin @code{divnum}:
4489 @deffn Builtin divnum
4490 Expands to the number of the current diversion.
4491 @end deffn
4493 @example
4494 Initial divnum
4495 @result{}Initial 0
4496 divert(`1')
4497 Diversion one: divnum
4498 divert(`2')
4499 Diversion two: divnum
4501 @result{}
4502 @result{}Diversion one: 1
4503 @result{}
4504 @result{}Diversion two: 2
4505 @end example
4507 @node Cleardivert
4508 @section Discarding diverted text
4510 @cindex discarding diverted text
4511 @cindex diverted text, discarding
4512 Often it is not known, when output is diverted, whether the diverted
4513 text is actually needed.  Since all non-empty diversion are brought back
4514 on the main output stream when the end of input is seen, a method of
4515 discarding a diversion is needed.  If all diversions should be
4516 discarded, the easiest is to end the input to @code{m4} with
4517 @samp{divert(`-1')} followed by an explicit @samp{undivert}:
4519 @example
4520 divert(`1')
4521 Diversion one: divnum
4522 divert(`2')
4523 Diversion two: divnum
4524 divert(`-1')
4525 undivert
4527 @end example
4529 @noindent
4530 No output is produced at all.
4532 Clearing selected diversions can be done with the following macro:
4534 @deffn Composite cleardivert (@ovar{diversions@dots{}})
4535 Discard the contents of each of the listed numeric @var{diversions}.
4536 @end deffn
4538 @example
4539 define(`cleardivert',
4540 `pushdef(`_n', divnum)divert(`-1')undivert($@@)divert(_n)popdef(`_n')')
4541 @result{}
4542 @end example
4544 It is called just like @code{undivert}, but the effect is to clear the
4545 diversions, given by the arguments.  (This macro has a nasty bug!  You
4546 should try to see if you can find it and correct it; or @pxref{Improved
4547 cleardivert, , Answers}).
4549 @node Text handling
4550 @chapter Macros for text handling
4552 There are a number of builtins in @code{m4} for manipulating text in
4553 various ways, extracting substrings, searching, substituting, and so on.
4555 @menu
4556 * Len::                         Calculating length of strings
4557 * Index macro::                 Searching for substrings
4558 * Regexp::                      Searching for regular expressions
4559 * Substr::                      Extracting substrings
4560 * Translit::                    Translating characters
4561 * Patsubst::                    Substituting text by regular expression
4562 * Format::                      Formatting strings (printf-like)
4563 @end menu
4565 @node Len
4566 @section Calculating length of strings
4568 @cindex length of strings
4569 @cindex strings, length of
4570 The length of a string can be calculated by @code{len}:
4572 @deffn Builtin len (@var{string})
4573 Expands to the length of @var{string}, as a decimal number.
4575 The macro @code{len} is recognized only with parameters.
4576 @end deffn
4578 @example
4579 len()
4580 @result{}0
4581 len(`abcdef')
4582 @result{}6
4583 @end example
4585 @node Index macro
4586 @section Searching for substrings
4588 @cindex substrings, locating
4589 Searching for substrings is done with @code{index}:
4591 @deffn Builtin index (@var{string}, @var{substring})
4592 Expands to the index of the first occurrence of @var{substring} in
4593 @var{string}.  The first character in @var{string} has index 0.  If
4594 @var{substring} does not occur in @var{string}, @code{index} expands to
4595 @samp{-1}.
4597 The macro @code{index} is recognized only with parameters.
4598 @end deffn
4600 @example
4601 index(`gnus, gnats, and armadillos', `nat')
4602 @result{}7
4603 index(`gnus, gnats, and armadillos', `dag')
4604 @result{}-1
4605 @end example
4607 Omitting @var{substring} evokes a warning, but still produces output.
4609 @example
4610 index(`abc')
4611 @error{}m4:stdin:1: Warning: too few arguments to builtin `index'
4612 @result{}0
4613 @end example
4615 @node Regexp
4616 @section Searching for regular expressions
4618 @cindex basic regular expressions
4619 @cindex regular expressions
4620 @cindex expressions, regular
4621 @cindex @acronym{GNU} extensions
4622 Searching for regular expressions is done with the builtin
4623 @code{regexp}:
4625 @deffn Builtin regexp (@var{string}, @var{regexp}, @ovar{replacement})
4626 Searches for @var{regexp} in @var{string}.  The syntax for regular
4627 expressions is the same as in @acronym{GNU} Emacs, which is similar to
4628 @acronym{BRE, Basic Regular Expressions} in @acronym{POSIX}.
4629 @ifnothtml
4630 @xref{Regexps, , Syntax of Regular Expressions, emacs, The GNU Emacs
4631 Manual}.
4632 @end ifnothtml
4633 @ifhtml
4635 @uref{http://www.gnu.org/@/software/@/emacs/@/manual/@/emacs.html#Regexps,
4636 Syntax of Regular Expressions} in the @acronym{GNU} Emacs Manual.
4637 @end ifhtml
4638 Support for @acronym{ERE, Extended Regular Expressions} is not
4639 available, but will be added in @acronym{GNU} M4 2.0.
4641 If @var{replacement} is omitted, @code{regexp} expands to the index of
4642 the first match of @var{regexp} in @var{string}.  If @var{regexp} does
4643 not match anywhere in @var{string}, it expands to -1.
4645 If @var{replacement} is supplied, and there was a match, @code{regexp}
4646 changes the expansion to this argument, with @samp{\@var{n}} substituted
4647 by the text matched by the @var{n}th parenthesized sub-expression of
4648 @var{regexp}, up to nine sub-expressions.  The escape @samp{\&} is
4649 replaced by the text of the entire regular expression matched.  For
4650 all other characters, @samp{\} treats the next character literally.  A
4651 warning is issued if there were fewer sub-expressions than the
4652 @samp{\@var{n}} requested, or if there is a trailing @samp{\}.  If there
4653 was no match, @code{regexp} expands to the empty string.
4655 The macro @code{regexp} is recognized only with parameters.
4656 @end deffn
4658 @example
4659 regexp(`GNUs not Unix', `\<[a-z]\w+')
4660 @result{}5
4661 regexp(`GNUs not Unix', `\<Q\w*')
4662 @result{}-1
4663 regexp(`GNUs not Unix', `\w\(\w+\)$', `*** \& *** \1 ***')
4664 @result{}*** Unix *** nix ***
4665 regexp(`GNUs not Unix', `\<Q\w*', `*** \& *** \1 ***')
4666 @result{}
4667 @end example
4669 Here are some more examples on the handling of backslash:
4671 @example
4672 regexp(`abc', `\(b\)', `\\\10\a')
4673 @result{}\b0a
4674 regexp(`abc', `b', `\1\')
4675 @error{}m4:stdin:2: Warning: sub-expression 1 not present
4676 @error{}m4:stdin:2: Warning: trailing \ ignored in replacement
4677 @result{}
4678 regexp(`abc', `\(\(d\)?\)\(c\)', `\1\2\3\4\5\6')
4679 @error{}m4:stdin:3: Warning: sub-expression 4 not present
4680 @error{}m4:stdin:3: Warning: sub-expression 5 not present
4681 @error{}m4:stdin:3: Warning: sub-expression 6 not present
4682 @result{}c
4683 @end example
4685 Omitting @var{regexp} evokes a warning, but still produces output.
4687 @example
4688 regexp(`abc')
4689 @error{}m4:stdin:1: Warning: too few arguments to builtin `regexp'
4690 @result{}0
4691 @end example
4693 @node Substr
4694 @section Extracting substrings
4696 @cindex extracting substrings
4697 @cindex substrings, extracting
4698 Substrings are extracted with @code{substr}:
4700 @deffn Builtin substr (@var{string}, @var{from}, @ovar{length})
4701 Expands to the substring of @var{string}, which starts at index
4702 @var{from}, and extends for @var{length} characters, or to the end of
4703 @var{string}, if @var{length} is omitted.  The starting index of a string
4704 is always 0.  The expansion is empty if there is an error parsing
4705 @var{from} or @var{length}, if @var{from} is beyond the end of
4706 @var{string}, or if @var{length} is negative.
4708 The macro @code{substr} is recognized only with parameters.
4709 @end deffn
4711 @example
4712 substr(`gnus, gnats, and armadillos', `6')
4713 @result{}gnats, and armadillos
4714 substr(`gnus, gnats, and armadillos', `6', `5')
4715 @result{}gnats
4716 @end example
4718 Omitting @var{from} evokes a warning, but still produces output.
4720 @example
4721 substr(`abc')
4722 @error{}m4:stdin:1: Warning: too few arguments to builtin `substr'
4723 @result{}abc
4724 substr(`abc',)
4725 @error{}m4:stdin:2: empty string treated as 0 in builtin `substr'
4726 @result{}abc
4727 @end example
4729 @node Translit
4730 @section Translating characters
4732 @cindex translating characters
4733 @cindex characters, translating
4734 Character translation is done with @code{translit}:
4736 @deffn Builtin translit (@var{string}, @var{chars}, @ovar{replacement})
4737 Expands to @var{string}, with each character that occurs in
4738 @var{chars} translated into the character from @var{replacement} with
4739 the same index.
4741 If @var{replacement} is shorter than @var{chars}, the excess characters
4742 of @var{chars} are deleted from the expansion; if @var{chars} is
4743 shorter, the excess characters in @var{replacement} are silently
4744 ignored.  If @var{replacement} is omitted, all characters in
4745 @var{string} that are present in @var{chars} are deleted from the
4746 expansion.  If a character appears more than once in @var{chars}, only
4747 the first instance is used in making the translation.  Only a single
4748 translation pass is made, even if characters in @var{replacement} also
4749 appear in @var{chars}.
4751 As a @acronym{GNU} extension, both @var{chars} and @var{replacement} can
4752 contain character-ranges, e.g., @samp{a-z} (meaning all lowercase
4753 letters) or @samp{0-9} (meaning all digits).  To include a dash @samp{-}
4754 in @var{chars} or @var{replacement}, place it first or last in the
4755 entire string, or as the last character of a range.  Back-to-back ranges
4756 can share a common endpoint.  It is not an error for the last character
4757 in the range to be `larger' than the first.  In that case, the range
4758 runs backwards, i.e., @samp{9-0} means the string @samp{9876543210}.
4759 The expansion of a range is dependent on the underlying encoding of
4760 characters, so using ranges is not always portable between machines.
4762 The macro @code{translit} is recognized only with parameters.
4763 @end deffn
4765 @example
4766 translit(`GNUs not Unix', `A-Z')
4767 @result{}s not nix
4768 translit(`GNUs not Unix', `a-z', `A-Z')
4769 @result{}GNUS NOT UNIX
4770 translit(`GNUs not Unix', `A-Z', `z-a')
4771 @result{}tmfs not fnix
4772 translit(`+,-12345', `+--1-5', `<;>a-c-a')
4773 @result{}<;>abcba
4774 translit(`abcdef', `aabdef', `bcged')
4775 @result{}bgced
4776 @end example
4778 In the @sc{ascii} encoding, the first example deletes all uppercase
4779 letters, the second converts lowercase to uppercase, and the third
4780 `mirrors' all uppercase letters, while converting them to lowercase.
4781 The two first cases are by far the most common, even though they are not
4782 portable to @sc{ebcdic} or other encodings.  The fourth example shows a
4783 range ending in @samp{-}, as well as back-to-back ranges.  The final
4784 example shows that @samp{a} is mapped to @samp{b}, not @samp{c}; the
4785 resulting @samp{b} is not further remapped to @samp{g}; the @samp{d} and
4786 @samp{e} are swapped, and the @samp{f} is discarded.
4788 @ignore
4789 @comment No need to fight 8-bit characters, as it is difficult to get
4790 @comment rendering right in both info and dvi.
4792 @example
4793 translit(`«abc~', `~-»')
4794 @result{}abc
4795 @end example
4796 @end ignore
4798 Omitting @var{chars} evokes a warning, but still produces output.
4800 @example
4801 translit(`abc')
4802 @error{}m4:stdin:1: Warning: too few arguments to builtin `translit'
4803 @result{}abc
4804 @end example
4806 @node Patsubst
4807 @section Substituting text by regular expression
4809 @cindex basic regular expressions
4810 @cindex regular expressions
4811 @cindex expressions, regular
4812 @cindex pattern substitution
4813 @cindex substitution by regular expression
4814 @cindex @acronym{GNU} extensions
4815 Global substitution in a string is done by @code{patsubst}:
4817 @deffn Builtin patsubst (@var{string}, @var{regexp}, @ovar{replacement})
4818 Searches @var{string} for matches of @var{regexp}, and substitutes
4819 @var{replacement} for each match.  The syntax for regular expressions
4820 is the same as in @acronym{GNU} Emacs (@pxref{Regexp}).
4822 The parts of @var{string} that are not covered by any match of
4823 @var{regexp} are copied to the expansion.  Whenever a match is found, the
4824 search proceeds from the end of the match, so a character from
4825 @var{string} will never be substituted twice.  If @var{regexp} matches a
4826 string of zero length, the start position for the search is incremented,
4827 to avoid infinite loops.
4829 When a replacement is to be made, @var{replacement} is inserted into
4830 the expansion, with @samp{\@var{n}} substituted by the text matched by
4831 the @var{n}th parenthesized sub-expression of @var{patsubst}, for up to
4832 nine sub-expressions.  The escape @samp{\&} is replaced by the text of
4833 the entire regular expression matched.  For all other characters,
4834 @samp{\} treats the next character literally.  A warning is issued if
4835 there were fewer sub-expressions than the @samp{\@var{n}} requested, or
4836 if there is a trailing @samp{\}.
4838 The @var{replacement} argument can be omitted, in which case the text
4839 matched by @var{regexp} is deleted.
4841 The macro @code{patsubst} is recognized only with parameters.
4842 @end deffn
4844 @example
4845 patsubst(`GNUs not Unix', `^', `OBS: ')
4846 @result{}OBS: GNUs not Unix
4847 patsubst(`GNUs not Unix', `\<', `OBS: ')
4848 @result{}OBS: GNUs OBS: not OBS: Unix
4849 patsubst(`GNUs not Unix', `\w*', `(\&)')
4850 @result{}(GNUs)() (not)() (Unix)()
4851 patsubst(`GNUs not Unix', `\w+', `(\&)')
4852 @result{}(GNUs) (not) (Unix)
4853 patsubst(`GNUs not Unix', `[A-Z][a-z]+')
4854 @result{}GN not@w{ }
4855 patsubst(`GNUs not Unix', `not', `NOT\')
4856 @error{}m4:stdin:6: Warning: trailing \ ignored in replacement
4857 @result{}GNUs NOT Unix
4858 @end example
4860 Here is a slightly more realistic example, which capitalizes individual
4861 words or whole sentences, by substituting calls of the macros
4862 @code{upcase} and @code{downcase} into the strings.
4864 @deffn Composite upcase (@var{text})
4865 @deffnx Composite downcase (@var{text})
4866 @deffnx Composite capitalize (@var{text})
4867 Expand to @var{text}, but with capitalization changed: @code{upcase}
4868 changes all letters to upper case, @code{downcase} changes all letters
4869 to lower case, and @code{capitalize} changes the first character of each
4870 word to upper case and the remaining characters to lower case.
4871 @end deffn
4873 @example
4874 define(`upcase', `translit(`$*', `a-z', `A-Z')')dnl
4875 define(`downcase', `translit(`$*', `A-Z', `a-z')')dnl
4876 define(`capitalize1',
4877        `regexp(`$1', `^\(\w\)\(\w*\)',
4878                `upcase(`\1')`'downcase(`\2')')')dnl
4879 define(`capitalize',
4880        `patsubst(`$1', `\w+', `capitalize1(`\&')')')dnl
4881 capitalize(`GNUs not Unix')
4882 @result{}Gnus Not Unix
4883 @end example
4885 While @code{regexp} replaces the whole input with the replacement as
4886 soon as there is a match, @code{patsubst} replaces each
4887 @emph{occurrence} of a match and preserves non-matching pieces:
4889 @example
4890 define(`patreg',
4891 `patsubst($@@)
4892 regexp($@@)')dnl
4893 patreg(`bar foo baz Foo', `foo\|Foo', `FOO')
4894 @result{}bar FOO baz FOO
4895 @result{}FOO
4896 patreg(`aba abb 121', `\(.\)\(.\)\1', `\2\1\2')
4897 @result{}bab abb 212
4898 @result{}bab
4899 @end example
4901 Omitting @var{regexp} evokes a warning, but still produces output.
4903 @example
4904 patsubst(`abc')
4905 @error{}m4:stdin:1: Warning: too few arguments to builtin `patsubst'
4906 @result{}abc
4907 @end example
4909 @node Format
4910 @section Formatting strings (printf-like)
4912 @cindex formatted output
4913 @cindex output, formatted
4914 @cindex @acronym{GNU} extensions
4915 Formatted output can be made with @code{format}:
4917 @deffn Builtin format (@var{format-string}, @dots{})
4918 Works much like the C function @code{printf}.  The first argument
4919 @var{format-string} can contain @samp{%} specifications which are
4920 satisfied by additional arguments, and the expansion of @code{format} is
4921 the formatted string.
4923 The macro @code{format} is recognized only with parameters.
4924 @end deffn
4926 Its use is best described by a few examples:
4928 @comment This test is a bit fragile, if someone tries to port to a
4929 @comment platform without infinity.
4930 @example
4931 define(`foo', `The brown fox jumped over the lazy dog')
4932 @result{}
4933 format(`The string "%s" uses %d characters', foo, len(foo))
4934 @result{}The string "The brown fox jumped over the lazy dog" uses 38 characters
4935 format(`%*.*d', `-1', `-1', `1')
4936 @result{}1
4937 format(`%.0f', `56789.9876')
4938 @result{}56790
4939 len(format(`%-*X', `5000', `1'))
4940 @result{}5000
4941 ifelse(format(`%010F', `infinity'), `       INF', `success',
4942        format(`%010F', `infinity'), `  INFINITY', `success',
4943        format(`%010F', `infinity'))
4944 @result{}success
4945 ifelse(format(`%.1A', `1.999'), `0X1.0P+1', `success',
4946        format(`%.1A', `1.999'), `0X2.0P+0', `success',
4947        format(`%.1A', `1.999'))
4948 @result{}success
4949 @end example
4951 Using the @code{forloop} macro defined earlier (@pxref{Forloop}), this
4952 example shows how @code{format} can be used to produce tabular output.
4954 @example
4955 $ @kbd{m4 -I examples}
4956 include(`forloop.m4')
4957 @result{}
4958 forloop(`i', `1', `10', `format(`%6d squared is %10d
4959 ', i, eval(i**2))')
4960 @result{}     1 squared is          1
4961 @result{}     2 squared is          4
4962 @result{}     3 squared is          9
4963 @result{}     4 squared is         16
4964 @result{}     5 squared is         25
4965 @result{}     6 squared is         36
4966 @result{}     7 squared is         49
4967 @result{}     8 squared is         64
4968 @result{}     9 squared is         81
4969 @result{}    10 squared is        100
4970 @result{}
4971 @end example
4973 The builtin @code{format} is modeled after the ANSI C @samp{printf}
4974 function, and supports these @samp{%} specifiers: @samp{c}, @samp{s},
4975 @samp{d}, @samp{o}, @samp{x}, @samp{X}, @samp{u}, @samp{a}, @samp{A},
4976 @samp{e}, @samp{E}, @samp{f}, @samp{F}, @samp{g}, @samp{G}, and
4977 @samp{%}; it supports field widths and precisions, and the flags
4978 @samp{+}, @samp{-}, @samp{ }, @samp{0}, @samp{#}, and @samp{'}.  For
4979 integer specifiers, the width modifiers @samp{hh}, @samp{h}, and
4980 @samp{l} are recognized, and for floating point specifiers, the width
4981 modifier @samp{l} is recognized.  Items not yet supported include
4982 positional arguments, the @samp{n}, @samp{p}, @samp{S}, and @samp{C}
4983 specifiers, the @samp{z}, @samp{t}, @samp{j}, @samp{L} and @samp{ll}
4984 modifiers, and any platform extensions available in the native
4985 @code{printf}.  For more details on the functioning of @code{printf},
4986 see the C Library Manual, or the @acronym{POSIX} specification (for
4987 example, @samp{%a} is supported even on platforms that haven't yet
4988 implemented C99 hexadecimal floating point output natively).
4990 Unrecognized specifiers result in a warning.  It is anticipated that a
4991 future release of @acronym{GNU} @code{m4} will support more specifiers,
4992 and give better warnings when various problems such as overflow are
4993 encountered.  Likewise, escape sequences are not yet recognized.
4995 @example
4996 format(`%p', `0')
4997 @error{}m4:stdin:1: Warning: unrecognized specifier in `%p'
4998 @result{}
4999 @end example
5001 @node Arithmetic
5002 @chapter Macros for doing arithmetic
5004 @cindex arithmetic
5005 @cindex integer arithmetic
5006 Integer arithmetic is included in @code{m4}, with a C-like syntax.  As
5007 convenient shorthands, there are builtins for simple increment and
5008 decrement operations.
5010 @menu
5011 * Incr::                        Decrement and increment operators
5012 * Eval::                        Evaluating integer expressions
5013 @end menu
5015 @node Incr
5016 @section Decrement and increment operators
5018 @cindex decrement operator
5019 @cindex increment operator
5020 Increment and decrement of integers are supported using the builtins
5021 @code{incr} and @code{decr}:
5023 @deffn Builtin incr (@var{number})
5024 @deffnx Builtin decr (@var{number})
5025 Expand to the numerical value of @var{number}, incremented
5026 or decremented, respectively, by one.  Except for the empty string, the
5027 expansion is empty if @var{number} could not be parsed.
5029 The macros @code{incr} and @code{decr} are recognized only with
5030 parameters.
5031 @end deffn
5033 @example
5034 incr(`4')
5035 @result{}5
5036 decr(`7')
5037 @result{}6
5038 incr()
5039 @error{}m4:stdin:3: empty string treated as 0 in builtin `incr'
5040 @result{}1
5041 decr()
5042 @error{}m4:stdin:4: empty string treated as 0 in builtin `decr'
5043 @result{}-1
5044 @end example
5046 @node Eval
5047 @section Evaluating integer expressions
5049 @cindex integer expression evaluation
5050 @cindex evaluation, of integer expressions
5051 @cindex expressions, evaluation of integer
5052 Integer expressions are evaluated with @code{eval}:
5054 @deffn Builtin eval (@var{expression}, @dvar{radix, 10}, @ovar{width})
5055 Expands to the value of @var{expression}.  The expansion is empty
5056 if a problem is encountered while parsing the arguments.  If specified,
5057 @var{radix} and @var{width} control the format of the output.
5059 Calculations are done with 32-bit signed numbers.  Overflow silently
5060 results in wraparound.  A warning is issued if division by zero is
5061 attempted, or if @var{expression} could not be parsed.
5063 Expressions can contain the following operators, listed in order of
5064 decreasing precedence.
5066 @table @samp
5067 @item ()
5068 Parentheses
5069 @item +  -  ~  !
5070 Unary plus and minus, and bitwise and logical negation
5071 @item **
5072 Exponentiation
5073 @item *  /  %
5074 Multiplication, division, and modulo
5075 @item +  -
5076 Addition and subtraction
5077 @item <<  >>
5078 Shift left or right
5079 @item >  >=  <  <=
5080 Relational operators
5081 @item ==  !=
5082 Equality operators
5083 @item &
5084 Bitwise and
5085 @item ^
5086 Bitwise exclusive-or
5087 @item |
5088 Bitwise or
5089 @item &&
5090 Logical and
5091 @item ||
5092 Logical or
5093 @end table
5095 The macro @code{eval} is recognized only with parameters.
5096 @end deffn
5098 All binary operators, except exponentiation, are left associative.  C
5099 operators that perform variable assignment, such as @samp{+=} or
5100 @samp{--}, are not implemented, since @code{eval} only operates on
5101 constants, not variables.  Attempting to use them results in an error.
5102 However, since traditional implementations treated @samp{=} as an
5103 undocumented alias for @samp{==} as opposed to an assignment operator,
5104 this usage is supported as a special case.  Be aware that a future
5105 version of @acronym{GNU} M4 may support assignment semantics as an
5106 extension when @acronym{POSIX} mode is not requested, and that using
5107 @samp{=} to check equality is not portable.
5109 @comment status: 1
5110 @example
5111 eval(`2 = 2')
5112 @error{}m4:stdin:1: Warning: recommend ==, not =, for equality operator
5113 @result{}1
5114 eval(`++0')
5115 @error{}m4:stdin:2: invalid operator in eval: ++0
5116 @result{}
5117 eval(`0 |= 1')
5118 @error{}m4:stdin:3: invalid operator in eval: 0 |= 1
5119 @result{}
5120 @end example
5122 Note that some older @code{m4} implementations use @samp{^} as an
5123 alternate operator for the exponentiation, although @acronym{POSIX}
5124 requires the C behavior of bitwise exclusive-or.  The precedence of the
5125 negation operators, @samp{~} and @samp{!}, was traditionally lower than
5126 equality.  The unary operators could not be used reliably more than once
5127 on the same term without intervening parentheses.  The traditional
5128 precedence of the equality operators @samp{==} and @samp{!=} was
5129 identical instead of lower than the relational operators such as
5130 @samp{<}, even through @acronym{GNU} M4 1.4.8.  Starting with version
5131 1.4.9, @acronym{GNU} M4 correctly follows @acronym{POSIX} precedence
5132 rules.  M4 scripts designed to be portable between releases must be
5133 aware that parentheses may be required to enforce C precedence rules.
5134 Likewise, division by zero, even in the unused branch of a
5135 short-circuiting operator, is not always well-defined in other
5136 implementations.
5138 Following are some examples where the current version of M4 follows C
5139 precedence rules, but where older versions and some other
5140 implementations of @code{m4} require explicit parentheses to get the
5141 correct result:
5143 @example
5144 eval(`1 == 2 > 0')
5145 @result{}1
5146 eval(`(1 == 2) > 0')
5147 @result{}0
5148 eval(`! 0 * 2')
5149 @result{}2
5150 eval(`! (0 * 2)')
5151 @result{}1
5152 eval(`1 | 1 ^ 1')
5153 @result{}1
5154 eval(`(1 | 1) ^ 1')
5155 @result{}0
5156 eval(`+ + - ~ ! ~ 0')
5157 @result{}1
5158 eval(`2 || 1 / 0')
5159 @result{}1
5160 eval(`0 || 1 / 0')
5161 @error{}m4:stdin:9: divide by zero in eval: 0 || 1 / 0
5162 @result{}
5163 eval(`0 && 1 % 0')
5164 @result{}0
5165 eval(`2 && 1 % 0')
5166 @error{}m4:stdin:11: modulo by zero in eval: 2 && 1 % 0
5167 @result{}
5168 @end example
5170 @cindex @acronym{GNU} extensions
5171 As a @acronym{GNU} extension, the operator @samp{**} performs integral
5172 exponentiation.  The operator is right-associative, and if evaluated,
5173 the exponent must be non-negative, and at least one of the arguments
5174 must be non-zero, or a warning is issued.
5176 @example
5177 eval(`2 ** 3 ** 2')
5178 @result{}512
5179 eval(`(2 ** 3) ** 2')
5180 @result{}64
5181 eval(`0 ** 1')
5182 @result{}0
5183 eval(`2 ** 0')
5184 @result{}1
5185 eval(`0 ** 0')
5186 @result{}
5187 @error{}m4:stdin:5: divide by zero in eval: 0 ** 0
5188 eval(`4 ** -2')
5189 @error{}m4:stdin:6: negative exponent in eval: 4 ** -2
5190 @result{}
5191 @end example
5193 Within @var{expression}, (but not @var{radix} or @var{width}), numbers
5194 without a special prefix are decimal.  A simple @samp{0} prefix
5195 introduces an octal number.  @samp{0x} introduces a hexadecimal number.
5196 As @acronym{GNU} extensions, @samp{0b} introduces a binary number.
5197 @samp{0r} introduces a number expressed in any radix between 1 and 36:
5198 the prefix should be immediately followed by the decimal expression of
5199 the radix, a colon, then the digits making the number.  For radix 1,
5200 leading zeros are ignored, and all remaining digits must be @samp{1};
5201 for all other radices, the digits are @samp{0}, @samp{1}, @samp{2},
5202 @dots{}.  Beyond @samp{9}, the digits are @samp{a}, @samp{b} @dots{} up
5203 to @samp{z}.  Lower and upper case letters can be used interchangeably
5204 in numbers prefixes and as number digits.
5206 Parentheses may be used to group subexpressions whenever needed.  For the
5207 relational operators, a true relation returns @code{1}, and a false
5208 relation return @code{0}.
5210 Here are a few examples of use of @code{eval}.
5212 @example
5213 eval(`-3 * 5')
5214 @result{}-15
5215 eval(`-99 / 10')
5216 @result{}-9
5217 eval(`-99 % 10')
5218 @result{}-9
5219 eval(`99 % -10')
5220 @result{}9
5221 eval(index(`Hello world', `llo') >= 0)
5222 @result{}1
5223 eval(`0r1:0111 + 0b100 + 0r3:12')
5224 @result{}12
5225 define(`square', `eval(`($1) ** 2')')
5226 @result{}
5227 square(`9')
5228 @result{}81
5229 square(square(`5')` + 1')
5230 @result{}676
5231 define(`foo', `666')
5232 @result{}
5233 eval(`foo / 6')
5234 @error{}m4:stdin:11: bad expression in eval: foo / 6
5235 @result{}
5236 eval(foo / 6)
5237 @result{}111
5238 @end example
5240 As the last two lines show, @code{eval} does not handle macro
5241 names, even if they expand to a valid expression (or part of a valid
5242 expression).  Therefore all macros must be expanded before they are
5243 passed to @code{eval}.
5245 Some calculations are not portable to other implementations, since they
5246 have undefined semantics in C, but @acronym{GNU} @code{m4} has
5247 well-defined behavior on overflow.  When shifting, an out-of-range shift
5248 amount is implicitly brought into the range of 32-bit signed integers
5249 using an implicit bit-wise and with 0x1f).
5251 @example
5252 define(`max_int', eval(`0x7fffffff'))
5253 @result{}
5254 define(`min_int', incr(max_int))
5255 @result{}
5256 eval(min_int` < 0')
5257 @result{}1
5258 eval(max_int` > 0')
5259 @result{}1
5260 ifelse(eval(min_int` / -1'), min_int, `overflow occurred')
5261 @result{}overflow occurred
5262 min_int
5263 @result{}-2147483648
5264 eval(`0x80000000 % -1')
5265 @result{}0
5266 eval(`-4 >> 1')
5267 @result{}-2
5268 eval(`-4 >> 33')
5269 @result{}-2
5270 @end example
5272 If @var{radix} is specified, it specifies the radix to be used in the
5273 expansion.  The default radix is 10; this is also the case if
5274 @var{radix} is the empty string.  A warning results if the radix is
5275 outside the range of 1 through 36, inclusive.  The result of @code{eval}
5276 is always taken to be signed.  No radix prefix is output, and for
5277 radices greater than 10, the digits are lower case.  The @var{width}
5278 argument specifies the minimum output width, excluding any negative
5279 sign.  The result is zero-padded to extend the expansion to the
5280 requested width.  A warning results if the width is negative.  If
5281 @var{radix} or @var{width} is out of bounds, the expansion of
5282 @code{eval} is empty.
5284 @example
5285 eval(`666', `10')
5286 @result{}666
5287 eval(`666', `11')
5288 @result{}556
5289 eval(`666', `6')
5290 @result{}3030
5291 eval(`666', `6', `10')
5292 @result{}0000003030
5293 eval(`-666', `6', `10')
5294 @result{}-0000003030
5295 eval(`10', `', `0')
5296 @result{}10
5297 `0r1:'eval(`10', `1', `11')
5298 @result{}0r1:01111111111
5299 eval(`10', `16')
5300 @result{}a
5301 eval(`1', `37')
5302 @error{}m4:stdin:9: radix 37 in builtin `eval' out of range
5303 @result{}
5304 eval(`1', , `-1')
5305 @error{}m4:stdin:10: negative width to builtin `eval'
5306 @result{}
5307 eval()
5308 @error{}m4:stdin:11: empty string treated as 0 in builtin `eval'
5309 @result{}0
5310 @end example
5312 @node Shell commands
5313 @chapter Macros for running shell commands
5315 @cindex UNIX commands, running
5316 @cindex executing shell commands
5317 @cindex running shell commands
5318 @cindex shell commands, running
5319 @cindex commands, running shell
5320 There are a few builtin macros in @code{m4} that allow you to run shell
5321 commands from within @code{m4}.
5323 Note that the definition of a valid shell command is system dependent.
5324 On UNIX systems, this is the typical @command{/bin/sh}.  But on other
5325 systems, such as native Windows, the shell has a different syntax of
5326 commands that it understands.  Some examples in this chapter assume
5327 @command{/bin/sh}, and also demonstrate how to quit early with a known
5328 exit value if this is not the case.
5330 @menu
5331 * Platform macros::             Determining the platform
5332 * Syscmd::                      Executing simple commands
5333 * Esyscmd::                     Reading the output of commands
5334 * Sysval::                      Exit status
5335 * Mkstemp::                     Making temporary files
5336 @end menu
5338 @node Platform macros
5339 @section Determining the platform
5341 @cindex platform macros
5342 Sometimes it is desirable for an input file to know which platform
5343 @code{m4} is running on.  @acronym{GNU} @code{m4} provides several
5344 macros that are predefined to expand to the empty string; checking for
5345 their existence will confirm platform details.
5347 @deffn {Optional builtin} __gnu__
5348 @deffnx {Optional builtin} __os2__
5349 @deffnx {Optional builtin} os2
5350 @deffnx {Optional builtin} __unix__
5351 @deffnx {Optional builtin} unix
5352 @deffnx {Optional builtin} __windows__
5353 @deffnx {Optional builtin} windows
5354 Each of these macros is conditionally defined as needed to describe the
5355 environment of @code{m4}.  If defined, each macro expands to the empty
5356 string.
5357 @end deffn
5359 When @acronym{GNU} extensions are in effect (that is, when you did not
5360 use the @option{-G} option, @pxref{Limits control, , Invoking m4}),
5361 @acronym{GNU} @code{m4} will define the macro @code{@w{__gnu__}} to
5362 expand to the empty string.
5364 @example
5365 __gnu__
5366 @result{}
5367 ifdef(`__gnu__', `Extensions are active')
5368 @result{}Extensions are active
5369 @end example
5371 On UNIX systems, @acronym{GNU} @code{m4} will define @code{@w{__unix__}}
5372 by default, or @code{unix} when the @option{-G} option is specified.
5374 On native Windows systems, @acronym{GNU} @code{m4} will define
5375 @code{@w{__windows__}} by default, or @code{windows} when the
5376 @option{-G} option is specified.
5378 On OS/2 systems, @acronym{GNU} @code{m4} will define @code{@w{__os2__}}
5379 by default, or @code{os2} when the @option{-G} option is specified.
5381 If @acronym{GNU} @code{m4} does not provide a platform macro for your system,
5382 please report that as a bug.
5384 @example
5385 define(`provided', `0')
5386 @result{}
5387 ifdef(`__unix__', `define(`provided', incr(provided))')
5388 @result{}
5389 ifdef(`__windows__', `define(`provided', incr(provided))')
5390 @result{}
5391 ifdef(`__os2__', `define(`provided', incr(provided))')
5392 @result{}
5393 provided
5394 @result{}1
5395 @end example
5397 @node Syscmd
5398 @section Executing simple commands
5400 Any shell command can be executed, using @code{syscmd}:
5402 @deffn Builtin syscmd (@var{shell-command})
5403 Executes @var{shell-command} as a shell command.
5405 The expansion of @code{syscmd} is void, @emph{not} the output from
5406 @var{shell-command}!  Output or error messages from @var{shell-command}
5407 are not read by @code{m4}.  @xref{Esyscmd}, if you need to process the
5408 command output.
5410 Prior to executing the command, @code{m4} flushes its buffers.
5411 The default standard input, output and error of @var{shell-command} are
5412 the same as those of @code{m4}.
5414 The macro @code{syscmd} is recognized only with parameters.
5415 @end deffn
5417 @example
5418 define(`foo', `FOO')
5419 @result{}
5420 syscmd(`echo foo')
5421 @result{}foo
5422 @result{}
5423 @end example
5425 Note how the expansion of @code{syscmd} keeps the trailing newline of
5426 the command, as well as using the newline that appeared after the macro.
5428 The following is an example of @var{shell-command} using the same
5429 standard input as @code{m4}:
5431 @comment ignore
5432 @example
5433 $ @kbd{echo "m4wrap(\`syscmd(\`cat')')" | m4}
5434 @result{}
5435 @end example
5437 @ignore
5438 @comment If the user types the example below with stdin being an
5439 @comment interactive terminal, then cat will hang waiting for additional
5440 @comment input after m4 has exited.  But the testsuite is using a pipe
5441 @comment for stdin.  Hence, we have two versions - the one we feed the
5442 @comment testsuite below, and the one we display to the user above that
5443 @comment more accurately shows what the testsuite is really doing but
5444 @comment which the testsuite cannot parse.
5446 @example
5447 m4wrap(`syscmd(`cat')')
5448 @result{}
5450 @end example
5451 @end ignore
5453 It tells @code{m4} to read all of its input before executing the wrapped
5454 text, then hand a valid (albeit emptied) pipe as standard input for the
5455 @code{cat} subcommand.  Therefore, you should be careful when using
5456 standard input (either by specifying no files, or by passing @samp{-} as
5457 a file name on the command line, @pxref{Command line files, , Invoking
5458 m4}), and also invoking subcommands via @code{syscmd} or @code{esyscmd}
5459 that consume data from standard input.  When standard input is a
5460 seekable file, the subprocess will pick up with the next character not
5461 yet processed by @code{m4}; when it is a pipe or other non-seekable
5462 file, there is no guarantee how much data will already be buffered by
5463 @code{m4} and thus unavailable to the child.
5465 @node Esyscmd
5466 @section Reading the output of commands
5468 @cindex @acronym{GNU} extensions
5469 If you want @code{m4} to read the output of a shell command, use
5470 @code{esyscmd}:
5472 @deffn Builtin esyscmd (@var{shell-command})
5473 Expands to the standard output of the shell command
5474 @var{shell-command}.
5476 Prior to executing the command, @code{m4} flushes its buffers.
5477 The default standard input and standard error of @var{shell-command} are
5478 the same as those of @code{m4}.  The error output of @var{shell-command}
5479 is not a part of the expansion: it will appear along with the error
5480 output of @code{m4}.
5482 The macro @code{esyscmd} is recognized only with parameters.
5483 @end deffn
5485 @example
5486 define(`foo', `FOO')
5487 @result{}
5488 esyscmd(`echo foo')
5489 @result{}FOO
5490 @result{}
5491 @end example
5493 Note how the expansion of @code{esyscmd} keeps the trailing newline of
5494 the command, as well as using the newline that appeared after the macro.
5496 Just as with @code{syscmd}, care must be exercised when sharing standard
5497 input between @code{m4} and the child process of @code{esyscmd}.
5499 @node Sysval
5500 @section Exit status
5502 @cindex UNIX commands, exit status from
5503 @cindex exit status from shell commands
5504 @cindex shell commands, exit status from
5505 @cindex commands, exit status from shell
5506 @cindex status of shell commands
5507 To see whether a shell command succeeded, use @code{sysval}:
5509 @deffn Builtin sysval
5510 Expands to the exit status of the last shell command run with
5511 @code{syscmd} or @code{esyscmd}.  Expands to 0 if no command has been
5512 run yet.
5513 @end deffn
5515 @example
5516 sysval
5517 @result{}0
5518 syscmd(`false')
5519 @result{}
5520 ifelse(sysval, `0', `zero', `non-zero')
5521 @result{}non-zero
5522 syscmd(`exit 2')
5523 @result{}
5524 sysval
5525 @result{}2
5526 syscmd(`true')
5527 @result{}
5528 sysval
5529 @result{}0
5530 esyscmd(`false')
5531 @result{}
5532 ifelse(sysval, `0', `zero', `non-zero')
5533 @result{}non-zero
5534 esyscmd(`exit 2')
5535 @result{}
5536 sysval
5537 @result{}2
5538 esyscmd(`true')
5539 @result{}
5540 sysval
5541 @result{}0
5542 @end example
5544 @code{sysval} results in 127 if there was a problem executing the
5545 command, for example, if the system-imposed argument length is exceeded,
5546 or if there were not enough resources to fork.  It is not possible to
5547 distinguish between failed execution and successful execution that had
5548 an exit status of 127.
5550 On UNIX platforms, where it is possible to detect when command execution
5551 is terminated by a signal, rather than a normal exit, the result is the
5552 signal number shifted left by eight bits.
5554 @comment This test has difficulties being portable, even on platforms
5555 @comment where syscmd invokes /bin/sh.  Kill is not portable with signal
5556 @comment names.  According to autoconf, the only portable signal numbers
5557 @comment are 1 (HUP), 2 (INT), 9 (KILL), 13 (PIPE) and 15 (TERM).  But
5558 @comment all shells handle SIGINT, and ksh handles HUP (as in, the shell
5559 @comment exits normally rather than letting the signal terminate it).
5560 @comment Also, TERM is flaky, as it can also kill the running m4 on
5561 @comment systems where /bin/sh does not create its own process group.
5562 @comment And PIPE is unreliable, since people tend to run with it
5563 @comment ignored, with m4 inheriting that choice.  That leaves KILL as
5564 @comment the only signal we can reliably test.
5565 @example
5566 dnl This test assumes kill is a shell builtin, and that signals are
5567 dnl recognizable.
5568 ifdef(`__unix__', ,
5569       `errprint(` skipping: syscmd does not have unix semantics
5570 ')m4exit(`77')')dnl
5571 syscmd(`kill -9 $$')
5572 @result{}
5573 sysval
5574 @result{}2304
5575 syscmd()
5576 @result{}
5577 sysval
5578 @result{}0
5579 esyscmd(`kill -9 $$')
5580 @result{}
5581 sysval
5582 @result{}2304
5583 @end example
5585 @node Mkstemp
5586 @section Making temporary files
5588 @cindex temporary file names
5589 @cindex files, names of temporary
5590 Commands specified to @code{syscmd} or @code{esyscmd} might need a
5591 temporary file, for output or for some other purpose.  There is a
5592 builtin macro, @code{mkstemp}, for making a temporary file:
5594 @deffn Builtin mkstemp (@var{template})
5595 @deffnx Builtin maketemp (@var{template})
5596 Expands to a name of a new, empty file, made from the string
5597 @var{template}, which should end with the string @samp{XXXXXX}.  The six
5598 @samp{X} characters are then replaced with random characters matching
5599 the regular expression @samp{[a-zA-Z0-9._-]}, in order to make the file
5600 name unique.  If fewer than six @samp{X} characters are found at the end
5601 of @code{template}, the result will be longer than the template.  The
5602 created file will have access permissions as if by @kbd{chmod =rw,go=},
5603 meaning that the current umask of the @code{m4} process is taken into
5604 account, and at most only the current user can read and write the file.
5606 The traditional behavior, standardized by @acronym{POSIX}, is that
5607 @code{maketemp} merely replaces the trailing @samp{X} with the process
5608 id, without creating a file, and without ensuring that the resulting
5609 string is a unique file name.  In part, this means that using the same
5610 @var{template} twice in the same input file will result in the same
5611 expansion.  This behavior is a security hole, as it is very easy for
5612 another process to guess the name that will be generated, and thus
5613 interfere with a subsequent use of @code{syscmd} trying to manipulate
5614 that file name.  Hence, @acronym{POSIX} has recommended that all new
5615 implementations of @code{m4} provide the secure @code{mkstemp} builtin,
5616 and that users of @code{m4} check for its existence.
5618 The expansion is void and an error issued if a temporary file could
5619 not be created.
5621 The macros @code{mkstemp} and @code{maketemp} are recognized only with
5622 parameters.
5623 @end deffn
5625 If you try this next example, you will most likely get different output
5626 for the two file names, since the replacement characters are randomly
5627 chosen:
5629 @comment ignore
5630 @example
5631 $ @kbd{m4}
5632 maketemp(`/tmp/fooXXXXXX')
5633 @result{}/tmp/fooa07346
5634 ifdef(`mkstemp', `define(`maketemp', defn(`mkstemp'))',
5635       `define(`mkstemp', defn(`maketemp'))dnl
5636 errprint(`warning: potentially insecure maketemp implementation
5637 ')')
5638 @result{}
5639 mkstemp(`doc')
5640 @result{}docQv83Uw
5641 @end example
5643 @cindex @acronym{GNU} extensions
5644 Unless you use the @option{--traditional} command line option (or
5645 @option{-G}, @pxref{Limits control, , Invoking m4}), the @acronym{GNU}
5646 version of @code{maketemp} is secure.  This means that using the same
5647 template to multiple calls will generate multiple files.  However, we
5648 recommend that you use the new @code{mkstemp} macro, introduced in
5649 @acronym{GNU} M4 1.4.8, which is secure even in traditional mode.
5651 @example
5652 $ @kbd{m4}
5653 syscmd(`echo foo??????')dnl
5654 @result{}foo??????
5655 define(`file1', maketemp(`fooXXXXXX'))dnl
5656 ifelse(esyscmd(`echo foo??????'), `foo??????', `no file', `created')
5657 @result{}created
5658 define(`file2', maketemp(`fooXX'))dnl
5659 define(`file3', mkstemp(`fooXXXXXX'))dnl
5660 ifelse(len(file1), len(file2), `same length', `different')
5661 @result{}same length
5662 ifelse(file1, file2, `same', `different file')
5663 @result{}different file
5664 ifelse(file2, file3, `same', `different file')
5665 @result{}different file
5666 ifelse(file1, file3, `same', `different file')
5667 @result{}different file
5668 syscmd(`rm 'file1 file2 file3)
5669 @result{}
5670 sysval
5671 @result{}0
5672 @end example
5674 @node Miscellaneous
5675 @chapter Miscellaneous builtin macros
5677 This chapter describes various builtins, that do not really belong in
5678 any of the previous chapters.
5680 @menu
5681 * Errprint::                    Printing error messages
5682 * Location::                    Printing current location
5683 * M4exit::                      Exiting from @code{m4}
5684 @end menu
5686 @node Errprint
5687 @section Printing error messages
5689 @cindex printing error messages
5690 @cindex error messages, printing
5691 @cindex messages, printing error
5692 @cindex standard error, output to
5693 You can print error messages using @code{errprint}:
5695 @deffn Builtin errprint (@var{message}, @dots{})
5696 Prints @var{message} and the rest of the arguments to standard error,
5697 separated by spaces.  Standard error is used, regardless of the
5698 @option{--debugfile} option (@pxref{Debugging options, , Invoking m4}).
5700 The expansion of @code{errprint} is void.
5701 The macro @code{errprint} is recognized only with parameters.
5702 @end deffn
5704 @example
5705 errprint(`Invalid arguments to forloop
5707 @error{}Invalid arguments to forloop
5708 @result{}
5709 errprint(`1')errprint(`2',`3
5711 @error{}12 3
5712 @result{}
5713 @end example
5715 A trailing newline is @emph{not} printed automatically, so it should be
5716 supplied as part of the argument, as in the example.  Unfortunately, the
5717 exact output of @code{errprint} is not very portable to other @code{m4}
5718 implementations: @acronym{POSIX} requires that all arguments be printed,
5719 but some implementations of @code{m4} only print the first.
5720 Furthermore, some BSD implementations always append a newline for each
5721 @code{errprint} call, regardless of whether the last argument already
5722 had one, and @acronym{POSIX} is silent on whether this is acceptable.
5724 @node Location
5725 @section Printing current location
5727 @cindex location, input
5728 @cindex input location
5729 To make it possible to specify the location of an error, three
5730 utility builtins exist:
5732 @deffn Builtin __file__
5733 @deffnx Builtin __line__
5734 @deffnx Builtin __program__
5735 Expand to the quoted name of the current input file, the
5736 current input line number in that file, and the quoted name of the
5737 current invocation of @code{m4}.
5738 @end deffn
5740 @example
5741 errprint(__program__:__file__:__line__: `input error
5743 @error{}m4:stdin:1: input error
5744 @result{}
5745 @end example
5747 Line numbers start at 1 for each file.  If the file was found due to the
5748 @option{-I} option or @env{M4PATH} environment variable, that is
5749 reflected in the file name.  The syncline option (@option{-s},
5750 @pxref{Preprocessor features, , Invoking m4}), and the
5751 @samp{f} and @samp{l} flags of @code{debugmode} (@pxref{Debug Levels}),
5752 also use this notion of current file and line.  Redefining the three
5753 location macros has no effect on syncline, debug, warning, or error
5754 message output.
5756 This example reuses the file @file{incl.m4} mentioned earlier
5757 (@pxref{Include}):
5759 @example
5760 $ @kbd{m4 -I examples}
5761 define(`foo', ``$0' called at __file__:__line__')
5762 @result{}
5764 @result{}foo called at stdin:2
5765 include(`incl.m4')
5766 @result{}Include file start
5767 @result{}foo called at ../examples/incl.m4:2
5768 @result{}Include file end
5769 @result{}
5770 @end example
5772 The location of macros invoked during the rescanning of macro expansion
5773 text corresponds to the location in the file where the expansion was
5774 triggered, regardless of how many newline characters the expansion text
5775 contains.  As of @acronym{GNU} M4 1.4.8, the location of text wrapped
5776 with @code{m4wrap} (@pxref{M4wrap}) is the point at which the
5777 @code{m4wrap} was invoked.  Previous versions, however, behaved as
5778 though wrapped text came from line 0 of the file ``''.
5780 @example
5781 define(`echo', `$@@')
5782 @result{}
5783 define(`foo', `echo(__line__
5784 __line__)')
5785 @result{}
5786 echo(__line__
5787 __line__)
5788 @result{}4
5789 @result{}5
5790 m4wrap(`foo
5792 @result{}
5793 foo(errprint(__line__
5794 __line__
5796 @error{}8
5797 @error{}9
5798 @result{}8
5799 @result{}8
5800 __line__
5801 @result{}11
5803 @result{}6
5804 @result{}6
5805 @end example
5807 The @code{@w{__program__}} macro behaves like @samp{$0} in shell
5808 terminology.  If you invoke @code{m4} through an absolute path or a link
5809 with a different spelling, rather than by relying on a @env{PATH} search
5810 for plain @samp{m4}, it will affect how @code{@w{__program__}} expands.
5811 The intent is that you can use it to produce error messages with the
5812 same formatting that @code{m4} produces internally.  It can also be used
5813 within @code{syscmd} (@pxref{Syscmd}) to pick the same version of
5814 @code{m4} that is currently running, rather than whatever version of
5815 @code{m4} happens to be first in @env{PATH}.  It was first introduced in
5816 @acronym{GNU} M4 1.4.6.
5818 @node M4exit
5819 @section Exiting from @code{m4}
5821 @cindex exiting from @code{m4}
5822 @cindex status, setting @code{m4} exit
5823 If you need to exit from @code{m4} before the entire input has been
5824 read, you can use @code{m4exit}:
5826 @deffn Builtin m4exit (@dvar{code, 0})
5827 Causes @code{m4} to exit, with exit status @var{code}.  If @var{code} is
5828 left out, the exit status is zero.  If @var{code} cannot be parsed, or
5829 is outside the range of 0 to 255, the exit status is one.  No further
5830 input is read, and all wrapped and diverted text is discarded.
5831 @end deffn
5833 @example
5834 m4wrap(`This text is lost due to `m4exit'.')
5835 @result{}
5836 divert(`1') So is this.
5837 divert
5838 @result{}
5839 m4exit And this is never read.
5840 @end example
5842 A common use of this is to abort processing:
5844 @deffn Composite fatal_error (@var{message})
5845 Abort processing with an error message and non-zero status.  Prefix
5846 @var{message} with details about where the error occurred, and print the
5847 resulting string to standard error.
5848 @end deffn
5850 @comment status: 1
5851 @example
5852 define(`fatal_error',
5853        `errprint(__program__:__file__:__line__`: fatal error: $*
5854 ')m4exit(`1')')
5855 @result{}
5856 fatal_error(`this is a BAD one, buster')
5857 @error{}m4:stdin:4: fatal error: this is a BAD one, buster
5858 @end example
5860 After this macro call, @code{m4} will exit with exit status 1.  This macro
5861 is only intended for error exits, since the normal exit procedures are
5862 not followed, e.g., diverted text is not undiverted, and saved text
5863 (@pxref{M4wrap}) is not reread.  (This macro could be made more robust
5864 to earlier versions of @code{m4}.  You should try to see if you can find
5865 weaknesses and correct them; or @pxref{Improved fatal_error, , Answers}).
5867 Note that it is still possible for the exit status to be different than
5868 what was requested by @code{m4exit}.  If @code{m4} detects some other
5869 error, such as a write error on standard output, the exit status will be
5870 non-zero even if @code{m4exit} requested zero.
5872 If standard input is seekable, then the file will be positioned at the
5873 next unread character.  If it is a pipe or other non-seekable file,
5874 then there are no guarantees how much data @code{m4} might have read
5875 into buffers, and thus discarded.
5877 @node Frozen files
5878 @chapter Fast loading of frozen state
5880 Some bigger @code{m4} applications may be built over a common base
5881 containing hundreds of definitions and other costly initializations.
5882 Usually, the common base is kept in one or more declarative files,
5883 which files are listed on each @code{m4} invocation prior to the
5884 user's input file, or else each input file uses @code{include}.
5886 Reading the common base of a big application, over and over again, may
5887 be time consuming.  @acronym{GNU} @code{m4} offers some machinery to
5888 speed up the start of an application using lengthy common bases.
5890 @menu
5891 * Using frozen files::          Using frozen files
5892 * Frozen file format::          Frozen file format
5893 @end menu
5895 @node Using frozen files
5896 @section Using frozen files
5898 @cindex fast loading of frozen files
5899 @cindex frozen files for fast loading
5900 @cindex initialization, frozen state
5901 @cindex dumping into frozen file
5902 @cindex reloading a frozen file
5903 @cindex @acronym{GNU} extensions
5904 Suppose a user has a library of @code{m4} initializations in
5905 @file{base.m4}, which is then used with multiple input files:
5907 @comment ignore
5908 @example
5909 $ @kbd{m4 base.m4 input1.m4}
5910 $ @kbd{m4 base.m4 input2.m4}
5911 $ @kbd{m4 base.m4 input3.m4}
5912 @end example
5914 Rather than spending time parsing the fixed contents of @file{base.m4}
5915 every time, the user might rather execute:
5917 @comment ignore
5918 @example
5919 $ @kbd{m4 -F base.m4f base.m4}
5920 @end example
5922 @noindent
5923 once, and further execute, as often as needed:
5925 @comment ignore
5926 @example
5927 $ @kbd{m4 -R base.m4f input1.m4}
5928 $ @kbd{m4 -R base.m4f input2.m4}
5929 $ @kbd{m4 -R base.m4f input3.m4}
5930 @end example
5932 @noindent
5933 with the varying input.  The first call, containing the @option{-F}
5934 option, only reads and executes file @file{base.m4}, defining
5935 various application macros and computing other initializations.
5936 Once the input file @file{base.m4} has been completely processed, @acronym{GNU}
5937 @code{m4} produces in @file{base.m4f} a @dfn{frozen} file, that is, a
5938 file which contains a kind of snapshot of the @code{m4} internal state.
5940 Later calls, containing the @option{-R} option, are able to reload
5941 the internal state of @code{m4}, from @file{base.m4f},
5942 @emph{prior} to reading any other input files.  This means
5943 instead of starting with a virgin copy of @code{m4}, input will be
5944 read after having effectively recovered the effect of a prior run.
5945 In our example, the effect is the same as if file @file{base.m4} has
5946 been read anew.  However, this effect is achieved a lot faster.
5948 Only one frozen file may be created or read in any one @code{m4}
5949 invocation.  It is not possible to recover two frozen files at once.
5950 However, frozen files may be updated incrementally, through using
5951 @option{-R} and @option{-F} options simultaneously.  For example, if
5952 some care is taken, the command:
5954 @comment ignore
5955 @example
5956 $ @kbd{m4 file1.m4 file2.m4 file3.m4 file4.m4}
5957 @end example
5959 @noindent
5960 could be broken down in the following sequence, accumulating the same
5961 output:
5963 @comment ignore
5964 @example
5965 $ @kbd{m4 -F file1.m4f file1.m4}
5966 $ @kbd{m4 -R file1.m4f -F file2.m4f file2.m4}
5967 $ @kbd{m4 -R file2.m4f -F file3.m4f file3.m4}
5968 $ @kbd{m4 -R file3.m4f file4.m4}
5969 @end example
5971 Some care is necessary because not every effort has been made for
5972 this to work in all cases.  In particular, the trace attribute of
5973 macros is not handled, nor the current setting of @code{changeword}.
5974 Currently, @code{m4wrap} and @code{sysval} also have problems.
5975 Also, interactions for some options of @code{m4}, being used in one call
5976 and not in the next, have not been fully analyzed yet.  On the other
5977 end, you may be confident that stacks of @code{pushdef} definitions
5978 are handled correctly, as well as undefined or renamed builtins, and
5979 changed strings for quotes or comments.  And future releases of
5980 @acronym{GNU} M4 will improve on the utility of frozen files.
5982 When an @code{m4} run is to be frozen, the automatic undiversion
5983 which takes place at end of execution is inhibited.  Instead, all
5984 positively numbered diversions are saved into the frozen file.
5985 The active diversion number is also transmitted.
5987 A frozen file to be reloaded need not reside in the current directory.
5988 It is looked up the same way as an @code{include} file (@pxref{Search
5989 Path}).
5991 If the frozen file was generated with a newer version of @code{m4}, and
5992 contains directives that an older @code{m4} cannot parse, attempting to
5993 load the frozen file with option @option{-R} will cause @code{m4} to
5994 exit with status 63 to indicate version mismatch.
5996 @node Frozen file format
5997 @section Frozen file format
5999 @cindex frozen file format
6000 @cindex file format, frozen file
6001 Frozen files are sharable across architectures.  It is safe to write
6002 a frozen file on one machine and read it on another, given that the
6003 second machine uses the same or newer version of @acronym{GNU} @code{m4}.
6004 It is conventional, but not required, to give a frozen file the suffix
6005 of @code{.m4f}.
6007 These are simple (editable) text files, made up of directives,
6008 each starting with a capital letter and ending with a newline
6009 (@key{NL}).  Wherever a directive is expected, the character
6010 @samp{#} introduces a comment line; empty lines are also ignored if they
6011 are not part of an embedded string.
6012 In the following descriptions, each @var{len} refers to the length of
6013 the corresponding strings @var{str} in the next line of input.  Numbers
6014 are always expressed in decimal.  There are no escape characters.  The
6015 directives are:
6017 @table @code
6018 @item C @var{len1} , @var{len2} @key{NL} @var{str1} @var{str2} @key{NL}
6019 Uses @var{str1} and @var{str2} as the begin-comment and
6020 end-comment strings.  If omitted, then @samp{#} and @key{NL} are the
6021 comment delimiters.
6023 @item D @var{number}, @var{len} @key{NL} @var{str} @key{NL}
6024 Selects diversion @var{number}, making it current, then copy
6025 @var{str} in the current diversion.  @var{number} may be a negative
6026 number for a non-existing diversion.  To merely specify an active
6027 selection, use this command with an empty @var{str}.  With 0 as the
6028 diversion @var{number}, @var{str} will be issued on standard output
6029 at reload time.  @acronym{GNU} @code{m4} will not produce the @samp{D}
6030 directive with non-zero length for diversion 0, but this can be done
6031 with manual edits.  This directive may
6032 appear more than once for the same diversion, in which case the
6033 diversion is the concatenation of the various uses.  If omitted, then
6034 diversion 0 is current.
6036 @item F @var{len1} , @var{len2} @key{NL} @var{str1} @var{str2} @key{NL}
6037 Defines, through @code{pushdef}, a definition for @var{str1}
6038 expanding to the function whose builtin name is @var{str2}.  If the
6039 builtin does not exist (for example, if the frozen file was produced by
6040 a copy of @code{m4} compiled with changeword support, but the version
6041 of @code{m4} reloading was compiled without it), the reload is silent,
6042 but any subsequent use of the definition of @var{str1} will result in
6043 a warning.  This directive may appear more than once for the same name,
6044 and its order, along with @samp{T}, is important.  If omitted, you will
6045 have no access to any builtins.
6047 @item Q @var{len1} , @var{len2} @key{NL} @var{str1} @var{str2} @key{NL}
6048 Uses @var{str1} and @var{str2} as the begin-quote and end-quote
6049 strings.  If omitted, then @samp{`} and @samp{'} are the quote
6050 delimiters.
6052 @item T @var{len1} , @var{len2} @key{NL} @var{str1} @var{str2} @key{NL}
6053 Defines, though @code{pushdef}, a definition for @var{str1}
6054 expanding to the text given by @var{str2}.  This directive may appear
6055 more than once for the same name, and its order, along with @samp{F}, is
6056 important.
6058 @item V @var{number} @key{NL}
6059 Confirms the format of the file.  @code{m4} @value{VERSION} only creates
6060 and understands frozen files where @var{number} is 1.  This directive
6061 must be the first non-comment in the file, and may not appear more than
6062 once.
6063 @end table
6065 @node Compatibility
6066 @chapter Compatibility with other versions of @code{m4}
6068 @cindex compatibility
6069 This chapter describes the differences between this implementation of
6070 @code{m4}, and the implementation found under UNIX, notably System V,
6071 Release 3.
6073 There are also differences in BSD flavors of @code{m4}.  No attempt
6074 is made to summarize these here.
6076 @menu
6077 * Extensions::                  Extensions in @acronym{GNU} M4
6078 * Incompatibilities::           Facilities in System V m4 not in GNU M4
6079 * Other Incompatibilities::     Other incompatibilities
6080 @end menu
6082 @node Extensions
6083 @section Extensions in @acronym{GNU} @code{m4}
6085 @cindex @acronym{GNU} extensions
6086 @cindex @acronym{POSIX}
6087 This version of @code{m4} contains a few facilities that do not exist
6088 in System V @code{m4}.  These extra facilities are all suppressed by
6089 using the @option{-G} command line option (@pxref{Limits control, ,
6090 Invoking m4}), unless overridden by other command line options.
6092 @itemize @bullet
6093 @item
6094 In the @code{$@var{n}} notation for macro arguments, @var{n} can contain
6095 several digits, while the System V @code{m4} only accepts one digit.
6096 This allows macros in @acronym{GNU} @code{m4} to take any number of
6097 arguments, and not only nine (@pxref{Arguments}).
6099 This means that @code{define(`foo', `$11')} is ambiguous between
6100 implementations.  To portably choose between grabbing the first
6101 parameter and appending 1 to the expansion, or grabbing the eleventh
6102 parameter, you can do the following:
6104 @example
6105 define(`a1', `A1')
6106 @result{}
6107 dnl First argument, concatenated with 1
6108 define(`_1', `$1')define(`first1', `_1($@@)1')
6109 @result{}
6110 dnl Eleventh argument, portable
6111 define(`_9', `$9')define(`eleventh', `_9(shift(shift($@@)))')
6112 @result{}
6113 dnl Eleventh argument, GNU style
6114 define(`Eleventh', `$11')
6115 @result{}
6116 first1(`a', `b', `c', `d', `e', `f', `g', `h', `i', `j', `k')
6117 @result{}A1
6118 eleventh(`a', `b', `c', `d', `e', `f', `g', `h', `i', `j', `k')
6119 @result{}k
6120 Eleventh(`a', `b', `c', `d', `e', `f', `g', `h', `i', `j', `k')
6121 @result{}k
6122 @end example
6124 @noindent
6125 Also see the @code{argn} macro (@pxref{Shift}).
6127 @item
6128 The @code{divert} (@pxref{Divert}) macro can manage more than 9
6129 diversions.  @acronym{GNU} @code{m4} treats all positive numbers as valid
6130 diversions, rather than discarding diversions greater than 9.
6132 @item
6133 Files included with @code{include} and @code{sinclude} are sought in a
6134 user specified search path, if they are not found in the working
6135 directory.  The search path is specified by the @option{-I} option and the
6136 @env{M4PATH} environment variable (@pxref{Search Path}).
6138 @item
6139 Arguments to @code{undivert} can be non-numeric, in which case the named
6140 file will be included uninterpreted in the output (@pxref{Undivert}).
6142 @item
6143 Formatted output is supported through the @code{format} builtin, which
6144 is modeled after the C library function @code{printf} (@pxref{Format}).
6146 @item
6147 Searches and text substitution through basic regular expressions are
6148 supported by the @code{regexp} (@pxref{Regexp}) and @code{patsubst}
6149 (@pxref{Patsubst}) builtins.
6151 @item
6152 The output of shell commands can be read into @code{m4} with
6153 @code{esyscmd} (@pxref{Esyscmd}).
6155 @item
6156 There is indirect access to any builtin macro with @code{builtin}
6157 (@pxref{Builtin}).
6159 @item
6160 Macros can be called indirectly through @code{indir} (@pxref{Indir}).
6162 @item
6163 The name of the program, the current input file, and the current input
6164 line number are accessible through the builtins @code{@w{__program__}},
6165 @code{@w{__file__}}, and @code{@w{__line__}} (@pxref{Location}).
6167 @item
6168 The format of the output from @code{dumpdef} and macro tracing can be
6169 controlled with @code{debugmode} (@pxref{Debug Levels}).
6171 @item
6172 The destination of trace and debug output can be controlled with
6173 @code{debugfile} (@pxref{Debug Output}).
6175 @item
6176 The @code{maketemp} (@pxref{Mkstemp}) macro behaves like @code{mkstemp},
6177 creating a new file with a unique name on every invocation, rather than
6178 following the insecure behavior of replacing the trailing @samp{X}
6179 characters with the @code{m4} process id.
6180 @end itemize
6182 In addition to the above extensions, @acronym{GNU} @code{m4} implements the
6183 following command line options: @option{-F}, @option{-G}, @option{-I},
6184 @option{-L}, @option{-R}, @option{-V}, @option{-W}, @option{-d}, @option{-i},
6185 @option{-l}, @option{--debugfile} and @option{-t}.  @xref{Invoking m4}, for a
6186 description of these options.
6188 Also, the debugging and tracing facilities in @acronym{GNU} @code{m4} are much
6189 more extensive than in most other versions of @code{m4}.
6191 @node Incompatibilities
6192 @section Facilities in System V @code{m4} not in @acronym{GNU} @code{m4}
6194 The version of @code{m4} from System V contains a few facilities that
6195 have not been implemented in @acronym{GNU} @code{m4} yet.  Additionally,
6196 @acronym{POSIX} requires some behaviors that @acronym{GNU} @code{m4} has not
6197 implemented yet.  Relying on these behaviors is non-portable, as a
6198 future release of @acronym{GNU} @code{m4} may change.
6200 @itemize @bullet
6201 @item
6202 @acronym{POSIX} requires support for multiple arguments to @code{defn},
6203 without any clarification on how @code{defn} behaves when one of the
6204 multiple arguments names a builtin.  System V @code{m4} and some other
6205 implementations allow mixing builtins and text macros into a single
6206 macro.  @acronym{GNU} @code{m4} only supports joining multiple text
6207 arguments, although a future implementation may lift this restriction to
6208 behave more like System V.  The only portable way to join text macros
6209 with builtins is via helper macros and implicit concatenation of macro
6210 results.
6212 @item
6213 @acronym{POSIX} requires an application to exit with non-zero status if
6214 it wrote an error message to stderr.  This has not yet been consistently
6215 implemented for the various builtins that are required to issue an error
6216 (such as @code{eval} (@pxref{Eval}) when an argument cannot be parsed).
6218 @item
6219 Some traditional implementations only allow reading standard input
6220 once, but @acronym{GNU} @code{m4} correctly handles multiple instances
6221 of @samp{-} on the command line.
6223 @item
6224 @acronym{POSIX} requires @code{m4wrap} (@pxref{M4wrap}) to act in FIFO
6225 (first-in, first-out) order, but @acronym{GNU} @code{m4} currently uses
6226 LIFO order.  Furthermore, @acronym{POSIX} states that only the first
6227 argument to @code{m4wrap} is saved for later evaluation, bug
6228 @acronym{GNU} @code{m4} saves and processes all arguments, with output
6229 separated by spaces.
6231 However, it is possible to emulate @acronym{POSIX} behavior by
6232 including the file @file{m4-@value{VERSION}/@/examples/@/wrapfifo.m4}
6233 from the distribution:
6235 @example
6236 undivert(`wrapfifo.m4')dnl
6237 @result{}dnl Redefine m4wrap to have FIFO semantics.
6238 @result{}define(`_m4wrap_level', `0')dnl
6239 @result{}define(`m4wrap',
6240 @result{}`ifdef(`m4wrap'_m4wrap_level,
6241 @result{}       `define(`m4wrap'_m4wrap_level,
6242 @result{}               defn(`m4wrap'_m4wrap_level)`$1')',
6243 @result{}       `builtin(`m4wrap', `define(`_m4wrap_level',
6244 @result{}                                  incr(_m4wrap_level))dnl
6245 @result{}m4wrap'_m4wrap_level)dnl
6246 @result{}define(`m4wrap'_m4wrap_level, `$1')')')dnl
6247 include(`wrapfifo.m4')
6248 @result{}
6249 m4wrap(`a`'m4wrap(`c
6250 ', `d')')m4wrap(`b')
6251 @result{}
6253 @result{}abc
6254 @end example
6256 @item
6257 @acronym{POSIX} states that builtins that require arguments, but are
6258 called without arguments, have undefined behavior.  Traditional
6259 implementations simply behave as though empty strings had been passed.
6260 For example, @code{a`'define`'b} would expand to @code{ab}.  But
6261 @acronym{GNU} @code{m4} ignores certain builtins if they have missing
6262 arguments, giving @code{adefineb} for the above example.
6264 @item
6265 Traditional implementations handle @code{define(`f',`1')} (@pxref{Define})
6266 by undefining the entire stack of previous definitions, and if doing
6267 @code{undefine(`f')} first.  @acronym{GNU} @code{m4} replaces just the top
6268 definition on the stack, as if doing @code{popdef(`f')} followed by
6269 @code{pushdef(`f',`1')}.  @acronym{POSIX} allows either behavior.
6271 @item
6272 @acronym{POSIX} 2001 requires @code{syscmd} (@pxref{Syscmd}) to evaluate
6273 command output for macro expansion, but this was a mistake that is
6274 anticipated to be corrected in the next version of @acronym{POSIX}.
6275 @acronym{GNU} @code{m4} follows traditional behavior in @code{syscmd}
6276 where output is not rescanned, and provides the extension @code{esyscmd}
6277 that does scan the output.
6279 @item
6280 At one point, @acronym{POSIX} required @code{changequote(@var{arg})}
6281 (@pxref{Changequote}) to use newline as the close quote, but this was a
6282 bug, and the next version of @acronym{POSIX} is anticipated to state
6283 that using empty strings or just one argument is unspecified.
6284 Meanwhile, the @acronym{GNU} @code{m4} behavior of treating an empty
6285 end-quote delimiter as @samp{'} is not portable, as Solaris treats it as
6286 repeating the start-quote delimiter, and BSD treats it as leaving the
6287 previous end-quote delimiter unchanged.  For predictable results, never
6288 call changequote with just one argument, or with empty strings for
6289 arguments.
6291 @item
6292 At one point, @acronym{POSIX} required @code{changecom(@var{arg},)}
6293 (@pxref{Changecom}) to make it impossible to end a comment, but this is
6294 a bug, and the next version of @acronym{POSIX} is anticipated to state
6295 that using empty strings is unspecified.  Meanwhile, the @acronym{GNU}
6296 @code{m4} behavior of treating an empty end-comment delimiter as newline
6297 is not portable, as BSD treats it as leaving the previous end-comment
6298 delimiter unchanged.  It is also impossible in BSD implementations to
6299 disable comments, even though that is required by @acronym{POSIX}.  For
6300 predictable results, never call changecom with empty strings for
6301 arguments.
6303 @item
6304 Most implementations of @code{m4} give macros a higher precedence than
6305 comments when parsing, meaning that if the start delimiter given to
6306 @code{changecom} (@pxref{Changecom}) starts with a macro name, comments
6307 are effectively disabled.  @acronym{POSIX} does not specify what the
6308 precedence is, so this version of @acronym{GNU} @code{m4} parser
6309 recognizes comments, then macros, then quoted strings.
6311 @item
6312 Traditional implementations allow argument collection, but not string
6313 and comment processing, to span file boundaries.  Thus, if @file{a.m4}
6314 contains @samp{len(}, and @file{b.m4} contains @samp{abc)},
6315 @kbd{m4 a.m4 b.m4} outputs @samp{3} with traditional @code{m4}, but
6316 gives an error message that the end of file was encountered inside a
6317 macro with @acronym{GNU} @code{m4}.  On the other hand, traditional
6318 implementations do end of file processing for files included with
6319 @code{include} or @code{sinclude} (@pxref{Include}), while @acronym{GNU}
6320 @code{m4} seamlessly integrates the content of those files.  Thus
6321 @code{include(`a.m4')include(`b.m4')} will output @samp{3} instead of
6322 giving an error.
6324 @item
6325 Traditional @code{m4} treats @code{traceon} (@pxref{Trace}) without
6326 arguments as a global variable, independent of named macro tracing.
6327 Also, once a macro is undefined, named tracing of that macro is lost.
6328 On the other hand, when @acronym{GNU} @code{m4} encounters
6329 @code{traceon} without
6330 arguments, it turns tracing on for all existing definitions at the time,
6331 but does not trace future definitions; @code{traceoff} without arguments
6332 turns tracing off for all definitions regardless of whether they were
6333 also traced by name; and tracing by name, such as with @option{-tfoo} at
6334 the command line or @code{traceon(`foo')} in the input, is an attribute
6335 that is preserved even if the macro is currently undefined.
6337 @item
6338 @acronym{POSIX} requires @code{eval} (@pxref{Eval}) to treat all
6339 operators with the same precedence as C.  However, earlier versions of
6340 @acronym{GNU} @code{m4} followed the traditional behavior of other
6341 @code{m4} implementations, where bitwise and logical negation (@samp{~}
6342 and @samp{!}) have lower precedence than equality operators; and where
6343 equality operators (@samp{==} and @samp{!=}) had the same precedence as
6344 relational operators (such as @samp{<}).  Use explicit parentheses to
6345 ensure proper precedence.  As extensions to @acronym{POSIX},
6346 @acronym{GNU} @code{m4} gives well-defined semantics to operations that
6347 C leaves undefined, such as when overflow occurs, when shifting negative
6348 numbers, or when performing division by zero.  @acronym{POSIX} also
6349 requires @samp{=} to cause an error, but many traditional
6350 implementations allowed it as an alias for @samp{==}.
6352 @item
6353 @acronym{POSIX} 2001 requires @code{translit} (@pxref{Translit}) to
6354 treat each character of the second and third arguments literally.
6355 However, it is anticipated that the next version of @acronym{POSIX} will
6356 allow the @acronym{GNU} @code{m4} behavior of treating @samp{-} as a
6357 range operator.
6359 @item
6360 @acronym{POSIX} requires @code{m4} to honor the locale environment
6361 variables of @env{LANG}, @env{LC_ALL}, @env{LC_CTYPE},
6362 @env{LC_MESSAGES}, and @env{NLSPATH}, but this has not yet been
6363 implemented in @acronym{GNU} @code{m4}.
6365 @item
6366 @acronym{POSIX} states that only unquoted leading newlines and blanks
6367 (that is, space and tab) are ignored when collecting macro arguments.
6368 However, this appears to be a bug in @acronym{POSIX}, since most
6369 traditional implementations also ignore all whitespace (formfeed,
6370 carriage return, and vertical tab).  @acronym{GNU} @code{m4} follows
6371 tradition and ignores all leading unquoted whitespace.
6372 @end itemize
6374 @node Other Incompatibilities
6375 @section Other incompatibilities
6377 There are a few other incompatibilities between this implementation of
6378 @code{m4}, and the System V version.
6380 @itemize @bullet
6381 @item
6382 @acronym{GNU} @code{m4} implements sync lines differently from System V
6383 @code{m4}, when text is being diverted.  @acronym{GNU} @code{m4} outputs
6384 the sync lines when the text is being diverted, and System V @code{m4}
6385 when the diverted text is being brought back.
6387 The problem is which lines and file names should be attached to text that
6388 is being, or has been, diverted.  System V @code{m4} regards all the
6389 diverted text as being generated by the source line containing the
6390 @code{undivert} call, whereas @acronym{GNU} @code{m4} regards the
6391 diverted text as being generated at the time it is diverted.
6393 The sync line option is used mostly when using @code{m4} as
6394 a front end to a compiler.  If a diverted line causes a compiler error,
6395 the error messages should most probably refer to the place where the
6396 diversion was made, and not where it was inserted again.
6398 @comment options: -s
6399 @example
6400 divert(2)2
6401 divert(1)1
6402 divert`'0
6403 @result{}#line 3 "stdin"
6404 @result{}0
6406 @result{}#line 2 "stdin"
6407 @result{}1
6408 @result{}#line 1 "stdin"
6409 @result{}2
6410 @end example
6412 The current @code{m4} implementation has a limitation that the syncline
6413 output at the start of each diversion occurs no matter what, even if the
6414 previous diversion did not end with a newline.  This goes contrary to
6415 the claim that synclines appear on a line by themselves, so this
6416 limitation may be corrected in a future version of @code{m4}.  In the
6417 meantime, when using @option{-s}, it is wisest to make sure all
6418 diversions end with newline.
6420 @item
6421 @acronym{GNU} @code{m4} makes no attempt at prohibiting self-referential
6422 definitions like:
6424 @example
6425 define(`x', `x')
6426 @result{}
6427 define(`x', `x ')
6428 @result{}
6429 @end example
6431 @cindex rescanning
6432 There is nothing inherently wrong with defining @samp{x} to
6433 return @samp{x}.  The wrong thing is to expand @samp{x} unquoted,
6434 because that would cause an infinite rescan loop.
6435 In @code{m4}, one might use macros to hold strings, as we do for
6436 variables in other programming languages, further checking them with:
6438 @comment ignore
6439 @example
6440 ifelse(defn(`@var{holder}'), `@var{value}', @dots{})
6441 @end example
6443 @noindent
6444 In cases like this one, an interdiction for a macro to hold its own name
6445 would be a useless limitation.  Of course, this leaves more rope for the
6446 @acronym{GNU} @code{m4} user to hang himself!  Rescanning hangs may be
6447 avoided through careful programming, a little like for endless loops in
6448 traditional programming languages.
6449 @end itemize
6451 @node Answers
6452 @chapter Correct version of some examples
6454 Some of the examples in this manuals are buggy or not very robust, for
6455 demonstration purposes.  Improved versions of these composite macros are
6456 presented here.
6458 @menu
6459 * Improved exch::               Solution for @code{exch}
6460 * Improved forloop::            Solution for @code{forloop}
6461 * Improved foreach::            Solution for @code{foreach}
6462 * Improved cleardivert::        Solution for @code{cleardivert}
6463 * Improved fatal_error::        Solution for @code{fatal_error}
6464 @end menu
6466 @node Improved exch
6467 @section Solution for @code{exch}
6469 The @code{exch} macro (@pxref{Arguments}) as presented requires clients
6470 to double quote their arguments.  A nicer definition, which lets
6471 clients follow the rule of thumb of one level of quoting per level of
6472 parentheses, involves adding quotes in the definition of @code{exch}, as
6473 follows:
6475 @example
6476 define(`exch', ``$2', `$1'')
6477 @result{}
6478 define(exch(`expansion text', `macro'))
6479 @result{}
6480 macro
6481 @result{}expansion text
6482 @end example
6484 @node Improved forloop
6485 @section Solution for @code{forloop}
6487 The @code{forloop} macro (@pxref{Forloop}) as presented earlier can go
6488 into an infinite loop if given an iterator that is not parsed as a macro
6489 name.  It does not do any sanity checking on its numeric bounds, and
6490 only permits decimal numbers for bounds.  Here is an improved version,
6491 shipped as @file{m4-@value{VERSION}/@/examples/@/forloop2.m4}; this
6492 version also optimizes based on the fact that the starting bound does
6493 not need to be passed to the helper @code{@w{_forloop}}.
6495 @example
6496 $ @kbd{m4 -I examples}
6497 undivert(`forloop2.m4')dnl
6498 @result{}divert(`-1')
6499 @result{}# forloop(var, from, to, stmt) - improved version:
6500 @result{}#   works even if VAR is not a strict macro name
6501 @result{}#   performs sanity check that FROM is larger than TO
6502 @result{}#   allows complex numerical expressions in TO and FROM
6503 @result{}define(`forloop', `ifelse(eval(`($3) >= ($2)'), `1',
6504 @result{}  `pushdef(`$1', eval(`$2'))_forloop(`$1',
6505 @result{}    eval(`$3'), `$4')popdef(`$1')')')
6506 @result{}define(`_forloop',
6507 @result{}  `$3`'ifelse(indir(`$1'), `$2', `',
6508 @result{}    `define(`$1', incr(indir(`$1')))$0($@@)')')
6509 @result{}divert`'dnl
6510 include(`forloop2.m4')
6511 @result{}
6512 forloop(`i', `2', `1', `no iteration occurs')
6513 @result{}
6514 forloop(`', `1', `2', ` odd iterator name')
6515 @result{} odd iterator name odd iterator name
6516 forloop(`i', `5 + 5', `0xc', ` 0x`'eval(i, `16')')
6517 @result{} 0xa 0xb 0xc
6518 forloop(`i', `a', `b', `non-numeric bounds')
6519 @error{}m4:stdin:6: bad expression in eval (bad input): (b) >= (a)
6520 @result{}
6521 @end example
6523 Of course, it is possible to make even more improvements, such as
6524 adding an optional step argument, or allowing iteration through
6525 descending sequences.  @acronym{GNU} Autoconf provides some of these
6526 additional bells and whistles in its @code{m4_for} macro.
6528 @node Improved foreach
6529 @section Solution for @code{foreach}
6531 The @code{foreach} and @code{foreachq} macros (@pxref{Foreach}) as
6532 presented earlier each have flaws.  First, we will examine and fix the
6533 quadratic behavior of @code{foreachq}:
6535 @example
6536 $ @kbd{m4 -I examples}
6537 include(`foreachq.m4')
6538 @result{}
6539 traceon(`shift')debugmode(`aq')
6540 @result{}
6541 foreachq(`x', ``1', `2', `3', `4'', `x
6542 ')dnl
6543 @result{}1
6544 @error{}m4trace: -3- shift(`1', `2', `3', `4')
6545 @error{}m4trace: -2- shift(`1', `2', `3', `4')
6546 @result{}2
6547 @error{}m4trace: -4- shift(`1', `2', `3', `4')
6548 @error{}m4trace: -3- shift(`2', `3', `4')
6549 @error{}m4trace: -3- shift(`1', `2', `3', `4')
6550 @error{}m4trace: -2- shift(`2', `3', `4')
6551 @result{}3
6552 @error{}m4trace: -5- shift(`1', `2', `3', `4')
6553 @error{}m4trace: -4- shift(`2', `3', `4')
6554 @error{}m4trace: -3- shift(`3', `4')
6555 @error{}m4trace: -4- shift(`1', `2', `3', `4')
6556 @error{}m4trace: -3- shift(`2', `3', `4')
6557 @error{}m4trace: -2- shift(`3', `4')
6558 @result{}4
6559 @error{}m4trace: -6- shift(`1', `2', `3', `4')
6560 @error{}m4trace: -5- shift(`2', `3', `4')
6561 @error{}m4trace: -4- shift(`3', `4')
6562 @error{}m4trace: -3- shift(`4')
6563 @end example
6565 @cindex quadratic behavior, avoiding
6566 @cindex avoiding quadratic behavior
6567 Each successive iteration was adding more quoted @code{shift}
6568 invocations, and the entire list contents were passing through every
6569 iteration.  In general, when recursing, it is a good idea to make the
6570 recursion use fewer arguments, rather than adding additional quoted
6571 uses of @code{shift}.  By doing so, @code{m4} uses less memory, invokes
6572 fewer macros, is less likely to run into machine limits, and most
6573 importantly, performs faster.  The fixed version of @code{foreachq} can
6574 be found in @file{m4-@value{VERSION}/@/examples/@/foreachq2.m4}:
6576 @example
6577 $ @kbd{m4 -I examples}
6578 include(`foreachq2.m4')
6579 @result{}
6580 undivert(`foreachq2.m4')dnl
6581 @result{}include(`quote.m4')dnl
6582 @result{}divert(`-1')
6583 @result{}# foreachq(x, `item_1, item_2, ..., item_n', stmt)
6584 @result{}#   quoted list, improved version
6585 @result{}define(`foreachq', `pushdef(`$1')_foreachq($@@)popdef(`$1')')
6586 @result{}define(`_arg1q', ``$1'')
6587 @result{}define(`_rest', `ifelse(`$#', `1', `', `dquote(shift($@@))')')
6588 @result{}define(`_foreachq', `ifelse(`$2', `', `',
6589 @result{}  `define(`$1', _arg1q($2))$3`'$0(`$1', _rest($2), `$3')')')
6590 @result{}divert`'dnl
6591 traceon(`shift')debugmode(`aq')
6592 @result{}
6593 foreachq(`x', ``1', `2', `3', `4'', `x
6594 ')dnl
6595 @result{}1
6596 @error{}m4trace: -3- shift(`1', `2', `3', `4')
6597 @result{}2
6598 @error{}m4trace: -3- shift(`2', `3', `4')
6599 @result{}3
6600 @error{}m4trace: -3- shift(`3', `4')
6601 @result{}4
6602 @end example
6604 Note that the fixed version calls unquoted helper macros in
6605 @code{@w{_foreachq}} to trim elements immediately; those helper macros
6606 in turn must re-supply the layer of quotes lost in the macro invocation.
6607 Contrast the use of @code{@w{_arg1q}}, which quotes the first list
6608 element, with @code{@w{_arg1}} of the earlier implementation that
6609 returned the first list element directly.
6611 For a different approach, the improved version of @code{foreach},
6612 available in @file{m4-@value{VERSION}/@/examples/@/foreach2.m4}, simply
6613 overquotes the arguments to @code{@w{_foreach}} to begin with, using
6614 @code{dquote_elt}.  Then @code{@w{_foreach}} can just use
6615 @code{@w{_arg1}} to remove the extra layer of quoting that was added up
6616 front:
6618 @example
6619 $ @kbd{m4 -I examples}
6620 include(`foreach2.m4')
6621 @result{}
6622 undivert(`foreach2.m4')dnl
6623 @result{}include(`quote.m4')dnl
6624 @result{}divert(`-1')
6625 @result{}# foreach(x, (item_1, item_2, ..., item_n), stmt)
6626 @result{}#   parenthesized list, improved version
6627 @result{}define(`foreach', `pushdef(`$1')_foreach(`$1',
6628 @result{}  (dquote(dquote_elt$2)), `$3')popdef(`$1')')
6629 @result{}define(`_arg1', `$1')
6630 @result{}define(`_foreach', `ifelse(`$2', `(`')', `',
6631 @result{}  `define(`$1', _arg1$2)$3`'$0(`$1', (dquote(shift$2)), `$3')')')
6632 @result{}divert`'dnl
6633 traceon(`shift')debugmode(`aq')
6634 @result{}
6635 foreach(`x', `(`1', `2', `3', `4')', `x
6636 ')dnl
6637 @error{}m4trace: -4- shift(`1', `2', `3', `4')
6638 @error{}m4trace: -4- shift(`2', `3', `4')
6639 @error{}m4trace: -4- shift(`3', `4')
6640 @result{}1
6641 @error{}m4trace: -3- shift(``1'', ``2'', ``3'', ``4'')
6642 @result{}2
6643 @error{}m4trace: -3- shift(``2'', ``3'', ``4'')
6644 @result{}3
6645 @error{}m4trace: -3- shift(``3'', ``4'')
6646 @result{}4
6647 @error{}m4trace: -3- shift(``4'')
6648 @end example
6650 In summary, recursion over list elements is trickier than it appeared at
6651 first glance, but provides a powerful idiom within @code{m4} processing.
6652 As a final demonstration, both list styles are now able to handle
6653 several scenarios that would wreak havoc on the original
6654 implementations.  This points out one other difference between the two
6655 list styles.  @code{foreach} evaluates unquoted list elements only once,
6656 in preparation for calling @code{@w{_foreach}}.  But @code{foreachq}
6657 evaluates unquoted list elements twice while visiting the first list
6658 element, once in @code{@w{_arg1q}} and once in @code{@w{_rest}}.  When
6659 deciding which list style to use, one must take into account whether
6660 repeating the side effects of unquoted list elements will have any
6661 detrimental effects.
6663 @example
6664 $ @kbd{m4 -I examples}
6665 include(`foreach2.m4')
6666 @result{}
6667 include(`foreachq2.m4')
6668 @result{}
6669 dnl 0-element list:
6670 foreach(`x', `', `<x>') / foreachq(`x', `', `<x>')
6671 @result{} /@w{ }
6672 dnl 1-element list of empty element
6673 foreach(`x', `()', `<x>') / foreachq(`x', ``'', `<x>')
6674 @result{}<> / <>
6675 dnl 2-element list of empty elements
6676 foreach(`x', `(`',`')', `<x>') / foreachq(`x', ``',`'', `<x>')
6677 @result{}<><> / <><>
6678 dnl 1-element list of a comma
6679 foreach(`x', `(`,')', `<x>') / foreachq(`x', ``,'', `<x>')
6680 @result{}<,> / <,>
6681 dnl 2-element list of unbalanced parentheses
6682 foreach(`x', `(`(', `)')', `<x>') / foreachq(`x', ``(', `)'', `<x>')
6683 @result{}<(><)> / <(><)>
6684 define(`active', `ACT, IVE')
6685 @result{}
6686 traceon(`active')
6687 @result{}
6688 dnl list of unquoted macros; expansion occurs before recursion
6689 foreach(`x', `(active, active)', `<x>
6690 ')dnl
6691 @error{}m4trace: -4- active -> `ACT, IVE'
6692 @error{}m4trace: -4- active -> `ACT, IVE'
6693 @result{}<ACT>
6694 @result{}<IVE>
6695 @result{}<ACT>
6696 @result{}<IVE>
6697 foreachq(`x', `active, active', `<x>
6698 ')dnl
6699 @error{}m4trace: -3- active -> `ACT, IVE'
6700 @error{}m4trace: -3- active -> `ACT, IVE'
6701 @result{}<ACT>
6702 @error{}m4trace: -3- active -> `ACT, IVE'
6703 @error{}m4trace: -3- active -> `ACT, IVE'
6704 @result{}<IVE>
6705 @result{}<ACT>
6706 @result{}<IVE>
6707 dnl list of quoted macros; expansion occurs during recursion
6708 foreach(`x', `(`active', `active')', `<x>
6709 ')dnl
6710 @error{}m4trace: -1- active -> `ACT, IVE'
6711 @result{}<ACT, IVE>
6712 @error{}m4trace: -1- active -> `ACT, IVE'
6713 @result{}<ACT, IVE>
6714 foreachq(`x', ``active', `active'', `<x>
6715 ')dnl
6716 @error{}m4trace: -1- active -> `ACT, IVE'
6717 @result{}<ACT, IVE>
6718 @error{}m4trace: -1- active -> `ACT, IVE'
6719 @result{}<ACT, IVE>
6720 dnl list of double-quoted macro names; no expansion
6721 foreach(`x', `(``active'', ``active'')', `<x>
6722 ')dnl
6723 @result{}<active>
6724 @result{}<active>
6725 foreachq(`x', ```active'', ``active''', `<x>
6726 ')dnl
6727 @result{}<active>
6728 @result{}<active>
6729 @end example
6731 @node Improved cleardivert
6732 @section Solution for @code{cleardivert}
6734 The @code{cleardivert} macro (@pxref{Cleardivert}) cannot, as it stands, be
6735 called without arguments to clear all pending diversions.  That is
6736 because using undivert with an empty string for an argument is different
6737 than using it with no arguments at all.  Compare the earlier definition
6738 with one that takes the number of arguments into account:
6740 @example
6741 define(`cleardivert',
6742   `pushdef(`_n', divnum)divert(`-1')undivert($@@)divert(_n)popdef(`_n')')
6743 @result{}
6744 divert(`1')one
6745 divert
6746 @result{}
6747 cleardivert
6748 @result{}
6749 undivert
6750 @result{}one
6751 @result{}
6752 define(`cleardivert',
6753   `pushdef(`_num', divnum)divert(`-1')ifelse(`$#', `0',
6754     `undivert`'', `undivert($@@)')divert(_num)popdef(`_num')')
6755 @result{}
6756 divert(`2')two
6757 divert
6758 @result{}
6759 cleardivert
6760 @result{}
6761 undivert
6762 @result{}
6763 @end example
6765 @node Improved fatal_error
6766 @section Solution for @code{fatal_error}
6768 The @code{fatal_error} macro (@pxref{M4exit}) is not robust to versions
6769 of @acronym{GNU} M4 earlier than 1.4.8, where invoking
6770 @code{@w{__file__}} (@pxref{Location}) inside @code{m4wrap} would result
6771 in an empty string, and @code{@w{__line__}} resulted in @samp{0} even
6772 though all files start at line 1.  Furthermore, versions earlier than
6773 1.4.6 did not support the @code{@w{__program__}} macro.  If you want
6774 @code{fatal_error} to work across the entire 1.4.x release series, a
6775 better implementation would be:
6777 @comment status: 1
6778 @example
6779 define(`fatal_error',
6780   `errprint(ifdef(`__program__', `__program__', ``m4'')'dnl
6781 `:ifelse(__line__, `0', `',
6782     `__file__:__line__:')` fatal error: $*
6783 ')m4exit(`1')')
6784 @result{}
6785 m4wrap(`divnum(`demo of internal message')
6786 fatal_error(`inside wrapped text')')
6787 @result{}
6789 @error{}m4:stdin:6: Warning: excess arguments to builtin `divnum' ignored
6790 @result{}0
6791 @error{}m4:stdin:6: fatal error: inside wrapped text
6792 @end example
6794 @c ========================================================== Appendices
6796 @node Copying This Package
6797 @appendix How to make copies of the overall M4 package
6798 @cindex License, code
6800 This appendix covers the license for copying the source code of the
6801 overall M4 package.  This manual is under a different set of
6802 restrictions, covered later (@pxref{Copying This Manual}).
6804 @menu
6805 * GNU General Public License::  License for copying the M4 package
6806 @end menu
6808 @node GNU General Public License
6809 @appendixsec License for copying the M4 package
6810 @cindex GPL, GNU General Public License
6811 @cindex GNU General Public License
6812 @cindex General Public License (GPL), GNU
6813 @include gpl-3.0.texi
6815 @node Copying This Manual
6816 @appendix How to make copies of this manual
6817 @cindex License, manual
6819 This appendix covers the license for copying this manual.  Note that
6820 some of the longer examples in this manual are also distributed in the
6821 directory @file{m4-@value{VERSION}/@/examples/}, where a more
6822 permissive license is in effect when copying just the examples.
6824 @menu
6825 * GNU Free Documentation License::  License for copying this manual
6826 @end menu
6828 @node GNU Free Documentation License
6829 @appendixsec License for copying this manual
6830 @cindex FDL, GNU Free Documentation License
6831 @cindex GNU Free Documentation License
6832 @cindex Free Documentation License (FDL), GNU
6833 @include fdl.texi
6835 @node Indices
6836 @appendix Indices of concepts and macros
6838 @menu
6839 * Macro index::                 Index for all @code{m4} macros
6840 * Concept index::               Index for many concepts
6841 @end menu
6843 @node Macro index
6844 @appendixsec Index for all @code{m4} macros
6846 This index covers all @code{m4} builtins, as well as several useful
6847 composite macros.  References are exclusively to the places where a
6848 macro is introduced the first time.
6850 @printindex fn
6852 @node Concept index
6853 @appendixsec Index for many concepts
6855 @printindex cp
6857 @bye
6859 @c Local Variables:
6860 @c coding: iso-8859-1
6861 @c fill-column: 72
6862 @c ispell-local-dictionary: "american"
6863 @c indent-tabs-mode: nil
6864 @c whitespace-check-buffer-indent: nil
6865 @c End: