m4: avoid spurious output with unrecognized format specifiers.
[m4/ericb.git] / doc / m4.texi
blob06d871db37d7961c849bc2be6e8b74a96115da0c
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 @set beta
15 @c @tabchar{}
16 @c ----------
17 @c The testsuite expects literal tab output in some examples, but
18 @c literal tabs in texinfo leads to formatting issues.
19 @macro tabchar
20 @       @c
21 @end macro
23 @c @ovar{ARG}
24 @c -------------------
25 @c The ARG is an optional argument.  To be used for macro arguments in
26 @c their documentation (@defmac).
27 @macro ovar{varname}
28 @r{[}@var{\varname\}@r{]}@c
29 @end macro
31 @c @dvar{ARG, DEFAULT}
32 @c -------------------
33 @c The ARG is an optional argument, defaulting to DEFAULT.  To be used
34 @c for macro arguments in their documentation (@defmac).
35 @macro dvar{varname, default}
36 @r{[}@var{\varname\} = @samp{\default\}@r{]}@c
37 @end macro
39 @comment %**end of header
40 @comment ========================================================
42 @copying
44 This manual (@value{UPDATED}) is for GNU M4 (version
45 @value{VERSION}), a package containing an implementation of the m4 macro
46 language.
48 Copyright @copyright{} 1989, 1990, 1991, 1992, 1993, 1994, 1998, 1999,
49 2000, 2001, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software
50 Foundation, Inc.
52 @quotation
53 Permission is granted to copy, distribute and/or modify this document
54 under the terms of the GNU Free Documentation License,
55 Version 1.3 or any later version published by the Free Software
56 Foundation; with no Invariant Sections, no Front-Cover Texts, and no
57 Back-Cover Texts.  A copy of the license is included in the section
58 entitled ``GNU Free Documentation License.''
59 @end quotation
60 @end copying
62 @dircategory Text creation and manipulation
63 @direntry
64 * M4: (m4).                     A powerful macro processor.
65 @end direntry
67 @titlepage
68 @title GNU M4, version @value{VERSION}
69 @subtitle A powerful macro processor
70 @subtitle Edition @value{EDITION}, @value{UPDATED}
71 @author by Ren@'e Seindal, Fran@,{c}ois Pinard,
72 @author Gary V. Vaughan, and Eric Blake
73 @author (@email{bug-m4@@gnu.org})
75 @page
76 @vskip 0pt plus 1filll
77 @insertcopying
78 @end titlepage
80 @contents
82 @ifnottex
83 @node Top
84 @top GNU M4
85 @insertcopying
86 @end ifnottex
88 GNU @code{m4} is an implementation of the traditional UNIX macro
89 processor.  It is mostly SVR4 compatible, although it has some
90 extensions (for example, handling more than 9 positional parameters
91 to macros).  @code{m4} also has builtin functions for including
92 files, running shell commands, doing arithmetic, etc.  Autoconf needs
93 GNU @code{m4} for generating @file{configure} scripts, but not for
94 running them.
96 GNU @code{m4} was originally written by Ren@'e Seindal, with
97 subsequent changes by Fran@,{c}ois Pinard and other volunteers
98 on the Internet.  All names and email addresses can be found in the
99 files @file{m4-@value{VERSION}/@/AUTHORS} and
100 @file{m4-@value{VERSION}/@/THANKS} from the GNU M4
101 distribution.
103 @ifclear beta
104 This is release @value{VERSION}.  It is now considered stable:  future
105 releases on this branch are only meant to fix bugs, increase speed, or
106 improve documentation.
107 @end ifclear
109 @ifset beta
110 This is BETA release @value{VERSION}.  This is a development release,
111 and as such, is prone to bugs, crashes, unforeseen features, incomplete
112 documentation@dots{}, therefore, use at your own peril.  In case of
113 problems, please do not hesitate to report them (see the
114 @file{m4-@value{VERSION}/@/README} file in the distribution).
115 @xref{Experiments}.
116 @end ifset
118 @menu
119 * Preliminaries::               Introduction and preliminaries
120 * Invoking m4::                 Invoking @code{m4}
121 * Syntax::                      Lexical and syntactic conventions
123 * Macros::                      How to invoke macros
124 * Definitions::                 How to define new macros
125 * Conditionals::                Conditionals, loops, and recursion
127 * Debugging::                   How to debug macros and input
129 * Input Control::               Input control
130 * File Inclusion::              File inclusion
131 * Diversions::                  Diverting and undiverting output
133 * Modules::                     Extending M4 with dynamic runtime modules
135 * Text handling::               Macros for text handling
136 * Arithmetic::                  Macros for doing arithmetic
137 * Shell commands::              Macros for running shell commands
138 * Miscellaneous::               Miscellaneous builtin macros
139 * Frozen files::                Fast loading of frozen state
141 * Compatibility::               Compatibility with other versions of @code{m4}
142 * Answers::                     Correct version of some examples
144 * Copying This Package::        How to make copies of the overall M4 package
145 * Copying This Manual::         How to make copies of this manual
146 * Indices::                     Indices of concepts and macros
148 @detailmenu
149  --- The Detailed Node Listing ---
151 Introduction and preliminaries
153 * Intro::                       Introduction to @code{m4}
154 * History::                     Historical references
155 * Bugs::                        Problems and bugs
156 * Manual::                      Using this manual
158 Invoking @code{m4}
160 * Operation modes::             Command line options for operation modes
161 * Preprocessor features::       Command line options for preprocessor features
162 * Limits control::              Command line options for limits control
163 * Frozen state::                Command line options for frozen state
164 * Debugging options::           Command line options for debugging
165 * Command line files::          Specifying input files on the command line
167 Lexical and syntactic conventions
169 * Names::                       Macro names
170 * Quoted strings::              Quoting input to @code{m4}
171 * Comments::                    Comments in @code{m4} input
172 * Other tokens::                Other kinds of input tokens
173 * Input processing::            How @code{m4} copies input to output
174 * Regular expression syntax::   How @code{m4} interprets regular expressions
176 How to invoke macros
178 * Invocation::                  Macro invocation
179 * Inhibiting Invocation::       Preventing macro invocation
180 * Macro Arguments::             Macro arguments
181 * Quoting Arguments::           On Quoting Arguments to macros
182 * Macro expansion::             Expanding macros
184 How to define new macros
186 * Define::                      Defining a new macro
187 * Arguments::                   Arguments to macros
188 * Pseudo Arguments::            Special arguments to macros
189 * Undefine::                    Deleting a macro
190 * Defn::                        Renaming macros
191 * Pushdef::                     Temporarily redefining macros
192 * Renamesyms::                  Renaming macros with regular expressions
194 * Indir::                       Indirect call of macros
195 * Builtin::                     Indirect call of builtins
196 * M4symbols::                   Getting the defined macro names
198 Conditionals, loops, and recursion
200 * Ifdef::                       Testing if a macro is defined
201 * Ifelse::                      If-else construct, or multibranch
202 * Shift::                       Recursion in @code{m4}
203 * Forloop::                     Iteration by counting
204 * Foreach::                     Iteration by list contents
205 * Stacks::                      Working with definition stacks
206 * Composition::                 Building macros with macros
208 How to debug macros and input
210 * Dumpdef::                     Displaying macro definitions
211 * Trace::                       Tracing macro calls
212 * Debugmode::                   Controlling debugging options
213 * Debuglen::                    Limiting debug output
214 * Debugfile::                   Saving debugging output
216 Input control
218 * Dnl::                         Deleting whitespace in input
219 * Changequote::                 Changing the quote characters
220 * Changecom::                   Changing the comment delimiters
221 * Changeresyntax::              Changing the regular expression syntax
222 * Changesyntax::                Changing the lexical structure of the input
223 * M4wrap::                      Saving text until end of input
225 File inclusion
227 * Include::                     Including named files
228 * Search Path::                 Searching for include files
230 Diverting and undiverting output
232 * Divert::                      Diverting output
233 * Undivert::                    Undiverting output
234 * Divnum::                      Diversion numbers
235 * Cleardivert::                 Discarding diverted text
237 Extending M4 with dynamic runtime modules
239 * M4modules::                   Listing loaded modules
240 * Unload::                      Removing loaded modules
241 * Refcount::                    Tracking module references
242 * Standard Modules::            Standard bundled modules
244 Macros for text handling
246 * Len::                         Calculating length of strings
247 * Index macro::                 Searching for substrings
248 * Regexp::                      Searching for regular expressions
249 * Substr::                      Extracting substrings
250 * Translit::                    Translating characters
251 * Patsubst::                    Substituting text by regular expression
252 * Format::                      Formatting strings (printf-like)
254 Macros for doing arithmetic
256 * Incr::                        Decrement and increment operators
257 * Eval::                        Evaluating integer expressions
258 * Mpeval::                      Multiple precision arithmetic
260 Macros for running shell commands
262 * Platform macros::             Determining the platform
263 * Syscmd::                      Executing simple commands
264 * Esyscmd::                     Reading the output of commands
265 * Sysval::                      Exit status
266 * Mkstemp::                     Making temporary files
267 * Mkdtemp::                     Making temporary directories
269 Miscellaneous builtin macros
271 * Errprint::                    Printing error messages
272 * Location::                    Printing current location
273 * M4exit::                      Exiting from @code{m4}
274 * Syncoutput::                  Turning on and off sync lines
276 Fast loading of frozen state
278 * Using frozen files::          Using frozen files
279 * Frozen file format 1::        Frozen file format 1
280 * Frozen file format 2::        Frozen file format 2
282 Compatibility with other versions of @code{m4}
284 * Extensions::                  Extensions in GNU M4
285 * Incompatibilities::           Other incompatibilities
286 * Experiments::                 Experimental features in GNU M4
288 Correct version of some examples
290 * Improved exch::               Solution for @code{exch}
291 * Improved forloop::            Solution for @code{forloop}
292 * Improved foreach::            Solution for @code{foreach}
293 * Improved copy::               Solution for @code{copy}
294 * Improved m4wrap::             Solution for @code{m4wrap}
295 * Improved cleardivert::        Solution for @code{cleardivert}
296 * Improved capitalize::         Solution for @code{capitalize}
297 * Improved fatal_error::        Solution for @code{fatal_error}
299 How to make copies of the overall M4 package
301 * GNU General Public License::  License for copying the M4 package
303 How to make copies of this manual
305 * GNU Free Documentation License::  License for copying this manual
307 Indices of concepts and macros
309 * Macro index::                 Index for all @code{m4} macros
310 * Concept index::               Index for many concepts
312 @end detailmenu
313 @end menu
315 @node Preliminaries
316 @chapter Introduction and preliminaries
318 This first chapter explains what GNU @code{m4} is, where @code{m4}
319 comes from, how to read and use this documentation, how to call the
320 @code{m4} program, and how to report bugs about it.  It concludes by
321 giving tips for reading the remainder of the manual.
323 The following chapters then detail all the features of the @code{m4}
324 language, as shipped in the GNU M4 package.
326 @menu
327 * Intro::                       Introduction to @code{m4}
328 * History::                     Historical references
329 * Bugs::                        Problems and bugs
330 * Manual::                      Using this manual
331 @end menu
333 @node Intro
334 @section Introduction to @code{m4}
336 @cindex overview of @code{m4}
337 @code{m4} is a macro processor, in the sense that it copies its
338 input to the output, expanding macros as it goes.  Macros are either
339 builtin or user-defined, and can take any number of arguments.
340 Besides just doing macro expansion, @code{m4} has builtin functions
341 for including named files, running shell commands, doing integer
342 arithmetic, manipulating text in various ways, performing recursion,
343 etc.@dots{}  @code{m4} can be used either as a front-end to a compiler,
344 or as a macro processor in its own right.
346 The @code{m4} macro processor is widely available on all UNIXes, and has
347 been standardized by POSIX.
348 Usually, only a small percentage of users are aware of its existence.
349 However, those who find it often become committed users.  The
350 popularity of GNU Autoconf, which requires GNU
351 @code{m4} for @emph{generating} @file{configure} scripts, is an incentive
352 for many to install it, while these people will not themselves
353 program in @code{m4}.  GNU @code{m4} is mostly compatible with the
354 System V, Release 3 version, except for some minor differences.
355 @xref{Compatibility}, for more details.
357 Some people find @code{m4} to be fairly addictive.  They first use
358 @code{m4} for simple problems, then take bigger and bigger challenges,
359 learning how to write complex sets of @code{m4} macros along the way.
360 Once really addicted, users pursue writing of sophisticated @code{m4}
361 applications even to solve simple problems, devoting more time
362 debugging their @code{m4} scripts than doing real work.  Beware that
363 @code{m4} may be dangerous for the health of compulsive programmers.
365 @node History
366 @section Historical references
368 @cindex history of @code{m4}
369 @cindex GNU M4, history of
370 @code{GPM} was an important ancestor of @code{m4}.  See
371 C. Strachey: ``A General Purpose Macro generator'', Computer Journal
372 8,3 (1965), pp.@: 225 ff.  @code{GPM} is also succinctly described into
373 David Gries classic ``Compiler Construction for Digital Computers''.
375 The classic B. Kernighan and P.J. Plauger: ``Software Tools'',
376 Addison-Wesley, Inc.@: (1976) describes and implements a Unix
377 macro-processor language, which inspired Dennis Ritchie to write
378 @code{m3}, a macro processor for the AP-3 minicomputer.
380 Kernighan and Ritchie then joined forces to develop the original
381 @code{m4}, as described in ``The M4 Macro Processor'', Bell
382 Laboratories (1977).  It had only 21 builtin macros.
384 While @code{GPM} was more @emph{pure}, @code{m4} is meant to deal with
385 the true intricacies of real life: macros can be recognized without
386 being pre-announced, skipping whitespace or end-of-lines is easier,
387 more constructs are builtin instead of derived, etc.
389 Originally, the Kernighan and Plauger macro-processor, and then
390 @code{m3}, formed the engine for the Rational FORTRAN preprocessor,
391 that is, the @code{Ratfor} equivalent of @code{cpp}.  Later, @code{m4}
392 was used as a front-end for @code{Ratfor}, @code{C} and @code{Cobol}.
394 Ren@'e Seindal released his implementation of @code{m4}, GNU
395 @code{m4},
396 in 1990, with the aim of removing the artificial limitations in many
397 of the traditional @code{m4} implementations, such as maximum line
398 length, macro size, or number of macros.
400 The late Professor A. Dain Samples described and implemented a further
401 evolution in the form of @code{M5}: ``User's Guide to the M5 Macro
402 Language: 2nd edition'', Electronic Announcement on comp.compilers
403 newsgroup (1992).
405 Fran@,{c}ois Pinard took over maintenance of GNU @code{m4} in
406 1992, until 1994 when he released GNU @code{m4} 1.4, which was
407 the stable release for 10 years.  It was at this time that GNU
408 Autoconf decided to require GNU @code{m4} as its underlying
409 engine, since all other implementations of @code{m4} had too many
410 limitations.
412 More recently, in 2004, Paul Eggert released 1.4.1 and 1.4.2 which
413 addressed some long standing bugs in the venerable 1.4 release.  Then in
414 2005, Gary V. Vaughan collected together the many patches to
415 GNU @code{m4} 1.4 that were floating around the net and
416 released 1.4.3 and 1.4.4.  And in 2006, Eric Blake joined the team and
417 prepared patches for the release of 1.4.5, 1.4.6, 1.4.7, and 1.4.8.
418 More bug fixes were incorporated in 2007, with releases 1.4.9 and
419 1.4.10.  Eric continued with some portability fixes for 1.4.11 and
420 1.4.12 in 2008, and 1.4.13 in 2009.
422 Additionally, in 2008, Eric rewrote the scanning engine to reduce
423 recursive evaluation from quadratic to linear complexity.  This was
424 released as M4 1.6 in 2009.  The 1.x branch series remains open for bug
425 fixes.
427 Meanwhile, development was underway for new features for @code{m4},
428 such as dynamic module loading and additional builtins, practically
429 rewriting the entire code base.  This development has spurred
430 improvements to other GNU software, such as GNU
431 Libtool.  GNU M4 2.0 is the result of this effort.
433 @node Bugs
434 @section Problems and bugs
436 @cindex reporting bugs
437 @cindex bug reports
438 @cindex suggestions, reporting
439 If you have problems with GNU M4 or think you've found a bug,
440 please report it.  Before reporting a bug, make sure you've actually
441 found a real bug.  Carefully reread the documentation and see if it
442 really says you can do what you're trying to do.  If it's not clear
443 whether you should be able to do something or not, report that too; it's
444 a bug in the documentation!
446 Before reporting a bug or trying to fix it yourself, try to isolate it
447 to the smallest possible input file that reproduces the problem.  Then
448 send us the input file and the exact results @code{m4} gave you.  Also
449 say what you expected to occur; this will help us decide whether the
450 problem was really in the documentation.
452 Once you've got a precise problem, send e-mail to
453 @email{bug-m4@@gnu.org}.  Please include the version number of @code{m4}
454 you are using.  You can get this information with the command
455 @kbd{m4 --version}.  You can also run @kbd{make check} to generate the
456 file @file{tests/@/testsuite.log}, useful for including in your report.
458 Non-bug suggestions are always welcome as well.  If you have questions
459 about things that are unclear in the documentation or are just obscure
460 features, please report them too.
462 @node Manual
463 @section Using this manual
465 @cindex examples, understanding
466 This manual contains a number of examples of @code{m4} input and output,
467 and a simple notation is used to distinguish input, output and error
468 messages from @code{m4}.  Examples are set out from the normal text, and
469 shown in a fixed width font, like this
471 @comment ignore
472 @example
473 This is an example of an example!
474 @end example
476 To distinguish input from output, all output from @code{m4} is prefixed
477 by the string @samp{@result{}}, and all error messages by the string
478 @samp{@error{}}.  When showing how command line options affect matters,
479 the command line is shown with a prompt @samp{$ @kbd{like this}},
480 otherwise, you can assume that a simple @kbd{m4} invocation will work.
481 Thus:
483 @comment ignore
484 @example
485 $ @kbd{command line to invoke m4}
486 Example of input line
487 @result{}Output line from m4
488 @error{}and an error message
489 @end example
491 The sequence @samp{^D} in an example indicates the end of the input
492 file.  The sequence @samp{@key{NL}} refers to the newline character.
493 The majority of these examples are self-contained, and you can run them
494 with similar results.  In fact, the testsuite that is bundled in the
495 GNU M4 package consists in part of the examples
496 in this document!  Some of the examples assume that your current
497 directory is located where you unpacked the installation, so if you plan
498 on following along, you may find it helpful to do this now:
500 @comment ignore
501 @example
502 $ @kbd{cd m4-@value{VERSION}}
503 @end example
505 As each of the predefined macros in @code{m4} is described, a prototype
506 call of the macro will be shown, giving descriptive names to the
507 arguments, e.g.,
509 @deffn {Composite (none)} example (@var{string}, @dvar{count, 1}, @
510   @ovar{argument}@dots{})
511 This is a sample prototype.  There is not really a macro named
512 @code{example}, but this documents that if there were, it would be a
513 Composite macro, rather than a Builtin, and would be provided by the
514 module @code{none}.
516 It requires at least one argument, @var{string}.  Remember that in
517 @code{m4}, there must not be a space between the macro name and the
518 opening parenthesis, unless it was intended to call the macro without
519 any arguments.  The brackets around @var{count} and @var{argument} show
520 that these arguments are optional.  If @var{count} is omitted, the macro
521 behaves as if count were @samp{1}, whereas if @var{argument} is omitted,
522 the macro behaves as if it were the empty string.  A blank argument is
523 not the same as an omitted argument.  For example, @samp{example(`a')},
524 @samp{example(`a',`1')}, and @samp{example(`a',`1',)} would behave
525 identically with @var{count} set to @samp{1}; while @samp{example(`a',)}
526 and @samp{example(`a',`')} would explicitly pass the empty string for
527 @var{count}.  The ellipses (@samp{@dots{}}) show that the macro
528 processes additional arguments after @var{argument}, rather than
529 ignoring them.
530 @end deffn
532 Each builtin definition will list, in parentheses, the module that must
533 be loaded to use that macro.  The standard modules include
534 @samp{m4} (which is always available), @samp{gnu} (for GNU specific
535 m4 extensions), and @samp{traditional} (for compatibility with System V
536 m4).  @xref{Modules}.
538 @cindex numbers
539 All macro arguments in @code{m4} are strings, but some are given
540 special interpretation, e.g., as numbers, file names, regular
541 expressions, etc.  The documentation for each macro will state how the
542 parameters are interpreted, and what happens if the argument cannot be
543 parsed according to the desired interpretation.  Unless specified
544 otherwise, a parameter specified to be a number is parsed as a decimal,
545 even if the argument has leading zeros; and parsing the empty string as
546 a number results in 0 rather than an error, although a warning will be
547 issued.
549 This document consistently writes and uses @dfn{builtin}, without a
550 hyphen, as if it were an English word.  This is how the @code{builtin}
551 primitive is spelled within @code{m4}.
553 @node Invoking m4
554 @chapter Invoking @code{m4}
556 @cindex command line
557 @cindex invoking @code{m4}
558 The format of the @code{m4} command is:
560 @comment ignore
561 @example
562 @code{m4} @r{[}@var{option}@dots{}@r{]} @r{[}@var{file}@dots{}@r{]}
563 @end example
565 @cindex command line, options
566 @cindex options, command line
567 @cindex @env{POSIXLY_CORRECT}
568 All options begin with @samp{-}, or if long option names are used, with
569 @samp{--}.  A long option name need not be written completely, any
570 unambiguous prefix is sufficient.  POSIX requires @code{m4} to
571 recognize arguments intermixed with files, even when
572 @env{POSIXLY_CORRECT} is set in the environment.  Most options take
573 effect at startup regardless of their position, but some are documented
574 below as taking effect after any files that occurred earlier in the
575 command line.  The argument @option{--} is a marker to denote the end of
576 options.
578 With short options, options that do not take arguments may be combined
579 into a single command line argument with subsequent options, options
580 with mandatory arguments may be provided either as a single command line
581 argument or as two arguments, and options with optional arguments must
582 be provided as a single argument.  In other words,
583 @kbd{m4 -QPDfoo -d a -d+f} is equivalent to
584 @kbd{m4 -Q -P -D foo -d ./a -d+f}, although the latter form is
585 considered canonical.
587 With long options, options with mandatory arguments may be provided with
588 an equal sign (@samp{=}) in a single argument, or as two arguments, and
589 options with optional arguments must be provided as a single argument.
590 In other words, @kbd{m4 --def foo --debug a} is equivalent to
591 @kbd{m4 --define=foo --debug= -- ./a}, although the latter form is
592 considered canonical (not to mention more robust, in case a future
593 version of @code{m4} introduces an option named @option{--default}).
595 @code{m4} understands the following options, grouped by functionality.
597 @menu
598 * Operation modes::             Command line options for operation modes
599 * Preprocessor features::       Command line options for preprocessor features
600 * Limits control::              Command line options for limits control
601 * Frozen state::                Command line options for frozen state
602 * Debugging options::           Command line options for debugging
603 * Command line files::          Specifying input files on the command line
604 @end menu
606 @node Operation modes
607 @section Command line options for operation modes
609 Several options control the overall operation of @code{m4}:
611 @table @code
612 @item --help
613 Print a help summary on standard output, then immediately exit
614 @code{m4} without reading any input files or performing any other
615 actions.
617 @item --version
618 Print the version number of the program on standard output, then
619 immediately exit @code{m4} without reading any input files or
620 performing any other actions.
622 @item -b
623 @itemx --batch
624 Makes this invocation of @code{m4} non-interactive.  This means that
625 output will be buffered, and an interrupt or pipe write error will halt
626 execution.  If neither
627 @option{-b} nor @option{-i} are specified, this is activated by default
628 when any input files are specified, or when either standard input or
629 standard error is not a terminal.  Note that this means that @kbd{m4}
630 alone might be interactive, but @kbd{m4 -} is not, even though both
631 commands process only standard input.  If both @option{-b} and
632 @option{-i} are specified, only the last one takes effect.
634 @item -c
635 @itemx --discard-comments
636 Discard all comments instead of copying them to the output.
638 @item -E
639 @itemx --fatal-warnings
640 @cindex errors, fatal
641 @cindex fatal errors
642 Controls the effect of warnings.  If unspecified, then execution
643 continues and exit status is unaffected when a warning is printed.  If
644 specified exactly once, warnings become fatal; when one is issued,
645 execution continues, but the exit status will be non-zero.  If specified
646 multiple times, then execution halts with non-zero status the first time
647 a warning is issued.  The introduction of behavior levels is new to M4
648 1.4.9; for behavior consistent with earlier versions, you should specify
649 @option{-E} twice.
652 For backwards compatibility reasons, using @option{-E} behaves as if an
653 implicit @option{--debug=-d} option is also present.  This is so that
654 scripts written for older M4 versions will not fail if they used
655 constructs that were previously silently allowed, but would now trigger
656 a warning.
658 @example
659 $ @kbd{m4}
660 defn(`oops')
661 @error{}m4:stdin:1: warning: defn: undefined macro 'oops'
662 @result{}
664 @end example
666 @comment ignore
667 @example
668 $ @kbd{echo $?}
669 @result{}0
670 @end example
672 @comment options: -E
673 @example
674 $ @kbd{m4 -E}
675 defn(`oops')
676 @result{}
678 @end example
680 @comment ignore
681 @example
682 $ @kbd{echo $?}
683 @result{}0
684 @end example
686 @comment options: -E -d
687 @comment status: 1
688 @example
689 $ @kbd{m4 -E -d}
690 defn(`oops')
691 @error{}m4:stdin:1: warning: defn: undefined macro 'oops'
692 @result{}
694 @end example
696 @comment ignore
697 @example
698 $ @kbd{echo $?}
699 @result{}1
700 @end example
702 @item -i
703 @itemx --interactive
704 @itemx -e
705 Makes this invocation of @code{m4} interactive.  This means that all
706 output will be unbuffered, interrupts will be ignored, and behavior on
707 pipe write errors is inherited from the parent process.  If neither
708 @option{-b} nor @option{-i} are specified, this is activated by default
709 when no input files are specified, and when both standard input and
710 standard error are terminals (similar to the way that /bin/sh determines
711 when to be interactive).  If both @option{-b} and @option{-i} are
712 specified, only the last one takes effect.  The spelling @option{-e}
713 exists for compatibility with other @code{m4} implementations, and
714 issues a warning because it may be withdrawn in a future version of
715 GNU M4.
717 @item -P
718 @itemx --prefix-builtins
719 Internally modify @emph{all} builtin macro names so they all start with
720 the prefix @samp{m4_}.  For example, using this option, one should write
721 @samp{m4_define} instead of @samp{define}, and @samp{@w{m4___file__}}
722 instead of @samp{@w{__file__}}.  This option has no effect if @option{-R}
723 is also specified.
725 @item -Q
726 @itemx --quiet
727 @itemx --silent
728 Suppress warnings, such as missing or superfluous arguments in macro
729 calls, or treating the empty string as zero.  Error messages are still
730 printed.  The distinction between error and warning is fuzzy, and if
731 you encounter a situation where the message output did not match your
732 expectations, please report that as a bug.  This option is implied if
733 @env{POSIXLY_CORRECT} is set in the environment.
735 @item -r@r{[}@var{resyntax-spec}@r{]}
736 @itemx --regexp-syntax@r{[}=@var{resyntax-spec}@r{]}
737 Set the regular expression syntax according to @var{resyntax-spec}.
738 When this option is not given, or @var{resyntax-spec} is omitted,
739 GNU M4 uses the flavor @code{GNU_M4}, which provides
740 emacs-compatible regular expressions.  @xref{Changeresyntax}, for more
741 details on the format and meaning of @var{resyntax-spec}.  This option
742 may be given more than once, and order with respect to file names is
743 significant.
745 @item --safer
746 Cripple the following builtins, since each can perform potentially
747 unsafe actions: @code{maketemp}, @code{mkstemp} (@pxref{Mkstemp}),
748 @code{mkdtemp} (@pxref{Mkdtemp}), @code{debugfile} (@pxref{Debugfile}),
749 @code{syscmd} (@pxref{Syscmd}), and @code{esyscmd} (@pxref{Esyscmd}).
750 An attempt to use any of these macros will result in an error.  This
751 option is intended to make it safer to preprocess an input file of
752 unknown origin.
754 @item -W
755 @itemx --warnings
756 Enable warnings.  Warnings are on by default unless
757 @env{POSIXLY_CORRECT} was set in the environment; this option exists to
758 allow overriding @option{--silent}.
759 @comment FIXME should we accept -Wall, -Wnone, -Wcategory,
760 @comment -Wno-category...?
761 @end table
763 @node Preprocessor features
764 @section Command line options for preprocessor features
766 @cindex macro definitions, on the command line
767 @cindex command line, macro definitions on the
768 @cindex preprocessor features
769 Several options allow @code{m4} to behave more like a preprocessor.
770 Macro definitions and deletions can be made on the command line, the
771 search path can be altered, and the output file can track where the
772 input came from.  These features occur with the following options:
774 @table @code
775 @item -B @var{directory}
776 @itemx --prepend-include=@var{directory}
777 Make @code{m4} search @var{directory} for included files, prior to
778 searching the current working directory.  @xref{Search Path}, for more
779 details.  This option may be given more than once.  Some other
780 implementations of @code{m4} use @option{-B @var{number}} to change their
781 hard-coded limits, but that is unnecessary in GNU where the
782 only limit is your hardware capability.  So although it is unlikely that
783 you will want to include a relative directory whose name is purely
784 numeric, GNU @code{m4} will warn you about this potential
785 compatibility issue; you can avoid the warning by using the long
786 spelling, or by using @samp{./@var{number}} if you really meant it.
788 @item -D @var{name}@r{[}=@var{value}@r{]}
789 @itemx --define=@var{name}@r{[}=@var{value}@r{]}
790 This enters @var{name} into the symbol table.  If @samp{=@var{value}} is
791 missing, the value is taken to be the empty string.  The @var{value} can
792 be any string, and the macro can be defined to take arguments, just as
793 if it was defined from within the input.  This option may be given more
794 than once; order with respect to file names is significant, and
795 redefining the same @var{name} loses the previous value.
797 @item --import-environment
798 Imports every variable in the environment as a macro.  This is done
799 before @option{-D} and @option{-U}, so they can override the
800 environment.
802 @item -I @var{directory}
803 @itemx --include=@var{directory}
804 Make @code{m4} search @var{directory} for included files that are not
805 found in the current working directory.  @xref{Search Path}, for more
806 details.  This option may be given more than once.
808 @item --popdef=@var{name}
809 This deletes the top-most meaning @var{name} might have.  Obviously,
810 only predefined macros can be deleted in this way.  This option may be
811 given more than once; popping a @var{name} that does not have a
812 definition is silently ignored.  Order is significant with respect to
813 file names.
815 @item -p @var{name}@r{[}=@var{value}@r{]}
816 @itemx --pushdef=@var{name}@r{[}=@var{value}@r{]}
817 This enters @var{name} into the symbol table.  If @samp{=@var{value}} is
818 missing, the value is taken to be the empty string.  The @var{value} can
819 be any string, and the macro can be defined to take arguments, just as
820 if it was defined from within the input.  This option may be given more
821 than once; order with respect to file names is significant, and
822 redefining the same @var{name} adds another definition to its stack.
824 @item -s
825 @itemx --synclines
826 Short for @option{--syncoutput=1}, turning on synchronization lines
827 (sometimes called @dfn{synclines}).
829 @item --syncoutput@r{[}=@var{state}@r{]}
830 @cindex synchronization lines
831 @cindex location, input
832 @cindex input location
833 Control the generation of synchronization lines from the command line.
834 Synchronization lines are for use by the C preprocessor or other
835 similar tools.  Order is significant with respect to file names.  This
836 option is useful, for example, when @code{m4} is used as a
837 front end to a compiler.  Source file name and line number information
838 is conveyed by directives of the form @samp{#line @var{linenum}
839 "@var{file}"}, which are inserted as needed into the middle of the
840 output.  Such directives mean that the following line originated or was
841 expanded from the contents of input file @var{file} at line
842 @var{linenum}.  The @samp{"@var{file}"} part is often omitted when
843 the file name did not change from the previous directive.
845 Synchronization directives are always given on complete lines by
846 themselves.  When a synchronization discrepancy occurs in the middle of
847 an output line, the associated synchronization directive is delayed
848 until the next newline that does not occur in the middle of a quoted
849 string or comment.  @xref{Syncoutput}, for runtime control.  @var{state}
850 is interpreted the same as the argument to @code{syncoutput}; if
851 @var{state} is omitted, or @option{--syncoutput} is not used,
852 synchronization lines are disabled.
854 @item -U @var{name}
855 @itemx --undefine=@var{name}
856 This deletes any predefined meaning @var{name} might have.  Obviously,
857 only predefined macros can be deleted in this way.  This option may be
858 given more than once; undefining a @var{name} that does not have a
859 definition is silently ignored.  Order is significant with respect to
860 file names.
861 @end table
863 @node Limits control
864 @section Command line options for limits control
866 There are some limits within @code{m4} that can be tuned.  For
867 compatibility, @code{m4} also accepts some options that control limits
868 in other implementations, but which are automatically unbounded (limited
869 only by your hardware and operating system constraints) in GNU
870 @code{m4}.
872 @table @code
873 @item -g
874 @itemx --gnu
875 Enable all the extensions in this implementation.  This is on by
876 default unless @env{POSIXLY_CORRECT} is set in the environment; it
877 exists to allow overriding @option{--traditional}.
879 @item -G
880 @itemx --posix
881 @itemx --traditional
882 Suppress all the extensions made in this implementation, compared to the
883 System V version.  @xref{Compatibility}, for a list of these.  This
884 loads the @samp{traditional} module in place of the @samp{gnu} module.
885 It is implied if @env{POSIXLY_CORRECT} is set in the environment.
887 @item -L @var{num}
888 @itemx --nesting-limit=@var{num}
889 @cindex nesting limit
890 @cindex limit, nesting
891 Artificially limit the nesting of macro calls to @var{num} levels,
892 stopping program execution if this limit is ever exceeded.  When not
893 specified, nesting is limited to 1024 levels.  A value of zero means
894 unlimited; but then heavily nested code could potentially cause a stack
895 overflow.  @var{num} can have an optional scaling suffix.
896 @comment FIXME - need a node on what scaling suffixes are supported (see
897 @comment [info coreutils 'block size'] for ideas), and need to consider
898 @comment whether builtins should also understand scaling suffixes:
899 @comment eval, mpeval, perhaps format
901 The precise effect of this option might be more correctly associated
902 with textual nesting than dynamic recursion.  It has been useful
903 when some complex @code{m4} input was generated by mechanical means.
904 Most users would never need this option.  If shown to be obtrusive,
905 this option (which is still experimental) might well disappear.
907 @cindex rescanning
908 This option does @emph{not} have the ability to break endless
909 rescanning loops, since these do not necessarily consume much memory
910 or stack space.  Through clever usage of rescanning loops, one can
911 request complex, time-consuming computations from @code{m4} with useful
912 results.  Putting limitations in this area would break @code{m4} power.
913 There are many pathological cases: @w{@samp{define(`a', `a')a}} is
914 only the simplest example (but @pxref{Compatibility}).  Expecting GNU
915 @code{m4} to detect these would be a little like expecting a compiler
916 system to detect and diagnose endless loops: it is a quite @emph{hard}
917 problem in general, if not undecidable!
919 @item -H @var{num}
920 @itemx --hashsize=@var{num}
921 @itemx --word-regexp=@var{regexp}
922 These options are present only for compatibility with previous versions
923 of GNU @code{m4}.  They do nothing except issue a warning, because the
924 symbol table size is not fixed anymore, and because the new
925 @code{changesyntax} feature is more efficient than the withdrawn
926 experimental @code{changeword}.  These options will eventually disappear
927 in future releases.
929 @item -S @var{num}
930 @itemx -T @var{num}
931 These options are present for compatibility with System V @code{m4}, but
932 do nothing in this implementation.  They may disappear in future
933 releases, and issue a warning to that effect.
934 @end table
936 @node Frozen state
937 @section Command line options for frozen state
939 GNU @code{m4} comes with a feature of freezing internal state
940 (@pxref{Frozen files}).  This can be used to speed up @code{m4}
941 execution when reusing a common initialization script.
943 @table @code
944 @item -F @var{file}
945 @itemx --freeze-state=@var{file}
946 Once execution is finished, write out the frozen state on the specified
947 @var{file}.  It is conventional, but not required, for @var{file} to end
948 in @samp{.m4f}.
950 @item -R @var{file}
951 @itemx --reload-state=@var{file}
952 Before execution starts, recover the internal state from the specified
953 frozen @var{file}.  The options @option{-D}, @option{-U}, @option{-t},
954 @option{-m}, @option{-r}, and @option{--import-environment} take effect
955 after state is reloaded, but before the input files are read.
956 @end table
958 @node Debugging options
959 @section Command line options for debugging
961 Finally, there are several options for aiding in debugging @code{m4}
962 scripts.
964 @table @code
965 @item -d@r{[}@r{[}-@r{|}+@r{]}@var{flags}@r{]}
966 @itemx --debug@r{[}=@r{[}-@r{|}+@r{]}@var{flags}@r{]}
967 @itemx --debugmode@r{[}=@r{[}-@r{|}+@r{]}@var{flags}@r{]}
968 Set the debug-level according to the flags @var{flags}.  The debug-level
969 controls the format and amount of information presented by the debugging
970 functions.  @xref{Debugmode}, for more details on the format and
971 meaning of @var{flags}.  If omitted, @var{flags} defaults to
972 @samp{+adeq}.  If the option occurs multiple times, @var{flags} starting
973 with @samp{-} or @samp{+} are cumulative, while @var{flags} starting
974 with a letter override all earlier settings.  The debug-level starts
975 with @samp{d} enabled and all other flags disabled.  To disable all
976 previously set flags, specify an explicit @var{flags} of @samp{-V}.  For
977 backward compatibility reasons, the option @option{--fatal-warnings}
978 implies @samp{--debug=-d} as part of its effects.  The spelling
979 @option{--debug} is recognized as an unambiguous option for
980 compatibility with earlier versions of GNU M4, but for
981 consistency with the builtin name, you can also use the spelling
982 @option{--debugmode}.  Order is significant with respect to file names.
984 The cumulative effect of the various options in this example is
985 equivalent to a single invocation of @code{debugmode(`adlqx')}:
987 @comment options: -d-V -d+lx --debug --debugmode=-e
988 @example
989 $ @kbd{m4 -d+lx --debug --debugmode=-e}
990 traceon(`len')
991 @result{}
992 len(`123')
993 @error{}m4trace:2: -1- id 2: len(`123')
994 @result{}3
995 @end example
997 @item --debugfile@r{[}=@var{file}@r{]}
998 @itemx -o @var{file}
999 @itemx --error-output=@var{file}
1000 Redirect debug messages and trace output to the
1001 named @var{file}.  Warnings, error messages, and @code{errprint} output
1002 are still printed to standard error.  Output from @code{dumpdef} goes to
1003 this file when the debug level @code{o} is not set (@pxref{Debugmode}).
1004 If these options are not used, or
1005 if @var{file} is unspecified (only possible for @option{--debugfile}),
1006 debug output goes to standard error; if @var{file} is the empty string,
1007 debug output is discarded.  @xref{Debugfile}, for more details.  The
1008 option @option{--debugfile} may be given more than once, and order is
1009 significant with respect to file names.  The spellings @option{-o} and
1010 @option{--error-output} are misleading and
1011 inconsistent with other GNU tools; using those spellings will
1012 evoke a warning, and they may be withdrawn or change semantics in a
1013 future release.
1015 @item -l @var{num}
1016 @itemx --debuglen=@var{num}
1017 @itemx --arglength=@var{num}
1018 Restrict the size of the output generated by macro tracing or by
1019 @code{dumpdef} to @var{num} characters per string.  If unspecified or
1020 zero, output is unlimited.  @xref{Debuglen}, for more details.
1021 @var{num} can have an optional scaling suffix.  The spelling
1022 @option{--arglength} is deprecated, since it does not match the
1023 @code{debuglen} macro; using it will evoke a warning, and it may be
1024 withdrawn in a future release.
1025 @comment FIXME - Should we add an option that controls whether output
1026 @comment strings are sanitized with escape sequences, so that dumpdef is
1027 @comment truly one line per macro?
1028 @comment FIXME - see comment on --nesting-limit about NUM.
1030 @item -t @var{name}
1031 @itemx --trace=@var{name}
1032 @itemx --traceon=@var{name}
1033 This enables tracing for the macro @var{name}, at any point where it is
1034 defined.  @var{name} need not be defined when this option is given.
1035 This option may be given more than once, and order is significant with
1036 respect to file names.  @xref{Trace}, for more details.
1038 @item --traceoff=@var{name}
1039 This disables tracing for the macro @var{name}, at any point where it is
1040 defined.  @var{name} need not be defined when this option is given.
1041 This option may be given more than once, and order is significant with
1042 respect to file names.  @xref{Trace}, for more details.
1043 @end table
1045 @node Command line files
1046 @section Specifying input files on the command line
1048 @cindex command line, file names on the
1049 @cindex file names, on the command line
1050 The remaining arguments on the command line are taken to be input file
1051 names or module names (@pxref{Modules}).  Whether or not any modules
1052 are loaded from command line arguments, when no actual input file names
1053 are given, then standard input is read.  A file name of @file{-} can be
1054 used to denote standard input.  It is conventional, but not required,
1055 for input file names to end in @samp{.m4} and for module names to end
1056 in @samp{.la}.  The input files and modules are attended to in the
1057 sequence given.
1059 Standard input can be read more than once, so the file name @file{-}
1060 may appear multiple times on the command line; this makes a difference
1061 when input is from a terminal or other special file type.  It is an
1062 error if an input file ends in the middle of argument collection, a
1063 comment, or a quoted string.
1064 @comment FIXME - it would be nicer if we let these three things
1065 @comment continue across file boundaries, provided that we warn in
1066 @comment interactive use when switching to stdin in a non-default parse
1067 @comment state.
1069 Various options, such as @option{--define} (@option{-D}), @option{--undefine}
1070 (@option{-U}), @option{--synclines} (@option{-s}), @option{--trace}
1071 (@option{-t}), and @option{--regexp-syntax} (@option{-r}), only take
1072 effect after processing input from any file names that occur earlier
1073 on the command line.  For example, assume the file @file{foo} contains:
1075 @comment file: foo
1076 @example
1077 $ @kbd{cat foo}
1079 @end example
1081 The text @samp{bar} can then be redefined over multiple uses of
1082 @file{foo}:
1084 @comment options: -Dbar=hello foo -Dbar=world foo
1085 @example
1086 $ @kbd{m4 -Dbar=hello foo -Dbar=world foo}
1087 @result{}hello
1088 @result{}world
1089 @end example
1091 @cindex command line, module names on the
1092 @cindex module names, on the command line
1093 The use of loadable runtime modules in any sense is a GNU M4
1094 extension, so if @option{-G} is also passed or if the @env{POSIXLY_CORRECT}
1095 environment variable is set, even otherwise valid module names will be
1096 treated as though they were input file names (and no doubt cause havoc as
1097 M4 tries to scan and expand the contents as if it were written in @code{m4}).
1099 If none of the input files invoked @code{m4exit} (@pxref{M4exit}), the
1100 exit status of @code{m4} will be 0 for success, 1 for general failure
1101 (such as problems with reading an input file), and 63 for version
1102 mismatch (@pxref{Using frozen files}).
1104 If you need to read a file whose name starts with a @file{-}, you can
1105 specify it as @samp{./-file}, or use @option{--} to mark the end of
1106 options.
1108 @node Syntax
1109 @chapter Lexical and syntactic conventions
1111 @cindex input tokens
1112 @cindex tokens
1113 As @code{m4} reads its input, it separates it into @dfn{tokens}.  A
1114 token is either a name, a quoted string, or any single character, that
1115 is not a part of either a name or a string.  Input to @code{m4} can also
1116 contain comments.  GNU @code{m4} does not yet understand
1117 multibyte locales; all operations are byte-oriented rather than
1118 character-oriented (although if your locale uses a single byte
1119 encoding, such as @sc{ISO-8859-1}, you will not notice a difference).
1120 However, @code{m4} is eight-bit clean, so you can
1121 use non-@sc{ascii} characters in quoted strings (@pxref{Changequote}),
1122 comments (@pxref{Changecom}), and macro names (@pxref{Indir}), with the
1123 exception of the @sc{nul} character (the zero byte @samp{'\0'}).
1125 @comment FIXME - each builtin needs to document how it handles NUL, then
1126 @comment update the above paragraph to mention that NUL is now handled
1127 @comment transparently.
1129 @menu
1130 * Names::                       Macro names
1131 * Quoted strings::              Quoting input to @code{m4}
1132 * Comments::                    Comments in @code{m4} input
1133 * Other tokens::                Other kinds of input tokens
1134 * Input processing::            How @code{m4} copies input to output
1135 * Regular expression syntax::   How @code{m4} interprets regular expressions
1136 @end menu
1138 @node Names
1139 @section Macro names
1141 @cindex names
1142 @cindex words
1143 A name is any sequence of letters, digits, and the character @samp{_}
1144 (underscore), where the first character is not a digit.  @code{m4} will
1145 use the longest such sequence found in the input.  If a name has a
1146 macro definition, it will be subject to macro expansion
1147 (@pxref{Macros}).  Names are case-sensitive.
1149 Examples of legal names are: @samp{foo}, @samp{_tmp}, and @samp{name01}.
1151 The definitions of letters, digits and other input characters can be
1152 changed at any time, using the builtin macro @code{changesyntax}.
1153 @xref{Changesyntax}, for more information.
1155 @node Quoted strings
1156 @section Quoting input to @code{m4}
1158 @cindex quoted string
1159 @cindex string, quoted
1160 A quoted string is a sequence of characters surrounded by quote
1161 strings, defaulting to
1162 @samp{`} (grave-accent, also known as back-tick, with UCS value U0060)
1163 and @samp{'} (apostrophe, also known as single-quote, with UCS value
1164 U0027), where the nested begin and end quotes within the
1165 string are balanced.  The value of a string token is the text, with one
1166 level of quotes stripped off.  Thus
1168 @comment ignore
1169 @example
1171 @result{}
1172 @end example
1174 @noindent
1175 is the empty string, and double-quoting turns into single-quoting.
1177 @comment ignore
1178 @example
1179 ``quoted''
1180 @result{}`quoted'
1181 @end example
1183 The quote characters can be changed at any time, using the builtin macros
1184 @code{changequote} (@pxref{Changequote}) or @code{changesyntax}
1185 (@pxref{Changesyntax}).
1187 @node Comments
1188 @section Comments in @code{m4} input
1190 @cindex comments
1191 Comments in @code{m4} are normally delimited by the characters @samp{#}
1192 and newline.  All characters between the comment delimiters are ignored,
1193 but the entire comment (including the delimiters) is passed through to
1194 the output, unless you supply the @option{--discard-comments} or
1195 @option{-c} option at the command line (@pxref{Operation modes, ,
1196 Invoking m4}).  When discarding comments, the comment delimiters are
1197 discarded, even if the close-comment string is a newline.
1199 Comments cannot be nested, so the first newline after a @samp{#} ends
1200 the comment.  The commenting effect of the begin-comment string
1201 can be inhibited by quoting it.
1203 @example
1204 $ @kbd{m4}
1205 `quoted text' # `commented text'
1206 @result{}quoted text # `commented text'
1207 `quoting inhibits' `#' `comments'
1208 @result{}quoting inhibits # comments
1209 @end example
1211 @comment options: -c
1212 @example
1213 $ @kbd{m4 -c}
1214 `quoted text' # `commented text'
1215 `quoting inhibits' `#' `comments'
1216 @result{}quoted text quoting inhibits # comments
1217 @end example
1219 The comment delimiters can be changed to any string at any time, using
1220 the builtin macros @code{changecom} (@pxref{Changecom}) or
1221 @code{changesyntax} (@pxref{Changesyntax}).
1223 @node Other tokens
1224 @section Other kinds of input tokens
1226 @cindex tokens, special
1227 Any character, that is neither a part of a name, nor of a quoted string,
1228 nor a comment, is a token by itself.  When not in the context of macro
1229 expansion, all of these tokens are just copied to output.  However,
1230 during macro expansion, whitespace characters (space, tab, newline,
1231 formfeed, carriage return, vertical tab), parentheses (@samp{(} and
1232 @samp{)}), comma (@samp{,}), and dollar (@samp{$}) have additional
1233 roles, explained later.  Which characters actually perform these roles
1234 can be adjusted with @code{changesyntax} (@pxref{Changesyntax}).
1236 @node Input processing
1237 @section How @code{m4} copies input to output
1239 As @code{m4} reads the input token by token, it will copy each token
1240 directly to the output immediately.
1242 The exception is when it finds a word with a macro definition.  In that
1243 case @code{m4} will calculate the macro's expansion, possibly reading
1244 more input to get the arguments.  It then inserts the expansion in front
1245 of the remaining input.  In other words, the resulting text from a macro
1246 call will be read and parsed into tokens again.
1248 @code{m4} expands a macro as soon as possible.  If it finds a macro call
1249 when collecting the arguments to another, it will expand the second call
1250 first.  This process continues until there are no more macro calls to
1251 expand and all the input has been consumed.
1253 For a running example, examine how @code{m4} handles this input:
1255 @comment ignore
1256 @example
1257 format(`Result is %d', eval(`2**15'))
1258 @end example
1260 @noindent
1261 First, @code{m4} sees that the token @samp{format} is a macro name, so
1262 it collects the tokens @samp{(}, @samp{`Result is %d'}, @samp{,},
1263 and @samp{@w{ }}, before encountering another potential macro.  Sure
1264 enough, @samp{eval} is a macro name, so the nested argument collection
1265 picks up @samp{(}, @samp{`2**15'}, and @samp{)}, invoking the eval macro
1266 with the lone argument of @samp{2**15}.  The expansion of
1267 @samp{eval(2**15)} is @samp{32768}, which is then rescanned as the five
1268 tokens @samp{3}, @samp{2}, @samp{7}, @samp{6}, and @samp{8}; and
1269 combined with the next @samp{)}, the format macro now has all its
1270 arguments, as if the user had typed:
1272 @comment ignore
1273 @example
1274 format(`Result is %d', 32768)
1275 @end example
1277 @noindent
1278 The format macro expands to @samp{Result is 32768}, and we have another
1279 round of scanning for the tokens @samp{Result}, @samp{@w{ }},
1280 @samp{is}, @samp{@w{ }}, @samp{3}, @samp{2}, @samp{7}, @samp{6}, and
1281 @samp{8}.  None of these are macros, so the final output is
1283 @comment ignore
1284 @example
1285 @result{}Result is 32768
1286 @end example
1288 As a more complicated example, we will contrast an actual code example
1289 from the Gnulib project@footnote{Derived from a patch in
1290 @uref{http://lists.gnu.org/archive/html/bug-gnulib/@/2007-01/@/msg00389.html},
1291 and a followup patch in
1292 @uref{http://lists.gnu.org/archive/html/bug-gnulib/@/2007-02/@/msg00000.html}},
1293 showing both a buggy approach and the desired results.  The user desires
1294 to output a shell assignment statement that takes its argument and turns
1295 it into a shell variable by converting it to uppercase and prepending a
1296 prefix.  The original attempt looks like this:
1298 @example
1299 changequote([,])dnl
1300 define([gl_STRING_MODULE_INDICATOR],
1301   [
1302     dnl comment
1303     GNULIB_]translit([$1],[a-z],[A-Z])[=1
1304   ])dnl
1305   gl_STRING_MODULE_INDICATOR([strcase])
1306 @result{} @w{ }
1307 @result{}        GNULIB_strcase=1
1308 @result{} @w{ }
1309 @end example
1311 Oops -- the argument did not get capitalized.  And although the manual
1312 is not able to easily show it, both lines that appear empty actually
1313 contain two trailing spaces.  By stepping through the parse, it is easy
1314 to see what happened.  First, @code{m4} sees the token
1315 @samp{changequote}, which it recognizes as a macro, followed by
1316 @samp{(}, @samp{[}, @samp{,}, @samp{]}, and @samp{)} to form the
1317 argument list.  The macro expands to the empty string, but changes the
1318 quoting characters to something more useful for generating shell code
1319 (unbalanced @samp{`} and @samp{'} appear all the time in shell scripts,
1320 but unbalanced @samp{[]} tend to be rare).  Also in the first line,
1321 @code{m4} sees the token @samp{dnl}, which it recognizes as a builtin
1322 macro that consumes the rest of the line, resulting in no output for
1323 that line.
1325 The second line starts a macro definition.  @code{m4} sees the token
1326 @samp{define}, which it recognizes as a macro, followed by a @samp{(},
1327 @samp{[gl_STRING_MODULE_INDICATOR]}, and @samp{,}.  Because an unquoted
1328 comma was encountered, the first argument is known to be the expansion
1329 of the single-quoted string token, or @samp{gl_STRING_MODULE_INDICATOR}.
1330 Next, @code{m4} sees @samp{@key{NL}}, @samp{ }, and @samp{ }, but this
1331 whitespace is discarded as part of argument collection.  Then comes a
1332 rather lengthy single-quoted string token, @samp{[@key{NL}@ @ @ @ dnl
1333 comment@key{NL}@ @ @ @ GNULIB_]}.  This is followed by the token
1334 @samp{translit}, which @code{m4} recognizes as a macro name, so a nested
1335 macro expansion has started.
1337 The arguments to the @code{translit} are found by the tokens @samp{(},
1338 @samp{[$1]}, @samp{,}, @samp{[a-z]}, @samp{,}, @samp{[A-Z]}, and finally
1339 @samp{)}.  All three string arguments are expanded (or in other words,
1340 the quotes are stripped), and since neither @samp{$} nor @samp{1} need
1341 capitalization, the result of the macro is @samp{$1}.  This expansion is
1342 rescanned, resulting in the two literal characters @samp{$} and
1343 @samp{1}.
1345 Scanning of the outer macro resumes, and picks up with
1346 @samp{[=1@key{NL}@ @ ]}, and finally @samp{)}.  The collected pieces of
1347 expanded text are concatenated, with the end result that the macro
1348 @samp{gl_STRING_MODULE_INDICATOR} is now defined to be the sequence
1349 @samp{@key{NL}@ @ @ @ dnl comment@key{NL}@ @ @ @ GNULIB_$1=1@key{NL}@ @ }.
1350 Once again, @samp{dnl} is recognized and avoids a newline in the output.
1352 The final line is then parsed, beginning with @samp{ } and @samp{ }
1353 that are output literally.  Then @samp{gl_STRING_MODULE_INDICATOR} is
1354 recognized as a macro name, with an argument list of @samp{(},
1355 @samp{[strcase]}, and @samp{)}.  Since the definition of the macro
1356 contains the sequence @samp{$1}, that sequence is replaced with the
1357 argument @samp{strcase} prior to starting the rescan.  The rescan sees
1358 @samp{@key{NL}} and four spaces, which are output literally, then
1359 @samp{dnl}, which discards the text @samp{ comment@key{NL}}.  Next
1360 comes four more spaces, also output literally, and the token
1361 @samp{GNULIB_strcase}, which resulted from the earlier parameter
1362 substitution.  Since that is not a macro name, it is output literally,
1363 followed by the literal tokens @samp{=}, @samp{1}, @samp{@key{NL}}, and
1364 two more spaces.  Finally, the original @samp{@key{NL}} seen after the
1365 macro invocation is scanned and output literally.
1367 Now for a corrected approach.  This rearranges the use of newlines and
1368 whitespace so that less whitespace is output (which, although harmless
1369 to shell scripts, can be visually unappealing), and fixes the quoting
1370 issues so that the capitalization occurs when the macro
1371 @samp{gl_STRING_MODULE_INDICATOR} is invoked, rather then when it is
1372 defined.  It also adds another layer of quoting to the first argument of
1373 @code{translit}, to ensure that the output will be rescanned as a string
1374 rather than a potential uppercase macro name needing further expansion.
1376 @example
1377 changequote([,])dnl
1378 define([gl_STRING_MODULE_INDICATOR],
1379   [dnl comment
1380   GNULIB_[]translit([[$1]], [a-z], [A-Z])=1dnl
1381 ])dnl
1382   gl_STRING_MODULE_INDICATOR([strcase])
1383 @result{}    GNULIB_STRCASE=1
1384 @end example
1386 The parsing of the first line is unchanged.  The second line sees the
1387 name of the macro to define, then sees the discarded @samp{@key{NL}}
1388 and two spaces, as before.  But this time, the next token is
1389 @samp{[dnl comment@key{NL}@ @ GNULIB_[]translit([[$1]], [a-z],
1390 [A-Z])=1dnl@key{NL}]}, which includes nested quotes, followed by
1391 @samp{)} to end the macro definition and @samp{dnl} to skip the
1392 newline.  No early expansion of @code{translit} occurs, so the entire
1393 string becomes the definition of the macro.
1395 The final line is then parsed, beginning with two spaces that are
1396 output literally, and an invocation of
1397 @code{gl_STRING_MODULE_INDICATOR} with the argument @samp{strcase}.
1398 Again, the @samp{$1} in the macro definition is substituted prior to
1399 rescanning.  Rescanning first encounters @samp{dnl}, and discards
1400 @samp{ comment@key{NL}}.  Then two spaces are output literally.  Next
1401 comes the token @samp{GNULIB_}, but that is not a macro, so it is
1402 output literally.  The token @samp{[]} is an empty string, so it does
1403 not affect output.  Then the token @samp{translit} is encountered.
1405 This time, the arguments to @code{translit} are parsed as @samp{(},
1406 @samp{[[strcase]]}, @samp{,}, @samp{ }, @samp{[a-z]}, @samp{,}, @samp{ },
1407 @samp{[A-Z]}, and @samp{)}.  The two spaces are discarded, and the
1408 translit results in the desired result @samp{[STRCASE]}.  This is
1409 rescanned, but since it is a string, the quotes are stripped and the
1410 only output is a literal @samp{STRCASE}.
1411 Then the scanner sees @samp{=} and @samp{1}, which are output
1412 literally, followed by @samp{dnl} which discards the rest of the
1413 definition of @code{gl_STRING_MODULE_INDICATOR}.  The newline at the
1414 end of output is the literal @samp{@key{NL}} that appeared after the
1415 invocation of the macro.
1417 The order in which @code{m4} expands the macros can be further explored
1418 using the trace facilities of GNU @code{m4} (@pxref{Trace}).
1420 @node Regular expression syntax
1421 @section How @code{m4} interprets regular expressions
1423 There are several contexts where @code{m4} parses an argument as a
1424 regular expression.  This section describes the various flavors of
1425 regular expressions.  @xref{Changeresyntax}.
1427 @include regexprops-generic.texi
1429 @node Macros
1430 @chapter How to invoke macros
1432 This chapter covers macro invocation, macro arguments and how macro
1433 expansion is treated.
1435 @menu
1436 * Invocation::                  Macro invocation
1437 * Inhibiting Invocation::       Preventing macro invocation
1438 * Macro Arguments::             Macro arguments
1439 * Quoting Arguments::           On Quoting Arguments to macros
1440 * Macro expansion::             Expanding macros
1441 @end menu
1443 @node Invocation
1444 @section Macro invocation
1446 @cindex macro invocation
1447 @cindex invoking macros
1448 Macro invocations has one of the forms
1450 @comment ignore
1451 @example
1452 name
1453 @end example
1455 @noindent
1456 which is a macro invocation without any arguments, or
1458 @comment ignore
1459 @example
1460 name(arg1, arg2, @dots{}, arg@var{n})
1461 @end example
1463 @noindent
1464 which is a macro invocation with @var{n} arguments.  Macros can have any
1465 number of arguments.  All arguments are strings, but different macros
1466 might interpret the arguments in different ways.
1468 The opening parenthesis @emph{must} follow the @var{name} directly, with
1469 no spaces in between.  If it does not, the macro is called with no
1470 arguments at all.
1472 For a macro call to have no arguments, the parentheses @emph{must} be
1473 left out.  The macro call
1475 @comment ignore
1476 @example
1477 name()
1478 @end example
1480 @noindent
1481 is a macro call with one argument, which is the empty string, not a call
1482 with no arguments.
1484 @node Inhibiting Invocation
1485 @section Preventing macro invocation
1487 An innovation of the @code{m4} language, compared to some of its
1488 predecessors (like Strachey's @code{GPM}, for example), is the ability
1489 to recognize macro calls without resorting to any special, prefixed
1490 invocation character.  While generally useful, this feature might
1491 sometimes be the source of spurious, unwanted macro calls.  So, GNU
1492 @code{m4} offers several mechanisms or techniques for inhibiting the
1493 recognition of names as macro calls.
1495 @cindex GNU extensions
1496 @cindex blind macro
1497 @cindex macro, blind
1498 First of all, many builtin macros cannot meaningfully be called without
1499 arguments.  As a GNU extension, for any of these macros,
1500 whenever an opening parenthesis does not immediately follow their name,
1501 the builtin macro call is not triggered.  This solves the most usual
1502 cases, like for @samp{include} or @samp{eval}.  Later in this document,
1503 the sentence ``This macro is recognized only with parameters'' refers to
1504 this specific provision of GNU M4, also known as a blind
1505 builtin macro.  For the builtins defined by POSIX that bear
1506 this disclaimer, POSIX specifically states that invoking those
1507 builtins without arguments is unspecified, because many other
1508 implementations simply invoke the builtin as though it were given one
1509 empty argument instead.
1511 @example
1512 $ @kbd{m4}
1513 eval
1514 @result{}eval
1515 eval(`1')
1516 @result{}1
1517 @end example
1519 There is also a command line option (@option{--prefix-builtins}, or
1520 @option{-P}, @pxref{Operation modes, , Invoking m4}) that renames all
1521 builtin macros with a prefix of @samp{m4_} at startup.  The option has
1522 no effect whatsoever on user defined macros.  For example, with this option,
1523 one has to write @code{m4_dnl} and even @code{m4_m4exit}.  It also has
1524 no effect on whether a macro requires parameters.
1526 @comment options: -P
1527 @example
1528 $ @kbd{m4 -P}
1529 eval
1530 @result{}eval
1531 eval(`1')
1532 @result{}eval(1)
1533 m4_eval
1534 @result{}m4_eval
1535 m4_eval(`1')
1536 @result{}1
1537 @end example
1539 Another alternative is to redefine problematic macros to a name less
1540 likely to cause conflicts, @xref{Definitions}.  Or the parsing engine
1541 can be changed to redefine what constitutes a valid macro name,
1542 @xref{Changesyntax}.
1544 Of course, the simplest way to prevent a name from being interpreted
1545 as a call to an existing macro is to quote it.  The remainder of
1546 this section studies a little more deeply how quoting affects macro
1547 invocation, and how quoting can be used to inhibit macro invocation.
1549 Even if quoting is usually done over the whole macro name, it can also
1550 be done over only a few characters of this name (provided, of course,
1551 that the unquoted portions are not also a macro).  It is also possible
1552 to quote the empty string, but this works only @emph{inside} the name.
1553 For example:
1555 @example
1556 `divert'
1557 @result{}divert
1558 `d'ivert
1559 @result{}divert
1560 di`ver't
1561 @result{}divert
1562 div`'ert
1563 @result{}divert
1564 @end example
1566 @noindent
1567 all yield the string @samp{divert}.  While in both:
1569 @example
1570 `'divert
1571 @result{}
1572 divert`'
1573 @result{}
1574 @end example
1576 @noindent
1577 the @code{divert} builtin macro will be called, which expands to the
1578 empty string.
1580 @cindex rescanning
1581 The output of macro evaluations is always rescanned.  In the following
1582 example, the input @samp{x`'y} yields the string @samp{bCD}, exactly as
1583 if @code{m4}
1584 has been given @w{@samp{substr(ab`'cde, `1', `3')}} as input:
1586 @example
1587 define(`cde', `CDE')
1588 @result{}
1589 define(`x', `substr(ab')
1590 @result{}
1591 define(`y', `cde, `1', `3')')
1592 @result{}
1593 x`'y
1594 @result{}bCD
1595 @end example
1597 Unquoted strings on either side of a quoted string are subject to
1598 being recognized as macro names.  In the following example, quoting the
1599 empty string allows for the second @code{macro} to be recognized as such:
1601 @example
1602 define(`macro', `m')
1603 @result{}
1604 macro(`m')macro
1605 @result{}mmacro
1606 macro(`m')`'macro
1607 @result{}mm
1608 @end example
1610 Quoting may prevent recognizing as a macro name the concatenation of a
1611 macro expansion with the surrounding characters.  In this example:
1613 @example
1614 define(`macro', `di$1')
1615 @result{}
1616 macro(`v')`ert'
1617 @result{}divert
1618 macro(`v')ert
1619 @result{}
1620 @end example
1622 @noindent
1623 the input will produce the string @samp{divert}.  When the quotes were
1624 removed, the @code{divert} builtin was called instead.
1626 @node Macro Arguments
1627 @section Macro arguments
1629 @cindex macros, arguments to
1630 @cindex arguments to macros
1631 When a name is seen, and it has a macro definition, it will be expanded
1632 as a macro.
1634 If the name is followed by an opening parenthesis, the arguments will be
1635 collected before the macro is called.  If too few arguments are
1636 supplied, the missing arguments are taken to be the empty string.
1637 However, some builtins are documented to behave differently for a
1638 missing optional argument than for an explicit empty string.  If there
1639 are too many arguments, the excess arguments are ignored.  Unquoted
1640 leading whitespace is stripped off all arguments, but whitespace
1641 generated by a macro expansion or occurring after a macro that expanded
1642 to an empty string remains intact.  Whitespace includes space, tab,
1643 newline, carriage return, vertical tab, and formfeed.
1645 @example
1646 define(`macro', `$1')
1647 @result{}
1648 macro( unquoted leading space lost)
1649 @result{}unquoted leading space lost
1650 macro(` quoted leading space kept')
1651 @result{} quoted leading space kept
1652 macro(
1653  divert `unquoted space kept after expansion')
1654 @result{} unquoted space kept after expansion
1655 macro(macro(`
1656 ')`whitespace from expansion kept')
1657 @result{}
1658 @result{}whitespace from expansion kept
1659 macro(`unquoted trailing whitespace kept'
1661 @result{}unquoted trailing whitespace kept
1662 @result{}
1663 @end example
1665 @cindex warnings, suppressing
1666 @cindex suppressing warnings
1667 Normally @code{m4} will issue warnings if a builtin macro is called
1668 with an inappropriate number of arguments, but it can be suppressed with
1669 the @option{--quiet} command line option (or @option{--silent}, or
1670 @option{-Q}, @pxref{Operation modes, , Invoking m4}).  For user
1671 defined macros, there is no check of the number of arguments given.
1673 @example
1674 $ @kbd{m4}
1675 index(`abc')
1676 @error{}m4:stdin:1: warning: index: too few arguments: 1 < 2
1677 @result{}0
1678 index(`abc',)
1679 @result{}0
1680 index(`abc', `b', `0', `ignored')
1681 @error{}m4:stdin:3: warning: index: extra arguments ignored: 4 > 3
1682 @result{}1
1683 @end example
1685 @comment options: -Q
1686 @example
1687 $ @kbd{m4 -Q}
1688 index(`abc')
1689 @result{}0
1690 index(`abc',)
1691 @result{}0
1692 index(`abc', `b', `', `ignored')
1693 @result{}1
1694 @end example
1696 Macros are expanded normally during argument collection, and whatever
1697 commas, quotes and parentheses that might show up in the resulting
1698 expanded text will serve to define the arguments as well.  Thus, if
1699 @var{foo} expands to @samp{, b, c}, the macro call
1701 @comment ignore
1702 @example
1703 bar(a foo, d)
1704 @end example
1706 @noindent
1707 is a macro call with four arguments, which are @samp{a }, @samp{b},
1708 @samp{c} and @samp{d}.  To understand why the first argument contains
1709 whitespace, remember that unquoted leading whitespace is never part
1710 of an argument, but trailing whitespace always is.
1712 It is possible for a macro's definition to change during argument
1713 collection, in which case the expansion uses the definition that was in
1714 effect at the time the opening @samp{(} was seen.
1716 @example
1717 define(`f', `1')
1718 @result{}
1719 f(define(`f', `2'))
1720 @result{}1
1722 @result{}2
1723 @end example
1725 It is an error if the end of file occurs while collecting arguments.
1727 @comment status: 1
1728 @example
1729 hello world
1730 @result{}hello world
1731 define(
1733 @error{}m4:stdin:2: define: end of file in argument list
1734 @end example
1736 @node Quoting Arguments
1737 @section On Quoting Arguments to macros
1739 @cindex quoted macro arguments
1740 @cindex macros, quoted arguments to
1741 @cindex arguments, quoted macro
1742 Each argument has unquoted leading whitespace removed.  Within each
1743 argument, all unquoted parentheses must match.  For example, if
1744 @var{foo} is a macro,
1746 @comment ignore
1747 @example
1748 foo(() (`(') `(')
1749 @end example
1751 @noindent
1752 is a macro call, with one argument, whose value is @samp{() (() (}.
1753 Commas separate arguments, except when they occur inside quotes,
1754 comments, or unquoted parentheses.  @xref{Pseudo Arguments}, for
1755 examples.
1757 It is common practice to quote all arguments to macros, unless you are
1758 sure you want the arguments expanded.  Thus, in the above
1759 example with the parentheses, the `right' way to do it is like this:
1761 @comment ignore
1762 @example
1763 foo(`() (() (')
1764 @end example
1766 @cindex quoting rule of thumb
1767 @cindex rule of thumb, quoting
1768 It is, however, in certain cases necessary (because nested expansion
1769 must occur to create the arguments for the outer macro) or convenient
1770 (because it uses fewer characters) to leave out quotes for some
1771 arguments, and there is nothing wrong in doing it.  It just makes life a
1772 bit harder, if you are not careful to follow a consistent quoting style.
1773 For consistency, this manual follows the rule of thumb that each layer
1774 of parentheses introduces another layer of single quoting, except when
1775 showing the consequences of quoting rules.  This is done even when the
1776 quoted string cannot be a macro, such as with integers when you have not
1777 changed the syntax via @code{changesyntax} (@pxref{Changesyntax}).
1779 The quoting rule of thumb of one level of quoting per parentheses has a
1780 nice property: when a macro name appears inside parentheses, you can
1781 determine when it will be expanded.  If it is not quoted, it will be
1782 expanded prior to the outer macro, so that its expansion becomes the
1783 argument.  If it is single-quoted, it will be expanded after the outer
1784 macro.  And if it is double-quoted, it will be used as literal text
1785 instead of a macro name.
1787 @example
1788 define(`active', `ACT, IVE')
1789 @result{}
1790 define(`show', `$1 $1')
1791 @result{}
1792 show(active)
1793 @result{}ACT ACT
1794 show(`active')
1795 @result{}ACT, IVE ACT, IVE
1796 show(``active'')
1797 @result{}active active
1798 @end example
1800 @node Macro expansion
1801 @section Macro expansion
1803 @cindex macros, expansion of
1804 @cindex expansion of macros
1805 When the arguments, if any, to a macro call have been collected, the
1806 macro is expanded, and the expansion text is pushed back onto the input
1807 (unquoted), and reread.  The expansion text from one macro call might
1808 therefore result in more macros being called, if the calls are included,
1809 completely or partially, in the first macro calls' expansion.
1811 Taking a very simple example, if @var{foo} expands to @samp{bar}, and
1812 @var{bar} expands to @samp{Hello world}, the input
1814 @comment options: -Dbar='Hello world' -Dfoo=bar
1815 @example
1816 $ @kbd{m4 -Dbar="Hello world" -Dfoo=bar}
1818 @result{}Hello world
1819 @end example
1821 @noindent
1822 will expand first to @samp{bar}, and when this is reread and
1823 expanded, into @samp{Hello world}.
1825 @node Definitions
1826 @chapter How to define new macros
1828 @cindex macros, how to define new
1829 @cindex defining new macros
1830 Macros can be defined, redefined and deleted in several different ways.
1831 Also, it is possible to redefine a macro without losing a previous
1832 value, and bring back the original value at a later time.
1834 @menu
1835 * Define::                      Defining a new macro
1836 * Arguments::                   Arguments to macros
1837 * Pseudo Arguments::            Special arguments to macros
1838 * Undefine::                    Deleting a macro
1839 * Defn::                        Renaming macros
1840 * Pushdef::                     Temporarily redefining macros
1841 * Renamesyms::                  Renaming macros with regular expressions
1843 * Indir::                       Indirect call of macros
1844 * Builtin::                     Indirect call of builtins
1845 * M4symbols::                   Getting the defined macro names
1846 @end menu
1848 @node Define
1849 @section Defining a macro
1851 The normal way to define or redefine macros is to use the builtin
1852 @code{define}:
1854 @deffn {Builtin (m4)} define (@var{name}, @ovar{expansion})
1855 Defines @var{name} to expand to @var{expansion}.  If
1856 @var{expansion} is not given, it is taken to be empty.
1858 The expansion of @code{define} is void.
1859 The macro @code{define} is recognized only with parameters.
1860 @end deffn
1861 @comment Other implementations, such as Solaris, can define a macro
1862 @comment with a builtin token attached to text:
1863 @comment  define(foo, a`'defn(`divnum')b)
1864 @comment  defn(`foo') => ab
1865 @comment  dumpdef(`foo') => foo: a<divnum>b
1866 @comment  len(defn(`foo')) => 3
1867 @comment  index(defn(`foo'), defn(`divnum')) => 1
1868 @comment  foo => a0b
1869 @comment It may be worth making some changes to support this behavior,
1870 @comment or something similar to it.
1871 @comment
1872 @comment But be sure it has sane semantics, with potentially deferred
1873 @comment expansion of builtins.  For example, this should not warn
1874 @comment about trying to access the definition of an undefined macro:
1875 @comment  define(`foo', `ifdef(`$1', 'defn(`defn')`)')foo(`oops')
1876 @comment Also, think how to handle conflicting argument counts:
1877 @comment  define(`bar', defn(`dnl', `len'))
1879 The following example defines the macro @var{foo} to expand to the text
1880 @samp{Hello World.}.
1882 @example
1883 define(`foo', `Hello world.')
1884 @result{}
1886 @result{}Hello world.
1887 @end example
1889 The empty line in the output is there because the newline is not
1890 a part of the macro definition, and it is consequently copied to
1891 the output.  This can be avoided by use of the macro @code{dnl}.
1892 @xref{Dnl}, for details.
1894 The first argument to @code{define} should be quoted; otherwise, if the
1895 macro is already defined, you will be defining a different macro.  This
1896 example shows the problems with underquoting, since we did not want to
1897 redefine @code{one}:
1899 @example
1900 define(foo, one)
1901 @result{}
1902 define(foo, two)
1903 @result{}
1905 @result{}two
1906 @end example
1908 @cindex GNU extensions
1909 GNU @code{m4} normally replaces only the @emph{topmost}
1910 definition of a macro if it has several definitions from @code{pushdef}
1911 (@pxref{Pushdef}).  Some other implementations of @code{m4} replace all
1912 definitions of a macro with @code{define}.  @xref{Incompatibilities},
1913 for more details.
1915 As a GNU extension, the first argument to @code{define} does
1916 not have to be a simple word.
1917 It can be any text string, even the empty string.  A macro with a
1918 non-standard name cannot be invoked in the normal way, as the name is
1919 not recognized.  It can only be referenced by the builtins @code{Indir}
1920 (@pxref{Indir}) and @code{Defn} (@pxref{Defn}).
1922 @cindex arrays
1923 Arrays and associative arrays can be simulated by using non-standard
1924 macro names.
1926 @deffn Composite array (@var{index})
1927 @deffnx Composite array_set (@var{index}, @ovar{value})
1928 Provide access to entries within an array.  @code{array} reads the entry
1929 at location @var{index}, and @code{array_set} assigns @var{value} to
1930 location @var{index}.
1931 @end deffn
1933 @example
1934 define(`array', `defn(format(``array[%d]'', `$1'))')
1935 @result{}
1936 define(`array_set', `define(format(``array[%d]'', `$1'), `$2')')
1937 @result{}
1938 array_set(`4', `array element no. 4')
1939 @result{}
1940 array_set(`17', `array element no. 17')
1941 @result{}
1942 array(`4')
1943 @result{}array element no. 4
1944 array(eval(`10 + 7'))
1945 @result{}array element no. 17
1946 @end example
1948 Change the @samp{%d} to @samp{%s} and it is an associative array.
1950 @node Arguments
1951 @section Arguments to macros
1953 @cindex macros, arguments to
1954 @cindex arguments to macros
1955 Macros can have arguments.  The @var{n}th argument is denoted by
1956 @code{$n} in the expansion text, and is replaced by the @var{n}th actual
1957 argument, when the macro is expanded.  Replacement of arguments happens
1958 before rescanning, regardless of how many nesting levels of quoting
1959 appear in the expansion.  Here is an example of a macro with
1960 two arguments.
1962 @deffn Composite exch (@var{arg1}, @var{arg2})
1963 Expands to @var{arg2} followed by @var{arg1}, effectively exchanging
1964 their order.
1965 @end deffn
1967 @example
1968 define(`exch', `$2, $1')
1969 @result{}
1970 exch(`arg1', `arg2')
1971 @result{}arg2, arg1
1972 @end example
1974 This can be used, for example, if you like the arguments to
1975 @code{define} to be reversed.
1977 @example
1978 define(`exch', `$2, $1')
1979 @result{}
1980 define(exch(``expansion text'', ``macro''))
1981 @result{}
1982 macro
1983 @result{}expansion text
1984 @end example
1986 @xref{Quoting Arguments}, for an explanation of the double quotes.
1987 (You should try and improve this example so that clients of @code{exch}
1988 do not have to double quote; or @pxref{Improved exch, , Answers}).
1990 @cindex GNU extensions
1991 GNU @code{m4} allows the number following the @samp{$} to
1992 consist of one
1993 or more digits, allowing macros to have any number of arguments.  This
1994 is not so in UNIX implementations of @code{m4}, which only recognize
1995 one digit.
1996 @comment FIXME - See Austin group XCU ERN 111.  POSIX says that $11 must
1997 @comment be the first argument concatenated with 1, and instead reserves
1998 @comment ${11} for implementation use.  Once this is implemented, the
1999 @comment documentation needs to reflect how these extended arguments
2000 @comment are handled, as well as backwards compatibility issues with
2001 @comment 1.4.x.  Also, consider adding further extensions such as
2002 @comment ${1-default}, which expands to `default' if $1 is empty.
2004 As a special case, the zeroth argument, @code{$0}, is always the name
2005 of the macro being expanded.
2007 @example
2008 define(`test', ``Macro name: $0'')
2009 @result{}
2010 test
2011 @result{}Macro name: test
2012 @end example
2014 If you want quoted text to appear as part of the expansion text,
2015 remember that quotes can be nested in quoted strings.  Thus, in
2017 @example
2018 define(`foo', `This is macro `foo'.')
2019 @result{}
2021 @result{}This is macro foo.
2022 @end example
2024 @noindent
2025 The @samp{foo} in the expansion text is @emph{not} expanded, since it is
2026 a quoted string, and not a name.
2028 @node Pseudo Arguments
2029 @section Special arguments to macros
2031 @cindex special arguments to macros
2032 @cindex macros, special arguments to
2033 @cindex arguments to macros, special
2034 There is a special notation for the number of actual arguments supplied,
2035 and for all the actual arguments.
2037 The number of actual arguments in a macro call is denoted by @code{$#}
2038 in the expansion text.
2040 @deffn Composite nargs (@dots{})
2041 Expands to a count of the number of arguments supplied.
2042 @end deffn
2044 @example
2045 define(`nargs', `$#')
2046 @result{}
2047 nargs
2048 @result{}0
2049 nargs()
2050 @result{}1
2051 nargs(`arg1', `arg2', `arg3')
2052 @result{}3
2053 nargs(`commas can be quoted, like this')
2054 @result{}1
2055 nargs(arg1#inside comments, commas do not separate arguments
2056 still arg1)
2057 @result{}1
2058 nargs((unquoted parentheses, like this, group arguments))
2059 @result{}1
2060 @end example
2062 Remember that @samp{#} defaults to the comment character; if you forget
2063 quotes to inhibit the comment behavior, your macro definition may not
2064 end where you expected.
2066 @example
2067 dnl Attempt to define a macro to just `$#'
2068 define(underquoted, $#)
2069 oops)
2070 @result{}
2071 underquoted
2072 @result{}0)
2073 @result{}oops
2074 @end example
2076 The notation @code{$*} can be used in the expansion text to denote all
2077 the actual arguments, unquoted, with commas in between.  For example
2079 @example
2080 define(`echo', `$*')
2081 @result{}
2082 echo(arg1,    arg2, arg3 , arg4)
2083 @result{}arg1,arg2,arg3 ,arg4
2084 @end example
2086 Often each argument should be quoted, and the notation @code{$@@} handles
2087 that.  It is just like @code{$*}, except that it quotes each argument.
2088 A simple example of that is:
2090 @example
2091 define(`echo', `$@@')
2092 @result{}
2093 echo(arg1,    arg2, arg3 , arg4)
2094 @result{}arg1,arg2,arg3 ,arg4
2095 @end example
2097 Where did the quotes go?  Of course, they were eaten, when the expanded
2098 text were reread by @code{m4}.  To show the difference, try
2100 @example
2101 define(`echo1', `$*')
2102 @result{}
2103 define(`echo2', `$@@')
2104 @result{}
2105 define(`foo', `This is macro `foo'.')
2106 @result{}
2107 echo1(foo)
2108 @result{}This is macro This is macro foo..
2109 echo1(`foo')
2110 @result{}This is macro foo.
2111 echo2(foo)
2112 @result{}This is macro foo.
2113 echo2(`foo')
2114 @result{}foo
2115 @end example
2117 @noindent
2118 @xref{Trace}, if you do not understand this.  As another example of the
2119 difference, remember that comments encountered in arguments are passed
2120 untouched to the macro, and that quoting disables comments.
2122 @example
2123 define(`echo1', `$*')
2124 @result{}
2125 define(`echo2', `$@@')
2126 @result{}
2127 define(`foo', `bar')
2128 @result{}
2129 echo1(#foo'foo
2130 foo)
2131 @result{}#foo'foo
2132 @result{}bar
2133 echo2(#foo'foo
2134 foo)
2135 @result{}#foobar
2136 @result{}bar'
2137 @end example
2139 A @samp{$} sign in the expansion text, that is not followed by anything
2140 @code{m4} understands, is simply copied to the macro expansion, as any
2141 other text is.
2143 @example
2144 define(`foo', `$$$ hello $$$')
2145 @result{}
2147 @result{}$$$ hello $$$
2148 @end example
2150 @cindex rescanning
2151 @cindex literal output
2152 @cindex output, literal
2153 If you want a macro to expand to something like @samp{$12}, the
2154 judicious use of nested quoting can put a safe character between the
2155 @code{$} and the next character, relying on the rescanning to remove the
2156 nested quote.  This will prevent @code{m4} from interpreting the
2157 @code{$} sign as a reference to an argument.
2159 @example
2160 define(`foo', `no nested quote: $1')
2161 @result{}
2162 foo(`arg')
2163 @result{}no nested quote: arg
2164 define(`foo', `nested quote around $: `$'1')
2165 @result{}
2166 foo(`arg')
2167 @result{}nested quote around $: $1
2168 define(`foo', `nested empty quote after $: $`'1')
2169 @result{}
2170 foo(`arg')
2171 @result{}nested empty quote after $: $1
2172 define(`foo', `nested quote around next character: $`1'')
2173 @result{}
2174 foo(`arg')
2175 @result{}nested quote around next character: $1
2176 define(`foo', `nested quote around both: `$1'')
2177 @result{}
2178 foo(`arg')
2179 @result{}nested quote around both: arg
2180 @end example
2182 @node Undefine
2183 @section Deleting a macro
2185 @cindex macros, how to delete
2186 @cindex deleting macros
2187 @cindex undefining macros
2188 A macro definition can be removed with @code{undefine}:
2190 @deffn {Builtin (m4)} undefine (@var{name}@dots{})
2191 For each argument, remove the macro @var{name}.  The macro names must
2192 necessarily be quoted, since they will be expanded otherwise.  If an
2193 argument is not a defined macro, then the @samp{d} debug level controls
2194 whether a warning is issued (@pxref{Debugmode}).
2196 The expansion of @code{undefine} is void.
2197 The macro @code{undefine} is recognized only with parameters.
2198 @end deffn
2200 @example
2201 foo bar blah
2202 @result{}foo bar blah
2203 define(`foo', `some')define(`bar', `other')define(`blah', `text')
2204 @result{}
2205 foo bar blah
2206 @result{}some other text
2207 undefine(`foo')
2208 @result{}
2209 foo bar blah
2210 @result{}foo other text
2211 undefine(`bar', `blah')
2212 @result{}
2213 foo bar blah
2214 @result{}foo bar blah
2215 @end example
2217 Undefining a macro inside that macro's expansion is safe; the macro
2218 still expands to the definition that was in effect at the @samp{(}.
2220 @example
2221 define(`f', ``$0':$1')
2222 @result{}
2223 f(f(f(undefine(`f')`hello world')))
2224 @result{}f:f:f:hello world
2225 f(`bye')
2226 @result{}f(bye)
2227 @end example
2229 As of M4 1.6, @code{undefine} can warn if @var{name} is not a macro, by
2230 using @code{debugmode} (@pxref{Debugmode}) or the command line option
2231 @option{-d} (@option{--debugmode}, @pxref{Debugging options, , Invoking
2232 m4}).
2234 @example
2235 $ @kbd{m4}
2236 undefine(`a')
2237 @error{}m4:stdin:1: warning: undefine: undefined macro 'a'
2238 @result{}
2239 debugmode(`-d')
2240 @result{}
2241 undefine(`a')
2242 @result{}
2243 @end example
2245 @node Defn
2246 @section Renaming macros
2248 @cindex macros, how to rename
2249 @cindex renaming macros
2250 @cindex macros, displaying definitions
2251 @cindex definitions, displaying macro
2252 It is possible to rename an already defined macro.  To do this, you need
2253 the builtin @code{defn}:
2255 @deffn {Builtin (m4)} defn (@var{name}@dots{})
2256 Expands to the @emph{quoted definition} of each @var{name}.  If an
2257 argument is not a defined macro, the expansion for that argument is
2258 empty, and the @samp{d} debug level controls whether a warning is issued
2259 (@pxref{Debugmode}).
2261 If @var{name} is a user-defined macro, the quoted definition is simply
2262 the quoted expansion text.  If, instead, @var{name} is a builtin, the
2263 expansion is a special token, which points to the builtin's internal
2264 definition.  This token meaningful primarily as the second argument to
2265 @code{define} (and @code{pushdef}), and is silently converted to an
2266 empty string in many other contexts.
2268 The macro @code{defn} is recognized only with parameters.
2269 @end deffn
2271 Its normal use is best understood through an example, which shows how to
2272 rename @code{undefine} to @code{zap}:
2274 @example
2275 define(`zap', defn(`undefine'))
2276 @result{}
2277 zap(`undefine')
2278 @result{}
2279 undefine(`zap')
2280 @result{}undefine(zap)
2281 @end example
2283 In this way, @code{defn} can be used to copy macro definitions, and also
2284 definitions of builtin macros.  Even if the original macro is removed,
2285 the other name can still be used to access the definition.
2287 The fact that macro definitions can be transferred also explains why you
2288 should use @code{$0}, rather than retyping a macro's name in its
2289 definition:
2291 @example
2292 define(`foo', `This is `$0'')
2293 @result{}
2294 define(`bar', defn(`foo'))
2295 @result{}
2297 @result{}This is bar
2298 @end example
2300 Macros used as string variables should be referred through @code{defn},
2301 to avoid unwanted expansion of the text:
2303 @example
2304 define(`string', `The macro dnl is very useful
2306 @result{}
2307 string
2308 @result{}The macro@w{ }
2309 defn(`string')
2310 @result{}The macro dnl is very useful
2311 @result{}
2312 @end example
2314 @cindex rescanning
2315 However, it is important to remember that @code{m4} rescanning is purely
2316 textual.  If an unbalanced end-quote string occurs in a macro
2317 definition, the rescan will see that embedded quote as the termination
2318 of the quoted string, and the remainder of the macro's definition will
2319 be rescanned unquoted.  Thus it is a good idea to avoid unbalanced
2320 end-quotes in macro definitions or arguments to macros.
2322 @example
2323 define(`foo', a'a)
2324 @result{}
2325 define(`a', `A')
2326 @result{}
2327 define(`echo', `$@@')
2328 @result{}
2330 @result{}A'A
2331 defn(`foo')
2332 @result{}aA'
2333 echo(foo)
2334 @result{}AA'
2335 @end example
2337 On the other hand, it is possible to exploit the fact that @code{defn}
2338 can concatenate multiple macros prior to the rescanning phase, in order
2339 to join the definitions of macros that, in isolation, have unbalanced
2340 quotes.  This is particularly useful when one has used several macros to
2341 accumulate text that M4 should rescan as a whole.  In the example below,
2342 note how the use of @code{defn} on @code{l} in isolation opens a string,
2343 which is not closed until the next line; but used on @code{l} and
2344 @code{r} together results in nested quoting.
2346 @example
2347 define(`l', `<[>')define(`r', `<]>')
2348 @result{}
2349 changequote(`[', `]')
2350 @result{}
2351 defn([l])defn([r])
2353 @result{}<[>]defn([r])
2354 @result{})
2355 defn([l], [r])
2356 @result{}<[>][<]>
2357 @end example
2359 @cindex builtins, special tokens
2360 @cindex tokens, builtin macro
2361 Using @code{defn} to generate special tokens for builtin macros will
2362 generate a warning in contexts where a macro name is expected.  But in
2363 contexts that operate on text, the builtin token is just silently
2364 converted to an empty string.  As of M4 1.6, expansion of user macros
2365 will also preserve builtin tokens.  However, any use of builtin tokens
2366 outside of the second argument to @code{define} and @code{pushdef} is
2367 generally not portable, since earlier GNU M4 versions, as well
2368 as other @code{m4} implementations, vary on how such tokens are treated.
2370 @example
2371 $ @kbd{m4 -d}
2372 defn(`defn')
2373 @result{}
2374 define(defn(`divnum'), `cannot redefine a builtin token')
2375 @error{}m4:stdin:2: warning: define: invalid macro name ignored
2376 @result{}
2377 divnum
2378 @result{}0
2379 len(defn(`divnum'))
2380 @result{}0
2381 define(`echo', `$@@')
2382 @result{}
2383 define(`mydivnum', shift(echo(`', defn(`divnum'))))
2384 @result{}
2385 mydivnum
2386 @result{}0
2387 define(`', `empty-$1')
2388 @result{}
2389 defn(defn(`divnum'))
2390 @error{}m4:stdin:9: warning: defn: invalid macro name ignored
2391 @result{}
2392 pushdef(defn(`divnum'), `oops')
2393 @error{}m4:stdin:10: warning: pushdef: invalid macro name ignored
2394 @result{}
2395 traceon(defn(`divnum'))
2396 @error{}m4:stdin:11: warning: traceon: invalid macro name ignored
2397 @result{}
2398 indir(defn(`divnum'), `string')
2399 @error{}m4:stdin:12: warning: indir: invalid macro name ignored
2400 @result{}
2401 indir(`', `string')
2402 @result{}empty-string
2403 traceoff(defn(`divnum'))
2404 @error{}m4:stdin:14: warning: traceoff: invalid macro name ignored
2405 @result{}
2406 popdef(defn(`divnum'))
2407 @error{}m4:stdin:15: warning: popdef: invalid macro name ignored
2408 @result{}
2409 dumpdef(defn(`divnum'))
2410 @error{}m4:stdin:16: warning: dumpdef: invalid macro name ignored
2411 @result{}
2412 undefine(defn(`divnum'))
2413 @error{}m4:stdin:17: warning: undefine: invalid macro name ignored
2414 @result{}
2415 dumpdef(`')
2416 @error{}:@tabchar{}`empty-$1'
2417 @result{}
2418 m4symbols(defn(`divnum'))
2419 @error{}m4:stdin:19: warning: m4symbols: invalid macro name ignored
2420 @result{}
2421 define(`foo', `define(`$1', $2)')dnl
2422 foo(`bar', defn(`divnum'))
2423 @result{}
2425 @result{}0
2426 @end example
2428 As of M4 1.6, @code{defn} can warn if @var{name} is not a macro, by
2429 using @code{debugmode} (@pxref{Debugmode}) or the command line option
2430 @option{-d} (@option{--debugmode}, @pxref{Debugging options, , Invoking
2431 m4}).  Also, @code{defn} with multiple arguments can join text with
2432 builtin tokens.  However, when defining a macro via @code{define} or
2433 @code{pushdef}, a warning is issued and the builtin token ignored if the
2434 builtin token does not occur in isolation.  A future version of
2435 GNU M4 may lift this restriction.
2437 @example
2438 $ @kbd{m4 -d}
2439 defn(`foo')
2440 @error{}m4:stdin:1: warning: defn: undefined macro 'foo'
2441 @result{}
2442 debugmode(`-d')
2443 @result{}
2444 defn(`foo')
2445 @result{}
2446 define(`a', `A')define(`AA', `b')
2447 @result{}
2448 traceon(`defn', `define')
2449 @result{}
2450 defn(`a', `divnum', `a')
2451 @error{}m4trace: -1- defn(`a', `divnum', `a') -> ``A'<divnum>`A''
2452 @result{}AA
2453 define(`mydivnum', defn(`divnum', `divnum'))mydivnum
2454 @error{}m4trace: -2- defn(`divnum', `divnum') -> `<divnum><divnum>'
2455 @error{}m4:stdin:7: warning: define: cannot concatenate builtins
2456 @error{}m4trace: -1- define(`mydivnum', `<divnum><divnum>') -> `'
2457 @result{}
2458 traceoff(`defn', `define')dumpdef(`mydivnum')
2459 @error{}mydivnum:@tabchar{}`'
2460 @result{}
2461 define(`mydivnum', defn(`divnum')defn(`divnum'))mydivnum
2462 @error{}m4:stdin:9: warning: define: cannot concatenate builtins
2463 @result{}
2464 define(`mydivnum', defn(`divnum')`a')mydivnum
2465 @error{}m4:stdin:10: warning: define: cannot concatenate builtins
2466 @result{}A
2467 define(`mydivnum', `a'defn(`divnum'))mydivnum
2468 @error{}m4:stdin:11: warning: define: cannot concatenate builtins
2469 @result{}A
2470 define(`q', ``$@@'')
2471 @result{}
2472 define(`foo', q(`a', defn(`divnum')))foo
2473 @error{}m4:stdin:13: warning: define: cannot concatenate builtins
2474 @result{}a,
2475 ifdef(`foo', `yes', `no')
2476 @result{}yes
2477 @end example
2479 @node Pushdef
2480 @section Temporarily redefining macros
2482 @cindex macros, temporary redefinition of
2483 @cindex temporary redefinition of macros
2484 @cindex redefinition of macros, temporary
2485 @cindex definition stack
2486 @cindex pushdef stack
2487 @cindex stack, macro definition
2488 It is possible to redefine a macro temporarily, reverting to the
2489 previous definition at a later time.  This is done with the builtins
2490 @code{pushdef} and @code{popdef}:
2492 @deffn {Builtin (m4)} pushdef (@var{name}, @ovar{expansion})
2493 @deffnx {Builtin (m4)} popdef (@var{name}@dots{})
2494 Analogous to @code{define} and @code{undefine}.
2496 These macros work in a stack-like fashion.  A macro is temporarily
2497 redefined with @code{pushdef}, which replaces an existing definition of
2498 @var{name}, while saving the previous definition, before the new one is
2499 installed.  If there is no previous definition, @code{pushdef} behaves
2500 exactly like @code{define}.
2502 If a macro has several definitions (of which only one is accessible),
2503 the topmost definition can be removed with @code{popdef}.  If there is
2504 no previous definition, @code{popdef} behaves like @code{undefine}, and
2505 if there is no definition at all, the @samp{d} debug level controls
2506 whether a warning is issued (@pxref{Debugmode}).
2508 The expansion of both @code{pushdef} and @code{popdef} is void.
2509 The macros @code{pushdef} and @code{popdef} are recognized only with
2510 parameters.
2511 @end deffn
2513 @example
2514 define(`foo', `Expansion one.')
2515 @result{}
2517 @result{}Expansion one.
2518 pushdef(`foo', `Expansion two.')
2519 @result{}
2521 @result{}Expansion two.
2522 pushdef(`foo', `Expansion three.')
2523 @result{}
2524 pushdef(`foo', `Expansion four.')
2525 @result{}
2526 popdef(`foo')
2527 @result{}
2529 @result{}Expansion three.
2530 popdef(`foo', `foo')
2531 @result{}
2533 @result{}Expansion one.
2534 popdef(`foo')
2535 @result{}
2537 @result{}foo
2538 @end example
2540 If a macro with several definitions is redefined with @code{define}, the
2541 topmost definition is @emph{replaced} with the new definition.  If it is
2542 removed with @code{undefine}, @emph{all} the definitions are removed,
2543 and not only the topmost one.  However, POSIX allows other
2544 implementations that treat @code{define} as replacing an entire stack
2545 of definitions with a single new definition, so to be portable to other
2546 implementations, it may be worth explicitly using @code{popdef} and
2547 @code{pushdef} rather than relying on the GNU behavior of
2548 @code{define}.
2550 @example
2551 define(`foo', `Expansion one.')
2552 @result{}
2554 @result{}Expansion one.
2555 pushdef(`foo', `Expansion two.')
2556 @result{}
2558 @result{}Expansion two.
2559 define(`foo', `Second expansion two.')
2560 @result{}
2562 @result{}Second expansion two.
2563 undefine(`foo')
2564 @result{}
2566 @result{}foo
2567 @end example
2569 @cindex local variables
2570 @cindex variables, local
2571 Local variables within macros are made with @code{pushdef} and
2572 @code{popdef}.  At the start of the macro a new definition is pushed,
2573 within the macro it is manipulated and at the end it is popped,
2574 revealing the former definition.
2576 It is possible to temporarily redefine a builtin with @code{pushdef}
2577 and @code{defn}.
2579 As of M4 1.6, @code{popdef} can warn if @var{name} is not a macro, by
2580 using @code{debugmode} (@pxref{Debugmode}) or the command line option
2581 @option{-d} (@option{--debugmode}, @pxref{Debugging options, , Invoking
2582 m4}).
2584 @example
2585 define(`a', `1')
2586 @result{}
2587 popdef
2588 @result{}popdef
2589 popdef(`a', `a')
2590 @error{}m4:stdin:3: warning: popdef: undefined macro 'a'
2591 @result{}
2592 debugmode(`-d')
2593 @result{}
2594 popdef(`a')
2595 @result{}
2596 @end example
2598 @node Renamesyms
2599 @section Renaming macros with regular expressions
2601 @cindex regular expressions
2602 @cindex macros, how to rename
2603 @cindex renaming macros
2604 @cindex GNU extensions
2605 Sometimes it is desirable to rename multiple symbols without having to
2606 use a long sequence of calls to @code{define}.  The @code{renamesyms}
2607 builtin allows this:
2609 @deffn {Builtin (gnu)} renamesyms (@var{regexp}, @var{replacement}, @
2610   @ovar{resyntax})
2611 Global renaming of macros is done by @code{renamesyms}, which selects
2612 all macros with names that match @var{regexp}, and renames each match
2613 according to @var{replacement}.  It is unspecified what happens if the
2614 rename causes multiple macros to map to the same name.
2615 @comment FIXME - right now, collisions cause a core dump on some platforms:
2616 @comment define(bar,1)define(baz,2)renamesyms(^ba., baa)dumpdef(`baa')
2618 If @var{resyntax} is given, the particular flavor of regular
2619 expression understood with respect to @var{regexp} can be changed from
2620 the current default.  @xref{Changeresyntax}, for details of the values
2621 that can be given for this argument.
2623 A macro that does not have a name that matches @var{regexp} is left
2624 with its original name.  If only part of the name matches, any part of
2625 the name that is not covered by @var{regexp} is copied to the
2626 replacement name.  Whenever a match is found in the name, the search
2627 proceeds from the end of the match, so no character in the original
2628 name can be substituted twice.  If @var{regexp} matches a string of
2629 zero length, the start position for the continued search is
2630 incremented to avoid infinite loops.
2632 Where a replacement is to be made, @var{replacement} replaces the
2633 matched text in the original name, with @samp{\@var{n}} substituted by
2634 the text matched by the @var{n}th parenthesized sub-expression of
2635 @var{regexp}, and @samp{\&} being the text matched by the entire
2636 regular expression.
2638 The expansion of @code{renamesyms} is void.
2639 The macro @code{renamesyms} is recognized only with parameters.
2640 This macro was added in M4 2.0.
2641 @end deffn
2643 The following example starts with a rename similar to the
2644 @option{--prefix-builtins} option (or @option{-P}), prefixing every
2645 macro with @code{m4_}.  However, note that @option{-P} only renames M4
2646 builtin macros, even if other macros were defined previously, while
2647 @code{renamesyms} will rename any macros that match when it runs,
2648 including text macros.  The rest of the example demonstrates the
2649 behavior of unanchored regular expressions in symbol renaming.
2651 @comment options: -Dfoo=bar -P
2652 @example
2653 $ @kbd{m4 -Dfoo=bar -P}
2655 @result{}bar
2656 m4_foo
2657 @result{}m4_foo
2658 m4_defn(`foo')
2659 @result{}bar
2660 @end example
2662 @example
2663 $ @kbd{m4}
2664 define(`foo', `bar')
2665 @result{}
2666 renamesyms(`^.*$', `m4_\&')
2667 @result{}
2669 @result{}foo
2670 m4_foo
2671 @result{}bar
2672 m4_defn(`m4_foo')
2673 @result{}bar
2674 m4_renamesyms(`f', `g')
2675 @result{}
2676 m4_igdeg(`m4_goo', `m4_goo')
2677 @result{}bar
2678 @end example
2680 If @var{resyntax} is given, @var{regexp} must be given according to
2681 the syntax chosen, though the default regular expression syntax
2682 remains unchanged for other invocations.  Here is a more realistic
2683 example that performs a similar renaming on macros, except that it
2684 ignores macros with names that begin with @samp{_}, and avoids creating
2685 macros with names that begin with @samp{m4_m4}.
2687 @example
2688 renamesyms(`^[^_]\w*$', `m4_\&')
2689 @result{}
2690 m4_renamesyms(`^m4_m4(\w*)$', `m4_\1', `POSIX_EXTENDED')
2691 @result{}
2692 m4_wrap(__line__
2694 @result{}
2696 @result{}3
2697 @end example
2699 When a symbol has multiple definitions, thanks to @code{pushdef}, the
2700 entire stack is renamed.
2702 @example
2703 pushdef(`foo', `1')pushdef(`foo', `2')
2704 @result{}
2705 renamesyms(`^foo$', `bar')
2706 @result{}
2708 @result{}2
2709 popdef(`bar')bar
2710 @result{}1
2711 popdef(`bar')bar
2712 @result{}bar
2713 @end example
2715 @node Indir
2716 @section Indirect call of macros
2718 @cindex indirect call of macros
2719 @cindex call of macros, indirect
2720 @cindex macros, indirect call of
2721 @cindex GNU extensions
2722 Any macro can be called indirectly with @code{indir}:
2724 @deffn {Builtin (gnu)} indir (@var{name}, @ovar{args@dots{}})
2725 Results in a call to the macro @var{name}, which is passed the rest of
2726 the arguments @var{args}.  If @var{name} is not defined, the expansion
2727 is void, and the @samp{d} debug level controls whether a warning is
2728 issued (@pxref{Debugmode}).
2730 The macro @code{indir} is recognized only with parameters.
2731 @end deffn
2733 This can be used to call macros with computed or ``invalid''
2734 names (@code{define} allows such names to be defined):
2736 @example
2737 define(`$$internal$macro', `Internal macro (name `$0')')
2738 @result{}
2739 $$internal$macro
2740 @result{}$$internal$macro
2741 indir(`$$internal$macro')
2742 @result{}Internal macro (name $$internal$macro)
2743 @end example
2745 The point is, here, that larger macro packages can have private macros
2746 defined, that will not be called by accident.  They can @emph{only} be
2747 called through the builtin @code{indir}.
2749 One other point to observe is that argument collection occurs before
2750 @code{indir} invokes @var{name}, so if argument collection changes the
2751 value of @var{name}, that will be reflected in the final expansion.
2752 This is different than the behavior when invoking macros directly,
2753 where the definition that was in effect before argument collection is
2754 used.
2756 @example
2757 $ @kbd{m4 -d}
2758 define(`f', `1')
2759 @result{}
2760 f(define(`f', `2'))
2761 @result{}1
2762 indir(`f', define(`f', `3'))
2763 @result{}3
2764 indir(`f', undefine(`f'))
2765 @error{}m4:stdin:4: warning: indir: undefined macro 'f'
2766 @result{}
2767 debugmode(`-d')
2768 @result{}
2769 indir(`f')
2770 @result{}
2771 @end example
2773 When handed the result of @code{defn} (@pxref{Defn}) as one of its
2774 arguments, @code{indir} defers to the invoked @var{name} for whether a
2775 token representing a builtin is recognized or flattened to the empty
2776 string.
2778 @example
2779 $ @kbd{m4 -d}
2780 indir(defn(`defn'), `divnum')
2781 @error{}m4:stdin:1: warning: indir: invalid macro name ignored
2782 @result{}
2783 indir(`define', defn(`defn'), `divnum')
2784 @error{}m4:stdin:2: warning: define: invalid macro name ignored
2785 @result{}
2786 indir(`define', `foo', defn(`divnum'))
2787 @result{}
2789 @result{}0
2790 indir(`divert', defn(`foo'))
2791 @error{}m4:stdin:5: warning: divert: empty string treated as 0
2792 @result{}
2793 @end example
2795 Warning messages issued on behalf of an indirect macro use an
2796 unambiguous representation of the macro name, using escape sequences
2797 similar to C strings, and with colons also quoted.
2799 @example
2800 define(`%%:\
2801 odd', defn(`divnum'))
2802 @result{}
2803 indir(`%%:\
2804 odd', `extra')
2805 @error{}m4:stdin:3: warning: %%\:\\\nodd: extra arguments ignored: 1 > 0
2806 @result{}0
2807 @end example
2809 @node Builtin
2810 @section Indirect call of builtins
2812 @cindex indirect call of builtins
2813 @cindex call of builtins, indirect
2814 @cindex builtins, indirect call of
2815 @cindex GNU extensions
2816 Builtin macros can be called indirectly with @code{builtin}:
2818 @deffn {Builtin (gnu)} builtin (@var{name}, @ovar{args@dots{}})
2819 @deffnx {Builtin (gnu)} builtin (@code{defn(`builtin')}, @var{name1})
2820 Results in a call to the builtin @var{name}, which is passed the
2821 rest of the arguments @var{args}.  If @var{name} does not name a
2822 builtin, the expansion is void, and the @samp{d} debug level controls
2823 whether a warning is issued (@pxref{Debugmode}).
2825 As a special case, if @var{name} is exactly the special token
2826 representing the @code{builtin} macro, as obtained by @code{defn}
2827 (@pxref{Defn}), then @var{args} must consist of a single @var{name1},
2828 and the expansion is the special token representing the builtin macro
2829 named by @var{name1}.
2831 The macro @code{builtin} is recognized only with parameters.
2832 @end deffn
2834 This can be used even if @var{name} has been given another definition
2835 that has covered the original, or been undefined so that no macro
2836 maps to the builtin.
2838 @example
2839 pushdef(`define', `hidden')
2840 @result{}
2841 undefine(`undefine')
2842 @result{}
2843 define(`foo', `bar')
2844 @result{}hidden
2846 @result{}foo
2847 builtin(`define', `foo', defn(`divnum'))
2848 @result{}
2850 @result{}0
2851 builtin(`define', `foo', `BAR')
2852 @result{}
2854 @result{}BAR
2855 undefine(`foo')
2856 @result{}undefine(foo)
2858 @result{}BAR
2859 builtin(`undefine', `foo')
2860 @result{}
2862 @result{}foo
2863 @end example
2865 The @var{name} argument only matches the original name of the builtin,
2866 even when the @option{--prefix-builtins} option (or @option{-P},
2867 @pxref{Operation modes, , Invoking m4}) is in effect.  This is different
2868 from @code{indir}, which only tracks current macro names.
2870 @comment options: -P
2871 @example
2872 $ @kbd{m4 -P}
2873 m4_builtin(`divnum')
2874 @result{}0
2875 m4_builtin(`m4_divnum')
2876 @error{}m4:stdin:2: warning: m4_builtin: undefined builtin 'm4_divnum'
2877 @result{}
2878 m4_indir(`divnum')
2879 @error{}m4:stdin:3: warning: m4_indir: undefined macro 'divnum'
2880 @result{}
2881 m4_indir(`m4_divnum')
2882 @result{}0
2883 m4_debugmode(`-d')
2884 @result{}
2885 m4_builtin(`m4_divnum')
2886 @result{}
2887 @end example
2889 Note that @code{indir} and @code{builtin} can be used to invoke builtins
2890 without arguments, even when they normally require parameters to be
2891 recognized; but it will provoke a warning, and the expansion will behave
2892 as though empty strings had been passed as the required arguments.
2894 @example
2895 builtin
2896 @result{}builtin
2897 builtin()
2898 @error{}m4:stdin:2: warning: builtin: undefined builtin ''
2899 @result{}
2900 builtin(`builtin')
2901 @error{}m4:stdin:3: warning: builtin: too few arguments: 0 < 1
2902 @result{}
2903 builtin(`builtin',)
2904 @error{}m4:stdin:4: warning: builtin: undefined builtin ''
2905 @result{}
2906 builtin(`builtin', ``'
2908 @error{}m4:stdin:5: warning: builtin: undefined builtin '`\'\n'
2909 @result{}
2910 indir(`index')
2911 @error{}m4:stdin:7: warning: index: too few arguments: 0 < 2
2912 @result{}0
2913 @end example
2915 Normally, once a builtin macro is undefined, the only way to retrieve
2916 its functionality is by defining a new macro that expands to
2917 @code{builtin} under the hood.  But this extra layer of expansion is
2918 slightly inefficient, not to mention the fact that it is not robust to
2919 changes in the current quoting scheme due to @code{changequote}
2920 (@pxref{Changequote}).  On the other hand, defining a macro to the
2921 special token produced by @code{defn} (@pxref{Defn}) is very efficient,
2922 and avoids the need for quoting within the macro definition; but
2923 @code{defn} only works if the desired macro is already defined by some
2924 other name.  So @code{builtin} provides a special case where it is
2925 possible to retrieve the same special token representing a builtin as
2926 what @code{defn} would provide, were the desired macro still defined.
2927 This feature is activated by passing @code{defn(`builtin')} as the first
2928 argument to builtin.  Normally, passing a special token representing a
2929 macro as @var{name} results in a warning and an empty expansion, but in
2930 this case, if the second argument @var{name1} names a valid builtin,
2931 there is no warning and the expansion is the appropriate special
2932 token.  In fact, with just the @code{builtin} macro accessible, it is
2933 possible to reconstitute the entire startup state of @code{m4}.
2935 In the example below, compare the number of macro invocations performed
2936 by @code{defn1} and @code{defn2}, and the differences once quoting is
2937 changed.
2939 @example
2940 $ @kbd{m4 -d}
2941 undefine(`defn')
2942 @result{}
2943 define(`foo', `bar')
2944 @result{}
2945 define(`defn1', `builtin(`defn', $@@)')
2946 @result{}
2947 define(`defn2', builtin(builtin(`defn', `builtin'), `defn'))
2948 @result{}
2949 dumpdef(`defn1', `defn2')
2950 @error{}defn1:@tabchar{}`builtin(`defn', $@@)'
2951 @error{}defn2:@tabchar{}<defn>
2952 @result{}
2953 traceon
2954 @result{}
2955 defn1(`foo')
2956 @error{}m4trace: -1- defn1(`foo') -> `builtin(`defn', `foo')'
2957 @error{}m4trace: -1- builtin(`defn', `foo') -> ``bar''
2958 @result{}bar
2959 defn2(`foo')
2960 @error{}m4trace: -1- defn2(`foo') -> ``bar''
2961 @result{}bar
2962 traceoff
2963 @error{}m4trace: -1- traceoff -> `'
2964 @result{}
2965 changequote(`[', `]')
2966 @result{}
2967 defn1([foo])
2968 @error{}m4:stdin:11: warning: builtin: undefined builtin '`defn\''
2969 @result{}
2970 defn2([foo])
2971 @result{}bar
2972 define([defn1], [builtin([defn], $@@)])
2973 @result{}
2974 defn1([foo])
2975 @result{}bar
2976 changequote
2977 @result{}
2978 defn1(`foo')
2979 @error{}m4:stdin:16: warning: builtin: undefined builtin '[defn]'
2980 @result{}
2981 @end example
2983 @node M4symbols
2984 @section Getting the defined macro names
2986 @cindex macro names, listing
2987 @cindex listing macro names
2988 @cindex currently defined macros
2989 @cindex GNU extensions
2990 The name of the currently defined macros can be accessed by
2991 @code{m4symbols}:
2993 @deffn {Builtin (gnu)} m4symbols (@ovar{names@dots{}})
2994 Without arguments, @code{m4symbols} expands to a sorted list of quoted
2995 strings, separated by commas.  This contrasts with @code{dumpdef}
2996 (@pxref{Dumpdef}), whose output cannot be accessed by @code{m4}
2997 programs.
2999 When given arguments, @code{m4symbols} returns the sorted subset of the
3000 @var{names} currently defined, and silently ignores the rest.
3001 This macro was added in M4 2.0.
3002 @end deffn
3004 @example
3005 m4symbols(`ifndef', `ifdef', `define', `undef')
3006 @result{}define,ifdef
3007 @end example
3009 @node Conditionals
3010 @chapter Conditionals, loops, and recursion
3012 Macros, expanding to plain text, perhaps with arguments, are not quite
3013 enough.  We would like to have macros expand to different things, based
3014 on decisions taken at run-time.  For that, we need some kind of conditionals.
3015 Also, we would like to have some kind of loop construct, so we could do
3016 something a number of times, or while some condition is true.
3018 @menu
3019 * Ifdef::                       Testing if a macro is defined
3020 * Ifelse::                      If-else construct, or multibranch
3021 * Shift::                       Recursion in @code{m4}
3022 * Forloop::                     Iteration by counting
3023 * Foreach::                     Iteration by list contents
3024 * Stacks::                      Working with definition stacks
3025 * Composition::                 Building macros with macros
3026 @end menu
3028 @node Ifdef
3029 @section Testing if a macro is defined
3031 @cindex conditionals
3032 There are two different builtin conditionals in @code{m4}.  The first is
3033 @code{ifdef}:
3035 @deffn {Builtin (m4)} ifdef (@var{name}, @var{string-1}, @ovar{string-2})
3036 If @var{name} is defined as a macro, @code{ifdef} expands to
3037 @var{string-1}, otherwise to @var{string-2}.  If @var{string-2} is
3038 omitted, it is taken to be the empty string (according to the normal
3039 rules).
3041 The macro @code{ifdef} is recognized only with parameters.
3042 @end deffn
3044 @example
3045 ifdef(`foo', ``foo' is defined', ``foo' is not defined')
3046 @result{}foo is not defined
3047 define(`foo', `')
3048 @result{}
3049 ifdef(`foo', ``foo' is defined', ``foo' is not defined')
3050 @result{}foo is defined
3051 ifdef(`no_such_macro', `yes', `no', `extra argument')
3052 @error{}m4:stdin:4: warning: ifdef: extra arguments ignored: 4 > 3
3053 @result{}no
3054 @end example
3056 As of M4 1.6, @code{ifdef} transparently handles builtin tokens
3057 generated by @code{defn} (@pxref{Defn}) that occur in either
3058 @var{string}, although a warning is issued for invalid macro names.
3060 @example
3061 define(`', `empty')
3062 @result{}
3063 ifdef(defn(`defn'), `yes', `no')
3064 @error{}m4:stdin:2: warning: ifdef: invalid macro name ignored
3065 @result{}no
3066 define(`foo', ifdef(`divnum', defn(`divnum'), `undefined'))
3067 @result{}
3069 @result{}0
3070 @end example
3072 @node Ifelse
3073 @section If-else construct, or multibranch
3075 @cindex comparing strings
3076 @cindex discarding input
3077 @cindex input, discarding
3078 The other conditional, @code{ifelse}, is much more powerful.  It can be
3079 used as a way to introduce a long comment, as an if-else construct, or
3080 as a multibranch, depending on the number of arguments supplied:
3082 @deffn {Builtin (m4)} ifelse (@var{comment})
3083 @deffnx {Builtin (m4)} ifelse (@var{string-1}, @var{string-2}, @var{equal}, @
3084   @ovar{not-equal})
3085 @deffnx {Builtin (m4)} ifelse (@var{string-1}, @var{string-2}, @var{equal-1}, @
3086   @var{string-3}, @var{string-4}, @var{equal-2}, @dots{}, @ovar{not-equal})
3087 Used with only one argument, the @code{ifelse} simply discards it and
3088 produces no output.
3090 If called with three or four arguments, @code{ifelse} expands into
3091 @var{equal}, if @var{string-1} and @var{string-2} are equal (character
3092 for character), otherwise it expands to @var{not-equal}.  A final fifth
3093 argument is ignored, after triggering a warning.
3095 If called with six or more arguments, and @var{string-1} and
3096 @var{string-2} are equal, @code{ifelse} expands into @var{equal-1},
3097 otherwise the first three arguments are discarded and the processing
3098 starts again.
3100 The macro @code{ifelse} is recognized only with parameters.
3101 @end deffn
3103 Using only one argument is a common @code{m4} idiom for introducing a
3104 block comment, as an alternative to repeatedly using @code{dnl}.  This
3105 special usage is recognized by GNU @code{m4}, so that in this
3106 case, the warning about missing arguments is never triggered.
3108 @example
3109 ifelse(`some comments')
3110 @result{}
3111 ifelse(`foo', `bar')
3112 @error{}m4:stdin:2: warning: ifelse: too few arguments: 2 < 3
3113 @result{}
3114 @end example
3116 Using three or four arguments provides decision points.
3118 @example
3119 ifelse(`foo', `bar', `true')
3120 @result{}
3121 ifelse(`foo', `foo', `true')
3122 @result{}true
3123 define(`foo', `bar')
3124 @result{}
3125 ifelse(foo, `bar', `true', `false')
3126 @result{}true
3127 ifelse(foo, `foo', `true', `false')
3128 @result{}false
3129 @end example
3131 @cindex macro, blind
3132 @cindex blind macro
3133 Notice how the first argument was used unquoted; it is common to compare
3134 the expansion of a macro with a string.  With this macro, you can now
3135 reproduce the behavior of blind builtins, where the macro is recognized
3136 only with arguments.
3138 @example
3139 define(`foo', `ifelse(`$#', `0', ``$0'', `arguments:$#')')
3140 @result{}
3142 @result{}foo
3143 foo()
3144 @result{}arguments:1
3145 foo(`a', `b', `c')
3146 @result{}arguments:3
3147 @end example
3149 For an example of a way to make defining blind macros easier, see
3150 @ref{Composition}.
3152 @cindex multibranches
3153 @cindex switch statement
3154 @cindex case statement
3155 The macro @code{ifelse} can take more than four arguments.  If given more
3156 than four arguments, @code{ifelse} works like a @code{case} or @code{switch}
3157 statement in traditional programming languages.  If @var{string-1} and
3158 @var{string-2} are equal, @code{ifelse} expands into @var{equal-1}, otherwise
3159 the procedure is repeated with the first three arguments discarded.  This
3160 calls for an example:
3162 @example
3163 ifelse(`foo', `bar', `third', `gnu', `gnats')
3164 @error{}m4:stdin:1: warning: ifelse: extra arguments ignored: 5 > 4
3165 @result{}gnu
3166 ifelse(`foo', `bar', `third', `gnu', `gnats', `sixth')
3167 @result{}
3168 ifelse(`foo', `bar', `third', `gnu', `gnats', `sixth', `seventh')
3169 @result{}seventh
3170 ifelse(`foo', `bar', `3', `gnu', `gnats', `6', `7', `8')
3171 @error{}m4:stdin:4: warning: ifelse: extra arguments ignored: 8 > 7
3172 @result{}7
3173 @end example
3175 As of M4 1.6, @code{ifelse} transparently handles builtin tokens
3176 generated by @code{defn} (@pxref{Defn}).  Because of this, it is always
3177 safe to compare two macro definitions, without worrying whether the
3178 macro might be a builtin.
3180 @example
3181 ifelse(defn(`defn'), `', `yes', `no')
3182 @result{}no
3183 ifelse(defn(`defn'), defn(`divnum'), `yes', `no')
3184 @result{}no
3185 ifelse(defn(`defn'), defn(`defn'), `yes', `no')
3186 @result{}yes
3187 define(`foo', ifelse(`', `', defn(`divnum')))
3188 @result{}
3190 @result{}0
3191 @end example
3193 Naturally, the normal case will be slightly more advanced than these
3194 examples.  A common use of @code{ifelse} is in macros implementing loops
3195 of various kinds.
3197 @node Shift
3198 @section Recursion in @code{m4}
3200 @cindex recursive macros
3201 @cindex macros, recursive
3202 There is no direct support for loops in @code{m4}, but macros can be
3203 recursive.  There is no limit on the number of recursion levels, other
3204 than those enforced by your hardware and operating system.
3206 @cindex loops
3207 Loops can be programmed using recursion and the conditionals described
3208 previously.
3210 There is a builtin macro, @code{shift}, which can, among other things,
3211 be used for iterating through the actual arguments to a macro:
3213 @deffn {Builtin (m4)} shift (@var{arg1}, @dots{})
3214 Takes any number of arguments, and expands to all its arguments except
3215 @var{arg1}, separated by commas, with each argument quoted.
3217 The macro @code{shift} is recognized only with parameters.
3218 @end deffn
3220 @example
3221 shift
3222 @result{}shift
3223 shift(`bar')
3224 @result{}
3225 shift(`foo', `bar', `baz')
3226 @result{}bar,baz
3227 @end example
3229 An example of the use of @code{shift} is this macro:
3231 @cindex reversing arguments
3232 @cindex arguments, reversing
3233 @deffn Composite reverse (@dots{})
3234 Takes any number of arguments, and reverses their order.
3235 @end deffn
3237 It is implemented as:
3239 @example
3240 define(`reverse', `ifelse(`$#', `0', , `$#', `1', ``$1'',
3241                           `reverse(shift($@@)), `$1'')')
3242 @result{}
3243 reverse
3244 @result{}
3245 reverse(`foo')
3246 @result{}foo
3247 reverse(`foo', `bar', `gnats', `and gnus')
3248 @result{}and gnus, gnats, bar, foo
3249 @end example
3251 While not a very interesting macro, it does show how simple loops can be
3252 made with @code{shift}, @code{ifelse} and recursion.  It also shows
3253 that @code{shift} is usually used with @samp{$@@}.  Another example of
3254 this is an implementation of a short-circuiting conditional operator.
3256 @cindex short-circuiting conditional
3257 @cindex conditional, short-circuiting
3258 @deffn Composite cond (@var{test-1}, @var{string-1}, @var{equal-1}, @
3259   @ovar{test-2}, @ovar{string-2}, @ovar{equal-2}, @dots{}, @ovar{not-equal})
3260 Similar to @code{ifelse}, where an equal comparison between the first
3261 two strings results in the third, otherwise the first three arguments
3262 are discarded and the process repeats.  The difference is that each
3263 @var{test-<n>} is expanded only when it is encountered.  This means that
3264 every third argument to @code{cond} is normally given one more level of
3265 quoting than the corresponding argument to @code{ifelse}.
3266 @end deffn
3268 Here is the implementation of @code{cond}, along with a demonstration of
3269 how it can short-circuit the side effects in @code{side}.  Notice how
3270 all the unquoted side effects happen regardless of how many comparisons
3271 are made with @code{ifelse}, compared with only the relevant effects
3272 with @code{cond}.
3274 @example
3275 define(`cond',
3276 `ifelse(`$#', `1', `$1',
3277         `ifelse($1, `$2', `$3',
3278                 `$0(shift(shift(shift($@@))))')')')dnl
3279 define(`side', `define(`counter', incr(counter))$1')dnl
3280 define(`example1',
3281 `define(`counter', `0')dnl
3282 ifelse(side(`$1'), `yes', `one comparison: ',
3283        side(`$1'), `no', `two comparisons: ',
3284        side(`$1'), `maybe', `three comparisons: ',
3285        `side(`default answer: ')')counter')dnl
3286 define(`example2',
3287 `define(`counter', `0')dnl
3288 cond(`side(`$1')', `yes', `one comparison: ',
3289      `side(`$1')', `no', `two comparisons: ',
3290      `side(`$1')', `maybe', `three comparisons: ',
3291      `side(`default answer: ')')counter')dnl
3292 example1(`yes')
3293 @result{}one comparison: 3
3294 example1(`no')
3295 @result{}two comparisons: 3
3296 example1(`maybe')
3297 @result{}three comparisons: 3
3298 example1(`feeling rather indecisive today')
3299 @result{}default answer: 4
3300 example2(`yes')
3301 @result{}one comparison: 1
3302 example2(`no')
3303 @result{}two comparisons: 2
3304 example2(`maybe')
3305 @result{}three comparisons: 3
3306 example2(`feeling rather indecisive today')
3307 @result{}default answer: 4
3308 @end example
3310 @cindex joining arguments
3311 @cindex arguments, joining
3312 @cindex concatenating arguments
3313 Another common task that requires iteration is joining a list of
3314 arguments into a single string.
3316 @deffn Composite join (@ovar{separator}, @ovar{args@dots{}})
3317 @deffnx Composite joinall (@ovar{separator}, @ovar{args@dots{}})
3318 Generate a single-quoted string, consisting of each @var{arg} separated
3319 by @var{separator}.  While @code{joinall} always outputs a
3320 @var{separator} between arguments, @code{join} avoids the
3321 @var{separator} for an empty @var{arg}.
3322 @end deffn
3324 Here are some examples of its usage, based on the implementation
3325 @file{m4-@value{VERSION}/@/examples/@/join.m4} distributed in this
3326 package:
3328 @comment examples
3329 @example
3330 $ @kbd{m4 -I examples}
3331 include(`join.m4')
3332 @result{}
3333 join,join(`-'),join(`-', `'),join(`-', `', `')
3334 @result{},,,
3335 joinall,joinall(`-'),joinall(`-', `'),joinall(`-', `', `')
3336 @result{},,,-
3337 join(`-', `1')
3338 @result{}1
3339 join(`-', `1', `2', `3')
3340 @result{}1-2-3
3341 join(`', `1', `2', `3')
3342 @result{}123
3343 join(`-', `', `1', `', `', `2', `')
3344 @result{}1-2
3345 joinall(`-', `', `1', `', `', `2', `')
3346 @result{}-1---2-
3347 join(`,', `1', `2', `3')
3348 @result{}1,2,3
3349 define(`nargs', `$#')dnl
3350 nargs(join(`,', `1', `2', `3'))
3351 @result{}1
3352 @end example
3354 Examining the implementation shows some interesting points about several
3355 m4 programming idioms.
3357 @comment examples
3358 @example
3359 $ @kbd{m4 -I examples}
3360 undivert(`join.m4')dnl
3361 @result{}divert(`-1')
3362 @result{}# join(sep, args) - join each non-empty ARG into a single
3363 @result{}# string, with each element separated by SEP
3364 @result{}define(`join',
3365 @result{}`ifelse(`$#', `2', ``$2'',
3366 @result{}  `ifelse(`$2', `', `', ``$2'_')$0(`$1', shift(shift($@@)))')')
3367 @result{}define(`_join',
3368 @result{}`ifelse(`$#$2', `2', `',
3369 @result{}  `ifelse(`$2', `', `', ``$1$2'')$0(`$1', shift(shift($@@)))')')
3370 @result{}# joinall(sep, args) - join each ARG, including empty ones,
3371 @result{}# into a single string, with each element separated by SEP
3372 @result{}define(`joinall', ``$2'_$0(`$1', shift($@@))')
3373 @result{}define(`_joinall',
3374 @result{}`ifelse(`$#', `2', `', ``$1$3'$0(`$1', shift(shift($@@)))')')
3375 @result{}divert`'dnl
3376 @end example
3378 First, notice that this implementation creates helper macros
3379 @code{_join} and @code{_joinall}.  This division of labor makes it
3380 easier to output the correct number of @var{separator} instances:
3381 @code{join} and @code{joinall} are responsible for the first argument,
3382 without a separator, while @code{_join} and @code{_joinall} are
3383 responsible for all remaining arguments, always outputting a separator
3384 when outputting an argument.
3386 Next, observe how @code{join} decides to iterate to itself, because the
3387 first @var{arg} was empty, or to output the argument and swap over to
3388 @code{_join}.  If the argument is non-empty, then the nested
3389 @code{ifelse} results in an unquoted @samp{_}, which is concatenated
3390 with the @samp{$0} to form the next macro name to invoke.  The
3391 @code{joinall} implementation is simpler since it does not have to
3392 suppress empty @var{arg}; it always executes once then defers to
3393 @code{_joinall}.
3395 Another important idiom is the idea that @var{separator} is reused for
3396 each iteration.  Each iteration has one less argument, but rather than
3397 discarding @samp{$1} by iterating with @code{$0(shift($@@))}, the macro
3398 discards @samp{$2} by using @code{$0(`$1', shift(shift($@@)))}.
3400 Next, notice that it is possible to compare more than one condition in a
3401 single @code{ifelse} test.  The test of @samp{$#$2} against @samp{2}
3402 allows @code{_join} to iterate for two separate reasons---either there
3403 are still more than two arguments, or there are exactly two arguments
3404 but the last argument is not empty.
3406 Finally, notice that these macros require exactly two arguments to
3407 terminate recursion, but that they still correctly result in empty
3408 output when given no @var{args} (i.e., zero or one macro argument).  On
3409 the first pass when there are too few arguments, the @code{shift}
3410 results in no output, but leaves an empty string to serve as the
3411 required second argument for the second pass.  Put another way,
3412 @samp{`$1', shift($@@)} is not the same as @samp{$@@}, since only the
3413 former guarantees at least two arguments.
3415 @cindex quote manipulation
3416 @cindex manipulating quotes
3417 Sometimes, a recursive algorithm requires adding quotes to each element,
3418 or treating multiple arguments as a single element:
3420 @deffn Composite quote (@dots{})
3421 @deffnx Composite dquote (@dots{})
3422 @deffnx Composite dquote_elt (@dots{})
3423 Takes any number of arguments, and adds quoting.  With @code{quote},
3424 only one level of quoting is added, effectively removing whitespace
3425 after commas and turning multiple arguments into a single string.  With
3426 @code{dquote}, two levels of quoting are added, one around each element,
3427 and one around the list.  And with @code{dquote_elt}, two levels of
3428 quoting are added around each element.
3429 @end deffn
3431 An actual implementation of these three macros is distributed as
3432 @file{m4-@value{VERSION}/@/examples/@/quote.m4} in this package.  First,
3433 let's examine their usage:
3435 @comment examples
3436 @example
3437 $ @kbd{m4 -I examples}
3438 include(`quote.m4')
3439 @result{}
3440 -quote-dquote-dquote_elt-
3441 @result{}----
3442 -quote()-dquote()-dquote_elt()-
3443 @result{}--`'-`'-
3444 -quote(`1')-dquote(`1')-dquote_elt(`1')-
3445 @result{}-1-`1'-`1'-
3446 -quote(`1', `2')-dquote(`1', `2')-dquote_elt(`1', `2')-
3447 @result{}-1,2-`1',`2'-`1',`2'-
3448 define(`n', `$#')dnl
3449 -n(quote(`1', `2'))-n(dquote(`1', `2'))-n(dquote_elt(`1', `2'))-
3450 @result{}-1-1-2-
3451 dquote(dquote_elt(`1', `2'))
3452 @result{}``1'',``2''
3453 dquote_elt(dquote(`1', `2'))
3454 @result{}``1',`2''
3455 @end example
3457 The last two lines show that when given two arguments, @code{dquote}
3458 results in one string, while @code{dquote_elt} results in two.  Now,
3459 examine the implementation.  Note that @code{quote} and
3460 @code{dquote_elt} make decisions based on their number of arguments, so
3461 that when called without arguments, they result in nothing instead of a
3462 quoted empty string; this is so that it is possible to distinguish
3463 between no arguments and an empty first argument.  @code{dquote}, on the
3464 other hand, results in a string no matter what, since it is still
3465 possible to tell whether it was invoked without arguments based on the
3466 resulting string.
3468 @comment examples
3469 @example
3470 $ @kbd{m4 -I examples}
3471 undivert(`quote.m4')dnl
3472 @result{}divert(`-1')
3473 @result{}# quote(args) - convert args to single-quoted string
3474 @result{}define(`quote', `ifelse(`$#', `0', `', ``$*'')')
3475 @result{}# dquote(args) - convert args to quoted list of quoted strings
3476 @result{}define(`dquote', ``$@@'')
3477 @result{}# dquote_elt(args) - convert args to list of double-quoted strings
3478 @result{}define(`dquote_elt', `ifelse(`$#', `0', `', `$#', `1', ```$1''',
3479 @result{}                             ```$1'',$0(shift($@@))')')
3480 @result{}divert`'dnl
3481 @end example
3483 It is worth pointing out that @samp{quote(@var{args})} is more efficient
3484 than @samp{joinall(`,', @var{args})} for producing the same output.
3486 @cindex nine arguments, more than
3487 @cindex more than nine arguments
3488 @cindex arguments, more than nine
3489 One more useful macro based on @code{shift} allows portably selecting
3490 an arbitrary argument (usually greater than the ninth argument), without
3491 relying on the GNU extension of multi-digit arguments
3492 (@pxref{Arguments}).
3494 @deffn Composite argn (@var{n}, @dots{})
3495 Expands to argument @var{n} out of the remaining arguments.  @var{n}
3496 must be a positive number.  Usually invoked as
3497 @samp{argn(`@var{n}',$@@)}.
3498 @end deffn
3500 It is implemented as:
3502 @example
3503 define(`argn', `ifelse(`$1', 1, ``$2'',
3504   `argn(decr(`$1'), shift(shift($@@)))')')
3505 @result{}
3506 argn(`1', `a')
3507 @result{}a
3508 define(`foo', `argn(`11', $@@)')
3509 @result{}
3510 foo(`a', `b', `c', `d', `e', `f', `g', `h', `i', `j', `k', `l')
3511 @result{}k
3512 @end example
3514 @node Forloop
3515 @section Iteration by counting
3517 @cindex for loops
3518 @cindex loops, counting
3519 @cindex counting loops
3520 Here is an example of a loop macro that implements a simple for loop.
3522 @deffn Composite forloop (@var{iterator}, @var{start}, @var{end}, @var{text})
3523 Takes the name in @var{iterator}, which must be a valid macro name, and
3524 successively assign it each integer value from @var{start} to @var{end},
3525 inclusive.  For each assignment to @var{iterator}, append @var{text} to
3526 the expansion of the @code{forloop}.  @var{text} may refer to
3527 @var{iterator}.  Any definition of @var{iterator} prior to this
3528 invocation is restored.
3529 @end deffn
3531 It can, for example, be used for simple counting:
3533 @comment examples
3534 @example
3535 $ @kbd{m4 -I examples}
3536 include(`forloop.m4')
3537 @result{}
3538 forloop(`i', `1', `8', `i ')
3539 @result{}1 2 3 4 5 6 7 8@w{ }
3540 @end example
3542 For-loops can be nested, like:
3544 @comment examples
3545 @example
3546 $ @kbd{m4 -I examples}
3547 include(`forloop.m4')
3548 @result{}
3549 forloop(`i', `1', `4', `forloop(`j', `1', `8', ` (i, j)')
3551 @result{} (1, 1) (1, 2) (1, 3) (1, 4) (1, 5) (1, 6) (1, 7) (1, 8)
3552 @result{} (2, 1) (2, 2) (2, 3) (2, 4) (2, 5) (2, 6) (2, 7) (2, 8)
3553 @result{} (3, 1) (3, 2) (3, 3) (3, 4) (3, 5) (3, 6) (3, 7) (3, 8)
3554 @result{} (4, 1) (4, 2) (4, 3) (4, 4) (4, 5) (4, 6) (4, 7) (4, 8)
3555 @result{}
3556 @end example
3558 The implementation of the @code{forloop} macro is fairly
3559 straightforward.  The @code{forloop} macro itself is simply a wrapper,
3560 which saves the previous definition of the first argument, calls the
3561 internal macro @code{@w{_forloop}}, and re-establishes the saved
3562 definition of the first argument.
3564 The macro @code{@w{_forloop}} expands the fourth argument once, and
3565 tests to see if the iterator has reached the final value.  If it has
3566 not finished, it increments the iterator (using the predefined macro
3567 @code{incr}, @pxref{Incr}), and recurses.
3569 Here is an actual implementation of @code{forloop}, distributed as
3570 @file{m4-@value{VERSION}/@/examples/@/forloop.m4} in this package:
3572 @comment examples
3573 @example
3574 $ @kbd{m4 -I examples}
3575 undivert(`forloop.m4')dnl
3576 @result{}divert(`-1')
3577 @result{}# forloop(var, from, to, stmt) - simple version
3578 @result{}define(`forloop', `pushdef(`$1', `$2')_forloop($@@)popdef(`$1')')
3579 @result{}define(`_forloop',
3580 @result{}       `$4`'ifelse($1, `$3', `', `define(`$1', incr($1))$0($@@)')')
3581 @result{}divert`'dnl
3582 @end example
3584 Notice the careful use of quotes.  Certain macro arguments are left
3585 unquoted, each for its own reason.  Try to find out @emph{why} these
3586 arguments are left unquoted, and see what happens if they are quoted.
3587 (As presented, these two macros are useful but not very robust for
3588 general use.  They lack even basic error handling for cases like
3589 @var{start} less than @var{end}, @var{end} not numeric, or
3590 @var{iterator} not being a macro name.  See if you can improve these
3591 macros; or @pxref{Improved forloop, , Answers}).
3593 @node Foreach
3594 @section Iteration by list contents
3596 @cindex for each loops
3597 @cindex loops, list iteration
3598 @cindex iterating over lists
3599 Here is an example of a loop macro that implements list iteration.
3601 @deffn Composite foreach (@var{iterator}, @var{paren-list}, @var{text})
3602 @deffnx Composite foreachq (@var{iterator}, @var{quote-list}, @var{text})
3603 Takes the name in @var{iterator}, which must be a valid macro name, and
3604 successively assign it each value from @var{paren-list} or
3605 @var{quote-list}.  In @code{foreach}, @var{paren-list} is a
3606 comma-separated list of elements contained in parentheses.  In
3607 @code{foreachq}, @var{quote-list} is a comma-separated list of elements
3608 contained in a quoted string.  For each assignment to @var{iterator},
3609 append @var{text} to the overall expansion.  @var{text} may refer to
3610 @var{iterator}.  Any definition of @var{iterator} prior to this
3611 invocation is restored.
3612 @end deffn
3614 As an example, this displays each word in a list inside of a sentence,
3615 using an implementation of @code{foreach} distributed as
3616 @file{m4-@value{VERSION}/@/examples/@/foreach.m4}, and @code{foreachq}
3617 in @file{m4-@value{VERSION}/@/examples/@/foreachq.m4}.
3619 @comment examples
3620 @example
3621 $ @kbd{m4 -I examples}
3622 include(`foreach.m4')
3623 @result{}
3624 foreach(`x', (foo, bar, foobar), `Word was: x
3625 ')dnl
3626 @result{}Word was: foo
3627 @result{}Word was: bar
3628 @result{}Word was: foobar
3629 include(`foreachq.m4')
3630 @result{}
3631 foreachq(`x', `foo, bar, foobar', `Word was: x
3632 ')dnl
3633 @result{}Word was: foo
3634 @result{}Word was: bar
3635 @result{}Word was: foobar
3636 @end example
3638 It is possible to be more complex; each element of the @var{paren-list}
3639 or @var{quote-list} can itself be a list, to pass as further arguments
3640 to a helper macro.  This example generates a shell case statement:
3642 @comment examples
3643 @example
3644 $ @kbd{m4 -I examples}
3645 include(`foreach.m4')
3646 @result{}
3647 define(`_case', `  $1)
3648     $2=" $1";;
3649 ')dnl
3650 define(`_cat', `$1$2')dnl
3651 case $`'1 in
3652 @result{}case $1 in
3653 foreach(`x', `(`(`a', `vara')', `(`b', `varb')', `(`c', `varc')')',
3654         `_cat(`_case', x)')dnl
3655 @result{}  a)
3656 @result{}    vara=" a";;
3657 @result{}  b)
3658 @result{}    varb=" b";;
3659 @result{}  c)
3660 @result{}    varc=" c";;
3661 esac
3662 @result{}esac
3663 @end example
3665 The implementation of the @code{foreach} macro is a bit more involved;
3666 it is a wrapper around two helper macros.  First, @code{@w{_arg1}} is
3667 needed to grab the first element of a list.  Second,
3668 @code{@w{_foreach}} implements the recursion, successively walking
3669 through the original list.  Here is a simple implementation of
3670 @code{foreach}:
3672 @comment examples
3673 @example
3674 $ @kbd{m4 -I examples}
3675 undivert(`foreach.m4')dnl
3676 @result{}divert(`-1')
3677 @result{}# foreach(x, (item_1, item_2, ..., item_n), stmt)
3678 @result{}#   parenthesized list, simple version
3679 @result{}define(`foreach', `pushdef(`$1')_foreach($@@)popdef(`$1')')
3680 @result{}define(`_arg1', `$1')
3681 @result{}define(`_foreach', `ifelse(`$2', `()', `',
3682 @result{}  `define(`$1', _arg1$2)$3`'$0(`$1', (shift$2), `$3')')')
3683 @result{}divert`'dnl
3684 @end example
3686 Unfortunately, that implementation is not robust to macro names as list
3687 elements.  Each iteration of @code{@w{_foreach}} is stripping another
3688 layer of quotes, leading to erratic results if list elements are not
3689 already fully expanded.  The first cut at implementing @code{foreachq}
3690 takes this into account.  Also, when using quoted elements in a
3691 @var{paren-list}, the overall list must be quoted.  A @var{quote-list}
3692 has the nice property of requiring fewer characters to create a list
3693 containing the same quoted elements.  To see the difference between the
3694 two macros, we attempt to pass double-quoted macro names in a list,
3695 expecting the macro name on output after one layer of quotes is removed
3696 during list iteration and the final layer removed during the final
3697 rescan:
3699 @comment examples
3700 @example
3701 $ @kbd{m4 -I examples}
3702 define(`a', `1')define(`b', `2')define(`c', `3')
3703 @result{}
3704 include(`foreach.m4')
3705 @result{}
3706 include(`foreachq.m4')
3707 @result{}
3708 foreach(`x', `(``a'', ``(b'', ``c)'')', `x
3710 @result{}1
3711 @result{}(2)1
3712 @result{}
3713 @result{}, x
3714 @result{})
3715 foreachq(`x', ```a'', ``(b'', ``c)''', `x
3716 ')dnl
3717 @result{}a
3718 @result{}(b
3719 @result{}c)
3720 @end example
3722 Obviously, @code{foreachq} did a better job; here is its implementation:
3724 @comment examples
3725 @example
3726 $ @kbd{m4 -I examples}
3727 undivert(`foreachq.m4')dnl
3728 @result{}include(`quote.m4')dnl
3729 @result{}divert(`-1')
3730 @result{}# foreachq(x, `item_1, item_2, ..., item_n', stmt)
3731 @result{}#   quoted list, simple version
3732 @result{}define(`foreachq', `pushdef(`$1')_foreachq($@@)popdef(`$1')')
3733 @result{}define(`_arg1', `$1')
3734 @result{}define(`_foreachq', `ifelse(quote($2), `', `',
3735 @result{}  `define(`$1', `_arg1($2)')$3`'$0(`$1', `shift($2)', `$3')')')
3736 @result{}divert`'dnl
3737 @end example
3739 Notice that @code{@w{_foreachq}} had to use the helper macro
3740 @code{quote} defined earlier (@pxref{Shift}), to ensure that the
3741 embedded @code{ifelse} call does not go haywire if a list element
3742 contains a comma.  Unfortunately, this implementation of @code{foreachq}
3743 has its own severe flaw.  Whereas the @code{foreach} implementation was
3744 linear, this macro is quadratic in the number of list elements, and is
3745 much more likely to trip up the limit set by the command line option
3746 @option{--nesting-limit} (or @option{-L}, @pxref{Limits control, ,
3747 Invoking m4}).  Additionally, this implementation does not expand
3748 @samp{defn(`@var{iterator}')} very well, when compared with
3749 @code{foreach}.
3751 @comment examples
3752 @example
3753 $ @kbd{m4 -I examples}
3754 include(`foreach.m4')include(`foreachq.m4')
3755 @result{}
3756 foreach(`name', `(`a', `b')', ` defn(`name')')
3757 @result{} a b
3758 foreachq(`name', ``a', `b'', ` defn(`name')')
3759 @result{} _arg1(`a', `b') _arg1(shift(`a', `b'))
3760 @end example
3762 It is possible to have robust iteration with linear behavior and sane
3763 @var{iterator} contents for either list style.  See if you can learn
3764 from the best elements of both of these implementations to create robust
3765 macros (or @pxref{Improved foreach, , Answers}).
3767 @node Stacks
3768 @section Working with definition stacks
3770 @cindex definition stack
3771 @cindex pushdef stack
3772 @cindex stack, macro definition
3773 Thanks to @code{pushdef}, manipulation of a stack is an intrinsic
3774 operation in @code{m4}.  Normally, only the topmost definition in a
3775 stack is important, but sometimes, it is desirable to manipulate the
3776 entire definition stack.
3778 @deffn Composite stack_foreach (@var{macro}, @var{action})
3779 @deffnx Composite stack_foreach_lifo (@var{macro}, @var{action})
3780 For each of the @code{pushdef} definitions associated with @var{macro},
3781 invoke the macro @var{action} with a single argument of that definition.
3782 @code{stack_foreach} visits the oldest definition first, while
3783 @code{stack_foreach_lifo} visits the current definition first.
3784 @var{action} should not modify or dereference @var{macro}.  There are a
3785 few special macros, such as @code{defn}, which cannot be used as the
3786 @var{macro} parameter.
3787 @end deffn
3789 A sample implementation of these macros is distributed in the file
3790 @file{m4-@value{VERSION}/@/examples/@/stack.m4}.
3792 @comment examples
3793 @example
3794 $ @kbd{m4 -I examples}
3795 include(`stack.m4')
3796 @result{}
3797 pushdef(`a', `1')pushdef(`a', `2')pushdef(`a', `3')
3798 @result{}
3799 define(`show', ``$1'
3801 @result{}
3802 stack_foreach(`a', `show')dnl
3803 @result{}1
3804 @result{}2
3805 @result{}3
3806 stack_foreach_lifo(`a', `show')dnl
3807 @result{}3
3808 @result{}2
3809 @result{}1
3810 @end example
3812 Now for the implementation.  Note the definition of a helper macro,
3813 @code{_stack_reverse}, which destructively swaps the contents of one
3814 stack of definitions into the reverse order in the temporary macro
3815 @samp{tmp-$1}.  By calling the helper twice, the original order is
3816 restored back into the macro @samp{$1}; since the operation is
3817 destructive, this explains why @samp{$1} must not be modified or
3818 dereferenced during the traversal.  The caller can then inject
3819 additional code to pass the definition currently being visited to
3820 @samp{$2}.  The choice of helper names is intentional; since @samp{-} is
3821 not valid as part of a macro name, there is no risk of conflict with a
3822 valid macro name, and the code is guaranteed to use @code{defn} where
3823 necessary.  Finally, note that any macro used in the traversal of a
3824 @code{pushdef} stack, such as @code{pushdef} or @code{defn}, cannot be
3825 handled by @code{stack_foreach}, since the macro would temporarily be
3826 undefined during the algorithm.
3828 @comment examples
3829 @example
3830 $ @kbd{m4 -I examples}
3831 undivert(`stack.m4')dnl
3832 @result{}divert(`-1')
3833 @result{}# stack_foreach(macro, action)
3834 @result{}# Invoke ACTION with a single argument of each definition
3835 @result{}# from the definition stack of MACRO, starting with the oldest.
3836 @result{}define(`stack_foreach',
3837 @result{}`_stack_reverse(`$1', `tmp-$1')'dnl
3838 @result{}`_stack_reverse(`tmp-$1', `$1', `$2(defn(`$1'))')')
3839 @result{}# stack_foreach_lifo(macro, action)
3840 @result{}# Invoke ACTION with a single argument of each definition
3841 @result{}# from the definition stack of MACRO, starting with the newest.
3842 @result{}define(`stack_foreach_lifo',
3843 @result{}`_stack_reverse(`$1', `tmp-$1', `$2(defn(`$1'))')'dnl
3844 @result{}`_stack_reverse(`tmp-$1', `$1')')
3845 @result{}define(`_stack_reverse',
3846 @result{}`ifdef(`$1', `pushdef(`$2', defn(`$1'))$3`'popdef(`$1')$0($@@)')')
3847 @result{}divert`'dnl
3848 @end example
3850 @node Composition
3851 @section Building macros with macros
3853 @cindex macro composition
3854 @cindex composing macros
3855 Since m4 is a macro language, it is possible to write macros that
3856 can build other macros.  First on the list is a way to automate the
3857 creation of blind macros.
3859 @cindex macro, blind
3860 @cindex blind macro
3861 @deffn Composite define_blind (@var{name}, @ovar{value})
3862 Defines @var{name} as a blind macro, such that @var{name} will expand to
3863 @var{value} only when given explicit arguments.  @var{value} should not
3864 be the result of @code{defn} (@pxref{Defn}).  This macro is only
3865 recognized with parameters, and results in an empty string.
3866 @end deffn
3868 Defining a macro to define another macro can be a bit tricky.  We want
3869 to use a literal @samp{$#} in the argument to the nested @code{define}.
3870 However, if @samp{$} and @samp{#} are adjacent in the definition of
3871 @code{define_blind}, then it would be expanded as the number of
3872 arguments to @code{define_blind} rather than the intended number of
3873 arguments to @var{name}.  The solution is to pass the difficult
3874 characters through extra arguments to a helper macro
3875 @code{_define_blind}.  When composing macros, it is a common idiom to
3876 need a helper macro to concatenate text that forms parameters in the
3877 composed macro, rather than interpreting the text as a parameter of the
3878 composing macro.
3880 As for the limitation against using @code{defn}, there are two reasons.
3881 If a macro was previously defined with @code{define_blind}, then it can
3882 safely be renamed to a new blind macro using plain @code{define}; using
3883 @code{define_blind} to rename it just adds another layer of
3884 @code{ifelse}, occupying memory and slowing down execution.  And if a
3885 macro is a builtin, then it would result in an attempt to define a macro
3886 consisting of both text and a builtin token; this is not supported, and
3887 the builtin token is flattened to an empty string.
3889 With that explanation, here's the definition, and some sample usage.
3890 Notice that @code{define_blind} is itself a blind macro.
3892 @example
3893 $ @kbd{m4 -d}
3894 define(`define_blind', `ifelse(`$#', `0', ``$0'',
3895 `_$0(`$1', `$2', `$'`#', `$'`0')')')
3896 @result{}
3897 define(`_define_blind', `define(`$1',
3898 `ifelse(`$3', `0', ``$4'', `$2')')')
3899 @result{}
3900 define_blind
3901 @result{}define_blind
3902 define_blind(`foo', `arguments were $*')
3903 @result{}
3905 @result{}foo
3906 foo(`bar')
3907 @result{}arguments were bar
3908 define(`blah', defn(`foo'))
3909 @result{}
3910 blah
3911 @result{}blah
3912 blah(`a', `b')
3913 @result{}arguments were a,b
3914 defn(`blah')
3915 @result{}ifelse(`$#', `0', ``$0'', `arguments were $*')
3916 @end example
3918 @cindex currying arguments
3919 @cindex argument currying
3920 Another interesting composition tactic is argument @dfn{currying}, or
3921 factoring a macro that takes multiple arguments for use in a context
3922 that provides exactly one argument.
3924 @deffn Composite curry (@var{macro}, @dots{})
3925 Expand to a macro call that takes exactly one argument, then appends
3926 that argument to the original arguments and invokes @var{macro} with the
3927 resulting list of arguments.
3928 @end deffn
3930 A demonstration of currying makes the intent of this macro a little more
3931 obvious.  The macro @code{stack_foreach} mentioned earlier is an example
3932 of a context that provides exactly one argument to a macro name.  But
3933 coupled with currying, we can invoke @code{reverse} with two arguments
3934 for each definition of a macro stack.  This example uses the file
3935 @file{m4-@value{VERSION}/@/examples/@/curry.m4} included in the
3936 distribution.
3938 @comment examples
3939 @example
3940 $ @kbd{m4 -I examples}
3941 include(`curry.m4')include(`stack.m4')
3942 @result{}
3943 define(`reverse', `ifelse(`$#', `0', , `$#', `1', ``$1'',
3944                           `reverse(shift($@@)), `$1'')')
3945 @result{}
3946 pushdef(`a', `1')pushdef(`a', `2')pushdef(`a', `3')
3947 @result{}
3948 stack_foreach(`a', `:curry(`reverse', `4')')
3949 @result{}:1, 4:2, 4:3, 4
3950 curry(`curry', `reverse', `1')(`2')(`3')
3951 @result{}3, 2, 1
3952 @end example
3954 Now for the implementation.  Notice how @code{curry} leaves off with a
3955 macro name but no open parenthesis, while still in the middle of
3956 collecting arguments for @samp{$1}.  The macro @code{_curry} is the
3957 helper macro that takes one argument, then adds it to the list and
3958 finally supplies the closing parenthesis.  The use of a comma inside the
3959 @code{shift} call allows currying to also work for a macro that takes
3960 one argument, although it often makes more sense to invoke that macro
3961 directly rather than going through @code{curry}.
3963 @comment examples
3964 @example
3965 $ @kbd{m4 -I examples}
3966 undivert(`curry.m4')dnl
3967 @result{}divert(`-1')
3968 @result{}# curry(macro, args)
3969 @result{}# Expand to a macro call that takes one argument, then invoke
3970 @result{}# macro(args, extra).
3971 @result{}define(`curry', `$1(shift($@@,)_$0')
3972 @result{}define(`_curry', ``$1')')
3973 @result{}divert`'dnl
3974 @end example
3976 Unfortunately, with M4 1.4.x, @code{curry} is unable to handle builtin
3977 tokens, which are silently flattened to the empty string when passed
3978 through another text macro.  The following example demonstrates a usage
3979 of @code{curry} that works in M4 1.6, but is not portable to earlier
3980 versions:
3982 @comment examples
3983 @example
3984 $ @kbd{m4 -I examples}
3985 include(`curry.m4')
3986 @result{}
3987 curry(`define', `mylen')(defn(`len'))
3988 @result{}
3989 mylen(`abc')
3990 @result{}3
3991 @end example
3993 @cindex renaming macros
3994 @cindex copying macros
3995 @cindex macros, copying
3996 Putting the last few concepts together, it is possible to copy or rename
3997 an entire stack of macro definitions.
3999 @deffn Composite copy (@var{source}, @var{dest})
4000 @deffnx Composite rename (@var{source}, @var{dest})
4001 Ensure that @var{dest} is undefined, then define it to the same stack of
4002 definitions currently in @var{source}.  @code{copy} leaves @var{source}
4003 unchanged, while @code{rename} undefines @var{source}.  There are only a
4004 few macros, such as @code{copy} or @code{defn}, which cannot be copied
4005 via this macro.
4006 @end deffn
4008 The implementation is relatively straightforward (although since it uses
4009 @code{curry}, it is unable to copy builtin macros when used with M4
4010 1.4.x.  See if you can design a portable version that works across all
4011 M4 versions, or @pxref{Improved copy, , Answers}).
4013 @comment examples
4014 @example
4015 $ @kbd{m4 -I examples}
4016 include(`curry.m4')include(`stack.m4')
4017 @result{}
4018 define(`rename', `copy($@@)undefine(`$1')')dnl
4019 define(`copy', `ifdef(`$2', `errprint(`$2 already defined
4020 ')m4exit(`1')',
4021    `stack_foreach(`$1', `curry(`pushdef', `$2')')')')dnl
4022 pushdef(`a', `1')pushdef(`a', defn(`divnum'))pushdef(`a', `2')
4023 @result{}
4024 copy(`a', `b')
4025 @result{}
4026 rename(`b', `c')
4027 @result{}
4028 a b c
4029 @result{}2 b 2
4030 popdef(`a', `c')a c
4031 @result{}0 0
4032 popdef(`a', `c')a c
4033 @result{}1 1
4034 @end example
4036 @node Debugging
4037 @chapter How to debug macros and input
4039 @cindex debugging macros
4040 @cindex macros, debugging
4041 When writing macros for @code{m4}, they often do not work as intended on
4042 the first try (as is the case with most programming languages).
4043 Fortunately, there is support for macro debugging in @code{m4}.
4045 @menu
4046 * Dumpdef::                     Displaying macro definitions
4047 * Trace::                       Tracing macro calls
4048 * Debugmode::                   Controlling debugging options
4049 * Debuglen::                    Limiting debug output
4050 * Debugfile::                   Saving debugging output
4051 @end menu
4053 @node Dumpdef
4054 @section Displaying macro definitions
4056 @cindex displaying macro definitions
4057 @cindex macros, displaying definitions
4058 @cindex definitions, displaying macro
4059 @cindex standard error, output to
4060 If you want to see what a name expands into, you can use the builtin
4061 @code{dumpdef}:
4063 @deffn {Builtin (m4)} dumpdef (@ovar{name@dots{}})
4064 Accepts any number of arguments.  If called without any arguments, it
4065 displays the definitions of all known names, otherwise it displays the
4066 definitions of each @var{name} given, sorted by name.  If a @var{name}
4067 is undefined, the @samp{d} debug level controls whether a warning is
4068 issued (@pxref{Debugmode}).  Likewise, the @samp{o} debug level controls
4069 whether the output is issued to standard error or the current debug
4070 file (@pxref{Debugfile}).
4072 The expansion of @code{dumpdef} is void.
4073 @end deffn
4075 @example
4076 $ @kbd{m4 -d}
4077 define(`foo', `Hello world.')
4078 @result{}
4079 dumpdef(`foo')
4080 @error{}foo:@tabchar{}`Hello world.'
4081 @result{}
4082 dumpdef(`define')
4083 @error{}define:@tabchar{}<define>
4084 @result{}
4085 @end example
4087 The last example shows how builtin macros definitions are displayed.
4088 The definition that is dumped corresponds to what would occur if the
4089 macro were to be called at that point, even if other definitions are
4090 still live due to redefining a macro during argument collection.
4092 @example
4093 $ @kbd{m4 -d}
4094 pushdef(`f', ``$0'1')pushdef(`f', ``$0'2')
4095 @result{}
4096 f(popdef(`f')dumpdef(`f'))
4097 @error{}f:@tabchar{}``$0'1'
4098 @result{}f2
4099 f(popdef(`f')dumpdef(`f'))
4100 @error{}m4:stdin:3: warning: dumpdef: undefined macro 'f'
4101 @result{}f1
4102 debugmode(`-d')
4103 @result{}
4104 dumpdef(`f')
4105 @result{}
4106 @end example
4108 @xref{Debugmode}, for information on how the @samp{m}, @samp{q}, and
4109 @samp{s} flags affect the details of the display.  Remember, the
4110 @samp{q} flag is implied when the @option{--debug} option (@option{-d},
4111 @pxref{Debugging options, , Invoking m4}) is used in the command line
4112 without arguments.  Also, @option{--debuglen} (@pxref{Debuglen}) can affect
4113 output, by truncating longer strings (but not builtin and module names).
4115 @comment options: -ds -l3
4116 @example
4117 $ @kbd{m4 -ds -l 3}
4118 pushdef(`foo', `1 long string')
4119 @result{}
4120 pushdef(`foo', defn(`divnum'))
4121 @result{}
4122 pushdef(`foo', `3')
4123 @result{}
4124 debugmode(`+m')
4125 @result{}
4126 dumpdef(`foo', `dnl', `indir', `__gnu__')
4127 @error{}__gnu__:@tabchar{}@{gnu@}
4128 @error{}dnl:@tabchar{}<dnl>@{m4@}
4129 @error{}foo:@tabchar{}3, <divnum>@{m4@}, 1 l...
4130 @error{}indir:@tabchar{}<indir>@{gnu@}
4131 @result{}
4132 debugmode(`-ms')debugmode(`+q')
4133 @result{}
4134 dumpdef(`foo')
4135 @error{}foo:@tabchar{}`3'
4136 @result{}
4137 @end example
4139 @node Trace
4140 @section Tracing macro calls
4142 @cindex tracing macro expansion
4143 @cindex macro expansion, tracing
4144 @cindex expansion, tracing macro
4145 @cindex standard error, output to
4146 It is possible to trace macro calls and expansions through the builtins
4147 @code{traceon} and @code{traceoff}:
4149 @deffn {Builtin (m4)} traceon (@ovar{names@dots{}})
4150 @deffnx {Builtin (m4)} traceoff (@ovar{names@dots{}})
4151 When called without any arguments, @code{traceon} and @code{traceoff}
4152 will turn tracing on and off, respectively, for all macros, identical to
4153 using the @samp{t} flag of @code{debugmode} (@pxref{Debugmode}).
4155 When called with arguments, only the macros listed in @var{names} are
4156 affected, whether or not they are currently defined.  A macro's
4157 expansion will be traced if global tracing is on, or if the individual
4158 macro tracing flag is set; to avoid tracing a macro, both the global
4159 flag and the macro must have tracing off.
4161 The expansion of @code{traceon} and @code{traceoff} is void.
4162 @end deffn
4164 Whenever a traced macro is called and the arguments have been collected,
4165 the call is displayed.  If the expansion of the macro call is not void,
4166 the expansion can be displayed after the call.  The output is printed
4167 to the current debug file (defaulting to standard error,
4168 @pxref{Debugfile}).
4170 @example
4171 $ @kbd{m4 -d}
4172 define(`foo', `Hello World.')
4173 @result{}
4174 define(`echo', `$@@')
4175 @result{}
4176 traceon(`foo', `echo')
4177 @result{}
4179 @error{}m4trace: -1- foo -> `Hello World.'
4180 @result{}Hello World.
4181 echo(`gnus', `and gnats')
4182 @error{}m4trace: -1- echo(`gnus', `and gnats') -> ``gnus',`and gnats''
4183 @result{}gnus,and gnats
4184 @end example
4186 The number between dashes is the depth of the expansion.  It is one most
4187 of the time, signifying an expansion at the outermost level, but it
4188 increases when macro arguments contain unquoted macro calls.  The
4189 maximum number that will appear between dashes is controlled by the
4190 option @option{--nesting-limit} (or @option{-L}, @pxref{Limits control,
4191 , Invoking m4}).  Additionally, the option @option{--trace} (or
4192 @option{-t}) can be used to invoke @code{traceon(@var{name})} before
4193 parsing input.
4195 @comment options: -d-V -L3 -tifelse
4196 @comment status: 1
4197 @example
4198 $ @kbd{m4 -L 3 -t ifelse}
4199 ifelse(`one level')
4200 @error{}m4trace: -1- ifelse
4201 @result{}
4202 ifelse(ifelse(ifelse(`three levels')))
4203 @error{}m4trace: -3- ifelse
4204 @error{}m4trace: -2- ifelse
4205 @error{}m4trace: -1- ifelse
4206 @result{}
4207 ifelse(ifelse(ifelse(ifelse(`four levels'))))
4208 @error{}m4:stdin:3: recursion limit of 3 exceeded, use -L<N> to change it
4209 @end example
4211 Tracing by name is an attribute that is preserved whether the macro is
4212 defined or not.  This allows the selection of macros to trace before
4213 those macros are defined.
4215 @example
4216 $ @kbd{m4 -d}
4217 traceoff(`foo')
4218 @result{}
4219 traceon(`foo')
4220 @result{}
4222 @result{}foo
4223 defn(`foo')
4224 @error{}m4:stdin:4: warning: defn: undefined macro 'foo'
4225 @result{}
4226 undefine(`foo')
4227 @error{}m4:stdin:5: warning: undefine: undefined macro 'foo'
4228 @result{}
4229 pushdef(`foo')
4230 @result{}
4231 popdef(`foo')
4232 @result{}
4233 popdef(`foo')
4234 @error{}m4:stdin:8: warning: popdef: undefined macro 'foo'
4235 @result{}
4236 define(`foo', `bar')
4237 @result{}
4239 @error{}m4trace: -1- foo -> `bar'
4240 @result{}bar
4241 undefine(`foo')
4242 @result{}
4243 ifdef(`foo', `yes', `no')
4244 @result{}no
4245 indir(`foo')
4246 @error{}m4:stdin:13: warning: indir: undefined macro 'foo'
4247 @result{}
4248 define(`foo', `blah')
4249 @result{}
4251 @error{}m4trace: -1- foo -> `blah'
4252 @result{}blah
4253 @end example
4255 Tracing even works on builtins.  However, @code{defn} (@pxref{Defn})
4256 does not transfer tracing status.
4258 @example
4259 $ @kbd{m4 -d}
4260 traceon(`traceon')
4261 @result{}
4262 traceon(`traceoff')
4263 @error{}m4trace: -1- traceon(`traceoff') -> `'
4264 @result{}
4265 traceoff(`traceoff')
4266 @error{}m4trace: -1- traceoff(`traceoff') -> `'
4267 @result{}
4268 traceoff(`traceon')
4269 @result{}
4270 traceon(`eval', `m4_divnum')
4271 @result{}
4272 define(`m4_eval', defn(`eval'))
4273 @result{}
4274 define(`m4_divnum', defn(`divnum'))
4275 @result{}
4276 eval(divnum)
4277 @error{}m4trace: -1- eval(`0') -> `0'
4278 @result{}0
4279 m4_eval(m4_divnum)
4280 @error{}m4trace: -2- m4_divnum -> `0'
4281 @result{}0
4282 @end example
4284 As of GNU M4 2.0, named macro tracing is independent of global
4285 tracing status; calling @code{traceoff} without arguments turns off the
4286 global trace flag, but does not turn off tracing for macros where
4287 tracing was requested by name.  Likewise, calling @code{traceon} without
4288 arguments will affect tracing of macros that are not defined yet.  This
4289 behavior matches traditional implementations of @code{m4}.
4291 @example
4292 $ @kbd{m4 -d}
4293 traceon
4294 @result{}
4295 define(`foo', `bar')
4296 @error{}m4trace: -1- define(`foo', `bar') -> `'
4297 @result{}
4298 foo # traced, even though foo was not defined at traceon
4299 @error{}m4trace: -1- foo -> `bar'
4300 @result{}bar # traced, even though foo was not defined at traceon
4301 traceoff(`foo')
4302 @error{}m4trace: -1- traceoff(`foo') -> `'
4303 @result{}
4304 foo # traced, since global tracing is still on
4305 @error{}m4trace: -1- foo -> `bar'
4306 @result{}bar # traced, since global tracing is still on
4307 traceon(`foo')
4308 @error{}m4trace: -1- traceon(`foo') -> `'
4309 @result{}
4310 traceoff
4311 @error{}m4trace: -1- traceoff -> `'
4312 @result{}
4313 foo # traced, since foo is now traced by name
4314 @error{}m4trace: -1- foo -> `bar'
4315 @result{}bar # traced, since foo is now traced by name
4316 traceoff(`foo')
4317 @result{}
4318 foo # untraced
4319 @result{}bar # untraced
4320 @end example
4322 However, GNU M4 prior to 2.0 had slightly different
4323 semantics, where @code{traceon} without arguments only affected symbols
4324 that were defined at that moment, and @code{traceoff} without arguments
4325 stopped all tracing, even when tracing was requested by macro name.  The
4326 addition of the macro @code{m4symbols} (@pxref{M4symbols}) in 2.0 makes it
4327 possible to write a file that approximates the older semantics
4328 regardless of which version of GNU M4 is in use.
4330 @comment options: -d-V
4331 @example
4332 $ @kbd{m4}
4333 ifdef(`m4symbols',
4334   `define(`traceon', `ifelse(`$#', `0', `builtin(`traceon', m4symbols)',
4335     `builtin(`traceon', $@@)')')dnl
4336 define(`traceoff', `ifelse(`$#', `0',
4337     `builtin(`traceoff')builtin(`traceoff', m4symbols)',
4338     `builtin(`traceoff', $@@)')')')dnl
4339 define(`a', `1')
4340 @result{}
4341 traceon # called before b is defined, so b is not traced
4342 @result{} # called before b is defined, so b is not traced
4343 define(`b', `2')
4344 @error{}m4trace: -1- define
4345 @result{}
4346 a b
4347 @error{}m4trace: -1- a
4348 @result{}1 2
4349 traceon(`b')
4350 @error{}m4trace: -1- traceon
4351 @error{}m4trace: -1- ifelse
4352 @error{}m4trace: -1- builtin
4353 @result{}
4354 a b
4355 @error{}m4trace: -1- a
4356 @error{}m4trace: -1- b
4357 @result{}1 2
4358 traceoff # stops tracing b, even though it was traced by name
4359 @error{}m4trace: -1- traceoff
4360 @error{}m4trace: -1- ifelse
4361 @error{}m4trace: -1- builtin
4362 @error{}m4trace: -2- m4symbols
4363 @error{}m4trace: -1- builtin
4364 @result{} # stops tracing b, even though it was traced by name
4365 a b
4366 @result{}1 2
4367 @end example
4369 @xref{Debugmode}, for information on controlling the details of the
4370 display.  The format of the trace output is not specified by
4371 POSIX, and varies between implementations of @code{m4}.
4373 Starting with M4 1.6, tracing also works via @code{indir}
4374 (@pxref{Indir}).  However, since tracing is an attribute tracked by
4375 macro names, and @code{builtin} bypasses macro names (@pxref{Builtin}),
4376 it is not possible for @code{builtin} to trace which subsidiary builtin
4377 it invokes.  If you are worried about tracking all invocations of a
4378 given builtin, you should also trace @code{builtin}, or enable global
4379 tracing (the @samp{t} debug level, @pxref{Debugmode}).
4381 @example
4382 $ @kbd{m4 -d}
4383 define(`my_defn', defn(`defn'))undefine(`defn')
4384 @result{}
4385 define(`foo', `bar')traceon(`foo', `defn', `my_defn')
4386 @result{}
4388 @error{}m4trace: -1- foo -> `bar'
4389 @result{}bar
4390 indir(`foo')
4391 @error{}m4trace: -1- foo -> `bar'
4392 @result{}bar
4393 my_defn(`foo')
4394 @error{}m4trace: -1- my_defn(`foo') -> ``bar''
4395 @result{}bar
4396 indir(`my_defn', `foo')
4397 @error{}m4trace: -1- my_defn(`foo') -> ``bar''
4398 @result{}bar
4399 builtin(`defn', `foo')
4400 @result{}bar
4401 debugmode(`+cxt')
4402 @result{}
4403 builtin(`defn', builtin(`shift', `', `foo'))
4404 @error{}m4trace: -1- id 12: builtin ... = <builtin>
4405 @error{}m4trace: -2- id 13: builtin ... = <builtin>
4406 @error{}m4trace: -2- id 13: builtin(`shift', `', `foo') -> ``foo''
4407 @error{}m4trace: -1- id 12: builtin(`defn', `foo') -> ``bar''
4408 @result{}bar
4409 indir(`my_defn', indir(`shift', `', `foo'))
4410 @error{}m4trace: -1- id 14: indir ... = <indir>
4411 @error{}m4trace: -2- id 15: indir ... = <indir>
4412 @error{}m4trace: -2- id 15: shift ... = <shift>
4413 @error{}m4trace: -2- id 15: shift(`', `foo') -> ``foo''
4414 @error{}m4trace: -2- id 15: indir(`shift', `', `foo') -> ``foo''
4415 @error{}m4trace: -1- id 14: my_defn ... = <defn>
4416 @error{}m4trace: -1- id 14: my_defn(`foo') -> ``bar''
4417 @error{}m4trace: -1- id 14: indir(`my_defn', `foo') -> ``bar''
4418 @result{}bar
4419 @end example
4421 @node Debugmode
4422 @section Controlling debugging options
4424 @cindex controlling debugging output
4425 @cindex debugging output, controlling
4426 The @option{--debug} option to @code{m4} (also spelled
4427 @option{--debugmode} or @option{-d}, @pxref{Debugging options, ,
4428 Invoking m4}) controls the amount of details presented in three
4429 categories of output.  Trace output is requested by @code{traceon}
4430 (@pxref{Trace}), and each line is prefixed by @samp{m4trace:} in
4431 relation to a macro invocation.  Debug output tracks useful events not
4432 associated with a macro invocation, and each line is prefixed by
4433 @samp{m4debug:}.  Finally, @code{dumpdef} (@pxref{Dumpdef}) output is
4434 affected, with no prefix added to the output lines.
4436 The @var{flags} following the option can be one or more of the
4437 following:
4439 @table @code
4440 @item a
4441 In trace output, show the actual arguments that were collected before
4442 invoking the macro.  Arguments are subject to length truncation
4443 specified by @code{debuglen} (@pxref{Debuglen}).
4445 @item c
4446 In trace output, show an additional line for each macro call, when the
4447 macro is seen, but before the arguments are collected, and show the
4448 definition of the macro that will be used for the expansion.  By
4449 default, only one line is printed, after all arguments are collected and
4450 the expansion determined.  The definition is subject to length
4451 truncation specified by @code{debuglen} (@pxref{Debuglen}).  This is
4452 often used with the @samp{x} flag.
4454 @item d
4455 Output a warning on any attempt to dereference an undefined macro via
4456 @code{builtin}, @code{defn}, @code{dumpdef}, @code{indir},
4457 @code{popdef}, or @code{undefine}.  Note that @code{indef},
4458 @code{m4symbols},
4459 @code{traceon}, and @code{traceoff} do not dereference undefined macros.
4460 Like any other warning, the warnings enabled by this flag go to standard
4461 error regardless of the current @code{debugfile} setting, and will
4462 change exit status if the command line option @option{--fatal-warnings}
4463 was specified.  This flag is useful in diagnosing spelling mistakes in
4464 macro names.  It is enabled by default when neither @option{--debug} nor
4465 @option{--fatal-warnings} are specified on the command line.
4467 @item e
4468 In trace output, show the expansion of each macro call.  The expansion
4469 is subject to length truncation specified by @code{debuglen}
4470 (@pxref{Debuglen}).
4472 @item f
4473 In debug and trace output, include the name of the current input file in
4474 the output line.
4476 @item i
4477 In debug output, print a message each time the current input file is
4478 changed.
4480 @item l
4481 In debug and trace output, include the current input line number in the
4482 output line.
4484 @item m
4485 In debug output, print a message each time a module is manipulated
4486 (@pxref{Modules}).  In trace output when the @samp{c} flag is in effect,
4487 and in dumpdef output, follow builtin macros with their module name,
4488 surrounded by braces (@samp{@{@}}).
4490 @item o
4491 Output @code{dumpdef} data to standard error instead of the current
4492 debug file.  This can be useful when post-processing trace output, where
4493 interleaving dumpdef and trace output can cause ambiguities.
4495 @item p
4496 In debug output, print a message when a named file is found through the
4497 path search mechanism (@pxref{Search Path}), giving the actual file name
4498 used.
4500 @item q
4501 In trace and dumpdef output, quote actual arguments and macro expansions
4502 in the display with the current quotes.  This is useful in connection
4503 with the @samp{a} and @samp{e} flags above.
4505 @item s
4506 In dumpdef output, show the entire stack of definitions associated with
4507 a symbol via @code{pushdef}.
4509 @item t
4510 In trace output, trace all macro calls made in this invocation of
4511 @code{m4}.  This is equivalent to using @code{traceon} without
4512 arguments.
4514 @item x
4515 In trace output, add a unique `macro call id' to each line of the trace
4516 output.  This is useful in connection with the @samp{c} flag above, to
4517 match where a macro is first recognized with where it is finally
4518 expanded, in spite of intermediate expansions that occur while
4519 collecting arguments.  It can also be used in isolation to determine how
4520 many macros have been expanded.
4522 @item V
4523 A shorthand for all of the above flags.
4524 @end table
4526 As special cases, if @var{flags} starts with a @samp{+}, the named flags
4527 are enabled without impacting other flags, and if it starts with a
4528 @samp{-}, the named flags are disabled without impacting other flags.
4529 Without either of these starting characters, @var{flags} simply replaces
4530 the previous setting.
4531 @comment FIXME - should we accept usage like debugmode(+fl-q)?  Also,
4532 @comment should we add debugmode(?) which expands to the current
4533 @comment enabled flags, and debugmode(e?) which expands to e if e is
4534 @comment currently enabled?
4536 If no flags are specified with the @option{--debug} option, the default is
4537 @samp{+adeq}.  Many examples in this manual show their output using
4538 default flags.
4540 @cindex GNU extensions
4541 There is a builtin macro @code{debugmode}, which allows on-the-fly control of
4542 the debugging output format:
4544 @deffn {Builtin (gnu)} debugmode (@ovar{flags})
4545 The argument @var{flags} should be a subset of the letters listed above.
4546 If no argument is present, all debugging flags are cleared (as if
4547 @var{flags} were an explicit @samp{-V}).  With an empty argument, the
4548 most common flags are enabled (as if @var{flags} were an explicit
4549 @samp{+adeq}).  If an unknown flag is encountered, an error is issued.
4551 The expansion of @code{debugmode} is void.
4552 @end deffn
4554 @comment options: -d-V
4555 @example
4556 $ @kbd{m4}
4557 define(`foo', `FOO$1')
4558 @result{}
4559 traceon(`foo', `divnum')
4560 @result{}
4561 debugmode()dnl same as debugmode(`+adeq')
4563 @error{}m4trace: -1- foo -> `FOO'
4564 @result{}FOO
4565 debugmode(`V')debugmode(`-q')
4566 @error{}m4trace:stdin:5: -1- id 7: debugmode ... = <debugmode>@{gnu@}
4567 @error{}m4trace:stdin:5: -1- id 7: debugmode(`-q') -> `'
4568 @result{}
4569 foo(
4570 `BAR')
4571 @error{}m4trace:stdin:6: -1- id 8: foo ... = FOO$1
4572 @error{}m4trace:stdin:6: -1- id 8: foo(BAR) -> FOOBAR
4573 @result{}FOOBAR
4574 debugmode`'dnl same as debugmode(`-V')
4575 @error{}m4trace:stdin:8: -1- id 9: debugmode ... = <debugmode>@{gnu@}
4576 @error{}m4trace:stdin:8: -1- id 9: debugmode ->@w{ }
4578 @error{}m4trace: -1- foo
4579 @result{}FOO
4580 debugmode(`+clmx')
4581 @result{}
4582 foo(divnum)
4583 @error{}m4trace:11: -1- id 13: foo ... = FOO$1
4584 @error{}m4trace:11: -2- id 14: divnum ... = <divnum>@{m4@}
4585 @error{}m4trace:11: -2- id 14: divnum
4586 @error{}m4trace:11: -1- id 13: foo
4587 @result{}FOO0
4588 debugmode(`-m')
4589 @result{}
4590 @end example
4592 This example shows the effects of the debug flags that are not related
4593 to macro tracing.
4595 @comment examples
4596 @comment options: -dip
4597 @example
4598 $ @kbd{m4 -dip -I examples}
4599 @error{}m4debug: input read from 'stdin'
4600 define(`foo', `m4wrap(`wrapped text
4601 ')dnl')
4602 @result{}
4603 include(`incl.m4')dnl
4604 @error{}m4debug: path search for 'incl.m4' found 'examples/incl.m4'
4605 @error{}m4debug: input read from 'examples/incl.m4'
4606 @result{}Include file start
4607 @result{}Include file end
4608 @error{}m4debug: input reverted to stdin, line 3
4610 @error{}m4debug: input exhausted
4611 @error{}m4debug: input from m4wrap recursion level 1
4612 @result{}wrapped text
4613 @error{}m4debug: input from m4wrap exhausted
4614 @end example
4616 @node Debuglen
4617 @section Limiting debug output
4619 @cindex GNU extensions
4620 @cindex arglength
4621 @cindex debuglen
4622 @cindex limiting trace output length
4623 @cindex trace output, limiting length
4624 @cindex dumpdef output, limiting length
4625 When debugging, sometimes it is desirable to reduce the clutter of
4626 arbitrary-length strings, because the prefix carries enough information
4627 to understand the issues.  The builtin macro @code{debuglen}, along with
4628 the command line option counterpart @option{--debuglen} (or @option{-l},
4629 @pxref{Debugging options, , Invoking m4}), allow on-the-fly control of
4630 debugging string lengths:
4632 @deffn {Builtin (gnu)} debuglen (@var{len})
4633 The argument @var{len} is an integer that controls how much of
4634 arbitrary-length strings should be output during trace and dumpdef
4635 output.  If specified to a non-zero value, then strings longer than that
4636 length are truncated, and @samp{...} included in the output to show that
4637 truncation took place.  A warning is issued if @var{len} cannot be
4638 parsed as an integer.
4639 @comment FIXME - make this understand an optional suffix, similar to how
4640 @comment --debuglen does.  Also, we need a section documenting scaling
4641 @comment suffixes.
4642 @comment FIXME - should we allow len to be `?', meaning expand to the
4643 @comment current value?
4645 The macro @code{debuglen} is recognized only with parameters.
4646 @end deffn
4648 The following example demonstrates the behavior of length truncation.
4649 Note that each argument and the final result are individually truncated.
4650 Also, the special tokens for builtin functions are not truncated.
4652 @comment options: -l6 -techo -tdefn
4653 @example
4654 $ @kbd{m4 -d -l 6 -t echo -t defn}
4655 debuglen(`oops')
4656 @error{}m4:stdin:1: warning: debuglen: non-numeric argument 'oops'
4657 @result{}
4658 define(`echo', `$@@')
4659 @result{}
4660 echo(`1', `long string')
4661 @error{}m4trace: -1- echo(`1', `long s...') -> ``1',`l...'
4662 @result{}1,long string
4663 indir(`echo', defn(`changequote'))
4664 @error{}m4trace: -2- defn(`change...') -> `<changequote>'
4665 @error{}m4trace: -1- echo(<changequote>) -> ``<changequote>''
4666 @result{}
4667 debuglen
4668 @result{}debuglen
4669 debuglen(`0')
4670 @result{}
4671 echo(`long string')
4672 @error{}m4trace: -1- echo(`long string') -> ``long string''
4673 @result{}long string
4674 debuglen(`12')
4675 @result{}
4676 echo(`long string')
4677 @error{}m4trace: -1- echo(`long string') -> ``long string...'
4678 @result{}long string
4679 @end example
4681 @node Debugfile
4682 @section Saving debugging output
4684 @cindex saving debugging output
4685 @cindex debugging output, saving
4686 @cindex output, saving debugging
4687 @cindex GNU extensions
4688 Debug and tracing output can be redirected to files using either the
4689 @option{--debugfile} option to @code{m4} (@pxref{Debugging options, ,
4690 Invoking m4}), or with the builtin macro @code{debugfile}:
4692 @deffn {Builtin (gnu)} debugfile (@ovar{file})
4693 Send all further debug and trace output to @var{file}, opened in append
4694 mode.  If @var{file} is the empty string, debug and trace output are
4695 discarded.  If @code{debugfile} is called without any arguments, debug
4696 and trace output are sent to standard error.  Output from @code{dumpdef}
4697 is sent to this file if the debug level @code{o} is not set
4698 (@pxref{Debugmode}).  This does not affect
4699 warnings, error messages, or @code{errprint} output, which are
4700 always sent to standard error.  If @var{file} cannot be opened, the
4701 current debug file is unchanged, and an error is issued.
4703 When the @option{--safer} option (@pxref{Operation modes, , Invoking
4704 m4}) is in effect, @var{file} must be empty or omitted, since otherwise
4705 an input file could cause the modification of arbitrary files.
4707 The expansion of @code{debugfile} is void.
4708 @end deffn
4710 @example
4711 $ @kbd{m4 -d}
4712 traceon(`divnum')
4713 @result{}
4714 divnum(`extra')
4715 @error{}m4:stdin:2: warning: divnum: extra arguments ignored: 1 > 0
4716 @error{}m4trace: -1- divnum(`extra') -> `0'
4717 @result{}0
4718 debugfile()
4719 @result{}
4720 divnum(`extra')
4721 @error{}m4:stdin:4: warning: divnum: extra arguments ignored: 1 > 0
4722 @result{}0
4723 debugfile
4724 @result{}
4725 divnum
4726 @error{}m4trace: -1- divnum -> `0'
4727 @result{}0
4728 @end example
4730 Although the @option{--safer} option cripples @code{debugfile} to a
4731 limited subset of capabilities, you may still use the @option{--debugfile}
4732 option from the command line with no restrictions.
4734 @comment options: --safer --debugfile=trace -tfoo -Dfoo=bar -d+l
4735 @comment status: 1
4736 @example
4737 $ @kbd{m4 --safer --debugfile trace -t foo -D foo=bar -daelq}
4738 foo # traced to `trace'
4739 @result{}bar # traced to `trace'
4740 debugfile(`file')
4741 @error{}m4:stdin:2: debugfile: disabled by --safer
4742 @result{}
4743 foo # traced to `trace'
4744 @result{}bar # traced to `trace'
4745 debugfile()
4746 @result{}
4747 foo # trace discarded
4748 @result{}bar # trace discarded
4749 debugfile
4750 @result{}
4751 foo # traced to stderr
4752 @error{}m4trace:7: -1- foo -> `bar'
4753 @result{}bar # traced to stderr
4754 undivert(`trace')dnl
4755 @result{}m4trace:1: -1- foo -> `bar'
4756 @result{}m4trace:3: -1- foo -> `bar'
4757 @end example
4759 Sometimes it is useful to post-process trace output, even though there
4760 is no standardized format for trace output.  In this situation, forcing
4761 @code{dumpdef} to output to standard error instead of the default of the
4762 current debug file will avoid any ambiguities between the two types of
4763 output; it also allows debugging via @code{dumpdef} when debug output is
4764 discarded.
4766 @example
4767 $ @kbd{m4 -d}
4768 traceon(`divnum')
4769 @result{}
4770 divnum
4771 @error{}m4trace: -1- divnum -> `0'
4772 @result{}0
4773 dumpdef(`divnum')
4774 @error{}divnum:@tabchar{}<divnum>
4775 @result{}
4776 debugfile(`')
4777 @result{}
4778 divnum
4779 @result{}0
4780 dumpdef(`divnum')
4781 @result{}
4782 debugmode(`+o')
4783 @result{}
4784 divnum
4785 @result{}0
4786 dumpdef(`divnum')
4787 @error{}divnum:@tabchar{}<divnum>
4788 @result{}
4789 @end example
4791 @node Input Control
4792 @chapter Input control
4794 This chapter describes various builtin macros for controlling the input
4795 to @code{m4}.
4797 @menu
4798 * Dnl::                         Deleting whitespace in input
4799 * Changequote::                 Changing the quote characters
4800 * Changecom::                   Changing the comment delimiters
4801 * Changeresyntax::              Changing the regular expression syntax
4802 * Changesyntax::                Changing the lexical structure of the input
4803 * M4wrap::                      Saving text until end of input
4804 @end menu
4806 @node Dnl
4807 @section Deleting whitespace in input
4809 @cindex deleting whitespace in input
4810 @cindex discarding input
4811 @cindex input, discarding
4812 The builtin @code{dnl} stands for ``Discard to Next Line'':
4814 @deffn {Builtin (m4)} dnl
4815 All characters, up to and including the next newline, are discarded
4816 without performing any macro expansion.  A warning is issued if the end
4817 of the file is encountered without a newline.
4819 The expansion of @code{dnl} is void.
4820 @end deffn
4822 It is often used in connection with @code{define}, to remove the
4823 newline that follows the call to @code{define}.  Thus
4825 @example
4826 define(`foo', `Macro `foo'.')dnl A very simple macro, indeed.
4828 @result{}Macro foo.
4829 @end example
4831 The input up to and including the next newline is discarded, as opposed
4832 to the way comments are treated (@pxref{Comments}), when the command
4833 line option @option{--discard-comments} is not in effect
4834 (@pxref{Operation modes, , Invoking m4}).
4836 Usually, @code{dnl} is immediately followed by an end of line or some
4837 other whitespace.  GNU @code{m4} will produce a warning diagnostic if
4838 @code{dnl} is followed by an open parenthesis.  In this case, @code{dnl}
4839 will collect and process all arguments, looking for a matching close
4840 parenthesis.  All predictable side effects resulting from this
4841 collection will take place.  @code{dnl} will return no output.  The
4842 input following the matching close parenthesis up to and including the
4843 next newline, on whatever line containing it, will still be discarded.
4845 @example
4846 dnl(`args are ignored, but side effects occur',
4847 define(`foo', `like this')) while this text is ignored: undefine(`foo')
4848 @error{}m4:stdin:1: warning: dnl: extra arguments ignored: 2 > 0
4849 See how `foo' was defined, foo?
4850 @result{}See how foo was defined, like this?
4851 @end example
4853 If the end of file is encountered without a newline character, a
4854 warning is issued and dnl stops consuming input.
4856 @example
4857 m4wrap(`m4wrap(`2 hi
4858 ')0 hi dnl 1 hi')
4859 @result{}
4860 define(`hi', `HI')
4861 @result{}
4863 @error{}m4:stdin:1: warning: dnl: end of file treated as newline
4864 @result{}0 HI 2 HI
4865 @end example
4867 @node Changequote
4868 @section Changing the quote characters
4870 @cindex changing quote delimiters
4871 @cindex quote delimiters, changing
4872 @cindex delimiters, changing
4873 The default quote delimiters can be changed with the builtin
4874 @code{changequote}:
4876 @deffn {Builtin (m4)} changequote (@dvar{start, `}, @dvar{end, '})
4877 This sets @var{start} as the new begin-quote delimiter and @var{end} as
4878 the new end-quote delimiter.  If both arguments are missing, the default
4879 quotes (@code{`} and @code{'}) are used.  If @var{start} is void, then
4880 quoting is disabled.  Otherwise, if @var{end} is missing or void, the
4881 default end-quote delimiter (@code{'}) is used.  The quote delimiters
4882 can be of any length.
4884 The expansion of @code{changequote} is void.
4885 @end deffn
4887 @example
4888 changequote(`[', `]')
4889 @result{}
4890 define([foo], [Macro [foo].])
4891 @result{}
4893 @result{}Macro foo.
4894 @end example
4896 The quotation strings can safely contain eight-bit characters.
4897 If no single character is appropriate, @var{start} and @var{end} can be
4898 of any length.  Other implementations cap the delimiter length to five
4899 characters, but GNU has no inherent limit.
4901 @example
4902 changequote(`[[[', `]]]')
4903 @result{}
4904 define([[[foo]]], [[[Macro [[[[[foo]]]]].]]])
4905 @result{}
4907 @result{}Macro [[foo]].
4908 @end example
4910 Calling @code{changequote} with @var{start} as the empty string will
4911 effectively disable the quoting mechanism, leaving no way to quote text.
4912 However, using an empty string is not portable, as some other
4913 implementations of @code{m4} revert to the default quoting, while others
4914 preserve the prior non-empty delimiter.  If @var{start} is not empty,
4915 then an empty @var{end} will use the default end-quote delimiter of
4916 @samp{'}, as otherwise, it would be impossible to end a quoted string.
4917 Again, this is not portable, as some other @code{m4} implementations
4918 reuse @var{start} as the end-quote delimiter, while others preserve the
4919 previous non-empty value.  Omitting both arguments restores the default
4920 begin-quote and end-quote delimiters; fortunately this behavior is
4921 portable to all implementations of @code{m4}.
4923 @example
4924 define(`foo', `Macro `FOO'.')
4925 @result{}
4926 changequote(`', `')
4927 @result{}
4929 @result{}Macro `FOO'.
4930 `foo'
4931 @result{}`Macro `FOO'.'
4932 changequote(`,)
4933 @result{}
4935 @result{}Macro FOO.
4936 @end example
4938 There is no way in @code{m4} to quote a string containing an unmatched
4939 begin-quote, except using @code{changequote} to change the current
4940 quotes.
4942 If the quotes should be changed from, say, @samp{[} to @samp{[[},
4943 temporary quote characters have to be defined.  To achieve this, two
4944 calls of @code{changequote} must be made, one for the temporary quotes
4945 and one for the new quotes.
4947 Macros are recognized in preference to the begin-quote string, so if a
4948 prefix of @var{start} can be recognized as part of a potential macro
4949 name, the quoting mechanism is effectively disabled.  Unless you use
4950 @code{changesyntax} (@pxref{Changesyntax}), this means that @var{start}
4951 should not begin with a letter, digit, or @samp{_} (underscore).
4952 However, even though quoted strings are not recognized, the quote
4953 characters can still be discerned in macro expansion and in trace
4954 output.
4956 @example
4957 define(`echo', `$@@')
4958 @result{}
4959 define(`hi', `HI')
4960 @result{}
4961 changequote(`q', `Q')
4962 @result{}
4963 q hi Q hi
4964 @result{}q HI Q HI
4965 echo(hi)
4966 @result{}qHIQ
4967 changequote
4968 @result{}
4969 changequote(`-', `EOF')
4970 @result{}
4971 - hi EOF hi
4972 @result{} hi  HI
4973 changequote
4974 @result{}
4975 changequote(`1', `2')
4976 @result{}
4977 hi1hi2
4978 @result{}hi1hi2
4979 hi 1hi2
4980 @result{}HI hi
4981 @end example
4983 Quotes are recognized in preference to argument collection.  In
4984 particular, if @var{start} is a single @samp{(}, then argument
4985 collection is effectively disabled.  For portability with other
4986 implementations, it is a good idea to avoid @samp{(}, @samp{,}, and
4987 @samp{)} as the first character in @var{start}.
4989 @example
4990 define(`echo', `$#:$@@:')
4991 @result{}
4992 define(`hi', `HI')
4993 @result{}
4994 changequote(`(',`)')
4995 @result{}
4996 echo(hi)
4997 @result{}0::hi
4998 changequote
4999 @result{}
5000 changequote(`((', `))')
5001 @result{}
5002 echo(hi)
5003 @result{}1:HI:
5004 echo((hi))
5005 @result{}0::hi
5006 changequote
5007 @result{}
5008 changequote(`,', `)')
5009 @result{}
5010 echo(hi,hi)bye)
5011 @result{}1:HIhibye:
5012 @end example
5014 However, if you are not worried about portability, using @samp{(} and
5015 @samp{)} as quoting characters has an interesting property---you can use
5016 it to compute a quoted string containing the expansion of any quoted
5017 text, as long as the expansion results in both balanced quotes and
5018 balanced parentheses.  The trick is realizing @code{expand} uses
5019 @samp{$1} unquoted, to trigger its expansion using the normal quoting
5020 characters, but uses extra parentheses to group unquoted commas that
5021 occur in the expansion without consuming whitespace following those
5022 commas.  Then @code{_expand} uses @code{changequote} to convert the
5023 extra parentheses back into quoting characters.  Note that it takes two
5024 more @code{changequote} invocations to restore the original quotes.
5025 Contrast the behavior on whitespace when using @samp{$*}, via
5026 @code{quote}, to attempt the same task.
5028 @example
5029 changequote(`[', `]')dnl
5030 define([a], [1, (b)])dnl
5031 define([b], [2])dnl
5032 define([quote], [[$*]])dnl
5033 define([expand], [_$0(($1))])dnl
5034 define([_expand],
5035   [changequote([(], [)])$1changequote`'changequote(`[', `]')])dnl
5036 expand([a, a, [a, a], [[a, a]]])
5037 @result{}1, (2), 1, (2), a, a, [a, a]
5038 quote(a, a, [a, a], [[a, a]])
5039 @result{}1,(2),1,(2),a, a,[a, a]
5040 @end example
5042 If @var{end} is a prefix of @var{start}, the end-quote will be
5043 recognized in preference to a nested begin-quote.  In particular,
5044 changing the quotes to have the same string for @var{start} and
5045 @var{end} disables nesting of quotes.  When quote nesting is disabled,
5046 it is impossible to double-quote strings across macro expansions, so
5047 using the same string is not done very often.
5049 @example
5050 define(`hi', `HI')
5051 @result{}
5052 changequote(`""', `"')
5053 @result{}
5054 ""hi"""hi"
5055 @result{}hihi
5056 ""hi" ""hi"
5057 @result{}hi hi
5058 ""hi"" "hi"
5059 @result{}hi" "HI"
5060 changequote
5061 @result{}
5062 `hi`hi'hi'
5063 @result{}hi`hi'hi
5064 changequote(`"', `"')
5065 @result{}
5066 "hi"hi"hi"
5067 @result{}hiHIhi
5068 @end example
5070 It is an error if the end of file occurs within a quoted string.
5072 @comment status: 1
5073 @example
5074 `hello world'
5075 @result{}hello world
5076 `dangling quote
5078 @error{}m4:stdin:2: end of file in string
5079 @end example
5081 @comment status: 1
5082 @example
5083 ifelse(`dangling quote
5085 @error{}m4:stdin:1: ifelse: end of file in string
5086 @end example
5088 @node Changecom
5089 @section Changing the comment delimiters
5091 @cindex changing comment delimiters
5092 @cindex comment delimiters, changing
5093 @cindex delimiters, changing
5094 The default comment delimiters can be changed with the builtin
5095 macro @code{changecom}:
5097 @deffn {Builtin (m4)} changecom (@ovar{start}, @dvar{end, @key{NL}})
5098 This sets @var{start} as the new begin-comment delimiter and @var{end}
5099 as the new end-comment delimiter.  If both arguments are missing, or
5100 @var{start} is void, then comments are disabled.  Otherwise, if
5101 @var{end} is missing or void, the default end-comment delimiter of
5102 newline is used.  The comment delimiters can be of any length.
5104 The expansion of @code{changecom} is void.
5105 @end deffn
5107 @example
5108 define(`comment', `COMMENT')
5109 @result{}
5110 # A normal comment
5111 @result{}# A normal comment
5112 changecom(`/*', `*/')
5113 @result{}
5114 # Not a comment anymore
5115 @result{}# Not a COMMENT anymore
5116 But: /* this is a comment now */ while this is not a comment
5117 @result{}But: /* this is a comment now */ while this is not a COMMENT
5118 @end example
5120 @cindex comments, copied to output
5121 Note how comments are copied to the output, much as if they were quoted
5122 strings.  If you want the text inside a comment expanded, quote the
5123 begin-comment delimiter.
5125 Calling @code{changecom} without any arguments, or with @var{start} as
5126 the empty string, will effectively disable the commenting mechanism.  To
5127 restore the original comment start of @samp{#}, you must explicitly ask
5128 for it.  If @var{start} is not empty, then an empty @var{end} will use
5129 the default end-comment delimiter of newline, as otherwise, it would be
5130 impossible to end a comment.  However, this is not portable, as some
5131 other @code{m4} implementations preserve the previous non-empty
5132 delimiters instead.
5134 @example
5135 define(`comment', `COMMENT')
5136 @result{}
5137 changecom
5138 @result{}
5139 # Not a comment anymore
5140 @result{}# Not a COMMENT anymore
5141 changecom(`#', `')
5142 @result{}
5143 # comment again
5144 @result{}# comment again
5145 @end example
5147 The comment strings can safely contain eight-bit characters.
5148 If no single character is appropriate, @var{start} and @var{end} can be
5149 of any length.  Other implementations cap the delimiter length to five
5150 characters, but GNU has no inherent limit.
5152 As of M4 1.6, macros and quotes are recognized in preference to
5153 comments, so if a prefix of @var{start} can be recognized as part of a
5154 potential macro name, or confused with a quoted string, the comment
5155 mechanism is effectively disabled (earlier versions of GNU M4
5156 favored comments, but this was inconsistent with other implementations).
5157 Unless you use @code{changesyntax} (@pxref{Changesyntax}), this means
5158 that @var{start} should not begin with a letter, digit, or @samp{_}
5159 (underscore), and that neither the start-quote nor the start-comment
5160 string should be a prefix of the other.
5162 @example
5163 define(`hi', `HI')
5164 @result{}
5165 define(`hi1hi2', `hello')
5166 @result{}
5167 changecom(`q', `Q')
5168 @result{}
5169 q hi Q hi
5170 @result{}q HI Q HI
5171 changecom(`1', `2')
5172 @result{}
5173 hi1hi2
5174 @result{}hello
5175 hi 1hi2
5176 @result{}HI 1hi2
5177 changecom(`[[', `]]')
5178 @result{}
5179 changequote(`[[[', `]]]')
5180 @result{}
5181 [hi]
5182 @result{}[HI]
5183 [[hi]]
5184 @result{}[[hi]]
5185 [[[hi]]]
5186 @result{}hi
5187 changequote
5188 @result{}
5189 changecom(`[[[', `]]]')
5190 @result{}
5191 changequote(`[[', `]]')
5192 @result{}
5193 [[hi]]
5194 @result{}hi
5195 [[[hi]]]
5196 @result{}[hi]
5197 @end example
5199 Comments are recognized in preference to argument collection.  In
5200 particular, if @var{start} is a single @samp{(}, then argument
5201 collection is effectively disabled.  For portability with other
5202 implementations, it is a good idea to avoid @samp{(}, @samp{,}, and
5203 @samp{)} as the first character in @var{start}.
5205 @example
5206 define(`echo', `$#:$*:$@@:')
5207 @result{}
5208 define(`hi', `HI')
5209 @result{}
5210 changecom(`(',`)')
5211 @result{}
5212 echo(hi)
5213 @result{}0:::(hi)
5214 changecom
5215 @result{}
5216 changecom(`((', `))')
5217 @result{}
5218 echo(hi)
5219 @result{}1:HI:HI:
5220 echo((hi))
5221 @result{}0:::((hi))
5222 changecom(`,', `)')
5223 @result{}
5224 echo(hi,hi)bye)
5225 @result{}1:HI,hi)bye:HI,hi)bye:
5226 changecom
5227 @result{}
5228 echo(hi,`,`'hi',hi)
5229 @result{}3:HI,,HI,HI:HI,,`'hi,HI:
5230 echo(hi,`,`'hi',hi`'changecom(`,,', `hi'))
5231 @result{}3:HI,,`'hi,HI:HI,,`'hi,HI:
5232 @end example
5234 It is an error if the end of file occurs within a comment.
5236 @comment status: 1
5237 @example
5238 changecom(`/*', `*/')
5239 @result{}
5240 /*dangling comment
5242 @error{}m4:stdin:2: end of file in comment
5243 @end example
5245 @comment status: 1
5246 @example
5247 changecom(`/*', `*/')
5248 @result{}
5249 len(/*dangling comment
5251 @error{}m4:stdin:2: len: end of file in comment
5252 @end example
5254 @node Changeresyntax
5255 @section Changing the regular expression syntax
5257 @cindex regular expression syntax, changing
5258 @cindex basic regular expressions
5259 @cindex extended regular expressions
5260 @cindex regular expressions
5261 @cindex expressions, regular
5262 @cindex syntax, changing regular expression
5263 @cindex flavors of regular expressions
5264 @cindex GNU extensions
5265 The GNU extensions @code{patsubst}, @code{regexp}, and more
5266 recently, @code{renamesyms} each deal with regular expressions.  There
5267 are multiple flavors of regular expressions, so the
5268 @code{changeresyntax} builtin exists to allow choosing the default
5269 flavor:
5271 @deffn {Builtin (gnu)} changeresyntax (@var{resyntax})
5272 Changes the default regular expression syntax used by M4 according to
5273 the value of @var{resyntax}, equivalent to passing @var{resyntax} as the
5274 argument to the command line option @option{--regexp-syntax}
5275 (@pxref{Operation modes, , Invoking m4}).  If @var{resyntax} is empty,
5276 the default flavor is reverted to the @code{GNU_M4} style, compatible
5277 with emacs.
5279 @var{resyntax} can be any one of the values in the table below.  Case is
5280 not important, and @samp{-} or @samp{ } can be substituted for @samp{_} in
5281 the given names.  If @var{resyntax} is unrecognized, a warning is
5282 issued and the default flavor is not changed.
5284 @table @dfn
5285 @item AWK
5286 @xref{awk regular expression syntax}, for details.
5288 @item BASIC
5289 @itemx ED
5290 @itemx POSIX_BASIC
5291 @itemx SED
5292 @xref{posix-basic regular expression syntax}, for details.
5294 @item BSD_M4
5295 @item EXTENDED
5296 @itemx POSIX_EXTENDED
5297 @xref{posix-extended regular expression syntax}, for details.
5299 @item GNU_AWK
5300 @itemx GAWK
5301 @xref{gnu-awk regular expression syntax}, for details.
5303 @item GNU_EGREP
5304 @itemx EGREP
5305 @xref{egrep regular expression syntax}, for details.
5307 @item GNU_M4
5308 @item EMACS
5309 @itemx GNU_EMACS
5310 @xref{emacs regular expression syntax}, for details.  This is the
5311 default regular expression flavor.
5313 @item GREP
5314 @xref{grep regular expression syntax}, for details.
5316 @item MINIMAL
5317 @itemx POSIX_MINIMAL
5318 @itemx POSIX_MINIMAL_BASIC
5319 @xref{posix-minimal-basic regular expression syntax}, for details.
5321 @item POSIX_AWK
5322 @xref{posix-awk regular expression syntax}, for details.
5324 @item POSIX_EGREP
5325 @xref{posix-egrep regular expression syntax}, for details.
5326 @end table
5328 The expansion of @code{changeresyntax} is void.
5329 The macro @code{changeresyntax} is recognized only with parameters.
5330 This macro was added in M4 2.0.
5331 @end deffn
5333 For an example of how @var{resyntax} is recognized, the first three
5334 usages select the @samp{GNU_M4} regular expression flavor:
5336 @example
5337 changeresyntax(`gnu m4')
5338 @result{}
5339 changeresyntax(`GNU-m4')
5340 @result{}
5341 changeresyntax(`Gnu_M4')
5342 @result{}
5343 changeresyntax(`unknown')
5344 @error{}m4:stdin:4: warning: changeresyntax: bad syntax-spec: 'unknown'
5345 @result{}
5346 @end example
5348 Using @code{changeresyntax} makes it possible to omit the optional
5349 @var{resyntax} parameter to other macros, while still using a different
5350 regular expression flavor.
5352 @example
5353 patsubst(`ab', `a|b', `c')
5354 @result{}ab
5355 patsubst(`ab', `a\|b', `c')
5356 @result{}cc
5357 patsubst(`ab', `a|b', `c', `EXTENDED')
5358 @result{}cc
5359 changeresyntax(`EXTENDED')
5360 @result{}
5361 patsubst(`ab', `a|b', `c')
5362 @result{}cc
5363 patsubst(`ab', `a\|b', `c')
5364 @result{}ab
5365 @end example
5367 @node Changesyntax
5368 @section Changing the lexical structure of the input
5370 @cindex lexical structure of the input
5371 @cindex input, lexical structure of the
5372 @cindex syntax table
5373 @cindex changing syntax
5374 @cindex GNU extensions
5375 @quotation
5376 The macro @code{changesyntax} and all associated functionality is
5377 experimental (@pxref{Experiments}).  The functionality might change in
5378 the future.  Please direct your comments about it the same way you would
5379 do for bugs.
5380 @end quotation
5382 The input to @code{m4} is read character by character, and these
5383 characters are grouped together to form input tokens (such as macro
5384 names, strings, comments, etc.).
5386 Each token is parsed according to certain rules.  For example, a macro
5387 name starts with a letter or @samp{_} and consists of the longest
5388 possible string of letters, @samp{_} and digits.  But who is to decide
5389 what characters are letters, digits, quotes, white space?  Earlier the
5390 operating system decided, now you do.  The builtin macro
5391 @code{changesyntax} is used to change the way @code{m4} parses the input
5392 stream into tokens.
5394 @deffn {Builtin (gnu)} changesyntax (@var{syntax-spec}, @dots{})
5395 Each @var{syntax-spec} is a two-part string.  The first part is a
5396 command, consisting of a single character describing a syntax category,
5397 and an optional one-character action.  The action can be @samp{-} to
5398 remove the listed characters from that category, @samp{=} to set the
5399 category to the listed characters
5400 and reassign all other characters previously in that category to
5401 `Other', or @samp{+} to add the listed characters to the category
5402 without affecting other characters.  If an action is not specified, but
5403 additional characters are present, then @samp{=} is assumed.
5405 The remaining characters of each @var{syntax-spec} form the set of
5406 characters to perform the action on for that syntax category.  Character
5407 ranges are expanded as for @code{translit} (@pxref{Translit}).  To start
5408 the character set with @samp{-}, @samp{+}, or @samp{=}, an action must
5409 be specified.
5411 If @var{syntax-spec} is just a category, and no action or characters
5412 were specified, then all characters in that category are reset to their
5413 default state.  A warning is issued if the category character is not
5414 valid.  If @var{syntax-spec} is the empty string, then all categories
5415 are reset to their default state.
5417 Syntax categories are divided into basic and context.  Every input
5418 byte belongs to exactly one basic syntax category.  Additionally, any
5419 byte can be assigned to a context category regardless of its current
5420 basic category.  Context categories exist because a character can
5421 behave differently when parsed in isolation than when it occurs in
5422 context to close out a token started by another basic category (for
5423 example, @kbd{newline} defaults to the basic category `Whitespace' as
5424 well as the context category `End comment').
5426 The following table describes the case-insensitive designation for each
5427 syntax category (the first byte in @var{syntax-spec}), and a description
5428 of what each category controls.
5430 @multitable @columnfractions .06 .20 .13 .55
5431 @headitem Code @tab Category @tab Type @tab Description
5433 @item @kbd{W} @tab @dfn{Words} @tab Basic
5434 @tab Characters that can start a macro name.  Defaults to the letters as
5435 defined by the locale, and the character @samp{_}.
5437 @item @kbd{D} @tab @dfn{Digits} @tab Basic
5438 @tab Characters that, together with the letters, form the remainder of a
5439 macro name.  Defaults to the ten digits @samp{0}@dots{}@samp{9}, and any
5440 other digits defined by the locale.
5442 @item @kbd{S} @tab @dfn{White space} @tab Basic
5443 @tab Characters that should be trimmed from the beginning of each argument to
5444 a macro call.  The defaults are space, tab, newline, carriage return,
5445 form feed, and vertical tab, and any others as defined by the locale.
5447 @item @kbd{(} @tab @dfn{Open parenthesis} @tab Basic
5448 @tab Characters that open the argument list of a macro call.  The default is
5449 the single character @samp{(}.
5451 @item @kbd{)} @tab @dfn{Close parenthesis} @tab Basic
5452 @tab Characters that close the argument list of a macro call.  The default
5453 is the single character @samp{)}.
5455 @item @kbd{,} @tab @dfn{Argument separator} @tab Basic
5456 @tab Characters that separate the arguments of a macro call.  The default is
5457 the single character @samp{,}.
5459 @item @kbd{L} @tab @dfn{Left quote} @tab Basic
5460 @tab The set of characters that can start a single-character quoted string.
5461 The default is the single character @samp{`}.  For multiple-character
5462 quote delimiters, use @code{changequote} (@pxref{Changequote}).
5464 @item @kbd{R} @tab @dfn{Right quote} @tab Context
5465 @tab The set of characters that can end a single-character quoted string.
5466 The default is the single character @samp{'}.  For multiple-character
5467 quote delimiters, use @code{changequote} (@pxref{Changequote}).  Note
5468 that @samp{'} also defaults to the syntax category `Other', when it
5469 appears in isolation.
5471 @item @kbd{B} @tab @dfn{Begin comment} @tab Basic
5472 @tab The set of characters that can start a single-character comment.  The
5473 default is the single character @samp{#}.  For multiple-character
5474 comment delimiters, use @code{changecom} (@pxref{Changecom}).
5476 @item @kbd{E} @tab @dfn{End comment} @tab Context
5477 @tab The set of characters that can end a single-character comment.  The
5478 default is the single character @kbd{newline}.  For multiple-character
5479 comment delimiters, use @code{changecom} (@pxref{Changecom}).  Note that
5480 newline also defaults to the syntax category `White space', when it
5481 appears in isolation.
5483 @item @kbd{$} @tab @dfn{Dollar} @tab Context
5484 @tab Characters that can introduce an argument reference in the body of a
5485 macro.  The default is the single character @samp{$}.
5487 @comment FIXME - implement ${10} argument parsing.
5488 @item @kbd{@{} @tab @dfn{Left brace} @tab Context
5489 @tab Characters that introduce an extended argument reference in the body of
5490 a macro immediately after a character in the Dollar category.  The
5491 default is the single character @samp{@{}.
5493 @item @kbd{@}} @tab @dfn{Right brace} @tab Context
5494 @tab Characters that conclude an extended argument reference in the body of a
5495 macro.  The default is the single character @samp{@}}.
5497 @item @kbd{O} @tab @dfn{Other} @tab Basic
5498 @tab Characters that have no special syntactical meaning to @code{m4}.
5499 Defaults to all characters except those in the categories above.
5501 @item @kbd{A} @tab @dfn{Active} @tab Basic
5502 @tab Characters that themselves, alone, form macro names.  This is a
5503 GNU extension, and active characters have lower precedence
5504 than comments.  By default, no characters are active.
5506 @item @kbd{@@} @tab @dfn{Escape} @tab Basic
5507 @tab Characters that must precede macro names for them to be recognized.
5508 This is a GNU extension.  When an escape character is defined,
5509 then macros are not recognized unless the escape character is present;
5510 however, the macro name, visible by @samp{$0} in macro definitions, does
5511 not include the escape character.  By default, no characters are
5512 escapes.
5514 @comment FIXME - we should also consider supporting:
5515 @comment @item @kbd{I} @tab @dfn{Ignore} @tab Basic
5516 @comment @tab Characters that are ignored if they appear in
5517 @comment the input; perhaps defaulting to '\0'.
5518 @end multitable
5520 The expansion of @code{changesyntax} is void.
5521 The macro @code{changesyntax} is recognized only with parameters.  Use
5522 this macro with caution, as it is possible to change the syntax in such
5523 a way that no further macros can be recognized by @code{m4}.
5524 This macro was added in M4 2.0.
5525 @end deffn
5527 With @code{changesyntax} we can modify what characters form a word.  For
5528 example, we can make @samp{.} a valid character in a macro name, or even
5529 start a macro name with a number.
5531 @example
5532 define(`test.1', `TEST ONE')
5533 @result{}
5534 define(`1', `one')
5535 @result{}
5536 __file__
5537 @result{}stdin
5538 test.1
5539 @result{}test.1
5540 dnl Add `.' and remove `_'.
5541 changesyntax(`W+.', `W-_')
5542 @result{}
5543 __file__
5544 @result{}__file__
5545 test.1
5546 @result{}TEST ONE
5547 dnl Set words to include numbers.
5548 changesyntax(`W=a-zA-Z0-9_')
5549 @result{}
5550 __file__
5551 @result{}stdin
5552 test.1
5553 @result{}test.one
5554 dnl Reset words to default (a-zA-Z_).
5555 changesyntax(`W')
5556 @result{}
5557 __file__
5558 @result{}stdin
5559 test.1
5560 @result{}test.1
5561 @end example
5563 Another possibility is to change the syntax of a macro call.
5565 @example
5566 define(`test', `$#')
5567 @result{}
5568 test(a, b, c)
5569 @result{}3
5570 dnl Change macro syntax.
5571 changesyntax(`(<', `,|', `)>')
5572 @result{}
5573 test(a, b, c)
5574 @result{}0(a, b, c)
5575 test<a|b|c>
5576 @result{}3
5577 @end example
5579 Leading spaces are always removed from macro arguments in @code{m4}, but
5580 by changing the syntax categories we can avoid it.  The use of
5581 @code{format} is an alternative to using a literal tab character.
5583 @example
5584 define(`test', `$1$2$3')
5585 @result{}
5586 test(`a', `b', `c')
5587 @result{}abc
5588 dnl Don't ignore whitespace.
5589 changesyntax(`O 'format(``%c'', `9')`
5591 @result{}
5592 test(a, b,
5594 @result{}a b
5595 @result{}c
5596 @end example
5598 It is possible to redefine the @samp{$} used to indicate macro arguments
5599 in user defined macros.  Dollar class syntax elements are copied to the
5600 output if there is no valid expansion.
5602 @example
5603 define(`argref', `Dollar: $#, Question: ?#')
5604 @result{}
5605 argref(1, 2, 3)
5606 @result{}Dollar: 3, Question: ?#
5607 dnl Change argument identifier.
5608 changesyntax(`$?')
5609 @result{}
5610 argref(1,2,3)
5611 @result{}Dollar: $#, Question: 3
5612 define(`escape', `$?`'1$?1?')
5613 @result{}
5614 escape(foo)
5615 @result{}$?1$foo?
5616 dnl Multiple argument identifiers.
5617 changesyntax(`$+$')
5618 @result{}
5619 argref(1, 2, 3)
5620 @result{}Dollar: 3, Question: 3
5621 @end example
5623 Macro calls can be given a @TeX{} or Texinfo like syntax using an
5624 escape.  If one or more characters are defined as escapes, macro names
5625 are only recognized if preceded by an escape character.
5627 If the escape is not followed by what is normally a word (a letter
5628 optionally followed by letters and/or numerals), that single character
5629 is returned as a macro name.
5631 As always, words without a macro definition cause no error message.
5632 They and the escape character are simply output.
5634 @example
5635 define(`foo', `bar')
5636 @result{}
5637 dnl Require @@ escape before any macro.
5638 changesyntax(`@@@@')
5639 @result{}
5641 @result{}foo
5642 @@foo
5643 @result{}bar
5644 @@bar
5645 @result{}@@bar
5646 @@dnl Change escape character.
5647 @@changesyntax(`@@\', `O@@')
5648 @result{}
5650 @result{}foo
5651 @@foo
5652 @result{}@@foo
5653 \foo
5654 @result{}bar
5655 define(`#', `No comment')
5656 @result{}define(#, No comment)
5657 \define(`#', `No comment')
5658 @result{}
5659 \# \foo # Comment \foo
5660 @result{}No comment bar # Comment \foo
5661 @end example
5663 Active characters are known from @TeX{}.  In @code{m4} an active
5664 character is always seen as a one-letter word, and so, if it has a macro
5665 definition, the macro will be called.
5667 @example
5668 define(`@@', `TEST')
5669 @result{}
5670 define(`a@@a', `hello')
5671 @result{}
5672 define(`a', `A')
5673 @result{}
5675 @result{}@@
5676 a@@a
5677 @result{}A@@A
5678 dnl Make @@ active.
5679 changesyntax(`A@@')
5680 @result{}
5682 @result{}TEST
5683 a@@a
5684 @result{}ATESTa
5685 @end example
5687 There is obviously an overlap between @code{changesyntax} and
5688 @code{changequote}, since there are now two ways to modify quote
5689 delimiters.  To avoid incompatibilities, if the quotes are modified by
5690 @code{changequote}, any characters previously set to either quote
5691 delimiter by @code{changesyntax} are first demoted to the other category
5692 (@samp{O}), so the result is only a single set of quotes.  In the other
5693 direction, if quotes were already disabled, or if both the start and end
5694 delimiter set by @code{changequote} are single bytes, then
5695 @code{changesyntax} preserves those settings.  But if either delimiter
5696 occupies multiple bytes, @code{changesyntax} first disables both
5697 delimiters.  Quotes can be disabled via @code{changesyntax} by emptying
5698 the left quote basic category (@samp{L}).  Meanwhile, the right quote
5699 context category (@samp{R}) will never be empty; if a
5700 @code{changesyntax} action would otherwise leave that category empty,
5701 then the default end delimiter from @code{changequote} (@samp{'}) is
5702 used; thus, it is never possible to get @code{m4} in a state where a
5703 quoted string cannot be terminated.  These interactions apply to comment
5704 delimiters as well, @i{mutatis mutandis} with @code{changecom}.
5706 @example
5707 define(`test', `TEST')
5708 @result{}
5709 dnl Add additional single-byte delimiters.
5710 changesyntax(`L+<', `R+>')
5711 @result{}
5712 <test> `test' [test] <<test>>
5713 @result{}test test [TEST] <test>
5714 dnl Use standard interface, overriding changesyntax settings.
5715 changequote(<[>, `]')
5716 @result{}
5717 <test> `test' [test] <<test>>
5718 @result{}<TEST> `TEST' test <<TEST>>
5719 dnl Introduce multi-byte delimiters.
5720 changequote([<<], [>>])
5721 @result{}
5722 <test> `test' [test] <<test>>
5723 @result{}<TEST> `TEST' [TEST] test
5724 dnl Change end quote, effectively disabling quotes.
5725 changesyntax(<<R]>>)
5726 @result{}
5727 <test> `test' [test] <<test>>
5728 @result{}<TEST> `TEST' [TEST] <<TEST>>
5729 dnl Change beginning quote, make ] normal, thus making ' end quote.
5730 changesyntax(L`, R-])
5731 @result{}
5732 <test> `test' [test] <<test>>
5733 @result{}<TEST> test [TEST] <<TEST>>
5734 dnl Set multi-byte quote; unrelated changes don't impact it.
5735 changequote(`<<', `>>')changesyntax(<<@@\>>)
5736 @result{}
5737 <\test> `\test' [\test] <<\test>>
5738 @result{}<TEST> `TEST' [TEST] \test
5739 @end example
5741 If several characters are assigned to a category that forms single
5742 character tokens, all such characters are treated as equal.  Any open
5743 parenthesis will match any close parenthesis, etc.
5745 @example
5746 dnl Go crazy with symbols.
5747 changesyntax(`(@{<', `)@}>', `,;:', `O(,)')
5748 @result{}
5749 eval@{2**4-1; 2: 8>
5750 @result{}00001111
5751 @end example
5753 The syntax table is initialized to be backwards compatible, so if you
5754 never call @code{changesyntax}, nothing will have changed.
5756 For now, debugging output continues to use @kbd{(}, @kbd{,} and @kbd{)}
5757 to show macro calls; and macro expansions that result in a list of
5758 arguments (such as @samp{$@@} or @code{shift}) use @samp{,}, regardless
5759 of the current syntax settings.  However, this is likely to change in a
5760 future release, so it should not be relied on, particularly since it is
5761 next to impossible to write recursive macros if the argument separator
5762 doesn't match between expansion and rescanning.
5764 @c FIXME - changing syntax of , should not break iterative macros.
5765 @example
5766 $ @kbd{m4 -d}
5767 changesyntax(`,=|')traceon(`foo')define(`foo'|`$#:$@@')
5768 @result{}
5769 foo(foo(1|2|3))
5770 @error{}m4trace: -2- foo(`1', `2', `3') -> `3:`1',`2',`3''
5771 @error{}m4trace: -1- foo(`3:1,2,3') -> `1:`3:1,2,3''
5772 @result{}1:3:1,2,3
5773 @end example
5775 @node M4wrap
5776 @section Saving text until end of input
5778 @cindex saving input
5779 @cindex input, saving
5780 @cindex deferring expansion
5781 @cindex expansion, deferring
5782 It is possible to `save' some text until the end of the normal input has
5783 been seen.  Text can be saved, to be read again by @code{m4} when the
5784 normal input has been exhausted.  This feature is normally used to
5785 initiate cleanup actions before normal exit, e.g., deleting temporary
5786 files.
5788 To save input text, use the builtin @code{m4wrap}:
5790 @deffn {Builtin (m4)} m4wrap (@var{string}, @dots{})
5791 Stores @var{string} in a safe place, to be reread when end of input is
5792 reached.  As a GNU extension, additional arguments are
5793 concatenated with a space to the @var{string}.
5795 Successive invocations of @code{m4wrap} accumulate saved text in
5796 first-in, first-out order, as required by POSIX.
5798 The expansion of @code{m4wrap} is void.
5799 The macro @code{m4wrap} is recognized only with parameters.
5800 @end deffn
5802 @example
5803 define(`cleanup', `This is the `cleanup' action.
5805 @result{}
5806 m4wrap(`cleanup')
5807 @result{}
5808 This is the first and last normal input line.
5809 @result{}This is the first and last normal input line.
5811 @result{}This is the cleanup action.
5812 @end example
5814 The saved input is only reread when the end of normal input is seen, and
5815 not if @code{m4exit} is used to exit @code{m4}.
5817 It is safe to call @code{m4wrap} from wrapped text, where all the
5818 recursively wrapped text is deferred until the current wrapped text is
5819 exhausted.  As of M4 1.6, when @code{m4wrap} is not used recursively,
5820 the saved pieces of text are reread in the same order in which they were
5821 saved (FIFO---first in, first out), as required by POSIX.
5823 @example
5824 m4wrap(`1
5826 @result{}
5827 m4wrap(`2', `3
5829 @result{}
5831 @result{}1
5832 @result{}2 3
5833 @end example
5835 However, earlier versions had reverse ordering (LIFO---last in, first
5836 out), as this behavior is more like the semantics of the C function
5837 @code{atexit}.  It is possible to emulate POSIX behavior even
5838 with older versions of GNU M4 by including the file
5839 @file{m4-@value{VERSION}/@/examples/@/wrapfifo.m4} from the
5840 distribution:
5842 @comment examples
5843 @example
5844 $ @kbd{m4 -I examples}
5845 undivert(`wrapfifo.m4')dnl
5846 @result{}dnl Redefine m4wrap to have FIFO semantics.
5847 @result{}define(`_m4wrap_level', `0')dnl
5848 @result{}define(`m4wrap',
5849 @result{}`ifdef(`m4wrap'_m4wrap_level,
5850 @result{}       `define(`m4wrap'_m4wrap_level,
5851 @result{}               defn(`m4wrap'_m4wrap_level)`$1')',
5852 @result{}       `builtin(`m4wrap', `define(`_m4wrap_level',
5853 @result{}                                  incr(_m4wrap_level))dnl
5854 @result{}m4wrap'_m4wrap_level)dnl
5855 @result{}define(`m4wrap'_m4wrap_level, `$1')')')dnl
5856 include(`wrapfifo.m4')
5857 @result{}
5858 m4wrap(`a`'m4wrap(`c
5859 ', `d')')m4wrap(`b')
5860 @result{}
5862 @result{}abc
5863 @end example
5865 It is likewise possible to emulate LIFO behavior without resorting to
5866 the GNU M4 extension of @code{builtin}, by including the file
5867 @file{m4-@value{VERSION}/@/examples/@/wraplifo.m4} from the
5868 distribution.  (Unfortunately, both examples shown here share some
5869 subtle bugs.  See if you can find and correct them; or @pxref{Improved
5870 m4wrap, , Answers}).
5872 @comment examples
5873 @example
5874 $ @kbd{m4 -I examples}
5875 undivert(`wraplifo.m4')dnl
5876 @result{}dnl Redefine m4wrap to have LIFO semantics.
5877 @result{}define(`_m4wrap_level', `0')dnl
5878 @result{}define(`_m4wrap', defn(`m4wrap'))dnl
5879 @result{}define(`m4wrap',
5880 @result{}`ifdef(`m4wrap'_m4wrap_level,
5881 @result{}       `define(`m4wrap'_m4wrap_level,
5882 @result{}               `$1'defn(`m4wrap'_m4wrap_level))',
5883 @result{}       `_m4wrap(`define(`_m4wrap_level', incr(_m4wrap_level))dnl
5884 @result{}m4wrap'_m4wrap_level)dnl
5885 @result{}define(`m4wrap'_m4wrap_level, `$1')')')dnl
5886 include(`wraplifo.m4')
5887 @result{}
5888 m4wrap(`a`'m4wrap(`c
5889 ', `d')')m4wrap(`b')
5890 @result{}
5892 @result{}bac
5893 @end example
5895 Here is an example of implementing a factorial function using
5896 @code{m4wrap}:
5898 @example
5899 define(`f', `ifelse(`$1', `0', `Answer: 0!=1
5900 ', eval(`$1>1'), `0', `Answer: $2$1=eval(`$2$1')
5901 ', `m4wrap(`f(decr(`$1'), `$2$1*')')')')
5902 @result{}
5903 f(`10')
5904 @result{}
5906 @result{}Answer: 10*9*8*7*6*5*4*3*2*1=3628800
5907 @end example
5909 Invocations of @code{m4wrap} at the same recursion level are
5910 concatenated and rescanned as usual:
5912 @example
5913 define(`ab', `AB
5915 @result{}
5916 m4wrap(`a')m4wrap(`b')
5917 @result{}
5919 @result{}AB
5920 @end example
5922 @noindent
5923 however, the transition between recursion levels behaves like an end of
5924 file condition between two input files.
5926 @comment status: 1
5927 @example
5928 m4wrap(`m4wrap(`)')len(abc')
5929 @result{}
5931 @error{}m4:stdin:1: len: end of file in argument list
5932 @end example
5934 As of M4 1.6, @code{m4wrap} transparently handles builtin tokens
5935 generated by @code{defn} (@pxref{Defn}).  However, for portability, it
5936 is better to defer the evaluation of @code{defn} along with the rest of
5937 the wrapped text, as is done for @code{foo} in the example below, rather
5938 than computing the builtin token up front, as is done for @code{bar}.
5940 @example
5941 m4wrap(`define(`foo', defn(`divnum'))foo
5943 @result{}
5944 m4wrap(`define(`bar', ')m4wrap(defn(`divnum'))m4wrap(`)bar
5946 @result{}
5948 @result{}0
5949 @result{}0
5950 @end example
5952 @node File Inclusion
5953 @chapter File inclusion
5955 @cindex file inclusion
5956 @cindex inclusion, of files
5957 @code{m4} allows you to include named files at any point in the input.
5959 @menu
5960 * Include::                     Including named files and modules
5961 * Search Path::                 Searching for include files
5962 @end menu
5964 @node Include
5965 @section Including named files and modules
5967 There are two builtin macros in @code{m4} for including files:
5969 @deffn {Builtin (m4)} include (@var{file})
5970 @deffnx {Builtin (m4)} sinclude (@var{file})
5971 Both macros cause the file named @var{file} to be read by
5972 @code{m4}.  When the end of the file is reached, input is resumed from
5973 the previous input file.
5975 The expansion of @code{include} and @code{sinclude} is therefore the
5976 contents of @var{file}.
5978 If @var{file} does not exist, is a directory, or cannot otherwise be
5979 read, the expansion is void,
5980 and @code{include} will fail with an error while @code{sinclude} is
5981 silent.  The empty string counts as a file that does not exist.
5983 The macros @code{include} and @code{sinclude} are recognized only with
5984 parameters.
5985 @end deffn
5987 @comment status: 1
5988 @example
5989 include(`n')
5990 @error{}m4:stdin:1: include: cannot open file 'n': No such file or directory
5991 @result{}
5992 include()
5993 @error{}m4:stdin:2: include: cannot open file '': No such file or directory
5994 @result{}
5995 sinclude(`n')
5996 @result{}
5997 sinclude()
5998 @result{}
5999 @end example
6001 This section uses the @option{--include} command-line option (or
6002 @option{-I}, @pxref{Preprocessor features, , Invoking m4}) to grab
6003 files from the @file{m4-@value{VERSION}/@/examples}
6004 directory shipped as part of the GNU @code{m4} package.  The
6005 file @file{m4-@value{VERSION}/@/examples/@/incl.m4} in the distribution
6006 contains the lines:
6008 @comment ignore
6009 @example
6010 $ @kbd{cat examples/incl.m4}
6011 @result{}Include file start
6012 @result{}foo
6013 @result{}Include file end
6014 @end example
6016 Normally file inclusion is used to insert the contents of a file
6017 into the input stream.  The contents of the file will be read by
6018 @code{m4} and macro calls in the file will be expanded:
6020 @comment examples
6021 @example
6022 $ @kbd{m4 -I examples}
6023 define(`foo', `FOO')
6024 @result{}
6025 include(`incl.m4')
6026 @result{}Include file start
6027 @result{}FOO
6028 @result{}Include file end
6029 @result{}
6030 @end example
6032 The fact that @code{include} and @code{sinclude} expand to the contents
6033 of the file can be used to define macros that operate on entire files.
6034 Here is an example, which defines @samp{bar} to expand to the contents
6035 of @file{incl.m4}:
6037 @comment examples
6038 @example
6039 $ @kbd{m4 -I examples}
6040 define(`bar', include(`incl.m4'))
6041 @result{}
6042 This is `bar':  >>bar<<
6043 @result{}This is bar:  >>Include file start
6044 @result{}foo
6045 @result{}Include file end
6046 @result{}<<
6047 @end example
6049 This use of @code{include} is not trivial, though, as files can contain
6050 quotes, commas, and parentheses, which can interfere with the way the
6051 @code{m4} parser works.  GNU M4 seamlessly concatenates
6052 the file contents with the next character, even if the included file
6053 ended in the middle of a comment, string, or macro call.  These
6054 conditions are only treated as end of file errors if specified as input
6055 files on the command line.
6057 In GNU M4, an alternative method of reading files is
6058 using @code{undivert} (@pxref{Undivert}) on a named file.
6060 In addition, as a GNU M4 extension, if the included file can
6061 not be found exactly as given, various standard suffixes are appended.
6062 If the included file name is absolute (a full path from the root directory
6063 is given) then additional search directories are not examined, although
6064 suffixes will be tried if the file is not found exactly as given.
6065 For each directory that is searched (according to the absolute directory
6066 give in the file name, or else by directories listed in @env{M4PATH} and
6067 given with the @option{-I} and @option{-B} options), first the unchanged
6068 file name is tried, and then again with the suffixes @samp{.m4f} and
6069 @samp{.m4}.
6071 Furthermore, if no matching file has yet been found, before moving on to
6072 the next directory, @samp{.la} and the usual binary module suffix for
6073 the host platform (usually @samp{.so}) are also tried.  Matching with one
6074 of those suffixes will attempt to load the matched file as a dynamic
6075 module. @xref{Modules}, for more details.
6077 @node Search Path
6078 @section Searching for include files
6080 @cindex search path for included files
6081 @cindex included files, search path for
6082 @cindex GNU extensions
6083 GNU @code{m4} allows included files to be found in other directories
6084 than the current working directory.
6086 @cindex @env{M4PATH}
6087 If the @option{--prepend-include} or @option{-B} command-line option was
6088 provided (@pxref{Preprocessor features, , Invoking m4}), those
6089 directories are searched first, in reverse order that those options were
6090 listed on the command line.  Then @code{m4} looks in the current working
6091 directory.  Next comes the directories specified with the
6092 @option{--include} or @option{-I} option, in the order found on the
6093 command line.  Finally, if the @env{M4PATH} environment variable is set,
6094 it is expected to contain a colon-separated list of directories, which
6095 will be searched in order.
6097 If the automatic search for include-files causes trouble, the @samp{p}
6098 debug flag (@pxref{Debugmode}) can help isolate the problem.
6100 @node Diversions
6101 @chapter Diverting and undiverting output
6103 @cindex deferring output
6104 Diversions are a way of temporarily saving output.  The output of
6105 @code{m4} can at any time be diverted to a temporary file, and be
6106 reinserted into the output stream, @dfn{undiverted}, again at a later
6107 time.
6109 @cindex @env{TMPDIR}
6110 Numbered diversions are counted from 0 upwards, diversion number 0
6111 being the normal output stream.  GNU
6112 @code{m4} tries to keep diversions in memory.  However, there is a
6113 limit to the overall memory usable by all diversions taken together
6114 (512K, currently).  When this maximum is about to be exceeded,
6115 a temporary file is opened to receive the contents of the biggest
6116 diversion still in memory, freeing this memory for other diversions.
6117 When creating the temporary file, @code{m4} honors the value of the
6118 environment variable @env{TMPDIR}, and falls back to @file{/tmp}.
6119 Thus, the amount of available disk space provides the only real limit on
6120 the number and aggregate size of diversions.
6122 Diversions make it possible to generate output in a different order than
6123 the input was read.  It is possible to implement topological sorting
6124 dependencies.  For example, GNU Autoconf makes use of
6125 diversions under the hood to ensure that the expansion of a prerequisite
6126 macro appears in the output prior to the expansion of a dependent macro,
6127 regardless of which order the two macros were invoked in the user's
6128 input file.
6130 @menu
6131 * Divert::                      Diverting output
6132 * Undivert::                    Undiverting output
6133 * Divnum::                      Diversion numbers
6134 * Cleardivert::                 Discarding diverted text
6135 @end menu
6137 @node Divert
6138 @section Diverting output
6140 @cindex diverting output to files
6141 @cindex output, diverting to files
6142 @cindex files, diverting output to
6143 Output is diverted using @code{divert}:
6145 @deffn {Builtin (m4)} divert (@dvar{number, 0}, @ovar{text})
6146 The current diversion is changed to @var{number}.  If @var{number} is left
6147 out or empty, it is assumed to be zero.  If @var{number} cannot be
6148 parsed, the diversion is unchanged.
6150 @cindex GNU extensions
6151 As a GNU extension, if optional @var{text} is supplied and
6152 @var{number} was valid, then @var{text} is immediately output to the
6153 new diversion, regardless of whether the expansion of @code{divert}
6154 occurred while collecting arguments for another macro.
6156 The expansion of @code{divert} is void.
6157 @end deffn
6159 When all the @code{m4} input will have been processed, all existing
6160 diversions are automatically undiverted, in numerical order.
6162 @example
6163 divert(`1')
6164 This text is diverted.
6165 divert
6166 @result{}
6167 This text is not diverted.
6168 @result{}This text is not diverted.
6170 @result{}
6171 @result{}This text is diverted.
6172 @end example
6174 Several calls of @code{divert} with the same argument do not overwrite
6175 the previous diverted text, but append to it.  Diversions are printed
6176 after any wrapped text is expanded.
6178 @example
6179 define(`text', `TEXT')
6180 @result{}
6181 divert(`1')`diverted text.'
6182 divert
6183 @result{}
6184 m4wrap(`Wrapped text precedes ')
6185 @result{}
6187 @result{}Wrapped TEXT precedes diverted text.
6188 @end example
6190 @cindex discarding input
6191 @cindex input, discarding
6192 If output is diverted to a negative diversion, it is simply discarded.
6193 This can be used to suppress unwanted output.  A common example of
6194 unwanted output is the trailing newlines after macro definitions.  Here
6195 is a common programming idiom in @code{m4} for avoiding them.
6197 @example
6198 divert(`-1')
6199 define(`foo', `Macro `foo'.')
6200 define(`bar', `Macro `bar'.')
6201 divert
6202 @result{}
6203 @end example
6205 @cindex GNU extensions
6206 Traditional implementations only supported ten diversions.  But as a
6207 GNU extension, diversion numbers can be as large as positive
6208 integers will allow, rather than treating a multi-digit diversion number
6209 as a request to discard text.
6211 @example
6212 divert(eval(`1<<28'))world
6213 divert(`2')hello
6215 @result{}hello
6216 @result{}world
6217 @end example
6219 The ability to immediately output extra text is a GNU
6220 extension, but it can prove useful for ensuring that text goes to a
6221 particular diversion no matter how many pending macro expansions are in
6222 progress.  For a demonstration of why this is useful, it is important to
6223 understand in the example below why @samp{one} is output in diversion 2,
6224 not diversion 1, while @samp{three} and @samp{five} both end up in the
6225 correctly numbered diversion.  The key point is that when @code{divert}
6226 is executed unquoted as part of the argument collection of another
6227 macro, the side effect takes place immediately, but the text @samp{one}
6228 is not passed to any diversion until after the @samp{divert(`2')} and
6229 the enclosing @code{echo} have also taken place.  The example with
6230 @samp{three} shows how following the quoting rule of thumb delays the
6231 invocation of @code{divert} until it is not nested in any argument
6232 collection context, while the example with @samp{five} shows the use of
6233 the optional argument to speed up the output process.
6235 @example
6236 define(`echo', `$1')
6237 @result{}
6238 echo(divert(`1')`one'divert(`2'))`'dnl
6239 echo(`divert(`3')three`'divert(`4')')`'dnl
6240 echo(divert(`5', `five')divert(`6'))`'dnl
6241 divert
6242 @result{}
6243 undivert(`1')
6244 @result{}
6245 undivert(`2')
6246 @result{}one
6247 undivert(`3')
6248 @result{}three
6249 undivert(`4')
6250 @result{}
6251 undivert(`5')
6252 @result{}five
6253 undivert(`6')
6254 @result{}
6255 @end example
6257 Note that @code{divert} is an English word, but also an active macro
6258 without arguments.  When processing plain text, the word might appear in
6259 normal text and be unintentionally swallowed as a macro invocation.  One
6260 way to avoid this is to use the @option{-P} option to rename all
6261 builtins (@pxref{Operation modes, , Invoking m4}).  Another is to write
6262 a wrapper that requires a parameter to be recognized.
6264 @example
6265 We decided to divert the stream for irrigation.
6266 @result{}We decided to  the stream for irrigation.
6267 define(`divert', `ifelse(`$#', `0', ``$0'', `builtin(`$0', $@@)')')
6268 @result{}
6269 divert(`-1')
6270 Ignored text.
6271 divert(`0')
6272 @result{}
6273 We decided to divert the stream for irrigation.
6274 @result{}We decided to divert the stream for irrigation.
6275 @end example
6277 @node Undivert
6278 @section Undiverting output
6280 Diverted text can be undiverted explicitly using the builtin
6281 @code{undivert}:
6283 @deffn {Builtin (m4)} undivert (@ovar{diversions@dots{}})
6284 Undiverts the numeric @var{diversions} given by the arguments, in the
6285 order given.  If no arguments are supplied, all diversions are
6286 undiverted, in numerical order.
6288 @cindex file inclusion
6289 @cindex inclusion, of files
6290 @cindex GNU extensions
6291 As a GNU extension, @var{diversions} may contain non-numeric
6292 strings, which are treated as the names of files to copy into the output
6293 without expansion.  A warning is issued if a file could not be opened.
6295 The expansion of @code{undivert} is void.
6296 @end deffn
6298 @example
6299 divert(`1')
6300 This text is diverted.
6301 divert
6302 @result{}
6303 This text is not diverted.
6304 @result{}This text is not diverted.
6305 undivert(`1')
6306 @result{}
6307 @result{}This text is diverted.
6308 @result{}
6309 @end example
6311 Notice the last two blank lines.  One of them comes from the newline
6312 following @code{undivert}, the other from the newline that followed the
6313 @code{divert}!  A diversion often starts with a blank line like this.
6315 When diverted text is undiverted, it is @emph{not} reread by @code{m4},
6316 but rather copied directly to the current output, and it is therefore
6317 not an error to undivert into a diversion.  Undiverting the empty string
6318 is the same as specifying diversion 0; in either case nothing happens
6319 since the output has already been flushed.
6321 @example
6322 divert(`1')diverted text
6323 divert
6324 @result{}
6325 undivert()
6326 @result{}
6327 undivert(`0')
6328 @result{}
6329 undivert
6330 @result{}diverted text
6331 @result{}
6332 divert(`1')more
6333 divert(`2')undivert(`1')diverted text`'divert
6334 @result{}
6335 undivert(`1')
6336 @result{}
6337 undivert(`2')
6338 @result{}more
6339 @result{}diverted text
6340 @end example
6342 When a diversion has been undiverted, the diverted text is discarded,
6343 and it is not possible to bring back diverted text more than once.
6345 @example
6346 divert(`1')
6347 This text is diverted first.
6348 divert(`0')undivert(`1')dnl
6349 @result{}
6350 @result{}This text is diverted first.
6351 undivert(`1')
6352 @result{}
6353 divert(`1')
6354 This text is also diverted but not appended.
6355 divert(`0')undivert(`1')dnl
6356 @result{}
6357 @result{}This text is also diverted but not appended.
6358 @end example
6360 Attempts to undivert the current diversion are silently ignored.  Thus,
6361 when the current diversion is not 0, the current diversion does not get
6362 rearranged among the other diversions.
6364 @example
6365 divert(`1')one
6366 divert(`2')two
6367 divert(`3')three
6368 divert(`4')four
6369 divert(`5')five
6370 divert(`2')undivert(`5', `2', `4')dnl
6371 undivert`'dnl effectively undivert(`1', `2', `3', `4', `5')
6372 divert`'undivert`'dnl
6373 @result{}two
6374 @result{}five
6375 @result{}four
6376 @result{}one
6377 @result{}three
6378 @end example
6380 @cindex GNU extensions
6381 @cindex file inclusion
6382 @cindex inclusion, of files
6383 GNU @code{m4} allows named files to be undiverted.  Given a
6384 non-numeric argument, the contents of the file named will be copied,
6385 uninterpreted, to the current output.  This complements the builtin
6386 @code{include} (@pxref{Include}).  To illustrate the difference, assume
6387 the file @file{foo} contains:
6389 @comment file: foo
6390 @example
6391 $ @kbd{cat foo}
6393 @end example
6395 @noindent
6396 then
6398 @example
6399 define(`bar', `BAR')
6400 @result{}
6401 undivert(`foo')
6402 @result{}bar
6403 @result{}
6404 include(`foo')
6405 @result{}BAR
6406 @result{}
6407 @end example
6409 If the file is not found (or cannot be read), an error message is
6410 issued, and the expansion is void.  It is possible to intermix files
6411 and diversion numbers.
6413 @example
6414 divert(`1')diversion one
6415 divert(`2')undivert(`foo')dnl
6416 divert(`3')diversion three
6417 divert`'dnl
6418 undivert(`1', `2', `foo', `3')dnl
6419 @result{}diversion one
6420 @result{}bar
6421 @result{}bar
6422 @result{}diversion three
6423 @end example
6425 @node Divnum
6426 @section Diversion numbers
6428 @cindex diversion numbers
6429 The current diversion is tracked by the builtin @code{divnum}:
6431 @deffn {Builtin (m4)} divnum
6432 Expands to the number of the current diversion.
6433 @end deffn
6435 @example
6436 Initial divnum
6437 @result{}Initial 0
6438 divert(`1')
6439 Diversion one: divnum
6440 divert(`2')
6441 Diversion two: divnum
6443 @result{}
6444 @result{}Diversion one: 1
6445 @result{}
6446 @result{}Diversion two: 2
6447 @end example
6449 @node Cleardivert
6450 @section Discarding diverted text
6452 @cindex discarding diverted text
6453 @cindex diverted text, discarding
6454 Often it is not known, when output is diverted, whether the diverted
6455 text is actually needed.  Since all non-empty diversion are brought back
6456 on the main output stream when the end of input is seen, a method of
6457 discarding a diversion is needed.  If all diversions should be
6458 discarded, the easiest is to end the input to @code{m4} with
6459 @samp{divert(`-1')} followed by an explicit @samp{undivert}:
6461 @example
6462 divert(`1')
6463 Diversion one: divnum
6464 divert(`2')
6465 Diversion two: divnum
6466 divert(`-1')
6467 undivert
6469 @end example
6471 @noindent
6472 No output is produced at all.
6474 Clearing selected diversions can be done with the following macro:
6476 @deffn Composite cleardivert (@ovar{diversions@dots{}})
6477 Discard the contents of each of the listed numeric @var{diversions}.
6478 @end deffn
6480 @example
6481 define(`cleardivert',
6482 `pushdef(`_n', divnum)divert(`-1')undivert($@@)divert(_n)popdef(`_n')')
6483 @result{}
6484 @end example
6486 It is called just like @code{undivert}, but the effect is to clear the
6487 diversions, given by the arguments.  (This macro has a nasty bug!  You
6488 should try to see if you can find it and correct it; or @pxref{Improved
6489 cleardivert, , Answers}).
6491 @node Modules
6492 @chapter Extending M4 with dynamic runtime modules
6494 @cindex modules
6495 @cindex dynamic modules
6496 @cindex loadable modules
6497 GNU M4 1.4.x had a monolithic architecture.  All of its
6498 functionality was contained in a single binary, and additional macros
6499 could be added only by writing more code in the M4 language, or at the
6500 extreme by hacking the sources and recompiling the whole thing to make
6501 a custom M4 installation.
6503 Starting with release 2.0, M4 uses Libtool's @code{libltdl} facilities
6504 (@pxref{Using libltdl, , libltdl, libtool, The GNU Libtool Manual})
6505 to move all of M4's builtins out to pluggable modules.  Unless compile
6506 time options are set to change the default build, the installed M4 2.0
6507 binary is virtually identical to 1.4.x, supporting the same builtins.
6508 However, additional modules can be loaded into the running M4 interpreter
6509 as it is started up at the command line, or during normal expansion of
6510 macros.  This facilitates runtime extension of the M4 builtin macro
6511 list using compiled C code linked against a new shared library,
6512 typically named @file{libm4.so}.
6514 For example, you might want to add a @code{setenv} builtin to M4, to
6515 use before invoking @code{esyscmd}.  We might write a @file{setenv.c}
6516 something like this:
6518 @comment ignore
6519 @example
6520 #include "m4module.h"
6522 M4BUILTIN(setenv);
6524 m4_builtin m4_builtin_table[] =
6526   /* name      handler         flags             minargs maxargs */
6527   @{ "setenv", builtin_setenv, M4_BUILTIN_BLIND, 2,      3 @},
6529   @{ NULL,     NULL,           0,                0,      0 @}
6533  * setenv(NAME, VALUE, [OVERWRITE])
6534  **/
6535 M4BUILTIN_HANDLER (setenv)
6537   int overwrite = 1;
6539   if (argc >= 4)
6540     if (!m4_numeric_arg (context, argc, argv, 3, &overwrite))
6541       return;
6543   setenv (M4ARG (1), M4ARG (2), overwrite);
6545 @end example
6547 Then, having compiled and linked the module, in (somewhat contrived)
6548 M4 code:
6550 @comment ignore
6551 @example
6552 $ @kbd{m4 setenv}
6553 setenv(`PATH', `/sbin:/bin:/usr/sbin:/usr/bin')
6554 @result{}
6555 esyscmd(`ifconfig -a')dnl
6556 @result{}@dots{}
6557 @end example
6559 Or instead of loading the module from the M4 invocation, you can use
6560 the @code{include} builtin:
6562 @comment ignore
6563 @example
6564 $ @kbd{m4}
6565 include(`setenv')
6566 @result{}
6567 setenv(`PATH', `/sbin:/bin:/usr/sbin:/usr/bin')
6568 @result{}
6569 @end example
6571 Also, at build time, you can choose which modules to build into
6572 the core (so that they will be available without dynamic loading).
6573 SUSv3 M4 functionality is contained in the module @samp{m4}, GNU
6574 extensions in the module @samp{gnu}, additional module builtins in the
6575 module @samp{load} and so on.
6577 We hinted earlier that the @code{m4} and @code{gnu} modules are
6578 preloaded into the installed M4 binary, but it is possible to install
6579 a @emph{thinner} binary; for example, omitting the GNU
6580 extensions by configuring the distribution with @kbd{./configure
6581 --with-modules=m4}.  For a binary built with that option to understand
6582 code that uses GNU extensions, you must then run @kbd{m4 gnu}.
6583 It is also possible to build a @emph{fatter} binary with additional
6584 modules preloaded: adding, say, the @code{load} module usingr
6585  @kbd{./configure --with-modules="m4 gnu load"}.
6587 GNU M4 now has a facility for defining additional builtins without
6588 recompiling the sources.  In actual fact, all of the builtins provided
6589 by GNU M4 are loaded from such modules.  All of the builtin
6590 descriptions in this manual are annotated with the module from which
6591 they are loaded -- mostly from the module @samp{m4}.
6593 When you start GNU M4, the modules @samp{m4} and @samp{gnu} are
6594 loaded by default.  If you supply the @option{-G} option at startup, the
6595 module @samp{traditional} is loaded instead of @samp{gnu}.
6596 @xref{Compatibility}, for more details on the differences between these
6597 two modes of startup.
6599 @menu
6600 * M4modules::                   Listing loaded modules
6601 * Unload::                      Removing loaded modules
6602 * Refcount::                    Tracking module references
6603 * Standard Modules::            Standard bundled modules
6604 @end menu
6606 @node M4modules
6607 @section Listing loaded modules
6609 @deffn {Builtin (load)} m4modules
6610 Expands to a quoted ordered list of currently loaded modules,
6611 with the most recently loaded module at the front of the list.  Loading
6612 a module multiple times will not affect the order of this list, the
6613 position depends on when the module was @emph{first} loaded.
6614 @end deffn
6616 For example, if GNU @code{m4} is started with the
6617 @option{load} module, @code{m4modules} will yield the following:
6619 @comment options: load -
6620 @example
6621 $ @kbd{m4 load -}
6622 m4modules
6623 @result{}load,gnu,m4
6624 @end example
6626 @node Unload
6627 @section Removing loaded modules
6629 @deffn {Builtin (load)} unload (@var{module-name})
6630 Any loaded modules that can be listed by the @code{m4modules} macro can be
6631 removed by naming them as the @var{module-name} parameter of the
6632 @code{unload} macro.  Unloading a module consists of removing all of the
6633 macros it provides from the internal table of visible macros, and
6634 running the module's finalization method (if any).
6636 The macro @code{unload} is recognized only with parameters.
6637 @end deffn
6639 @comment options: mpeval load -
6640 @example
6641 $ @kbd{m4 mpeval load -}
6642 m4modules
6643 @result{}load,mpeval,gnu,m4
6644 unload(`mpeval')
6645 @result{}
6646 m4modules
6647 @result{}load,gnu,m4
6648 @end example
6650 @node Refcount
6651 @section Tracking module references
6653 @deffn {Builtin (load)} refcount (@var{module-name})
6654 This macro expands to an integer representing the number of times
6655 @var{module-name} has been loaded but not yet unloaded.  No warning is
6656 issued, even if @var{module-name} does not represent a valid module.
6658 The macro @code{refcount} is recognized only with parameters.
6659 @end deffn
6661 This example demonstrates tracking the reference count of the gnu
6662 module.
6664 @comment options: load -
6665 @example
6666 $ @kbd{m4 load -}
6667 m4modules
6668 @result{}load,gnu,m4
6669 refcount(`gnu')
6670 @result{}1
6671 m4modules
6672 @result{}load,gnu,m4
6673 include(`gnu')
6674 @result{}
6675 refcount(`gnu')
6676 @result{}2
6677 unload(`gnu')
6678 @result{}
6679 m4modules
6680 @result{}load,gnu,m4
6681 refcount(`gnu')
6682 @result{}1
6683 unload(`gnu')
6684 @result{}
6685 m4modules
6686 @result{}load,m4
6687 refcount(`gnu')
6688 @result{}0
6689 refcount(`NoSuchModule')
6690 @result{}0
6691 @end example
6693 @node Standard Modules
6694 @section Standard bundled modules
6696 GNU @code{m4} ships with several bundled modules as standard.
6697 By convention, these modules define a text macro that can be tested
6698 with @code{ifdef} when they are loaded; only the @code{m4} module lacks
6699 this feature test macro, since it is not permitted by POSIX.
6700 Each of the feature test macros are intended to be used without
6701 arguments.
6703 @table @code
6704 @item m4
6705 Provides all of the builtins defined by POSIX.  This module
6706 is always loaded --- GNU @code{m4} would only be a very slow
6707 version of @command{cat} without the builtins supplied by this module.
6709 @item gnu
6710 Provides all of the GNU extensions, as defined by
6711 GNU M4 through the 1.4.x release series.  It also provides a
6712 couple of feature test macros:
6714 @deffn {Macro (gnu)} __gnu__
6715 Expands to the empty string, as an indication that the @samp{gnu}
6716 module is loaded.
6717 @end deffn
6719 @deffn {Macro (gnu)} __m4_version__
6720 Expands to an unquoted string containing the release version number of
6721 the running GNU @code{m4} executable.
6722 @end deffn
6724 This module is always loaded, unless the @option{-G} command line
6725 option is supplied at startup (@pxref{Limits control, , Invoking m4}).
6727 @item traditional
6728 This module provides compatibility with System V @code{m4}, for anything
6729 not specified by POSIX, and is loaded instead of the
6730 @samp{gnu} module if the @option{-G} command line option is specified.
6732 @deffn {Macro (traditional)} __traditional__
6733 Expands to the empty string, as an indication that the
6734 @samp{traditional} module is loaded.
6735 @end deffn
6737 @item load
6738 This module supplies the builtins for advanced use of modules from within a
6739 GNU @code{m4} program.  @xref{Modules}, for more details.  The
6740 module also defines the following macro:
6742 @deffn {Macro (load)} __load__
6743 Expands to the empty string, as an indication that the @samp{load}
6744 module is loaded.
6745 @end deffn
6747 @item mpeval
6748 This module provides the implementation for the experimental
6749 @code{mpeval} feature.  If the host machine does not have the
6750 GNU gmp library, the builtin will generate an error if called.
6751 @xref{Mpeval}, for more details.  The module also defines the following
6752 macro:
6754 @deffn {Macro (mpeval)} __mpeval__
6755 Expands to the empty string, as an indication that the @samp{mpeval}
6756 module is loaded.
6757 @end deffn
6758 @end table
6760 Here is an example of using the feature test macros.
6762 @example
6763 $ @kbd{m4}
6764 __gnu__-__traditional__
6765 @result{}-__traditional__
6766 ifdef(`__gnu__', `Extensions are active', `Minimal features')
6767 @result{}Extensions are active
6768 __gnu__(`ignored')
6769 @error{}m4:stdin:3: warning: __gnu__: extra arguments ignored: 1 > 0
6770 @result{}
6771 @end example
6773 @comment options: -G
6774 @example
6775 $ @kbd{m4 --traditional}
6776 __gnu__-__traditional__
6777 @result{}__gnu__-
6778 ifdef(`__gnu__', `Extensions are active', `Minimal features')
6779 @result{}Minimal features
6780 @end example
6782 Since the version string is unquoted and can potentially contain macro
6783 names (for example, a beta release could be numbered @samp{1.9b}), or be
6784 impacted by the use of @code{changesyntax}), the
6785 @code{__m4_version__} macro should generally be used via @code{defn}
6786 rather than directly invoked (@pxref{Defn}).  In general, feature tests
6787 are more reliable than version number checks, so exercise caution when
6788 using this macro.
6790 @comment This test is excluded from the testsuite since it depends on a
6791 @comment texinfo macro; but builtins.at covers the same thing.
6792 @comment ignore
6793 @example
6794 defn(`__m4_version__')
6795 @result{}@value{VERSION}
6796 @end example
6798 @node Text handling
6799 @chapter Macros for text handling
6801 There are a number of builtins in @code{m4} for manipulating text in
6802 various ways, extracting substrings, searching, substituting, and so on.
6804 @menu
6805 * Len::                         Calculating length of strings
6806 * Index macro::                 Searching for substrings
6807 * Regexp::                      Searching for regular expressions
6808 * Substr::                      Extracting substrings
6809 * Translit::                    Translating characters
6810 * Patsubst::                    Substituting text by regular expression
6811 * Format::                      Formatting strings (printf-like)
6812 @end menu
6814 @node Len
6815 @section Calculating length of strings
6817 @cindex length of strings
6818 @cindex strings, length of
6819 The length of a string can be calculated by @code{len}:
6821 @deffn {Builtin (m4)} len (@var{string})
6822 Expands to the length of @var{string}, as a decimal number.
6824 The macro @code{len} is recognized only with parameters.
6825 @end deffn
6827 @example
6828 len()
6829 @result{}0
6830 len(`abcdef')
6831 @result{}6
6832 @end example
6834 @node Index macro
6835 @section Searching for substrings
6837 @cindex substrings, locating
6838 Searching for substrings is done with @code{index}:
6840 @deffn {Builtin (m4)} index (@var{string}, @var{substring}, @ovar{offset})
6841 Expands to the index of the first occurrence of @var{substring} in
6842 @var{string}.  The first character in @var{string} has index 0.  If
6843 @var{substring} does not occur in @var{string}, @code{index} expands to
6844 @samp{-1}.  If @var{offset} is provided, it determines the index at
6845 which the search starts; a negative @var{offset} specifies the offset
6846 relative to the end of @var{string}.
6848 The macro @code{index} is recognized only with parameters.
6849 @end deffn
6851 @example
6852 index(`gnus, gnats, and armadillos', `nat')
6853 @result{}7
6854 index(`gnus, gnats, and armadillos', `dag')
6855 @result{}-1
6856 @end example
6858 Omitting @var{substring} evokes a warning, but still produces output;
6859 contrast this with an empty @var{substring}.
6861 @example
6862 index(`abc')
6863 @error{}m4:stdin:1: warning: index: too few arguments: 1 < 2
6864 @result{}0
6865 index(`abc', `')
6866 @result{}0
6867 index(`abc', `b')
6868 @result{}1
6869 @end example
6871 @cindex GNU extensions
6872 As an extension, an @var{offset} can be provided to limit the search to
6873 the tail of the @var{string}.  A negative offset is interpreted relative
6874 to the end of @var{string}, and it is not an error if @var{offset}
6875 exceeds the bounds of @var{string}.
6877 @example
6878 index(`aba', `a', `1')
6879 @result{}2
6880 index(`ababa', `ba', `-3')
6881 @result{}3
6882 index(`abc', `ab', `4')
6883 @result{}-1
6884 index(`abc', `bc', `-4')
6885 @result{}1
6886 @end example
6888 @node Regexp
6889 @section Searching for regular expressions
6891 @cindex regular expressions
6892 @cindex expressions, regular
6893 @cindex GNU extensions
6894 Searching for regular expressions is done with the builtin
6895 @code{regexp}:
6897 @deffn {Builtin (gnu)} regexp (@var{string}, @var{regexp}, @var{resyntax})
6898 @deffnx {Builtin (gnu)} regexp (@var{string}, @var{regexp}, @
6899   @ovar{replacement}, @ovar{resyntax})
6900 Searches for @var{regexp} in @var{string}.
6902 If @var{resyntax} is given, the particular flavor of regular expression
6903 understood with respect to @var{regexp} can be changed from the current
6904 default.  @xref{Changeresyntax}, for details of the values that can be
6905 given for this argument.  If exactly three arguments given, then the
6906 third argument is treated as @var{resyntax} only if it matches a known
6907 syntax name, otherwise it is treated as @var{replacement}.
6909 If @var{replacement} is omitted, @code{regexp} expands to the index of
6910 the first match of @var{regexp} in @var{string}.  If @var{regexp} does
6911 not match anywhere in @var{string}, it expands to -1.
6913 If @var{replacement} is supplied, and there was a match, @code{regexp}
6914 changes the expansion to this argument, with @samp{\@var{n}} substituted
6915 by the text matched by the @var{n}th parenthesized sub-expression of
6916 @var{regexp}, up to nine sub-expressions.  The escape @samp{\&} is
6917 replaced by the text of the entire regular expression matched.  For
6918 all other characters, @samp{\} treats the next character literally.  A
6919 warning is issued if there were fewer sub-expressions than the
6920 @samp{\@var{n}} requested, or if there is a trailing @samp{\}.  If there
6921 was no match, @code{regexp} expands to the empty string.
6923 The macro @code{regexp} is recognized only with parameters.
6924 @end deffn
6926 @example
6927 regexp(`GNUs not Unix', `\<[a-z]\w+')
6928 @result{}5
6929 regexp(`GNUs not Unix', `\<Q\w*')
6930 @result{}-1
6931 regexp(`GNUs not Unix', `\w\(\w+\)$', `*** \& *** \1 ***')
6932 @result{}*** Unix *** nix ***
6933 regexp(`GNUs not Unix', `\<Q\w*', `*** \& *** \1 ***')
6934 @result{}
6935 @end example
6937 Here are some more examples on the handling of backslash:
6939 @example
6940 regexp(`abc', `\(b\)', `\\\10\a')
6941 @result{}\b0a
6942 regexp(`abc', `b', `\1\')
6943 @error{}m4:stdin:2: warning: regexp: sub-expression 1 not present
6944 @error{}m4:stdin:2: warning: regexp: trailing \ ignored in replacement
6945 @result{}
6946 regexp(`abc', `\(\(d\)?\)\(c\)', `\1\2\3\4\5\6')
6947 @error{}m4:stdin:3: warning: regexp: sub-expression 4 not present
6948 @error{}m4:stdin:3: warning: regexp: sub-expression 5 not present
6949 @error{}m4:stdin:3: warning: regexp: sub-expression 6 not present
6950 @result{}c
6951 @end example
6953 Omitting @var{regexp} evokes a warning, but still produces output;
6954 contrast this with an empty @var{regexp} argument.
6956 @example
6957 regexp(`abc')
6958 @error{}m4:stdin:1: warning: regexp: too few arguments: 1 < 2
6959 @result{}0
6960 regexp(`abc', `')
6961 @result{}0
6962 regexp(`abc', `', `\\def')
6963 @result{}\def
6964 @end example
6966 If @var{resyntax} is given, @var{regexp} must be given according to
6967 the syntax chosen, though the default regular expression syntax
6968 remains unchanged for other invocations:
6970 @example
6971 regexp(`GNUs not Unix', `\w(\w+)$', `*** \& *** \1 ***',
6972        `POSIX_EXTENDED')
6973 @result{}*** Unix *** nix ***
6974 regexp(`GNUs not Unix', `\w(\w+)$', `*** \& *** \1 ***')
6975 @result{}
6976 @end example
6978 Occasionally, you might want to pass an @var{resyntax} argument without
6979 wishing to give @var{replacement}.  If there are exactly three
6980 arguments, and the last argument is a valid @var{resyntax}, it is used
6981 as such, rather than as a replacement.
6983 @example
6984 regexp(`GNUs not Unix', `\w(\w+)$', `POSIX_EXTENDED')
6985 @result{}9
6986 regexp(`GNUs not Unix', `\w(\w+)$', `POSIX_EXTENDED', `POSIX_EXTENDED')
6987 @result{}POSIX_EXTENDED
6988 regexp(`GNUs not Unix', `\w(\w+)$', `POSIX_EXTENDED', `')
6989 @result{}
6990 regexp(`GNUs not Unix', `\w\(\w+\)$', `POSIX_EXTENDED', `')
6991 @result{}POSIX_EXTENDED
6992 @end example
6994 @node Substr
6995 @section Extracting substrings
6997 @cindex extracting substrings
6998 @cindex substrings, extracting
6999 Substrings are extracted with @code{substr}:
7001 @deffn {Builtin (m4)} substr (@var{string}, @var{from}, @ovar{length}, @
7002   @ovar{replace})
7003 Performs a substring operation on @var{string}.  If @var{from} is
7004 positive, it represents the 0-based index where the substring begins.
7005 If @var{length} is omitted, the substring ends at the end of
7006 @var{string}; if it is positive, @var{length} is added to the starting
7007 index to determine the ending index.
7009 @cindex GNU extensions
7010 As a GNU extension, if @var{from} is negative, it is added to
7011 the length of @var{string} to determine the starting index; if it is
7012 empty, the start of the string is used.  Likewise, if @var{length} is
7013 negative, it is added to the length of @var{string} to determine the
7014 ending index, and an emtpy @var{length} behaves like an omitted
7015 @var{length}.  It is not an error if either of the resulting indices lie
7016 outside the string, but the selected substring only contains the bytes
7017 of @var{string} that overlap the selected indices.  If the end point
7018 lies before the beginning point, the substring chosen is the empty
7019 string located at the starting index.
7021 If @var{replace} is omitted, then the expansion is only the selected
7022 substring, which may be empty.  As a GNU extension,if
7023 @var{replace} is provided, then the expansion is the original
7024 @var{string} with the selected substring replaced by @var{replace}.  The
7025 expansion is empty and a warning issued if @var{from} or @var{length}
7026 cannot be parsed, or if @var{replace} is provided but the selected
7027 indices do not overlap with @var{string}.
7029 The macro @code{substr} is recognized only with parameters.
7030 @end deffn
7032 @example
7033 substr(`gnus, gnats, and armadillos', `6')
7034 @result{}gnats, and armadillos
7035 substr(`gnus, gnats, and armadillos', `6', `5')
7036 @result{}gnats
7037 @end example
7039 Omitting @var{from} evokes a warning, but still produces output.  On the
7040 other hand, selecting a @var{from} or @var{length} that lies beyond
7041 @var{string} is not a problem.
7043 @example
7044 substr(`abc')
7045 @error{}m4:stdin:1: warning: substr: too few arguments: 1 < 2
7046 @result{}abc
7047 substr(`abc', `')
7048 @result{}abc
7049 substr(`abc', `4')
7050 @result{}
7051 substr(`abc', `1', `4')
7052 @result{}bc
7053 @end example
7055 Using negative values for @var{from} or @var{length} are GNU
7056 extensions, useful for accessing a fixed size tail of an
7057 arbitrary-length string.  Prior to M4 1.6, using these values would
7058 silently result in the empty string.  Some other implementations crash
7059 on negative values, and many treat an explicitly empty @var{length} as
7060 0, which is different from the omitted @var{length} implying the rest of
7061 the original @var{string}.
7063 @example
7064 substr(`abcde', `2', `')
7065 @result{}cde
7066 substr(`abcde', `-3')
7067 @result{}cde
7068 substr(`abcde', `', `-3')
7069 @result{}ab
7070 substr(`abcde', `-6')
7071 @result{}abcde
7072 substr(`abcde', `-6', `5')
7073 @result{}abcd
7074 substr(`abcde', `-7', `1')
7075 @result{}
7076 substr(`abcde', `1', `-2')
7077 @result{}bc
7078 substr(`abcde', `-4', `-1')
7079 @result{}bcd
7080 substr(`abcde', `4', `-3')
7081 @result{}
7082 substr(`abcdefghij', `-09', `08')
7083 @result{}bcdefghi
7084 @end example
7086 Another useful GNU extension, also added in M4 1.6, is the
7087 ability to replace a substring within the original @var{string}.  An
7088 empty length substring at the beginning or end of @var{string} is valid,
7089 but selecting a substring that does not overlap @var{string} causes a
7090 warning.
7092 @example
7093 substr(`abcde', `1', `3', `t')
7094 @result{}ate
7095 substr(`abcde', `5', `', `f')
7096 @result{}abcdef
7097 substr(`abcde', `-3', `-4', `f')
7098 @result{}abfcde
7099 substr(`abcde', `-6', `1', `f')
7100 @result{}fabcde
7101 substr(`abcde', `-7', `1', `f')
7102 @error{}m4:stdin:5: warning: substr: substring out of range
7103 @result{}
7104 substr(`abcde', `6', `', `f')
7105 @error{}m4:stdin:6: warning: substr: substring out of range
7106 @result{}
7107 @end example
7109 If backwards compabitility to M4 1.4.x behavior is necessary, the
7110 following macro is sufficient to do the job (mimicking warnings about
7111 empty @var{from} or @var{length} or an ignored fourth argument is left
7112 as an exercise to the reader).
7114 @example
7115 define(`substr', `ifelse(`$#', `0', ``$0'',
7116   eval(`2 < $#')`$3', `1', `',
7117   index(`$2$3', `-'), `-1', `builtin(`$0', `$1', `$2', `$3')')')
7118 @result{}
7119 substr(`abcde', `3')
7120 @result{}de
7121 substr(`abcde', `3', `')
7122 @result{}
7123 substr(`abcde', `-1')
7124 @result{}
7125 substr(`abcde', `1', `-1')
7126 @result{}
7127 substr(`abcde', `2', `1', `C')
7128 @result{}c
7129 @end example
7131 On the other hand, it is possible to portably emulate the GNU
7132 extension of negative @var{from} and @var{length} arguments across all
7133 @code{m4} implementations, albeit with a lot more overhead.  This
7134 example uses @code{incr} and @code{decr} to normalize @samp{-08} to
7135 something that a later @code{eval} will treat as a decimal value, rather
7136 than looking like an invalid octal number, while avoiding using these
7137 macros on an empty string.  The helper macro @code{_substr_normalize} is
7138 recursive, since it is easier to fix @var{length} after @var{from} has
7139 been normalized, with the final iteration supplying two non-negative
7140 arguments to the original builtin, now named @code{_substr}.
7142 @comment options: -daq -t_substr
7143 @example
7144 $ @kbd{m4 -daq -t _substr}
7145 define(`_substr', defn(`substr'))dnl
7146 define(`substr', `ifelse(`$#', `0', ``$0'',
7147   `_$0(`$1', _$0_normalize(len(`$1'),
7148     ifelse(`$2', `', `0', `incr(decr(`$2'))'),
7149     ifelse(`$3', `', `', `incr(decr(`$3'))')))')')dnl
7150 define(`_substr_normalize', `ifelse(
7151   eval(`$2 < 0 && $1 + $2 >= 0'), `1',
7152     `$0(`$1', eval(`$1 + $2'), `$3')',
7153   eval(`$2 < 0')`$3', `1', ``0', `$1'',
7154   eval(`$2 < 0 && $3 - 0 >= 0 && $1 + $2 + $3 - 0 >= 0'), `1',
7155     `$0(`$1', `0', eval(`$1 + $2 + $3 - 0'))',
7156   eval(`$2 < 0 && $3 - 0 >= 0'), `1', ``0', `0'',
7157   eval(`$2 < 0'), `1', `$0(`$1', `0', `$3')',
7158   `$3', `', ``$2', `$1'',
7159   eval(`$3 - 0 < 0 && $1 - $2 + $3 - 0 >= 0'), `1',
7160     ``$2', eval(`$1 - $2 + $3')',
7161   eval(`$3 - 0 < 0'), `1', ``$2', `0'',
7162   ``$2', `$3'')')dnl
7163 substr(`abcde', `2', `')
7164 @error{}m4trace: -1- _substr(`abcde', `2', `5')
7165 @result{}cde
7166 substr(`abcde', `-3')
7167 @error{}m4trace: -1- _substr(`abcde', `2', `5')
7168 @result{}cde
7169 substr(`abcde', `', `-3')
7170 @error{}m4trace: -1- _substr(`abcde', `0', `2')
7171 @result{}ab
7172 substr(`abcde', `-6')
7173 @error{}m4trace: -1- _substr(`abcde', `0', `5')
7174 @result{}abcde
7175 substr(`abcde', `-6', `5')
7176 @error{}m4trace: -1- _substr(`abcde', `0', `4')
7177 @result{}abcd
7178 substr(`abcde', `-7', `1')
7179 @error{}m4trace: -1- _substr(`abcde', `0', `0')
7180 @result{}
7181 substr(`abcde', `1', `-2')
7182 @error{}m4trace: -1- _substr(`abcde', `1', `2')
7183 @result{}bc
7184 substr(`abcde', `-4', `-1')
7185 @error{}m4trace: -1- _substr(`abcde', `1', `3')
7186 @result{}bcd
7187 substr(`abcde', `4', `-3')
7188 @error{}m4trace: -1- _substr(`abcde', `4', `0')
7189 @result{}
7190 substr(`abcdefghij', `-09', `08')
7191 @error{}m4trace: -1- _substr(`abcdefghij', `1', `8')
7192 @result{}bcdefghi
7193 @end example
7195 @node Translit
7196 @section Translating characters
7198 @cindex translating characters
7199 @cindex characters, translating
7200 Character translation is done with @code{translit}:
7202 @deffn {Builtin (m4)} translit (@var{string}, @var{chars}, @ovar{replacement})
7203 Expands to @var{string}, with each character that occurs in
7204 @var{chars} translated into the character from @var{replacement} with
7205 the same index.
7207 If @var{replacement} is shorter than @var{chars}, the excess characters
7208 of @var{chars} are deleted from the expansion; if @var{chars} is
7209 shorter, the excess characters in @var{replacement} are silently
7210 ignored.  If @var{replacement} is omitted, all characters in
7211 @var{string} that are present in @var{chars} are deleted from the
7212 expansion.  If a character appears more than once in @var{chars}, only
7213 the first instance is used in making the translation.  Only a single
7214 translation pass is made, even if characters in @var{replacement} also
7215 appear in @var{chars}.
7217 As a GNU extension, both @var{chars} and @var{replacement} can
7218 contain character-ranges, e.g., @samp{a-z} (meaning all lowercase
7219 letters) or @samp{0-9} (meaning all digits).  To include a dash @samp{-}
7220 in @var{chars} or @var{replacement}, place it first or last in the
7221 entire string, or as the last character of a range.  Back-to-back ranges
7222 can share a common endpoint.  It is not an error for the last character
7223 in the range to be `larger' than the first.  In that case, the range
7224 runs backwards, i.e., @samp{9-0} means the string @samp{9876543210}.
7225 The expansion of a range is dependent on the underlying encoding of
7226 characters, so using ranges is not always portable between machines.
7228 The macro @code{translit} is recognized only with parameters.
7229 @end deffn
7231 @example
7232 translit(`GNUs not Unix', `A-Z')
7233 @result{}s not nix
7234 translit(`GNUs not Unix', `a-z', `A-Z')
7235 @result{}GNUS NOT UNIX
7236 translit(`GNUs not Unix', `A-Z', `z-a')
7237 @result{}tmfs not fnix
7238 translit(`+,-12345', `+--1-5', `<;>a-c-a')
7239 @result{}<;>abcba
7240 translit(`abcdef', `aabdef', `bcged')
7241 @result{}bgced
7242 @end example
7244 In the @sc{ascii} encoding, the first example deletes all uppercase
7245 letters, the second converts lowercase to uppercase, and the third
7246 `mirrors' all uppercase letters, while converting them to lowercase.
7247 The two first cases are by far the most common, even though they are not
7248 portable to @sc{ebcdic} or other encodings.  The fourth example shows a
7249 range ending in @samp{-}, as well as back-to-back ranges.  The final
7250 example shows that @samp{a} is mapped to @samp{b}, not @samp{c}; the
7251 resulting @samp{b} is not further remapped to @samp{g}; the @samp{d} and
7252 @samp{e} are swapped, and the @samp{f} is discarded.
7254 Omitting @var{chars} evokes a warning, but still produces output.
7256 @example
7257 translit(`abc')
7258 @error{}m4:stdin:1: warning: translit: too few arguments: 1 < 2
7259 @result{}abc
7260 @end example
7262 @node Patsubst
7263 @section Substituting text by regular expression
7265 @cindex regular expressions
7266 @cindex expressions, regular
7267 @cindex pattern substitution
7268 @cindex substitution by regular expression
7269 @cindex GNU extensions
7270 Global substitution in a string is done by @code{patsubst}:
7272 @deffn {Builtin (gnu)} patsubst (@var{string}, @var{regexp}, @
7273   @ovar{replacement}, @ovar{resyntax})
7274 Searches @var{string} for matches of @var{regexp}, and substitutes
7275 @var{replacement} for each match.
7277 If @var{resyntax} is given, the particular flavor of regular expression
7278 understood with respect to @var{regexp} can be changed from the current
7279 default.  @xref{Changeresyntax}, for details of the values that can be
7280 given for this argument.  Unlike @var{regexp}, if exactly three
7281 arguments given, the third argument is always treated as
7282 @var{replacement}, even if it matches a known syntax name.
7284 The parts of @var{string} that are not covered by any match of
7285 @var{regexp} are copied to the expansion.  Whenever a match is found, the
7286 search proceeds from the end of the match, so a character from
7287 @var{string} will never be substituted twice.  If @var{regexp} matches a
7288 string of zero length, the start position for the search is incremented,
7289 to avoid infinite loops.
7291 When a replacement is to be made, @var{replacement} is inserted into
7292 the expansion, with @samp{\@var{n}} substituted by the text matched by
7293 the @var{n}th parenthesized sub-expression of @var{patsubst}, for up to
7294 nine sub-expressions.  The escape @samp{\&} is replaced by the text of
7295 the entire regular expression matched.  For all other characters,
7296 @samp{\} treats the next character literally.  A warning is issued if
7297 there were fewer sub-expressions than the @samp{\@var{n}} requested, or
7298 if there is a trailing @samp{\}.
7300 The @var{replacement} argument can be omitted, in which case the text
7301 matched by @var{regexp} is deleted.
7303 The macro @code{patsubst} is recognized only with parameters.
7304 @end deffn
7306 When used with two arguments, @code{regexp} returns the position of the
7307 match, but @code{patsubst} deletes the match:
7309 @example
7310 patsubst(`GNUs not Unix', `^', `OBS: ')
7311 @result{}OBS: GNUs not Unix
7312 patsubst(`GNUs not Unix', `\<', `OBS: ')
7313 @result{}OBS: GNUs OBS: not OBS: Unix
7314 patsubst(`GNUs not Unix', `\w*', `(\&)')
7315 @result{}(GNUs)() (not)() (Unix)()
7316 patsubst(`GNUs not Unix', `\w+', `(\&)')
7317 @result{}(GNUs) (not) (Unix)
7318 patsubst(`GNUs not Unix', `[A-Z][a-z]+')
7319 @result{}GN not@w{ }
7320 patsubst(`GNUs not Unix', `not', `NOT\')
7321 @error{}m4:stdin:6: warning: patsubst: trailing \ ignored in replacement
7322 @result{}GNUs NOT Unix
7323 @end example
7325 Here is a slightly more realistic example, which capitalizes individual
7326 words or whole sentences, by substituting calls of the macros
7327 @code{upcase} and @code{downcase} into the strings.
7329 @deffn Composite upcase (@var{text})
7330 @deffnx Composite downcase (@var{text})
7331 @deffnx Composite capitalize (@var{text})
7332 Expand to @var{text}, but with capitalization changed: @code{upcase}
7333 changes all letters to upper case, @code{downcase} changes all letters
7334 to lower case, and @code{capitalize} changes the first character of each
7335 word to upper case and the remaining characters to lower case.
7336 @end deffn
7338 First, an example of their usage, using implementations distributed in
7339 @file{m4-@value{VERSION}/@/examples/@/capitalize.m4}.
7341 @comment examples
7342 @example
7343 $ @kbd{m4 -I examples}
7344 include(`capitalize.m4')
7345 @result{}
7346 upcase(`GNUs not Unix')
7347 @result{}GNUS NOT UNIX
7348 downcase(`GNUs not Unix')
7349 @result{}gnus not unix
7350 capitalize(`GNUs not Unix')
7351 @result{}Gnus Not Unix
7352 @end example
7354 Now for the implementation.  There is a helper macro @code{_capitalize}
7355 which puts only its first word in mixed case.  Then @code{capitalize}
7356 merely parses out the words, and replaces them with an invocation of
7357 @code{_capitalize}.  (As presented here, the @code{capitalize} macro has
7358 some subtle flaws.  You should try to see if you can find and correct
7359 them; or @pxref{Improved capitalize, , Answers}).
7361 @comment examples
7362 @example
7363 $ @kbd{m4 -I examples}
7364 undivert(`capitalize.m4')dnl
7365 @result{}divert(`-1')
7366 @result{}# upcase(text)
7367 @result{}# downcase(text)
7368 @result{}# capitalize(text)
7369 @result{}#   change case of text, simple version
7370 @result{}define(`upcase', `translit(`$*', `a-z', `A-Z')')
7371 @result{}define(`downcase', `translit(`$*', `A-Z', `a-z')')
7372 @result{}define(`_capitalize',
7373 @result{}       `regexp(`$1', `^\(\w\)\(\w*\)',
7374 @result{}               `upcase(`\1')`'downcase(`\2')')')
7375 @result{}define(`capitalize', `patsubst(`$1', `\w+', `_$0(`\&')')')
7376 @result{}divert`'dnl
7377 @end example
7379 If @var{resyntax} is given, @var{regexp} must be given according to
7380 the syntax chosen, though the default regular expression syntax
7381 remains unchanged for other invocations:
7383 @example
7384 define(`epatsubst',
7385        `builtin(`patsubst', `$1', `$2', `$3', `POSIX_EXTENDED')')dnl
7386 epatsubst(`bar foo baz Foo', `(\w*) (foo|Foo)', `_\1_')
7387 @result{}_bar_ _baz_
7388 patsubst(`bar foo baz Foo', `\(\w*\) \(foo\|Foo\)', `_\1_')
7389 @result{}_bar_ _baz_
7390 @end example
7392 While @code{regexp} replaces the whole input with the replacement as
7393 soon as there is a match, @code{patsubst} replaces each
7394 @emph{occurrence} of a match and preserves non-matching pieces:
7396 @example
7397 define(`patreg',
7398 `patsubst($@@)
7399 regexp($@@)')dnl
7400 patreg(`bar foo baz Foo', `foo\|Foo', `FOO')
7401 @result{}bar FOO baz FOO
7402 @result{}FOO
7403 patreg(`aba abb 121', `\(.\)\(.\)\1', `\2\1\2')
7404 @result{}bab abb 212
7405 @result{}bab
7406 @end example
7408 Omitting @var{regexp} evokes a warning, but still produces output;
7409 contrast this with an empty @var{regexp} argument.
7411 @example
7412 patsubst(`abc')
7413 @error{}m4:stdin:1: warning: patsubst: too few arguments: 1 < 2
7414 @result{}abc
7415 patsubst(`abc', `')
7416 @result{}abc
7417 patsubst(`abc', `', `\\-')
7418 @result{}\-a\-b\-c\-
7419 @end example
7421 @node Format
7422 @section Formatting strings (printf-like)
7424 @cindex formatted output
7425 @cindex output, formatted
7426 @cindex GNU extensions
7427 Formatted output can be made with @code{format}:
7429 @deffn {Builtin (gnu)} format (@var{format-string}, @dots{})
7430 Works much like the C function @code{printf}.  The first argument
7431 @var{format-string} can contain @samp{%} specifications which are
7432 satisfied by additional arguments, and the expansion of @code{format} is
7433 the formatted string.
7435 The macro @code{format} is recognized only with parameters.
7436 @end deffn
7438 Its use is best described by a few examples:
7440 @comment This test is a bit fragile, if someone tries to port to a
7441 @comment platform without infinity.
7442 @example
7443 define(`foo', `The brown fox jumped over the lazy dog')
7444 @result{}
7445 format(`The string "%s" uses %d characters', foo, len(foo))
7446 @result{}The string "The brown fox jumped over the lazy dog" uses 38 characters
7447 format(`%*.*d', `-1', `-1', `1')
7448 @result{}1
7449 format(`%.0f', `56789.9876')
7450 @result{}56790
7451 len(format(`%-*X', `5000', `1'))
7452 @result{}5000
7453 ifelse(format(`%010F', `infinity'), `       INF', `success',
7454        format(`%010F', `infinity'), `  INFINITY', `success',
7455        format(`%010F', `infinity'))
7456 @result{}success
7457 ifelse(format(`%.1A', `1.999'), `0X1.0P+1', `success',
7458        format(`%.1A', `1.999'), `0X2.0P+0', `success',
7459        format(`%.1A', `1.999'))
7460 @result{}success
7461 format(`%g', `0xa.P+1')
7462 @result{}20
7463 @end example
7465 Using the @code{forloop} macro defined earlier (@pxref{Forloop}), this
7466 example shows how @code{format} can be used to produce tabular output.
7468 @comment examples
7469 @example
7470 $ @kbd{m4 -I examples}
7471 include(`forloop.m4')
7472 @result{}
7473 forloop(`i', `1', `10', `format(`%6d squared is %10d
7474 ', i, eval(i**2))')
7475 @result{}     1 squared is          1
7476 @result{}     2 squared is          4
7477 @result{}     3 squared is          9
7478 @result{}     4 squared is         16
7479 @result{}     5 squared is         25
7480 @result{}     6 squared is         36
7481 @result{}     7 squared is         49
7482 @result{}     8 squared is         64
7483 @result{}     9 squared is         81
7484 @result{}    10 squared is        100
7485 @result{}
7486 @end example
7488 The builtin @code{format} is modeled after the ANSI C @samp{printf}
7489 function, and supports these @samp{%} specifiers: @samp{c}, @samp{s},
7490 @samp{d}, @samp{o}, @samp{x}, @samp{X}, @samp{u}, @samp{a}, @samp{A},
7491 @samp{e}, @samp{E}, @samp{f}, @samp{F}, @samp{g}, @samp{G}, and
7492 @samp{%}; it supports field widths and precisions, and the flags
7493 @samp{+}, @samp{-}, @samp{ }, @samp{0}, @samp{#}, and @samp{'}.  For
7494 integer specifiers, the width modifiers @samp{hh}, @samp{h}, and
7495 @samp{l} are recognized, and for floating point specifiers, the width
7496 modifier @samp{l} is recognized.  Items not yet supported include
7497 positional arguments, the @samp{n}, @samp{p}, @samp{S}, and @samp{C}
7498 specifiers, the @samp{z}, @samp{t}, @samp{j}, @samp{L} and @samp{ll}
7499 modifiers, and any platform extensions available in the native
7500 @code{printf}.  For more details on the functioning of @code{printf},
7501 see the C Library Manual, or the POSIX specification (for
7502 example, @samp{%a} is supported even on platforms that haven't yet
7503 implemented C99 hexadecimal floating point output natively).
7505 @c FIXME - format still needs some improvements.
7506 Warnings are issued for unrecognized specifiers, an improper number of
7507 arguments, or difficulty parsing an argument according to the format
7508 string (such as overflow or extra characters).  It is anticipated that a
7509 future release of GNU @code{m4} will support more specifiers.
7510 Likewise, escape sequences are not yet recognized.
7512 @example
7513 format(`%p', `0')
7514 @error{}m4:stdin:1: warning: format: unrecognized specifier in '%p'
7515 @result{}
7516 format(`%*d', `')
7517 @error{}m4:stdin:2: warning: format: empty string treated as 0
7518 @error{}m4:stdin:2: warning: format: too few arguments: 2 < 3
7519 @result{}0
7520 format(`%.1f', `2a')
7521 @error{}m4:stdin:3: warning: format: non-numeric argument '2a'
7522 @result{}2.0
7523 @end example
7525 @ignore
7526 @comment Expose a crash with a bad format string fixed in 1.4.15.
7527 @comment Unfortunately, 8-bit bytes are hard to check for; but the
7528 @comment exit status is enough to sniff the crash in broken versions.
7530 @example
7531 format(`%'format(`%c', `128'))
7532 @result{}
7533 @error{}ignore
7534 @end example
7535 @end ignore
7537 @node Arithmetic
7538 @chapter Macros for doing arithmetic
7540 @cindex arithmetic
7541 @cindex integer arithmetic
7542 Integer arithmetic is included in @code{m4}, with a C-like syntax.  As
7543 convenient shorthands, there are builtins for simple increment and
7544 decrement operations.
7546 @menu
7547 * Incr::                        Decrement and increment operators
7548 * Eval::                        Evaluating integer expressions
7549 * Mpeval::                      Multiple precision arithmetic
7550 @end menu
7552 @node Incr
7553 @section Decrement and increment operators
7555 @cindex decrement operator
7556 @cindex increment operator
7557 Increment and decrement of integers are supported using the builtins
7558 @code{incr} and @code{decr}:
7560 @deffn {Builtin (m4)} incr (@var{number})
7561 @deffnx {Builtin (m4)} decr (@var{number})
7562 Expand to the numerical value of @var{number}, incremented
7563 or decremented, respectively, by one.  Except for the empty string, the
7564 expansion is empty if @var{number} could not be parsed.
7566 The macros @code{incr} and @code{decr} are recognized only with
7567 parameters.
7568 @end deffn
7570 @example
7571 incr(`4')
7572 @result{}5
7573 decr(`7')
7574 @result{}6
7575 incr()
7576 @error{}m4:stdin:3: warning: incr: empty string treated as 0
7577 @result{}1
7578 decr()
7579 @error{}m4:stdin:4: warning: decr: empty string treated as 0
7580 @result{}-1
7581 @end example
7583 The builtin macros @code{incr} and @code{decr} are recognized only when
7584 given arguments.
7586 @node Eval
7587 @section Evaluating integer expressions
7589 @cindex integer expression evaluation
7590 @cindex evaluation, of integer expressions
7591 @cindex expressions, evaluation of integer
7592 Integer expressions are evaluated with @code{eval}:
7594 @deffn {Builtin (m4)} eval (@var{expression}, @dvar{radix, 10}, @ovar{width})
7595 Expands to the value of @var{expression}.  The expansion is empty
7596 if a problem is encountered while parsing the arguments.  If specified,
7597 @var{radix} and @var{width} control the format of the output.
7599 Calculations are done with signed numbers, using at least 31-bit
7600 precision, but as a GNU extension, @code{m4} will use wider
7601 integers if available.  Precision is finite, based on the platform's
7602 notion of @code{intmax_t}, and overflow silently results in wraparound.
7603 A warning is issued if division by zero is attempted, or if
7604 @var{expression} could not be parsed.
7606 Expressions can contain the following operators, listed in order of
7607 decreasing precedence.
7609 @table @samp
7610 @item ()
7611 Parentheses
7612 @item +  -  ~  !
7613 Unary plus and minus, and bitwise and logical negation
7614 @item **
7615 Exponentiation
7616 @item *  /  %  \
7617 Multiplication, division, modulo, and ratio
7618 @item +  -
7619 Addition and subtraction
7620 @item <<  >>  >>>
7621 Shift left, shift right, unsigned shift right
7622 @item >  >=  <  <=
7623 Relational operators
7624 @item ==  !=
7625 Equality operators
7626 @item &
7627 Bitwise and
7628 @item ^
7629 Bitwise exclusive-or
7630 @item |
7631 Bitwise or
7632 @item &&
7633 Logical and
7634 @item ||
7635 Logical or
7636 @item ?:
7637 Conditional ternary
7638 @item ,
7639 Sequential evaluation
7640 @end table
7642 The macro @code{eval} is recognized only with parameters.
7643 @end deffn
7645 All binary operators, except exponentiation, are left associative.  C
7646 operators that perform variable assignment, such as @samp{+=} or
7647 @samp{--}, are not implemented, since @code{eval} only operates on
7648 constants, not variables.  Attempting to use them results in an error.
7649 @comment FIXME - since XCU ERN 137 is approved, we could provide an
7650 @comment extension that supported assignment operators.
7652 Note that some older @code{m4} implementations use @samp{^} as an
7653 alternate operator for the exponentiation, although POSIX
7654 requires the C behavior of bitwise exclusive-or.  The precedence of the
7655 negation operators, @samp{~} and @samp{!}, was traditionally lower than
7656 equality.  The unary operators could not be used reliably more than once
7657 on the same term without intervening parentheses.  The traditional
7658 precedence of the equality operators @samp{==} and @samp{!=} was
7659 identical instead of lower than the relational operators such as
7660 @samp{<}, even through GNU M4 1.4.8.  Starting with version
7661 1.4.9, GNU M4 correctly follows POSIX precedence
7662 rules.  M4 scripts designed to be portable between releases must be
7663 aware that parentheses may be required to enforce C precedence rules.
7664 Likewise, division by zero, even in the unused branch of a
7665 short-circuiting operator, is not always well-defined in other
7666 implementations.
7668 Following are some examples where the current version of M4 follows C
7669 precedence rules, but where older versions and some other
7670 implementations of @code{m4} require explicit parentheses to get the
7671 correct result:
7673 @example
7674 eval(`1 == 2 > 0')
7675 @result{}1
7676 eval(`(1 == 2) > 0')
7677 @result{}0
7678 eval(`! 0 * 2')
7679 @result{}2
7680 eval(`! (0 * 2)')
7681 @result{}1
7682 eval(`1 | 1 ^ 1')
7683 @result{}1
7684 eval(`(1 | 1) ^ 1')
7685 @result{}0
7686 eval(`+ + - ~ ! ~ 0')
7687 @result{}1
7688 eval(`++0')
7689 @error{}m4:stdin:8: warning: eval: invalid operator: '++0'
7690 @result{}
7691 eval(`1 = 1')
7692 @error{}m4:stdin:9: warning: eval: invalid operator: '1 = 1'
7693 @result{}
7694 eval(`0 |= 1')
7695 @error{}m4:stdin:10: warning: eval: invalid operator: '0 |= 1'
7696 @result{}
7697 eval(`2 || 1 / 0')
7698 @result{}1
7699 eval(`0 || 1 / 0')
7700 @error{}m4:stdin:12: warning: eval: divide by zero: '0 || 1 / 0'
7701 @result{}
7702 eval(`0 && 1 % 0')
7703 @result{}0
7704 eval(`2 && 1 % 0')
7705 @error{}m4:stdin:14: warning: eval: modulo by zero: '2 && 1 % 0'
7706 @result{}
7707 @end example
7709 @cindex GNU extensions
7710 As a GNU extension, @code{eval} supports several operators
7711 that do not appear in C@.  A right-associative exponentiation operator
7712 @samp{**} computes the value of the left argument raised to the right,
7713 modulo the numeric precision width.  If evaluated, the exponent must be
7714 non-negative, and at least one of the arguments must be non-zero, or a
7715 warning is issued.  An unsigned shift operator @samp{>>>} allows
7716 shifting a negative number as though it were an unsigned bit pattern,
7717 which shifts in 0 bits rather than twos-complement sign-extension.  A
7718 ratio operator @samp{\} behaves like normal division @samp{/} on
7719 integers, but is provided for symmetry with @code{mpeval}.
7720 Additionally, the C operators @samp{,} and @samp{?:} are supported.
7722 @example
7723 eval(`2 ** 3 ** 2')
7724 @result{}512
7725 eval(`(2 ** 3) ** 2')
7726 @result{}64
7727 eval(`0 ** 1')
7728 @result{}0
7729 eval(`2 ** 0')
7730 @result{}1
7731 eval(`0 ** 0')
7732 @result{}
7733 @error{}m4:stdin:5: warning: eval: divide by zero: '0 ** 0'
7734 eval(`4 ** -2')
7735 @error{}m4:stdin:6: warning: eval: negative exponent: '4 ** -2'
7736 @result{}
7737 eval(`2 || 4 ** -2')
7738 @result{}1
7739 eval(`(-1 >> 1) == -1')
7740 @result{}1
7741 eval(`(-1 >>> 1) > (1 << 30)')
7742 @result{}1
7743 eval(`6 \ 3')
7744 @result{}2
7745 eval(`1 ? 2 : 3')
7746 @result{}2
7747 eval(`0 ? 2 : 3')
7748 @result{}3
7749 eval(`1 ? 2 : 1/0')
7750 @result{}2
7751 eval(`0 ? 1/0 : 3')
7752 @result{}3
7753 eval(`4, 5')
7754 @result{}5
7755 @end example
7757 Within @var{expression}, (but not @var{radix} or @var{width}), numbers
7758 without a special prefix are decimal.  A simple @samp{0} prefix
7759 introduces an octal number.  @samp{0x} introduces a hexadecimal number.
7760 As GNU extensions, @samp{0b} introduces a binary number.
7761 @samp{0r} introduces a number expressed in any radix between 1 and 36:
7762 the prefix should be immediately followed by the decimal expression of
7763 the radix, a colon, then the digits making the number.  For radix 1,
7764 leading zeros are ignored, and all remaining digits must be @samp{1};
7765 for all other radices, the digits are @samp{0}, @samp{1}, @samp{2},
7766 @dots{}.  Beyond @samp{9}, the digits are @samp{a}, @samp{b} @dots{} up
7767 to @samp{z}.  Lower and upper case letters can be used interchangeably
7768 in numbers prefixes and as number digits.
7770 Parentheses may be used to group subexpressions whenever needed.  For the
7771 relational operators, a true relation returns @code{1}, and a false
7772 relation return @code{0}.
7774 Here are a few examples of use of @code{eval}.
7776 @example
7777 eval(`-3 * 5')
7778 @result{}-15
7779 eval(`-99 / 10')
7780 @result{}-9
7781 eval(`-99 % 10')
7782 @result{}-9
7783 eval(`99 % -10')
7784 @result{}9
7785 eval(index(`Hello world', `llo') >= 0)
7786 @result{}1
7787 eval(`0r1:0111 + 0b100 + 0r3:12')
7788 @result{}12
7789 define(`square', `eval(`($1) ** 2')')
7790 @result{}
7791 square(`9')
7792 @result{}81
7793 square(square(`5')` + 1')
7794 @result{}676
7795 define(`foo', `666')
7796 @result{}
7797 eval(`foo / 6')
7798 @error{}m4:stdin:11: warning: eval: bad expression: 'foo / 6'
7799 @result{}
7800 eval(foo / 6)
7801 @result{}111
7802 @end example
7804 As the last two lines show, @code{eval} does not handle macro
7805 names, even if they expand to a valid expression (or part of a valid
7806 expression).  Therefore all macros must be expanded before they are
7807 passed to @code{eval}.
7808 @comment update this if we add support for variables.
7810 Some calculations are not portable to other implementations, since they
7811 have undefined semantics in C, but GNU @code{m4} has
7812 well-defined behavior on overflow.  When shifting, an out-of-range shift
7813 amount is implicitly brought into the range of the precision using
7814 modulo arithmetic (for example, on 32-bit integers, this would be an
7815 implicit bit-wise and with 0x1f).  This example should work whether your
7816 platform uses 32-bit integers, 64-bit integers, or even some other
7817 atypical size.
7819 @example
7820 define(`max_int', eval(`-1 >>> 1'))
7821 @result{}
7822 define(`min_int', eval(max_int` + 1'))
7823 @result{}
7824 eval(min_int` < 0')
7825 @result{}1
7826 eval(max_int` > 0')
7827 @result{}1
7828 ifelse(eval(min_int` / -1'), min_int, `overflow occurred')
7829 @result{}overflow occurred
7830 eval(`0x80000000 % -1')
7831 @result{}0
7832 eval(`-4 >> 1')
7833 @result{}-2
7834 eval(`-4 >> 'eval(len(eval(max_int, `2'))` + 2'))
7835 @result{}-2
7836 @end example
7838 If @var{radix} is specified, it specifies the radix to be used in the
7839 expansion.  The default radix is 10; this is also the case if
7840 @var{radix} is the empty string.  A warning results if the radix is
7841 outside the range of 1 through 36, inclusive.  The result of @code{eval}
7842 is always taken to be signed.  No radix prefix is output, and for
7843 radices greater than 10, the digits are lower case (although some
7844 other implementations use upper case).  The output is unquoted, and
7845 subject to further macro expansion.  The @var{width}
7846 argument specifies the minimum output width, excluding any negative
7847 sign.  The result is zero-padded to extend the expansion to the
7848 requested width.  A warning results if the width is negative.  If
7849 @var{radix} or @var{width} is out of bounds, the expansion of
7850 @code{eval} is empty.
7852 @example
7853 eval(`666', `10')
7854 @result{}666
7855 eval(`666', `11')
7856 @result{}556
7857 eval(`666', `6')
7858 @result{}3030
7859 eval(`666', `6', `10')
7860 @result{}0000003030
7861 eval(`-666', `6', `10')
7862 @result{}-0000003030
7863 eval(`10', `', `0')
7864 @result{}10
7865 `0r1:'eval(`10', `1', `11')
7866 @result{}0r1:01111111111
7867 eval(`10', `16')
7868 @result{}a
7869 eval(`1', `37')
7870 @error{}m4:stdin:9: warning: eval: radix out of range: 37
7871 @result{}
7872 eval(`1', , `-1')
7873 @error{}m4:stdin:10: warning: eval: negative width: -1
7874 @result{}
7875 eval()
7876 @error{}m4:stdin:11: warning: eval: empty string treated as 0
7877 @result{}0
7878 eval(` ')
7879 @error{}m4:stdin:12: warning: eval: empty string treated as 0
7880 @result{}0
7881 define(`a', `hi')eval(` 10 ', `16')
7882 @result{}hi
7883 @end example
7885 @node Mpeval
7886 @section Multiple precision arithmetic
7888 When @code{m4} is compiled with a multiple precision arithmetic library
7889 (@pxref{Experiments}), a builtin @code{mpeval} is defined.
7891 @deffn {Builtin (mpeval)} mpeval (@var{expression}, @dvar{radix, 10}, @
7892   @ovar{width})
7893 Behaves similarly to @code{eval}, except the calculations are done with
7894 infinite precision, and rational numbers are supported.  Numbers may be
7895 of any length.
7897 The macro @code{mpeval} is recognized only with parameters.
7898 @end deffn
7900 For the most part, using @code{mpeval} is similar to using @code{eval}:
7902 @comment options: mpeval -
7903 @example
7904 $ @kbd{m4 mpeval -}
7905 mpeval(`(1 << 70) + 2 ** 68 * 3', `16')
7906 @result{}700000000000000000
7907 `0r24:'mpeval(`0r36:zYx', `24', `5')
7908 @result{}0r24:038m9
7909 @end example
7911 The ratio operator, @samp{\}, is provided with the same precedence as
7912 division, and rationally divides two numbers and canonicalizes the
7913 result, whereas the division operator @samp{/} always returns the
7914 integer quotient of the division.  To convert a rational value to
7915 integral, divide (@samp{/}) by 1.  Some operators, such as @samp{%},
7916 @samp{<<}, @samp{>>}, @samp{~}, @samp{&}, @samp{|} and @samp{^} operate
7917 only on integers and will truncate any rational remainder.  The unsigned
7918 shift operator, @samp{>>>}, behaves identically with regular right
7919 shifts, @samp{>>}, since with infinite precision, it is not possible to
7920 convert a negative number to a positive using shifts.  The
7921 exponentiation operator, @samp{**}, assumes that the exponent is
7922 integral, but allows negative exponents.  With the short-circuit logical
7923 operators, @samp{||} and @samp{&&}, a non-zero result preserves the
7924 value of the argument that ended evaluation, rather than collapsing to
7925 @samp{1}.  The operators @samp{?:} and @samp{,} are always available,
7926 even in POSIX mode, since @code{mpeval} does not have to
7927 conform to the POSIX rules for @code{eval}.
7929 @comment options: mpeval -
7930 @example
7931 $ @kbd{m4 mpeval -}
7932 mpeval(`2 / 4')
7933 @result{}0
7934 mpeval(`2 \ 4')
7935 @result{}1\2
7936 mpeval(`2 || 3')
7937 @result{}2
7938 mpeval(`1 && 3')
7939 @result{}3
7940 mpeval(`-1 >> 1')
7941 @result{}-1
7942 mpeval(`-1 >>> 1')
7943 @result{}-1
7944 @end example
7946 @node Shell commands
7947 @chapter Macros for running shell commands
7949 @cindex UNIX commands, running
7950 @cindex executing shell commands
7951 @cindex running shell commands
7952 @cindex shell commands, running
7953 @cindex commands, running shell
7954 There are a few builtin macros in @code{m4} that allow you to run shell
7955 commands from within @code{m4}.
7957 Note that the definition of a valid shell command is system dependent.
7958 On UNIX systems, this is the typical @command{/bin/sh}.  But on other
7959 systems, such as native Windows, the shell has a different syntax of
7960 commands that it understands.  Some examples in this chapter assume
7961 @command{/bin/sh}, and also demonstrate how to quit early with a known
7962 exit value if this is not the case.
7964 @menu
7965 * Platform macros::             Determining the platform
7966 * Syscmd::                      Executing simple commands
7967 * Esyscmd::                     Reading the output of commands
7968 * Sysval::                      Exit status
7969 * Mkstemp::                     Making temporary files
7970 * Mkdtemp::                     Making temporary directories
7971 @end menu
7973 @node Platform macros
7974 @section Determining the platform
7976 @cindex platform macros
7977 Sometimes it is desirable for an input file to know which platform
7978 @code{m4} is running on.  GNU @code{m4} provides several
7979 macros that are predefined to expand to the empty string; checking for
7980 their existence will confirm platform details.
7982 @deffn {Optional builtin (gnu)} __os2__
7983 @deffnx {Optional builtin (traditional)} os2
7984 @deffnx {Optional builtin (gnu)} __unix__
7985 @deffnx {Optional builtin (traditional)} unix
7986 @deffnx {Optional builtin (gnu)} __windows__
7987 @deffnx {Optional builtin (traditional)} windows
7988 Each of these macros is conditionally defined as needed to describe the
7989 environment of @code{m4}.  If defined, each macro expands to the empty
7990 string.
7991 @end deffn
7993 On UNIX systems, GNU @code{m4} will define @code{@w{__unix__}}
7994 in the @samp{gnu} module, and @code{unix} in the @samp{traditional}
7995 module.
7997 On native Windows systems, GNU @code{m4} will define
7998 @code{@w{__windows__}} in the @samp{gnu} module, and @code{windows} in
7999 the @samp{traditional} module.
8001 On OS/2 systems, GNU @code{m4} will define @code{@w{__os2__}}
8002 in the @samp{gnu} module, and @code{os2} in the @samp{traditional}
8003 module.
8005 If GNU M4 does not provide a platform macro for your system,
8006 please report that as a bug.
8008 @example
8009 define(`provided', `0')
8010 @result{}
8011 ifdef(`__unix__', `define(`provided', incr(provided))')
8012 @result{}
8013 ifdef(`__windows__', `define(`provided', incr(provided))')
8014 @result{}
8015 ifdef(`__os2__', `define(`provided', incr(provided))')
8016 @result{}
8017 provided
8018 @result{}1
8019 @end example
8021 @node Syscmd
8022 @section Executing simple commands
8024 Any shell command can be executed, using @code{syscmd}:
8026 @deffn {Builtin (m4)} syscmd (@var{shell-command})
8027 Executes @var{shell-command} as a shell command.
8029 The expansion of @code{syscmd} is void, @emph{not} the output from
8030 @var{shell-command}!  Output or error messages from @var{shell-command}
8031 are not read by @code{m4}.  @xref{Esyscmd}, if you need to process the
8032 command output.
8034 Prior to executing the command, @code{m4} flushes its buffers.
8035 The default standard input, output and error of @var{shell-command} are
8036 the same as those of @code{m4}.
8038 By default, the @var{shell-command} will be used as the argument to the
8039 @option{-c} option of the @command{/bin/sh} shell (or the version of
8040 @command{sh} specified by @samp{command -p getconf PATH}, if your system
8041 supports that).  If you prefer a different shell, the
8042 @command{configure} script can be given the option
8043 @option{--with-syscmd-shell=@var{location}} to set the location of an
8044 alternative shell at GNU @code{m4} installation; the
8045 alternative shell must still support @option{-c}.
8047 When the @option{--safer} option (@pxref{Operation modes, , Invoking
8048 m4}) is in effect, @code{syscmd} results in an error, since otherwise an
8049 input file could execute arbitrary code.
8051 The macro @code{syscmd} is recognized only with parameters.
8052 @end deffn
8054 @example
8055 define(`foo', `FOO')
8056 @result{}
8057 syscmd(`echo foo')
8058 @result{}foo
8059 @result{}
8060 @end example
8062 Note how the expansion of @code{syscmd} keeps the trailing newline of
8063 the command, as well as using the newline that appeared after the macro.
8065 The following is an example of @var{shell-command} using the same
8066 standard input as @code{m4}:
8068 @comment The testsuite does not know how to parse pipes from the
8069 @comment texinfo.  Fortunately, there are other tests in the testsuite
8070 @comment that test this same feature.
8071 @comment ignore
8072 @example
8073 $ @kbd{echo "m4wrap(\`syscmd(\`cat')')" | m4}
8074 @result{}
8075 @end example
8077 It tells @code{m4} to read all of its input before executing the wrapped
8078 text, then hands a valid (albeit emptied) pipe as standard input for the
8079 @code{cat} subcommand.  Therefore, you should be careful when using
8080 standard input (either by specifying no files, or by passing @samp{-} as
8081 a file name on the command line, @pxref{Command line files, , Invoking
8082 m4}), and also invoking subcommands via @code{syscmd} or @code{esyscmd}
8083 that consume data from standard input.  When standard input is a
8084 seekable file, the subprocess will pick up with the next character not
8085 yet processed by @code{m4}; when it is a pipe or other non-seekable
8086 file, there is no guarantee how much data will already be buffered by
8087 @code{m4} and thus unavailable to the child.
8089 Following is an example of how potentially unsafe actions can be
8090 suppressed.
8092 @comment options: --safer
8093 @comment status: 1
8094 @example
8095 $ @kbd{m4 --safer}
8096 syscmd(`echo hi')
8097 @error{}m4:stdin:1: syscmd: disabled by --safer
8098 @result{}
8099 @end example
8101 @node Esyscmd
8102 @section Reading the output of commands
8104 @cindex GNU extensions
8105 If you want @code{m4} to read the output of a shell command, use
8106 @code{esyscmd}:
8108 @deffn {Builtin (gnu)} esyscmd (@var{shell-command})
8109 Expands to the standard output of the shell command
8110 @var{shell-command}.
8112 Prior to executing the command, @code{m4} flushes its buffers.
8113 The default standard input and standard error of @var{shell-command} are
8114 the same as those of @code{m4}.  The error output of @var{shell-command}
8115 is not a part of the expansion: it will appear along with the error
8116 output of @code{m4}.
8118 By default, the @var{shell-command} will be used as the argument to the
8119 @option{-c} option of the @command{/bin/sh} shell (or the version of
8120 @command{sh} specified by @samp{command -p getconf PATH}, if your system
8121 supports that).  If you prefer a different shell, the
8122 @command{configure} script can be given the option
8123 @option{--with-syscmd-shell=@var{location}} to set the location of an
8124 alternative shell at GNU @code{m4} installation; the
8125 alternative shell must still support @option{-c}.
8127 When the @option{--safer} option (@pxref{Operation modes, , Invoking
8128 m4}) is in effect, @code{esyscmd} results in an error, since otherwise
8129 an input file could execute arbitrary code.
8131 The macro @code{esyscmd} is recognized only with parameters.
8132 @end deffn
8134 @example
8135 define(`foo', `FOO')
8136 @result{}
8137 esyscmd(`echo foo')
8138 @result{}FOO
8139 @result{}
8140 @end example
8142 Note how the expansion of @code{esyscmd} keeps the trailing newline of
8143 the command, as well as using the newline that appeared after the macro.
8145 Just as with @code{syscmd}, care must be exercised when sharing standard
8146 input between @code{m4} and the child process of @code{esyscmd}.
8147 Likewise, potentially unsafe actions can be suppressed.
8149 @comment options: --safer
8150 @comment status: 1
8151 @example
8152 $ @kbd{m4 --safer}
8153 esyscmd(`echo hi')
8154 @error{}m4:stdin:1: esyscmd: disabled by --safer
8155 @result{}
8156 @end example
8158 @node Sysval
8159 @section Exit status
8161 @cindex UNIX commands, exit status from
8162 @cindex exit status from shell commands
8163 @cindex shell commands, exit status from
8164 @cindex commands, exit status from shell
8165 @cindex status of shell commands
8166 To see whether a shell command succeeded, use @code{sysval}:
8168 @deffn {Builtin (m4)} sysval
8169 Expands to the exit status of the last shell command run with
8170 @code{syscmd} or @code{esyscmd}.  Expands to 0 if no command has been
8171 run yet.
8172 @end deffn
8174 @example
8175 sysval
8176 @result{}0
8177 syscmd(`false')
8178 @result{}
8179 ifelse(sysval, `0', `zero', `non-zero')
8180 @result{}non-zero
8181 syscmd(`exit 2')
8182 @result{}
8183 sysval
8184 @result{}2
8185 syscmd(`true')
8186 @result{}
8187 sysval
8188 @result{}0
8189 esyscmd(`false')
8190 @result{}
8191 ifelse(sysval, `0', `zero', `non-zero')
8192 @result{}non-zero
8193 esyscmd(`echo dnl && exit 127')
8194 @result{}
8195 sysval
8196 @result{}127
8197 esyscmd(`true')
8198 @result{}
8199 sysval
8200 @result{}0
8201 @end example
8203 @code{sysval} results in 127 if there was a problem executing the
8204 command, for example, if the system-imposed argument length is exceeded,
8205 or if there were not enough resources to fork.  It is not possible to
8206 distinguish between failed execution and successful execution that had
8207 an exit status of 127, unless there was output from the child process.
8209 On UNIX platforms, where it is possible to detect when command execution
8210 is terminated by a signal, rather than a normal exit, the result is the
8211 signal number shifted left by eight bits.
8213 @comment This test has difficulties being portable, even on platforms
8214 @comment where syscmd invokes /bin/sh.  Kill is not portable with signal
8215 @comment names.  According to autoconf, the only portable signal numbers
8216 @comment are 1 (HUP), 2 (INT), 9 (KILL), 13 (PIPE) and 15 (TERM).  But
8217 @comment all shells handle SIGINT, and ksh handles HUP (as in, the shell
8218 @comment exits normally rather than letting the signal terminate it).
8219 @comment Also, TERM is flaky, as it can also kill the running m4 on
8220 @comment systems where /bin/sh does not create its own process group.
8221 @comment And PIPE is unreliable, since people tend to run with it
8222 @comment ignored, with m4 inheriting that choice.  That leaves KILL as
8223 @comment the only signal we can reliably test.
8224 @example
8225 dnl This test assumes kill is a shell builtin, and that signals are
8226 dnl recognizable.
8227 ifdef(`__unix__', ,
8228       `errprint(` skipping: syscmd does not have unix semantics
8229 ')m4exit(`77')')dnl
8230 syscmd(`kill -9 $$')
8231 @result{}
8232 sysval
8233 @result{}2304
8234 syscmd()
8235 @result{}
8236 sysval
8237 @result{}0
8238 esyscmd(`kill -9 $$')
8239 @result{}
8240 sysval
8241 @result{}2304
8242 @end example
8244 When the @option{--safer} option (@pxref{Operation modes, , Invoking
8245 m4}) is in effect, @code{sysval} will always remain at its default value
8246 of zero.
8248 @comment options: --safer
8249 @comment status: 1
8250 @example
8251 $ @kbd{m4 --safer}
8252 sysval
8253 @result{}0
8254 syscmd(`false')
8255 @error{}m4:stdin:2: syscmd: disabled by --safer
8256 @result{}
8257 sysval
8258 @result{}0
8259 @end example
8261 @node Mkstemp
8262 @section Making temporary files
8264 @cindex temporary file names
8265 @cindex files, names of temporary
8266 Commands specified to @code{syscmd} or @code{esyscmd} might need a
8267 temporary file, for output or for some other purpose.  There is a
8268 builtin macro, @code{mkstemp}, for making a temporary file:
8270 @deffn {Builtin (m4)} mkstemp (@var{template})
8271 @deffnx {Builtin (m4)} maketemp (@var{template})
8272 Expands to the quoted name of a new, empty file, made from the string
8273 @var{template}, which should end with the string @samp{XXXXXX}.  The six
8274 @samp{X} characters are then replaced with random characters matching
8275 the regular expression @samp{[a-zA-Z0-9._-]}, in order to make the file
8276 name unique.  If fewer than six @samp{X} characters are found at the end
8277 of @code{template}, the result will be longer than the template.  The
8278 created file will have access permissions as if by @kbd{chmod =rw,go=},
8279 meaning that the current umask of the @code{m4} process is taken into
8280 account, and at most only the current user can read and write the file.
8282 The traditional behavior, standardized by POSIX, is that
8283 @code{maketemp} merely replaces the trailing @samp{X} with the process
8284 id, without creating a file or quoting the expansion, and without
8285 ensuring that the resulting
8286 string is a unique file name.  In part, this means that using the same
8287 @var{template} twice in the same input file will result in the same
8288 expansion.  This behavior is a security hole, as it is very easy for
8289 another process to guess the name that will be generated, and thus
8290 interfere with a subsequent use of @code{syscmd} trying to manipulate
8291 that file name.  Hence, POSIX has recommended that all new
8292 implementations of @code{m4} provide the secure @code{mkstemp} builtin,
8293 and that users of @code{m4} check for its existence.
8295 The expansion is void and an error issued if a temporary file could
8296 not be created.
8298 When the @option{--safer} option (@pxref{Operation modes, Invoking m4})
8299 is in effect, @code{mkstemp} and GNU-mode @code{maketemp}
8300 result in an error, since otherwise an input file could perform a mild
8301 denial-of-service attack by filling up a disk with multiple empty files.
8303 The macros @code{mkstemp} and @code{maketemp} are recognized only with
8304 parameters.
8305 @end deffn
8307 If you try this next example, you will most likely get different output
8308 for the two file names, since the replacement characters are randomly
8309 chosen:
8311 @comment ignore
8312 @example
8313 $ @kbd{m4}
8314 define(`tmp', `oops')
8315 @result{}
8316 maketemp(`/tmp/fooXXXXXX')
8317 @error{}m4:stdin:1: warning: maketemp: recommend using mkstemp instead
8318 @result{}/tmp/fooa07346
8319 ifdef(`mkstemp', `define(`maketemp', defn(`mkstemp'))',
8320       `define(`mkstemp', defn(`maketemp'))dnl
8321 errprint(`warning: potentially insecure maketemp implementation
8322 ')')
8323 @result{}
8324 mkstemp(`doc')
8325 @result{}docQv83Uw
8326 @end example
8328 @comment options: --safer
8329 @comment status: 1
8330 @example
8331 $ @kbd{m4 --safer}
8332 maketemp(`/tmp/fooXXXXXX')
8333 @error{}m4:stdin:1: warning: maketemp: recommend using mkstemp instead
8334 @error{}m4:stdin:1: maketemp: disabled by --safer
8335 @result{}
8336 mkstemp(`/tmp/fooXXXXXX')
8337 @error{}m4:stdin:2: mkstemp: disabled by --safer
8338 @result{}
8339 @end example
8341 @cindex GNU extensions
8342 Unless you use the @option{--traditional} command line option (or
8343 @option{-G}, @pxref{Limits control, , Invoking m4}), the GNU
8344 version of @code{maketemp} is secure.  This means that using the same
8345 template to multiple calls will generate multiple files.  However, we
8346 recommend that you use the new @code{mkstemp} macro, introduced in
8347 GNU M4 1.4.8, which is secure even in traditional mode.  Also,
8348 as of M4 1.4.11, the secure implementation quotes the resulting file
8349 name, so that you are guaranteed to know what file was created even if
8350 the random file name happens to match an existing macro.  Notice that
8351 this example is careful to use @code{defn} to avoid unintended expansion
8352 of @samp{foo}.
8354 @example
8355 $ @kbd{m4}
8356 define(`foo', `errprint(`oops')')
8357 @result{}
8358 syscmd(`rm -f foo-??????')sysval
8359 @result{}0
8360 define(`file1', maketemp(`foo-XXXXXX'))dnl
8361 @error{}m4:stdin:3: warning: maketemp: recommend using mkstemp instead
8362 ifelse(esyscmd(`echo \` foo-?????? \''), `foo-??????',
8363        `no file', `created')
8364 @result{}created
8365 define(`file2', maketemp(`foo-XX'))dnl
8366 @error{}m4:stdin:6: warning: maketemp: recommend using mkstemp instead
8367 define(`file3', mkstemp(`foo-XXXXXX'))dnl
8368 ifelse(len(defn(`file1')), len(defn(`file2')),
8369        `same length', `different')
8370 @result{}same length
8371 ifelse(defn(`file1'), defn(`file2'), `same', `different file')
8372 @result{}different file
8373 ifelse(defn(`file2'), defn(`file3'), `same', `different file')
8374 @result{}different file
8375 ifelse(defn(`file1'), defn(`file3'), `same', `different file')
8376 @result{}different file
8377 syscmd(`rm 'defn(`file1') defn(`file2') defn(`file3'))
8378 @result{}
8379 sysval
8380 @result{}0
8381 @end example
8383 @comment options: -G
8384 @example
8385 $ @kbd{m4 -G}
8386 syscmd(`rm -f foo-*')sysval
8387 @result{}0
8388 define(`file1', maketemp(`foo-XXXXXX'))dnl
8389 @error{}m4:stdin:2: warning: maketemp: recommend using mkstemp instead
8390 define(`file2', maketemp(`foo-XXXXXX'))dnl
8391 @error{}m4:stdin:3: warning: maketemp: recommend using mkstemp instead
8392 ifelse(file1, file2, `same', `different file')
8393 @result{}same
8394 len(maketemp(`foo-XXXXX'))
8395 @error{}m4:stdin:5: warning: maketemp: recommend using mkstemp instead
8396 @result{}9
8397 define(`abc', `def')
8398 @result{}
8399 maketemp(`foo-abc')
8400 @result{}foo-def
8401 @error{}m4:stdin:7: warning: maketemp: recommend using mkstemp instead
8402 syscmd(`test -f foo-*')sysval
8403 @result{}1
8404 @end example
8406 @node Mkdtemp
8407 @section Making temporary directories
8409 @cindex temporary directory
8410 @cindex directories, temporary
8411 @cindex GNU extensions
8412 Commands specified to @code{syscmd} or @code{esyscmd} might need a
8413 temporary directory, for holding multiple temporary files; such a
8414 directory can be created with @code{mkdtemp}:
8416 @deffn {Builtin (gnu)} mkdtemp (@var{template})
8417 Expands to the quoted name of a new, empty directory, made from the string
8418 @var{template}, which should end with the string @samp{XXXXXX}.  The six
8419 @samp{X} characters are then replaced with random characters matching
8420 the regular expression @samp{[a-zA-Z0-9._-]}, in order to make the name
8421 unique.  If fewer than six @samp{X} characters are found at the end of
8422 @code{template}, the result will be longer than the template.  The
8423 created directory will have access permissions as if by @kbd{chmod
8424 =rwx,go=}, meaning that the current umask of the @code{m4} process is
8425 taken into account, and at most only the current user can read, write,
8426 and search the directory.
8428 The expansion is void and an error issued if a temporary directory could
8429 not be created.
8431 When the @option{--safer} option (@pxref{Operation modes, Invoking m4})
8432 is in effect, @code{mkdtemp} results in an error, since otherwise an
8433 input file could perform a mild denial-of-service attack by filling up a
8434 disk with multiple directories.
8436 The macro @code{mkdtemp} is recognized only with parameters.
8437 This macro was added in M4 2.0.
8438 @end deffn
8440 If you try this next example, you will most likely get different output
8441 for the directory names, since the replacement characters are randomly
8442 chosen:
8444 @comment ignore
8445 @example
8446 $ @kbd{m4}
8447 define(`tmp', `oops')
8448 @result{}
8449 mkdtemp(`/tmp/fooXXXXXX')
8450 @result{}/tmp/foo2h89Vo
8451 mkdtemp(`dir)
8452 @result{}dirrg079A
8453 @end example
8455 @comment options: --safer
8456 @comment status: 1
8457 @example
8458 $ @kbd{m4 --safer}
8459 mkdtemp(`/tmp/fooXXXXXX')
8460 @error{}m4:stdin:1: mkdtemp: disabled by --safer
8461 @result{}
8462 @end example
8464 Multiple calls with the same template will generate multiple
8465 directories.
8467 @example
8468 $ @kbd{m4}
8469 syscmd(`echo foo??????')dnl
8470 @result{}foo??????
8471 define(`dir1', mkdtemp(`fooXXXXXX'))dnl
8472 ifelse(esyscmd(`echo foo??????'), `foo??????', `no dir', `created')
8473 @result{}created
8474 define(`dir2', mkdtemp(`fooXXXXXX'))dnl
8475 ifelse(dir1, dir2, `same', `different directories')
8476 @result{}different directories
8477 syscmd(`rmdir 'dir1 dir2)
8478 @result{}
8479 sysval
8480 @result{}0
8481 @end example
8483 @node Miscellaneous
8484 @chapter Miscellaneous builtin macros
8486 This chapter describes various builtins, that do not really belong in
8487 any of the previous chapters.
8489 @menu
8490 * Errprint::                    Printing error messages
8491 * Location::                    Printing current location
8492 * M4exit::                      Exiting from @code{m4}
8493 * Syncoutput::                  Turning on and off sync lines
8494 @end menu
8496 @node Errprint
8497 @section Printing error messages
8499 @cindex printing error messages
8500 @cindex error messages, printing
8501 @cindex messages, printing error
8502 @cindex standard error, output to
8503 You can print error messages using @code{errprint}:
8505 @deffn {Builtin (m4)} errprint (@var{message}, @dots{})
8506 Prints @var{message} and the rest of the arguments to standard error,
8507 separated by spaces.  Standard error is used, regardless of the
8508 @option{--debugfile} option (@pxref{Debugging options, , Invoking m4}).
8510 The expansion of @code{errprint} is void.
8511 The macro @code{errprint} is recognized only with parameters.
8512 @end deffn
8514 @example
8515 errprint(`Invalid arguments to forloop
8517 @error{}Invalid arguments to forloop
8518 @result{}
8519 errprint(`1')errprint(`2',`3
8521 @error{}12 3
8522 @result{}
8523 @end example
8525 A trailing newline is @emph{not} printed automatically, so it should be
8526 supplied as part of the argument, as in the example.  Unfortunately, the
8527 exact output of @code{errprint} is not very portable to other @code{m4}
8528 implementations: POSIX requires that all arguments be printed,
8529 but some implementations of @code{m4} only print the first.
8530 Furthermore, some BSD implementations always append a newline
8531 for each @code{errprint} call, regardless of whether the last argument
8532 already had one, and POSIX is silent on whether this is
8533 acceptable.
8535 @node Location
8536 @section Printing current location
8538 @cindex location, input
8539 @cindex input location
8540 To make it possible to specify the location of an error, three
8541 utility builtins exist:
8543 @deffn {Builtin (gnu)} __file__
8544 @deffnx {Builtin (gnu)} __line__
8545 @deffnx {Builtin (gnu)} __program__
8546 Expand to the quoted name of the current input file, the
8547 current input line number in that file, and the quoted name of the
8548 current invocation of @code{m4}.
8549 @end deffn
8551 @example
8552 errprint(__program__:__file__:__line__: `input error
8554 @error{}m4:stdin:1: input error
8555 @result{}
8556 @end example
8558 Line numbers start at 1 for each file.  If the file was found due to the
8559 @option{-I} option or @env{M4PATH} environment variable, that is
8560 reflected in the file name.  Synclines, via @code{syncoutput}
8561 (@pxref{Syncoutput}) or the command line option @option{--synclines}
8562 (or @option{-s}, @pxref{Preprocessor features, , Invoking m4}), and the
8563 @samp{f} and @samp{l} flags of @code{debugmode} (@pxref{Debugmode}),
8564 also use this notion of current file and line.  Redefining the three
8565 location macros has no effect on syncline, debug, warning, or error
8566 message output.
8568 This example reuses the file @file{incl.m4} mentioned earlier
8569 (@pxref{Include}):
8571 @comment examples
8572 @example
8573 $ @kbd{m4 -I examples}
8574 define(`foo', ``$0' called at __file__:__line__')
8575 @result{}
8577 @result{}foo called at stdin:2
8578 include(`incl.m4')
8579 @result{}Include file start
8580 @result{}foo called at examples/incl.m4:2
8581 @result{}Include file end
8582 @result{}
8583 @end example
8585 The location of macros invoked during the rescanning of macro expansion
8586 text corresponds to the location in the file where the expansion was
8587 triggered, regardless of how many newline characters the expansion text
8588 contains.  As of GNU M4 1.4.8, the location of text wrapped
8589 with @code{m4wrap} (@pxref{M4wrap}) is the point at which the
8590 @code{m4wrap} was invoked.  Previous versions, however, behaved as
8591 though wrapped text came from line 0 of the file ``''.
8593 @example
8594 define(`echo', `$@@')
8595 @result{}
8596 define(`foo', `echo(__line__
8597 __line__)')
8598 @result{}
8599 echo(__line__
8600 __line__)
8601 @result{}4
8602 @result{}5
8603 m4wrap(`foo
8605 @result{}
8606 foo(errprint(__line__
8607 __line__
8609 @error{}8
8610 @error{}9
8611 @result{}8
8612 @result{}8
8613 __line__
8614 @result{}11
8615 m4wrap(`__line__
8617 @result{}
8619 @result{}6
8620 @result{}6
8621 @result{}12
8622 @end example
8624 The @code{@w{__program__}} macro behaves like @samp{$0} in shell
8625 terminology.  If you invoke @code{m4} through an absolute path or a link
8626 with a different spelling, rather than by relying on a @env{PATH} search
8627 for plain @samp{m4}, it will affect how @code{@w{__program__}} expands.
8628 The intent is that you can use it to produce error messages with the
8629 same formatting that @code{m4} produces internally.  It can also be used
8630 within @code{syscmd} (@pxref{Syscmd}) to pick the same version of
8631 @code{m4} that is currently running, rather than whatever version of
8632 @code{m4} happens to be first in @env{PATH}.  It was first introduced in
8633 GNU M4 1.4.6.
8635 @node M4exit
8636 @section Exiting from @code{m4}
8638 @cindex exiting from @code{m4}
8639 @cindex status, setting @code{m4} exit
8640 If you need to exit from @code{m4} before the entire input has been
8641 read, you can use @code{m4exit}:
8643 @deffn {Builtin (m4)} m4exit (@ovar{code})
8644 Causes @code{m4} to exit, with exit status @var{code}.  If @var{code} is
8645 left out, the exit status is zero.  If @var{code} cannot be parsed, or
8646 is outside the range of 0 to 255, the exit status is one.  No further
8647 input is read, and all wrapped and diverted text is discarded.
8648 @end deffn
8650 @example
8651 m4wrap(`This text is lost due to `m4exit'.')
8652 @result{}
8653 divert(`1') So is this.
8654 divert
8655 @result{}
8656 m4exit And this is never read.
8657 @end example
8659 A common use of this is to abort processing:
8661 @deffn Composite fatal_error (@var{message})
8662 Abort processing with an error message and non-zero status.  Prefix
8663 @var{message} with details about where the error occurred, and print the
8664 resulting string to standard error.
8665 @end deffn
8667 @comment status: 1
8668 @example
8669 define(`fatal_error',
8670        `errprint(__program__:__file__:__line__`: fatal error: $*
8671 ')m4exit(`1')')
8672 @result{}
8673 fatal_error(`this is a BAD one, buster')
8674 @error{}m4:stdin:4: fatal error: this is a BAD one, buster
8675 @end example
8677 After this macro call, @code{m4} will exit with exit status 1.  This macro
8678 is only intended for error exits, since the normal exit procedures are
8679 not followed, i.e., diverted text is not undiverted, and saved text
8680 (@pxref{M4wrap}) is not reread.  (This macro could be made more robust
8681 to earlier versions of @code{m4}.  You should try to see if you can find
8682 weaknesses and correct them; or @pxref{Improved fatal_error, , Answers}).
8684 Note that it is still possible for the exit status to be different than
8685 what was requested by @code{m4exit}.  If @code{m4} detects some other
8686 error, such as a write error on standard output, the exit status will be
8687 non-zero even if @code{m4exit} requested zero.
8689 If standard input is seekable, then the file will be positioned at the
8690 next unread character.  If it is a pipe or other non-seekable file,
8691 then there are no guarantees how much data @code{m4} might have read
8692 into buffers, and thus discarded.
8694 @node Syncoutput
8695 @section Turning on and off sync lines
8697 @cindex toggling synchronization lines
8698 @cindex synchronization lines
8699 @cindex location, input
8700 @cindex input location
8701 It is possible to adjust whether synclines are printed to output:
8703 @deffn {Builtin (gnu)} syncoutput (@var{truth})
8704 If @var{truth} matches the extended regular expression
8705 @samp{^[1yY]|^([oO][nN])}, it causes @code{m4} to emit sync lines of the
8706 form: @samp{#line <number> ["<file>"]}.
8708 If @var{truth} is empty, or matches the extended regular expression
8709 @samp{^[0nN]|^([oO][fF])}, it causes @code{m4} to turn sync lines off.
8711 All other arguments are ignored and issue a warning.
8713 The macro @code{syncoutput} is recognized only with parameters.
8714 This macro was added in M4 2.0.
8715 @end deffn
8717 @example
8718 define(`twoline', `1
8720 @result{}
8721 changecom(`/*', `*/')
8722 @result{}
8723 define(`comment', `/*1
8724 2*/')
8725 @result{}
8726 twoline
8727 @result{}1
8728 @result{}2
8729 dnl no line
8730 syncoutput(`on')
8731 @result{}#line 8 "stdin"
8732 @result{}
8733 twoline
8734 @result{}1
8735 @result{}#line 9
8736 @result{}2
8737 dnl no line
8738 hello
8739 @result{}#line 11
8740 @result{}hello
8741 comment
8742 @result{}/*1
8743 @result{}2*/
8744 one comment `two
8745 three'
8746 @result{}#line 13
8747 @result{}one /*1
8748 @result{}2*/ two
8749 @result{}three
8750 goodbye
8751 @result{}#line 15
8752 @result{}goodbye
8753 syncoutput(`off')
8754 @result{}
8755 twoline
8756 @result{}1
8757 @result{}2
8758 syncoutput(`blah')
8759 @error{}m4:stdin:18: warning: syncoutput: unknown directive 'blah'
8760 @result{}
8761 @end example
8763 Notice that a syncline is output any time a single source line expands
8764 to multiple output lines, or any time multiple source lines expand to a
8765 single output line.  When there is a one-for-one correspondence, no
8766 additional synclines are needed.
8768 Synchronization lines can be used to track where input comes from; an
8769 optional file designation is printed when the syncline algorithm
8770 detects that consecutive output lines come from different files.  You
8771 can also use the @option{--synclines} command-line option (or
8772 @option{-s}, @pxref{Preprocessor features, , Invoking m4}) to start
8773 with synchronization on.  This example reuses the file @file{incl.m4}
8774 mentioned earlier (@pxref{Include}):
8776 @comment examples
8777 @comment options: -s
8778 @example
8779 $ @kbd{m4 --synclines -I examples}
8780 include(`incl.m4')
8781 @result{}#line 1 "examples/incl.m4"
8782 @result{}Include file start
8783 @result{}foo
8784 @result{}Include file end
8785 @result{}#line 1 "stdin"
8786 @result{}
8787 @end example
8789 @node Frozen files
8790 @chapter Fast loading of frozen state
8792 Some bigger @code{m4} applications may be built over a common base
8793 containing hundreds of definitions and other costly initializations.
8794 Usually, the common base is kept in one or more declarative files,
8795 which files are listed on each @code{m4} invocation prior to the
8796 user's input file, or else each input file uses @code{include}.
8798 Reading the common base of a big application, over and over again, may
8799 be time consuming.  GNU @code{m4} offers some machinery to
8800 speed up the start of an application using lengthy common bases.
8802 @menu
8803 * Using frozen files::          Using frozen files
8804 * Frozen file format 1::        Frozen file format 1
8805 * Frozen file format 2::        Frozen file format 2
8806 @end menu
8808 @node Using frozen files
8809 @section Using frozen files
8811 @cindex fast loading of frozen files
8812 @cindex frozen files for fast loading
8813 @cindex initialization, frozen state
8814 @cindex dumping into frozen file
8815 @cindex reloading a frozen file
8816 @cindex GNU extensions
8817 Suppose a user has a library of @code{m4} initializations in
8818 @file{base.m4}, which is then used with multiple input files:
8820 @comment ignore
8821 @example
8822 $ @kbd{m4 base.m4 input1.m4}
8823 $ @kbd{m4 base.m4 input2.m4}
8824 $ @kbd{m4 base.m4 input3.m4}
8825 @end example
8827 Rather than spending time parsing the fixed contents of @file{base.m4}
8828 every time, the user might rather execute:
8830 @comment ignore
8831 @example
8832 $ @kbd{m4 -F base.m4f base.m4}
8833 @end example
8835 @noindent
8836 once, and further execute, as often as needed:
8838 @comment ignore
8839 @example
8840 $ @kbd{m4 -R base.m4f input1.m4}
8841 $ @kbd{m4 -R base.m4f input2.m4}
8842 $ @kbd{m4 -R base.m4f input3.m4}
8843 @end example
8845 @noindent
8846 with the varying input.  The first call, containing the @option{-F}
8847 option, only reads and executes file @file{base.m4}, defining
8848 various application macros and computing other initializations.
8849 Once the input file @file{base.m4} has been completely processed, GNU
8850 @code{m4} produces in @file{base.m4f} a @dfn{frozen} file, that is, a
8851 file which contains a kind of snapshot of the @code{m4} internal state.
8853 Later calls, containing the @option{-R} option, are able to reload
8854 the internal state of @code{m4}, from @file{base.m4f},
8855 @emph{prior} to reading any other input files.  This means
8856 instead of starting with a virgin copy of @code{m4}, input will be
8857 read after having effectively recovered the effect of a prior run.
8858 In our example, the effect is the same as if file @file{base.m4} has
8859 been read anew.  However, this effect is achieved a lot faster.
8861 Only one frozen file may be created or read in any one @code{m4}
8862 invocation.  It is not possible to recover two frozen files at once.
8863 However, frozen files may be updated incrementally, through using
8864 @option{-R} and @option{-F} options simultaneously.  For example, if
8865 some care is taken, the command:
8867 @comment ignore
8868 @example
8869 $ @kbd{m4 file1.m4 file2.m4 file3.m4 file4.m4}
8870 @end example
8872 @noindent
8873 could be broken down in the following sequence, accumulating the same
8874 output:
8876 @comment ignore
8877 @example
8878 $ @kbd{m4 -F file1.m4f file1.m4}
8879 $ @kbd{m4 -R file1.m4f -F file2.m4f file2.m4}
8880 $ @kbd{m4 -R file2.m4f -F file3.m4f file3.m4}
8881 $ @kbd{m4 -R file3.m4f file4.m4}
8882 @end example
8884 Some care is necessary because the frozen file does not save all state
8885 information.  Stacks of macro definitions via @code{pushdef} are
8886 accurately stored, along with all renamed or undefined builtins, as are
8887 the current syntax rules such as from @code{changequote}.  However, the
8888 value of @code{sysval} and text saved in @code{m4wrap} are not currently
8889 preserved.  Also, changing command line options between runs may cause
8890 unexpected behavior.  A future release of GNU M4 may improve
8891 on the quality of frozen files.
8893 When an @code{m4} run is to be frozen, the automatic undiversion
8894 which takes place at end of execution is inhibited.  Instead, all
8895 positively numbered diversions are saved into the frozen file.
8896 The active diversion number is also transmitted.
8898 A frozen file to be reloaded need not reside in the current directory.
8899 It is looked up the same way as an @code{include} file (@pxref{Search
8900 Path}).
8902 If the frozen file was generated with a newer version of @code{m4}, and
8903 contains directives that an older @code{m4} cannot parse, attempting to
8904 load the frozen file with option @option{-R} will cause @code{m4} to
8905 exit with status 63 to indicate version mismatch.
8907 @node Frozen file format 1
8908 @section Frozen file format 1
8910 @cindex frozen file format 1
8911 @cindex file format, frozen file version 1
8912 Frozen files are sharable across architectures.  It is safe to write
8913 a frozen file on one machine and read it on another, given that the
8914 second machine uses the same or newer version of GNU @code{m4}.
8915 It is conventional, but not required, to give a frozen file the suffix
8916 of @code{.m4f}.
8918 Older versions of GNU @code{m4} create frozen files with
8919 syntax version 1.  These files can be read by the current version, but
8920 are no longer produced.  Version 1 files are mostly text files, although
8921 any macros or diversions that contained nonprintable characters or long
8922 lines cause the resulting frozen file to do likewise, since there are no
8923 escape sequences.  The file can be edited to change the state that
8924 @code{m4} will start with.  It is composed of several directives, each
8925 starting with a single letter and ending with a newline (@key{NL}).
8926 Wherever a directive is expected, the character @samp{#} can be used
8927 instead to introduce a comment line; empty lines are also ignored if
8928 they are not part of an embedded string.
8930 In the following descriptions, each @var{len} refers to the length of a
8931 corresponding subsequent @var{str}.  Numbers are always expressed in
8932 decimal, and an omitted number defaults to 0.  The valid directives in
8933 version 1 are:
8935 @table @code
8936 @item V @var{number} @key{NL}
8937 Confirms the format of the file.  Version 1 is recognized when
8938 @var{number} is 1.  This directive must be the first non-comment in the
8939 file, and may not appear more than once.
8941 @item C @var{len1} , @var{len2} @key{NL} @var{str1} @var{str2} @key{NL}
8942 Uses @var{str1} and @var{str2} as the begin-comment and
8943 end-comment strings.  If omitted, then @samp{#} and @key{NL} are the
8944 comment delimiters.
8946 @item D @var{number}, @var{len} @key{NL} @var{str} @key{NL}
8947 Selects diversion @var{number}, making it current, then copy @var{str}
8948 in the current diversion.  @var{number} may be a negative number for a
8949 diversion that discards text.  To merely specify an active selection,
8950 use this command with an empty @var{str}.  With 0 as the diversion
8951 @var{number}, @var{str} will be issued on standard output at reload
8952 time.  GNU @code{m4} will not produce the @samp{D} directive
8953 with non-zero length for diversion 0, but this can be done with manual
8954 edits.  This directive may appear more than once for the same diversion,
8955 in which case the diversion is the concatenation of the various uses.
8956 If omitted, then diversion 0 is current.
8958 @item F @var{len1} , @var{len2} @key{NL} @var{str1} @var{str2} @key{NL}
8959 Defines, through @code{pushdef}, a definition for @var{str1} expanding
8960 to the function whose builtin name is @var{str2}.  If the builtin does
8961 not exist (for example, if the frozen file was produced by a copy of
8962 @code{m4} compiled with the now-abandoned @code{changeword} support),
8963 the reload is silent, but any subsequent use of the definition of
8964 @var{str1} will result in a warning.  This directive may appear more
8965 than once for the same name, and its order, along with @samp{T}, is
8966 important.  If omitted, you will have no access to any builtins.
8968 @item Q @var{len1} , @var{len2} @key{NL} @var{str1} @var{str2} @key{NL}
8969 Uses @var{str1} and @var{str2} as the begin-quote and end-quote
8970 strings.  If omitted, then @samp{`} and @samp{'} are the quote
8971 delimiters.
8973 @item T @var{len1} , @var{len2} @key{NL} @var{str1} @var{str2} @key{NL}
8974 Defines, though @code{pushdef}, a definition for @var{str1}
8975 expanding to the text given by @var{str2}.  This directive may appear
8976 more than once for the same name, and its order, along with @samp{F}, is
8977 important.
8978 @end table
8980 When loading format 1, the syntax categories @samp{@{} and @samp{@}} are
8981 disabled (reverting braces to be treated like plain characters).  This
8982 is because frozen files created with M4 1.4.x did not understand
8983 @samp{$@{@dots{}@}} extended argument notation, and a frozen macro that
8984 contained this character sequence should not behave differently just
8985 because a newer version of M4 reloaded the file.
8987 @node Frozen file format 2
8988 @section Frozen file format 2
8990 @cindex frozen file format 2
8991 @cindex file format, frozen file version 2
8992 The syntax of version 1 has some drawbacks; if any macro or diversion
8993 contained non-printable characters or long lines, the resulting frozen
8994 file would not qualify as a text file, making it harder to edit with
8995 some vendor tools.  The concatenation of multiple strings on a single
8996 line, such as for the @samp{T} directive, makes distinguishing the two
8997 strings a bit more difficult.  Finally, the format lacks support for
8998 several items of @code{m4} state, such that a reloaded file did not
8999 always behave the same as the original file.
9001 These shortcomings have been addressed in version 2 of the frozen file
9002 syntax.  New directives have been added, and existing directives have
9003 additional, and sometimes optional, parameters.  All @var{str} instances
9004 in the grammar are now followed by @key{NL}, which makes the split
9005 between consecutive strings easier to recognize.  Strings may now
9006 contain escape sequences modeled after C, such as @samp{\n} for newline
9007 or @samp{\0} for @sc{nul}, so that the frozen file can be pure
9008 @sc{ascii} (although when hand-editing a frozen file, it is still
9009 acceptable to use the original byte rather than an escape sequence for
9010 all bytes except @samp{\}).  Also in the context of a @var{str}, the
9011 escape sequence @samp{\@key{NL}} is discarded, allowing a user to split
9012 lines that are too long for some platform tools.
9014 @table @code
9015 @item V @var{number} @key{NL}
9016 Confirms the format of the file.  @code{m4} @value{VERSION} only creates
9017 frozen files where @var{number} is 2.  This directive must be the first
9018 non-comment in the file, and may not appear more than once.
9020 @item C @var{len1} , @var{len2} @key{NL} @var{str1} @key{NL} @var{str2} @key{NL}
9021 Uses @var{str1} and @var{str2} as the begin-comment and
9022 end-comment strings.  If omitted, then @samp{#} and @key{NL} are the
9023 comment delimiters.
9025 @item d @var{len} @key{NL} @var{str} @key{NL}
9026 Sets the debug flags, using @var{str} as the argument to
9027 @code{debugmode}.  If omitted, then the debug flags start in their
9028 default disabled state.
9030 @item D @var{number} , @var{len} @key{NL} @var{str} @key{NL}
9031 Selects diversion @var{number}, making it current, then copy @var{str}
9032 in the current diversion.  @var{number} may be a negative number for a
9033 diversion that discards text.  To merely specify an active selection,
9034 use this command with an empty @var{string}.  With 0 as the diversion
9035 @var{number}, @var{str} will be issued on standard output at reload
9036 time.  GNU @code{m4} will not produce the @samp{D} directive
9037 with non-zero length for diversion 0, but this can be done with manual
9038 edits.  This directive may appear more than once for the same diversion,
9039 in which case the diversion is the concatenation of the various uses.
9040 If omitted, then diversion 0 is current.
9042 @comment FIXME - the first usage, with only one string, is not supported
9043 @comment in the current code
9044 @c @item F @var{len1} @key{NL} @var{str1} @key{NL}
9045 @item F @var{len1} , @var{len2} @key{NL} @var{str1} @key{NL} @var{str2} @key{NL}
9046 @itemx F @var{len1} , @var{len2} , @var{len3} @key{NL} @var{str1} @key{NL} @var{str2} @key{NL} @var{str3} @key{NL}
9047 Defines, through @code{pushdef}, a definition for @var{str1} expanding
9048 to the function whose builtin name is given by @var{str2} (defaulting to
9049 @var{str1} if not present).  With two arguments, the builtin name is
9050 searched for among the intrinsic builtin functions only; with three
9051 arguments, the builtin name is searched for amongst the builtin
9052 functions defined by the module named by @var{str3}.
9054 @item M @var{len} @key{NL} @var{str} @key{NL}
9055 Names a module which will be searched for according to the module search
9056 path and loaded.  Modules loaded from a frozen file don't add their
9057 builtin entries to the symbol table.  Modules must be loaded prior to
9058 specifying module-specific builtins via the three-argument @code{F} or
9059 @code{T}.
9061 @item Q @var{len1} , @var{len2} @key{NL} @var{str1} @key{NL} @var{str2} @key{NL}
9062 Uses @var{str1} and @var{str2} as the begin-quote and end-quote strings.
9063 If omitted, then @samp{`} and @samp{'} are the quote delimiters.
9065 @item R @var{len} @key{NL} @var{str} @key{NL}
9066 Sets the default regexp syntax, where @var{str} encodes one of the
9067 regular expression syntaxes supported by GNU M4.
9068 @xref{Changeresyntax}, for more details.
9070 @item S @var{syntax-code} @var{len} @key{NL} @var{str} @key{NL}
9071 Defines, through @code{changesyntax}, a syntax category for each of the
9072 characters in @var{str}.  The @var{syntax-code} must be one of the
9073 characters described in @ref{Changesyntax}.
9075 @item t @var{len} @key{NL} @var{str} @key{NL}
9076 Enables tracing for any macro named @var{str}, similar to using the
9077 @code{traceon} builtin.  This option may occur more than once for
9078 multiple macros; if omitted, no macro starts out as traced.
9080 @item T @var{len1} , @var{len2} @key{NL} @var{str1} @key{NL} @var{str2} @key{NL}
9081 @itemx T @var{len1} , @var{len2} , @var{len3} @key{NL} @var{str1} @key{NL} @var{str2} @key{NL} @var{str3} @key{NL}
9082 Defines, though @code{pushdef}, a definition for @var{str1} expanding to
9083 the text given by @var{str2}.  This directive may appear more than once
9084 for the same name, and its order, along with @samp{F}, is important.  If
9085 present, the optional third argument associates the macro with a module
9086 named by @var{str3}.
9087 @end table
9089 @node Compatibility
9090 @chapter Compatibility with other versions of @code{m4}
9092 @cindex compatibility
9093 This chapter describes the many of the differences between this
9094 implementation of @code{m4}, and of other implementations found under
9095 UNIX, such as System V Release 3, Solaris, and BSD flavors.
9096 In particular, it lists the known differences and extensions to
9097 POSIX.  However, the list is not necessarily comprehensive.
9099 At the time of this writing, POSIX 2001 (also known as IEEE
9100 Std 1003.1-2001) is the latest standard, although a new version of
9101 POSIX is under development and includes several proposals for
9102 modifying what @code{m4} is required to do.  The requirements for
9103 @code{m4} are shared between SUSv3 and POSIX, and
9104 can be viewed at
9105 @uref{http://www.opengroup.org/onlinepubs/@/000095399/@/utilities/@/m4.html}.
9107 @menu
9108 * Extensions::                  Extensions in GNU M4
9109 * Incompatibilities::           Other incompatibilities
9110 * Experiments::                 Experimental features in GNU M4
9111 @end menu
9113 @node Extensions
9114 @section Extensions in GNU M4
9116 @cindex GNU extensions
9117 @cindex POSIX
9118 @cindex @env{POSIXLY_CORRECT}
9119 This version of @code{m4} contains a few facilities that do not exist
9120 in System V @code{m4}.  These extra facilities are all suppressed by
9121 using the @option{-G} command line option, unless overridden by other
9122 command line options.
9123 Most of these extensions are compatible with
9124 @uref{http://www.unix.org/single_unix_specification/,
9125 POSIX}; the few exceptions are suppressed if the
9126 @env{POSIXLY_CORRECT} environment variable is set.
9128 @itemize @bullet
9129 @item
9130 In the @code{$@var{n}} notation for macro arguments, @var{n} can contain
9131 several digits, while the System V @code{m4} only accepts one digit.
9132 This allows macros in GNU @code{m4} to take any number of
9133 arguments, and not only nine (@pxref{Arguments}).
9134 POSIX does not allow this extension, so it is disabled if
9135 @env{POSIXLY_CORRECT} is set.
9136 @c FIXME - update this bullet when ${11} is implemented.
9138 @item
9139 The @code{divert} (@pxref{Divert}) macro can manage more than 9
9140 diversions.  GNU @code{m4} treats all positive numbers as valid
9141 diversions, rather than discarding diversions greater than 9.
9143 @item
9144 Files included with @code{include} and @code{sinclude} are sought in a
9145 user specified search path, if they are not found in the working
9146 directory.  The search path is specified by the @option{-I} option and the
9147 @samp{M4PATH} environment variable (@pxref{Search Path}).
9149 @item
9150 Arguments to @code{undivert} can be non-numeric, in which case the named
9151 file will be included uninterpreted in the output (@pxref{Undivert}).
9153 @item
9154 Formatted output is supported through the @code{format} builtin, which
9155 is modeled after the C library function @code{printf} (@pxref{Format}).
9157 @item
9158 Searches and text substitution through regular expressions are supported
9159 by the @code{regexp} (@pxref{Regexp}) and @code{patsubst}
9160 (@pxref{Patsubst}) builtins.
9162 The syntax of regular expressions in M4 has never been clearly
9163 formalized.  While OpenBSD M4 uses extended regular
9164 expressions for @code{regexp} and @code{patsubst}, GNU M4
9165 defaults to basic regular expressions, but provides
9166 @code{changeresyntax} (@pxref{Changeresyntax}) to change the flavor of
9167 regular expression syntax in use.
9169 @item
9170 The output of shell commands can be read into @code{m4} with
9171 @code{esyscmd} (@pxref{Esyscmd}).
9173 @item
9174 There is indirect access to any builtin macro with @code{builtin}
9175 (@pxref{Builtin}).
9177 @item
9178 Macros can be called indirectly through @code{indir} (@pxref{Indir}).
9180 @item
9181 The name of the program, the current input file, and the current input
9182 line number are accessible through the builtins @code{@w{__program__}},
9183 @code{@w{__file__}}, and @code{@w{__line__}} (@pxref{Location}).
9185 @item
9186 The generation of sync lines can be controlled through @code{syncoutput}
9187 (@pxref{Syncoutput}).
9189 @item
9190 The format of the output from @code{dumpdef} and macro tracing can be
9191 controlled with @code{debugmode} (@pxref{Debugmode}).
9193 @item
9194 The destination of trace and debug output can be controlled with
9195 @code{debugfile} (@pxref{Debugfile}).
9197 @item
9198 The @code{maketemp} (@pxref{Mkstemp}) macro behaves like @code{mkstemp},
9199 creating a new file with a unique name on every invocation, rather than
9200 following the insecure behavior of replacing the trailing @samp{X}
9201 characters with the @code{m4} process id.  POSIX does not
9202 allow this extension, so @code{maketemp} is insecure if
9203 @env{POSIXLY_CORRECT} is set, but you should be using @code{mkstemp} in
9204 the first place.
9206 @item
9207 POSIX only requires support for the command line options
9208 @option{-s}, @option{-D}, and @option{-U}, so all other options accepted
9209 by GNU M4 are extensions.  @xref{Invoking m4}, for a
9210 description of these options.
9212 @item
9213 The debugging and tracing facilities in GNU @code{m4} are much
9214 more extensive than in most other versions of @code{m4}.
9216 @item
9217 Some traditional implementations only allow reading standard input
9218 once, but GNU @code{m4} correctly handles multiple instances
9219 of @samp{-} on the command line.
9221 @item
9222 POSIX requires @code{m4wrap} (@pxref{M4wrap}) to act in FIFO
9223 (first-in, first-out) order, and most other implementations obey this.
9224 However, versions of GNU @code{m4} earlier than 1.6 used
9225 LIFO order.  Furthermore, POSIX states that only the first
9226 argument to @code{m4wrap} is saved for later evaluation, but
9227 GNU @code{m4} saves and processes all arguments, with output
9228 separated by spaces.
9230 @item
9231 POSIX states that builtins that require arguments, but are
9232 called without arguments, have undefined behavior.  Traditional
9233 implementations simply behave as though empty strings had been passed.
9234 For example, @code{a`'define`'b} would expand to @code{ab}.  But
9235 GNU @code{m4} ignores certain builtins if they have missing
9236 arguments, giving @code{adefineb} for the above example.
9237 @end itemize
9239 @node Incompatibilities
9240 @section Other incompatibilities
9242 There are a few other incompatibilities between this implementation of
9243 @code{m4}, and what POSIX requires, or what the System V
9244 version implemented.
9246 @itemize @bullet
9247 @item
9248 Traditional implementations handle @code{define(`f',`1')} (@pxref{Define})
9249 by undefining the entire stack of previous definitions, and if doing
9250 @code{undefine(`f')} first.  GNU @code{m4} replaces just the top
9251 definition on the stack, as if doing @code{popdef(`f')} followed by
9252 @code{pushdef(`f',`1')}.  POSIX allows either behavior.
9254 @item
9255 At one point, POSIX required @code{changequote(@var{arg})}
9256 (@pxref{Changequote}) to use newline as the close quote, but this was a
9257 bug, and the next version of POSIX is anticipated to state
9258 that using empty strings or just one argument is unspecified.
9259 Meanwhile, the GNU @code{m4} behavior of treating an empty
9260 end-quote delimiter as @samp{'} is not portable, as Solaris treats it as
9261 repeating the start-quote delimiter, and BSD treats it as leaving the
9262 previous end-quote delimiter unchanged.  For predictable results, never
9263 call changequote with just one argument, or with empty strings for
9264 arguments.
9266 @item
9267 At one point, POSIX required @code{changecom(@var{arg},)}
9268 (@pxref{Changecom}) to make it impossible to end a comment, but this is
9269 a bug, and the next version of POSIX is anticipated to state
9270 that using empty strings is unspecified.  Meanwhile, the GNU
9271 @code{m4} behavior of treating an empty end-comment delimiter as newline
9272 is not portable, as BSD treats it as leaving the previous end-comment
9273 delimiter unchanged.  It is also impossible in BSD implementations to
9274 disable comments, even though that is required by POSIX.  For
9275 predictable results, never call changecom with empty strings for
9276 arguments.
9278 @item
9279 Traditional implementations allow argument collection, but not string
9280 and comment processing, to span file boundaries.  Thus, if @file{a.m4}
9281 contains @samp{len(}, and @file{b.m4} contains @samp{abc)},
9282 @kbd{m4 a.m4 b.m4} outputs @samp{3} with traditional @code{m4}, but
9283 gives an error message that the end of file was encountered inside a
9284 macro with GNU @code{m4}.  On the other hand, traditional
9285 implementations do end of file processing for files included with
9286 @code{include} or @code{sinclude} (@pxref{Include}), while GNU
9287 @code{m4} seamlessly integrates the content of those files.  Thus
9288 @code{include(`a.m4')include(`b.m4')} will output @samp{3} instead of
9289 giving an error.
9291 @item
9292 POSIX requires @code{eval} (@pxref{Eval}) to treat all
9293 operators with the same precedence as C@.  However, earlier versions of
9294 GNU @code{m4} followed the traditional behavior of other
9295 @code{m4} implementations, where bitwise and logical negation (@samp{~}
9296 and @samp{!}) have lower precedence than equality operators; and where
9297 equality operators (@samp{==} and @samp{!=}) had the same precedence as
9298 relational operators (such as @samp{<}).  Use explicit parentheses to
9299 ensure proper precedence.  As extensions to POSIX,
9300 GNU @code{m4} gives well-defined semantics to operations that
9301 C leaves undefined, such as when overflow occurs, when shifting negative
9302 numbers, or when performing division by zero.  POSIX also
9303 requires @samp{=} to cause an error, but many traditional
9304 implementations allowed it as an alias for @samp{==}.
9306 @item
9307 POSIX 2001 requires @code{translit} (@pxref{Translit}) to
9308 treat each character of the second and third arguments literally.
9309 However, it is anticipated that the next version of POSIX will
9310 allow the GNU @code{m4} behavior of treating @samp{-} as a
9311 range operator.
9313 @item
9314 POSIX requires @code{m4} to honor the locale environment
9315 variables of @env{LANG}, @env{LC_ALL}, @env{LC_CTYPE},
9316 @env{LC_MESSAGES}, and @env{NLSPATH}, but this has not yet been
9317 implemented in GNU @code{m4}.
9319 @item
9320 GNU @code{m4} implements sync lines differently from System V
9321 @code{m4}, when text is being diverted.  GNU @code{m4} outputs
9322 the sync lines when the text is being diverted, and System V @code{m4}
9323 when the diverted text is being brought back.
9325 The problem is which lines and file names should be attached to text
9326 that is being, or has been, diverted.  System V @code{m4} regards all
9327 the diverted text as being generated by the source line containing the
9328 @code{undivert} call, whereas GNU @code{m4} regards the
9329 diverted text as being generated at the time it is diverted.
9331 The sync line option is used mostly when using @code{m4} as
9332 a front end to a compiler.  If a diverted line causes a compiler error,
9333 the error messages should most probably refer to the place where the
9334 diversion was made, and not where it was inserted again.
9336 @comment options: -s
9337 @example
9338 divert(2)2
9339 divert(1)1
9340 divert`'0
9341 @result{}#line 3 "stdin"
9342 @result{}0
9344 @result{}#line 2 "stdin"
9345 @result{}1
9346 @result{}#line 1 "stdin"
9347 @result{}2
9348 @end example
9350 @comment FIXME - this needs to be fixed before 2.0.
9351 The current @code{m4} implementation has a limitation that the syncline
9352 output at the start of each diversion occurs no matter what, even if the
9353 previous diversion did not end with a newline.  This goes contrary to
9354 the claim that synclines appear on a line by themselves, so this
9355 limitation may be corrected in a future version of @code{m4}.  In the
9356 meantime, when using @option{-s}, it is wisest to make sure all
9357 diversions end with newline.
9359 @item
9360 GNU @code{m4} makes no attempt at prohibiting self-referential
9361 definitions like:
9363 @comment ignore
9364 @example
9365 define(`x', `x')
9366 @result{}
9367 define(`x', `x ')
9368 @result{}
9369 @end example
9371 @cindex rescanning
9372 There is nothing inherently wrong with defining @samp{x} to
9373 return @samp{x}.  The wrong thing is to expand @samp{x} unquoted,
9374 because that would cause an infinite rescan loop.
9375 In @code{m4}, one might use macros to hold strings, as we do for
9376 variables in other programming languages, further checking them with:
9378 @comment ignore
9379 @example
9380 ifelse(defn(`@var{holder}'), `@var{value}', @dots{})
9381 @end example
9383 @noindent
9384 In cases like this one, an interdiction for a macro to hold its own name
9385 would be a useless limitation.  Of course, this leaves more rope for the
9386 GNU @code{m4} user to hang himself!  Rescanning hangs may be
9387 avoided through careful programming, a little like for endless loops in
9388 traditional programming languages.
9390 @item
9391 POSIX states that only unquoted leading newlines and blanks
9392 (that is, space and tab) are ignored when collecting macro arguments.
9393 However, this appears to be a bug in POSIX, since most
9394 traditional implementations also ignore all whitespace (formfeed,
9395 carriage return, and vertical tab).  GNU @code{m4} follows
9396 tradition and ignores all leading unquoted whitespace.
9397 @end itemize
9399 @node Experiments
9400 @section Experimental features in GNU M4
9402 Certain features of GNU @code{m4} are experimental.
9404 Some are only available if activated by an option given to
9405 @file{m4-@value{VERSION}/@/configure} at GNU @code{m4} installation
9406 time.  The functionality
9407 might change or even go away in the future.  @emph{Do not rely on it}.
9408 Please direct your comments about it the same way you would do for bugs.
9410 @section Changesyntax
9412 An experimental feature, which improves the flexibility of @code{m4},
9413 allows for changing the way the input is parsed (@pxref{Changesyntax}).
9414 No compile time option is needed for @code{changesyntax}.  The
9415 implementation is careful to not slow down @code{m4} parsing, unlike the
9416 withdrawn experiment of @code{changeword} that appeared earlier in M4
9417 1.4.x.
9419 @section Multiple precision arithmetic
9421 Another experimental feature, which would improve @code{m4} usefulness,
9422 allows for multiple precision rational arithmetic similar to
9423 @code{eval}.  You must have the GNU multi-precision (gmp)
9424 library installed, and should use @kbd{./configure --with-gmp} if you
9425 want this feature compiled in.  The current implementation is unproven
9426 and might go away.  Do not count on it yet.
9428 @node Answers
9429 @chapter Correct version of some examples
9431 Some of the examples in this manuals are buggy or not very robust, for
9432 demonstration purposes.  Improved versions of these composite macros are
9433 presented here.
9435 @menu
9436 * Improved exch::               Solution for @code{exch}
9437 * Improved forloop::            Solution for @code{forloop}
9438 * Improved foreach::            Solution for @code{foreach}
9439 * Improved copy::               Solution for @code{copy}
9440 * Improved m4wrap::             Solution for @code{m4wrap}
9441 * Improved cleardivert::        Solution for @code{cleardivert}
9442 * Improved capitalize::         Solution for @code{capitalize}
9443 * Improved fatal_error::        Solution for @code{fatal_error}
9444 @end menu
9446 @node Improved exch
9447 @section Solution for @code{exch}
9449 The @code{exch} macro (@pxref{Arguments}) as presented requires clients
9450 to double quote their arguments.  A nicer definition, which lets
9451 clients follow the rule of thumb of one level of quoting per level of
9452 parentheses, involves adding quotes in the definition of @code{exch}, as
9453 follows:
9455 @example
9456 define(`exch', ``$2', `$1'')
9457 @result{}
9458 define(exch(`expansion text', `macro'))
9459 @result{}
9460 macro
9461 @result{}expansion text
9462 @end example
9464 @node Improved forloop
9465 @section Solution for @code{forloop}
9467 The @code{forloop} macro (@pxref{Forloop}) as presented earlier can go
9468 into an infinite loop if given an iterator that is not parsed as a macro
9469 name.  It does not do any sanity checking on its numeric bounds, and
9470 only permits decimal numbers for bounds.  Here is an improved version,
9471 shipped as @file{m4-@value{VERSION}/@/examples/@/forloop2.m4}; this
9472 version also optimizes overhead by calling four macros instead of six
9473 per iteration (excluding those in @var{text}), by not dereferencing the
9474 @var{iterator} in the helper @code{@w{_forloop}}.
9476 @comment examples
9477 @example
9478 $ @kbd{m4 -I examples}
9479 undivert(`forloop2.m4')dnl
9480 @result{}divert(`-1')
9481 @result{}# forloop(var, from, to, stmt) - improved version:
9482 @result{}#   works even if VAR is not a strict macro name
9483 @result{}#   performs sanity check that FROM is larger than TO
9484 @result{}#   allows complex numerical expressions in TO and FROM
9485 @result{}define(`forloop', `ifelse(eval(`($2) <= ($3)'), `1',
9486 @result{}  `pushdef(`$1')_$0(`$1', eval(`$2'),
9487 @result{}    eval(`$3'), `$4')popdef(`$1')')')
9488 @result{}define(`_forloop',
9489 @result{}  `define(`$1', `$2')$4`'ifelse(`$2', `$3', `',
9490 @result{}    `$0(`$1', incr(`$2'), `$3', `$4')')')
9491 @result{}divert`'dnl
9492 include(`forloop2.m4')
9493 @result{}
9494 forloop(`i', `2', `1', `no iteration occurs')
9495 @result{}
9496 forloop(`', `1', `2', ` odd iterator name')
9497 @result{} odd iterator name odd iterator name
9498 forloop(`i', `5 + 5', `0xc', ` 0x`'eval(i, `16')')
9499 @result{} 0xa 0xb 0xc
9500 forloop(`i', `a', `b', `non-numeric bounds')
9501 @error{}m4:stdin:6: warning: eval: bad input: '(a) <= (b)'
9502 @result{}
9503 @end example
9505 One other change to notice is that the improved version used @samp{_$0}
9506 rather than @samp{_foreach} to invoke the helper routine.  In general,
9507 this is a good practice to follow, because then the set of macros can be
9508 uniformly transformed.  The following example shows a transformation
9509 that doubles the current quoting and appends a suffix @samp{2} to each
9510 transformed macro.  If @code{foreach} refers to the literal
9511 @samp{_foreach}, then @code{foreach2} invokes @code{_foreach} instead of
9512 the intended @code{_foreach2}, and the mixing of quoting paradigms leads
9513 to an infinite recursion loop in this example.
9515 @comment options: -L9
9516 @comment status: 1
9517 @comment examples
9518 @example
9519 $ @kbd{m4 -d -L 9 -I examples}
9520 define(`arg1', `$1')include(`forloop2.m4')include(`quote.m4')
9521 @result{}
9522 define(`double', `define(`$1'`2',
9523   arg1(patsubst(dquote(defn(`$1')), `[`']', `\&\&')))')
9524 @result{}
9525 double(`forloop')double(`_forloop')defn(`forloop2')
9526 @result{}ifelse(eval(``($2) <= ($3)''), ``1'',
9527 @result{}  ``pushdef(``$1'')_$0(``$1'', eval(``$2''),
9528 @result{}    eval(``$3''), ``$4'')popdef(``$1'')'')
9529 forloop(i, 1, 5, `ifelse(')forloop(i, 1, 5, `)')
9530 @result{}
9531 changequote(`[', `]')changequote([``], [''])
9532 @result{}
9533 forloop2(i, 1, 5, ``ifelse('')forloop2(i, 1, 5, ``)'')
9534 @result{}
9535 changequote`'include(`forloop.m4')
9536 @result{}
9537 double(`forloop')double(`_forloop')defn(`forloop2')
9538 @result{}pushdef(``$1'', ``$2'')_forloop($@@)popdef(``$1'')
9539 forloop(i, 1, 5, `ifelse(')forloop(i, 1, 5, `)')
9540 @result{}
9541 changequote(`[', `]')changequote([``], [''])
9542 @result{}
9543 forloop2(i, 1, 5, ``ifelse('')forloop2(i, 1, 5, ``)'')
9544 @error{}m4:stdin:12: recursion limit of 9 exceeded, use -L<N> to change it
9545 @end example
9547 One more optimization is still possible.  Instead of repeatedly
9548 assigning a variable then invoking or dereferencing it, it is possible
9549 to pass the current iterator value as a single argument.  Coupled with
9550 @code{curry} if other arguments are needed (@pxref{Composition}), or
9551 with helper macros if the argument is needed in more than one place in
9552 the expansion, the output can be generated with three, rather than four,
9553 macros of overhead per iteration.  Notice how the file
9554 @file{m4-@value{VERSION}/@/examples/@/forloop3.m4} rearranges the
9555 arguments of the helper @code{_forloop} to take two arguments that are
9556 placed around the current value.  By splitting a balanced set of
9557 parantheses across multiple arguments, the helper macro can now be
9558 shared by @code{forloop} and the new @code{forloop_arg}.
9560 @comment examples
9561 @example
9562 $ @kbd{m4 -I examples}
9563 include(`forloop3.m4')
9564 @result{}
9565 undivert(`forloop3.m4')dnl
9566 @result{}divert(`-1')
9567 @result{}# forloop_arg(from, to, macro) - invoke MACRO(value) for
9568 @result{}#   each value between FROM and TO, without define overhead
9569 @result{}define(`forloop_arg', `ifelse(eval(`($1) <= ($2)'), `1',
9570 @result{}  `_forloop(`$1', eval(`$2'), `$3(', `)')')')
9571 @result{}# forloop(var, from, to, stmt) - refactored to share code
9572 @result{}define(`forloop', `ifelse(eval(`($2) <= ($3)'), `1',
9573 @result{}  `pushdef(`$1')_forloop(eval(`$2'), eval(`$3'),
9574 @result{}    `define(`$1',', `)$4')popdef(`$1')')')
9575 @result{}define(`_forloop',
9576 @result{}  `$3`$1'$4`'ifelse(`$1', `$2', `',
9577 @result{}    `$0(incr(`$1'), `$2', `$3', `$4')')')
9578 @result{}divert`'dnl
9579 forloop(`i', `1', `3', ` i')
9580 @result{} 1 2 3
9581 define(`echo', `$@@')
9582 @result{}
9583 forloop_arg(`1', `3', ` echo')
9584 @result{} 1 2 3
9585 include(`curry.m4')
9586 @result{}
9587 forloop_arg(`1', `3', `curry(`pushdef', `a')')
9588 @result{}
9590 @result{}3
9591 popdef(`a')a
9592 @result{}2
9593 popdef(`a')a
9594 @result{}1
9595 popdef(`a')a
9596 @result{}a
9597 @end example
9599 Of course, it is possible to make even more improvements, such as
9600 adding an optional step argument, or allowing iteration through
9601 descending sequences.  GNU Autoconf provides some of these
9602 additional bells and whistles in its @code{m4_for} macro.
9604 @node Improved foreach
9605 @section Solution for @code{foreach}
9607 The @code{foreach} and @code{foreachq} macros (@pxref{Foreach}) as
9608 presented earlier each have flaws.  First, we will examine and fix the
9609 quadratic behavior of @code{foreachq}:
9611 @comment examples
9612 @example
9613 $ @kbd{m4 -I examples}
9614 include(`foreachq.m4')
9615 @result{}
9616 traceon(`shift')debugmode(`aq')
9617 @result{}
9618 foreachq(`x', ``1', `2', `3', `4'', `x
9619 ')dnl
9620 @result{}1
9621 @error{}m4trace: -3- shift(`1', `2', `3', `4')
9622 @error{}m4trace: -2- shift(`1', `2', `3', `4')
9623 @result{}2
9624 @error{}m4trace: -4- shift(`1', `2', `3', `4')
9625 @error{}m4trace: -3- shift(`2', `3', `4')
9626 @error{}m4trace: -3- shift(`1', `2', `3', `4')
9627 @error{}m4trace: -2- shift(`2', `3', `4')
9628 @result{}3
9629 @error{}m4trace: -5- shift(`1', `2', `3', `4')
9630 @error{}m4trace: -4- shift(`2', `3', `4')
9631 @error{}m4trace: -3- shift(`3', `4')
9632 @error{}m4trace: -4- shift(`1', `2', `3', `4')
9633 @error{}m4trace: -3- shift(`2', `3', `4')
9634 @error{}m4trace: -2- shift(`3', `4')
9635 @result{}4
9636 @error{}m4trace: -6- shift(`1', `2', `3', `4')
9637 @error{}m4trace: -5- shift(`2', `3', `4')
9638 @error{}m4trace: -4- shift(`3', `4')
9639 @error{}m4trace: -3- shift(`4')
9640 @end example
9642 @cindex quadratic behavior, avoiding
9643 @cindex avoiding quadratic behavior
9644 Each successive iteration was adding more quoted @code{shift}
9645 invocations, and the entire list contents were passing through every
9646 iteration.  In general, when recursing, it is a good idea to make the
9647 recursion use fewer arguments, rather than adding additional quoted
9648 uses of @code{shift}.  By doing so, @code{m4} uses less memory, invokes
9649 fewer macros, is less likely to run into machine limits, and most
9650 importantly, performs faster.  The fixed version of @code{foreachq} can
9651 be found in @file{m4-@value{VERSION}/@/examples/@/foreachq2.m4}:
9653 @comment examples
9654 @example
9655 $ @kbd{m4 -I examples}
9656 include(`foreachq2.m4')
9657 @result{}
9658 undivert(`foreachq2.m4')dnl
9659 @result{}include(`quote.m4')dnl
9660 @result{}divert(`-1')
9661 @result{}# foreachq(x, `item_1, item_2, ..., item_n', stmt)
9662 @result{}#   quoted list, improved version
9663 @result{}define(`foreachq', `pushdef(`$1')_$0($@@)popdef(`$1')')
9664 @result{}define(`_arg1q', ``$1'')
9665 @result{}define(`_rest', `ifelse(`$#', `1', `', `dquote(shift($@@))')')
9666 @result{}define(`_foreachq', `ifelse(`$2', `', `',
9667 @result{}  `define(`$1', _arg1q($2))$3`'$0(`$1', _rest($2), `$3')')')
9668 @result{}divert`'dnl
9669 traceon(`shift')debugmode(`aq')
9670 @result{}
9671 foreachq(`x', ``1', `2', `3', `4'', `x
9672 ')dnl
9673 @result{}1
9674 @error{}m4trace: -3- shift(`1', `2', `3', `4')
9675 @result{}2
9676 @error{}m4trace: -3- shift(`2', `3', `4')
9677 @result{}3
9678 @error{}m4trace: -3- shift(`3', `4')
9679 @result{}4
9680 @end example
9682 Note that the fixed version calls unquoted helper macros in
9683 @code{@w{_foreachq}} to trim elements immediately; those helper macros
9684 in turn must re-supply the layer of quotes lost in the macro invocation.
9685 Contrast the use of @code{@w{_arg1q}}, which quotes the first list
9686 element, with @code{@w{_arg1}} of the earlier implementation that
9687 returned the first list element directly.  Additionally, by calling the
9688 helper method immediately, the @samp{defn(`@var{iterator}')} no longer
9689 contains unexpanded macros.
9691 The astute m4 programmer might notice that the solution above still uses
9692 more macro invocations than strictly necessary.  Note that @samp{$2},
9693 which contains an arbitrarily long quoted list, is expanded and
9694 rescanned three times per iteration of @code{_foreachq}.  Furthermore,
9695 every iteration of the algorithm effectively unboxes then reboxes the
9696 list, which costs a couple of macro invocations.  It is possible to
9697 rewrite the algorithm by swapping the order of the arguments to
9698 @code{_foreachq} in order to operate on an unboxed list in the first
9699 place, and by using the fixed-length @samp{$#} instead of an arbitrary
9700 length list as the key to end recursion.  The result is an overhead of
9701 six macro invocations per loop (excluding any macros in @var{text}),
9702 instead of eight.  This alternative approach is available as
9703 @file{m4-@value{VERSION}/@/examples/@/foreach3.m4}:
9705 @comment examples
9706 @example
9707 $ @kbd{m4 -I examples}
9708 include(`foreachq3.m4')
9709 @result{}
9710 undivert(`foreachq3.m4')dnl
9711 @result{}divert(`-1')
9712 @result{}# foreachq(x, `item_1, item_2, ..., item_n', stmt)
9713 @result{}#   quoted list, alternate improved version
9714 @result{}define(`foreachq', `ifelse(`$2', `', `',
9715 @result{}  `pushdef(`$1')_$0(`$1', `$3', `', $2)popdef(`$1')')')
9716 @result{}define(`_foreachq', `ifelse(`$#', `3', `',
9717 @result{}  `define(`$1', `$4')$2`'$0(`$1', `$2',
9718 @result{}    shift(shift(shift($@@))))')')
9719 @result{}divert`'dnl
9720 traceon(`shift')debugmode(`aq')
9721 @result{}
9722 foreachq(`x', ``1', `2', `3', `4'', `x
9723 ')dnl
9724 @result{}1
9725 @error{}m4trace: -4- shift(`x', `x
9726 @error{}', `', `1', `2', `3', `4')
9727 @error{}m4trace: -3- shift(`x
9728 @error{}', `', `1', `2', `3', `4')
9729 @error{}m4trace: -2- shift(`', `1', `2', `3', `4')
9730 @result{}2
9731 @error{}m4trace: -4- shift(`x', `x
9732 @error{}', `1', `2', `3', `4')
9733 @error{}m4trace: -3- shift(`x
9734 @error{}', `1', `2', `3', `4')
9735 @error{}m4trace: -2- shift(`1', `2', `3', `4')
9736 @result{}3
9737 @error{}m4trace: -4- shift(`x', `x
9738 @error{}', `2', `3', `4')
9739 @error{}m4trace: -3- shift(`x
9740 @error{}', `2', `3', `4')
9741 @error{}m4trace: -2- shift(`2', `3', `4')
9742 @result{}4
9743 @error{}m4trace: -4- shift(`x', `x
9744 @error{}', `3', `4')
9745 @error{}m4trace: -3- shift(`x
9746 @error{}', `3', `4')
9747 @error{}m4trace: -2- shift(`3', `4')
9748 @end example
9750 Prior to M4 1.6, every instance of @samp{$@@} was rescanned as it was
9751 encountered.  Thus, the @file{foreachq3.m4} alternative used much less
9752 memory than @file{foreachq2.m4}, and executed as much as 10% faster,
9753 since each iteration encountered fewer @samp{$@@}.  However, the
9754 implementation of rescanning every byte in @samp{$@@} was quadratic in
9755 the number of bytes scanned (for example, making the broken version in
9756 @file{foreachq.m4} cubic, rather than quadratic, in behavior).  Once the
9757 underlying M4 implementation was improved in 1.6 to reuse results of
9758 previous scans, both styles of @code{foreachq} become linear in the
9759 number of bytes scanned, but the @file{foreachq3.m4} version remains
9760 noticeably faster because of fewer macro invocations.  Notice how the
9761 implementation injects an empty argument prior to expanding @samp{$2}
9762 within @code{foreachq}; the helper macro @code{_foreachq} then ignores
9763 the third argument altogether, and ends recursion when there are three
9764 arguments left because there was nothing left to pass through
9765 @code{shift}.  Thus, each iteration only needs one @code{ifelse}, rather
9766 than the two conditionals used in the version from @file{foreachq2.m4}.
9768 @cindex nine arguments, more than
9769 @cindex more than nine arguments
9770 @cindex arguments, more than nine
9771 So far, all of the implementations of @code{foreachq} presented have
9772 been quadratic with M4 1.4.x.  But @code{forloop} is linear, because
9773 each iteration parses a constant amount of arguments.  So, it is
9774 possible to design a variant that uses @code{forloop} to do the
9775 iteration, then uses @samp{$@@} only once at the end, giving a linear
9776 result even with older M4 implementations.  This implementation relies
9777 on the GNU extension that @samp{$10} expands to the tenth
9778 argument rather than the first argument concatenated with @samp{0}.  The
9779 trick is to define an intermediate macro that repeats the text
9780 @code{m4_define(`$1', `$@var{n}')$2`'}, with @samp{n} set to successive
9781 integers corresponding to each argument.  The helper macro
9782 @code{_foreachq_} is needed in order to generate the literal sequences
9783 such as @samp{$1} into the intermediate macro, rather than expanding
9784 them as the arguments of @code{_foreachq}.  With this approach, no
9785 @code{shift} calls are even needed!  However, when linear recursion is
9786 available in new enough M4, the time and memory cost of using
9787 @code{forloop} to build an intermediate macro outweigh the costs of any
9788 of the previous implementations (there are seven macros of overhead per
9789 iteration instead of six in @file{foreachq3.m4}, and the entire
9790 intermediate macro must be built in memory before any iteration is
9791 expanded).  Additionally, this approach will need adjustment when a
9792 future version of M4 follows POSIX by no longer treating
9793 @samp{$10} as the tenth argument; the anticipation is that
9794 @samp{$@{10@}} can be used instead, although that alternative syntax is
9795 not yet supported.
9797 @comment examples
9798 @example
9799 $ @kbd{m4 -I examples}
9800 include(`foreachq4.m4')
9801 @result{}
9802 undivert(`foreachq4.m4')dnl
9803 @result{}include(`forloop2.m4')dnl
9804 @result{}divert(`-1')
9805 @result{}# foreachq(x, `item_1, item_2, ..., item_n', stmt)
9806 @result{}#   quoted list, version based on forloop
9807 @result{}define(`foreachq',
9808 @result{}`ifelse(`$2', `', `', `_$0(`$1', `$3', $2)')')
9809 @result{}define(`_foreachq',
9810 @result{}`pushdef(`$1', forloop(`$1', `3', `$#',
9811 @result{}  `$0_(`1', `2', indir(`$1'))')`popdef(
9812 @result{}    `$1')')indir(`$1', $@@)')
9813 @result{}define(`_foreachq_',
9814 @result{}``define(`$$1', `$$3')$$2`''')
9815 @result{}divert`'dnl
9816 traceon(`shift')debugmode(`aq')
9817 @result{}
9818 foreachq(`x', ``1', `2', `3', `4'', `x
9819 ')dnl
9820 @result{}1
9821 @result{}2
9822 @result{}3
9823 @result{}4
9824 @end example
9826 For yet another approach, the improved version of @code{foreach},
9827 available in @file{m4-@value{VERSION}/@/examples/@/foreach2.m4}, simply
9828 overquotes the arguments to @code{@w{_foreach}} to begin with, using
9829 @code{dquote_elt}.  Then @code{@w{_foreach}} can just use
9830 @code{@w{_arg1}} to remove the extra layer of quoting that was added up
9831 front:
9833 @comment examples
9834 @example
9835 $ @kbd{m4 -I examples}
9836 include(`foreach2.m4')
9837 @result{}
9838 undivert(`foreach2.m4')dnl
9839 @result{}include(`quote.m4')dnl
9840 @result{}divert(`-1')
9841 @result{}# foreach(x, (item_1, item_2, ..., item_n), stmt)
9842 @result{}#   parenthesized list, improved version
9843 @result{}define(`foreach', `pushdef(`$1')_$0(`$1',
9844 @result{}  (dquote(dquote_elt$2)), `$3')popdef(`$1')')
9845 @result{}define(`_arg1', `$1')
9846 @result{}define(`_foreach', `ifelse(`$2', `(`')', `',
9847 @result{}  `define(`$1', _arg1$2)$3`'$0(`$1', (dquote(shift$2)), `$3')')')
9848 @result{}divert`'dnl
9849 traceon(`shift')debugmode(`aq')
9850 @result{}
9851 foreach(`x', `(`1', `2', `3', `4')', `x
9852 ')dnl
9853 @error{}m4trace: -4- shift(`1', `2', `3', `4')
9854 @error{}m4trace: -4- shift(`2', `3', `4')
9855 @error{}m4trace: -4- shift(`3', `4')
9856 @result{}1
9857 @error{}m4trace: -3- shift(``1'', ``2'', ``3'', ``4'')
9858 @result{}2
9859 @error{}m4trace: -3- shift(``2'', ``3'', ``4'')
9860 @result{}3
9861 @error{}m4trace: -3- shift(``3'', ``4'')
9862 @result{}4
9863 @error{}m4trace: -3- shift(``4'')
9864 @end example
9866 It is likewise possible to write a variant of @code{foreach} that
9867 performs in linear time on M4 1.4.x; the easiest method is probably
9868 writing a version of @code{foreach} that unboxes its list, then invokes
9869 @code{_foreachq} as previously defined in @file{foreachq4.m4}.
9871 @cindex filtering defined symbols
9872 @cindex subset of defined symbols
9873 @cindex defined symbols, filtering
9874 With a robust @code{foreachq} implementation, it is possible to create a
9875 filter on a list of defined symbols.  This next example will find all
9876 symbols that contain @samp{if} or @samp{def}, via two different
9877 approaches.  In the first approach, @code{dquote_elt} is used to
9878 overquote each list element, then @code{dquote} forms the list; that
9879 way, the iterator @code{macro} can be expanded in place because its
9880 contents are already quoted.  This approach also uses a self-modifying
9881 macro @code{sep} to provide the correct number of commas.  In the second
9882 approach, the iterator @code{macro} contains live text, so it must be
9883 used with @code{defn} to avoid unintentional expansion.  The correct
9884 number of commas is achieved by using @code{shift} to ignore the first
9885 one, although a leading space still remains.
9887 @comment examples
9888 @example
9889 $ @kbd{m4 -I examples}
9890 include(`quote.m4')include(`foreachq2.m4')
9891 @result{}
9892 pushdef(`sep', `define(`sep', ``, '')')
9893 @result{}
9894 foreachq(`macro', dquote(dquote_elt(m4symbols)),
9895   `regexp(macro, `.*if.*', `sep`\&'')')
9896 @result{}ifdef, ifelse, shift
9897 popdef(`sep')
9898 @result{}
9899 shift(foreachq(`macro', dquote(m4symbols),
9900   `regexp(defn(`macro'), `def', `,` ''dquote(defn(`macro')))'))
9901 @result{} define, defn, dumpdef, ifdef, popdef, pushdef, undefine
9902 @end example
9904 In summary, recursion over list elements is trickier than it appeared at
9905 first glance, but provides a powerful idiom within @code{m4} processing.
9906 As a final demonstration, both list styles are now able to handle
9907 several scenarios that would wreak havoc on one or both of the original
9908 implementations.  This points out one other difference between the
9909 list styles.  @code{foreach} evaluates unquoted list elements only once,
9910 in preparation for calling @code{@w{_foreach}}, similary for
9911 @code{foreachq} as provided by @file{foreachq3.m4} or
9912 @file{foreachq4.m4}.  But
9913 @code{foreachq}, as provided by @file{foreachq2.m4},
9914 evaluates unquoted list elements twice while visiting the first list
9915 element, once in @code{@w{_arg1q}} and once in @code{@w{_rest}}.  When
9916 deciding which list style to use, one must take into account whether
9917 repeating the side effects of unquoted list elements will have any
9918 detrimental effects.
9920 @comment examples
9921 @example
9922 $ @kbd{m4 -d -I examples}
9923 include(`foreach2.m4')
9924 @result{}
9925 include(`foreachq2.m4')
9926 @result{}
9927 dnl 0-element list:
9928 foreach(`x', `', `<x>') / foreachq(`x', `', `<x>')
9929 @result{} /@w{ }
9930 dnl 1-element list of empty element
9931 foreach(`x', `()', `<x>') / foreachq(`x', ``'', `<x>')
9932 @result{}<> / <>
9933 dnl 2-element list of empty elements
9934 foreach(`x', `(`',`')', `<x>') / foreachq(`x', ``',`'', `<x>')
9935 @result{}<><> / <><>
9936 dnl 1-element list of a comma
9937 foreach(`x', `(`,')', `<x>') / foreachq(`x', ``,'', `<x>')
9938 @result{}<,> / <,>
9939 dnl 2-element list of unbalanced parentheses
9940 foreach(`x', `(`(', `)')', `<x>') / foreachq(`x', ``(', `)'', `<x>')
9941 @result{}<(><)> / <(><)>
9942 define(`ab', `oops')dnl using defn(`iterator')
9943 foreach(`x', `(`a', `b')', `defn(`x')') /dnl
9944  foreachq(`x', ``a', `b'', `defn(`x')')
9945 @result{}ab / ab
9946 define(`active', `ACT, IVE')
9947 @result{}
9948 traceon(`active')
9949 @result{}
9950 dnl list of unquoted macros; expansion occurs before recursion
9951 foreach(`x', `(active, active)', `<x>
9952 ')dnl
9953 @error{}m4trace: -4- active -> `ACT, IVE'
9954 @error{}m4trace: -4- active -> `ACT, IVE'
9955 @result{}<ACT>
9956 @result{}<IVE>
9957 @result{}<ACT>
9958 @result{}<IVE>
9959 foreachq(`x', `active, active', `<x>
9960 ')dnl
9961 @error{}m4trace: -3- active -> `ACT, IVE'
9962 @error{}m4trace: -3- active -> `ACT, IVE'
9963 @result{}<ACT>
9964 @error{}m4trace: -3- active -> `ACT, IVE'
9965 @error{}m4trace: -3- active -> `ACT, IVE'
9966 @result{}<IVE>
9967 @result{}<ACT>
9968 @result{}<IVE>
9969 dnl list of quoted macros; expansion occurs during recursion
9970 foreach(`x', `(`active', `active')', `<x>
9971 ')dnl
9972 @error{}m4trace: -1- active -> `ACT, IVE'
9973 @result{}<ACT, IVE>
9974 @error{}m4trace: -1- active -> `ACT, IVE'
9975 @result{}<ACT, IVE>
9976 foreachq(`x', ``active', `active'', `<x>
9977 ')dnl
9978 @error{}m4trace: -1- active -> `ACT, IVE'
9979 @result{}<ACT, IVE>
9980 @error{}m4trace: -1- active -> `ACT, IVE'
9981 @result{}<ACT, IVE>
9982 dnl list of double-quoted macro names; no expansion
9983 foreach(`x', `(``active'', ``active'')', `<x>
9984 ')dnl
9985 @result{}<active>
9986 @result{}<active>
9987 foreachq(`x', ```active'', ``active''', `<x>
9988 ')dnl
9989 @result{}<active>
9990 @result{}<active>
9991 @end example
9993 @node Improved copy
9994 @section Solution for @code{copy}
9996 The macro @code{copy} presented above works with M4 1.6 and newer, but
9997 is unable to handle builtin tokens with M4 1.4.x, because it tries to
9998 pass the builtin token through the macro @code{curry}, where it is
9999 silently flattened to an empty string (@pxref{Composition}).  Rather
10000 than using the problematic @code{curry} to work around the limitation
10001 that @code{stack_foreach} expects to invoke a macro that takes exactly
10002 one argument, we can write a new macro that lets us form the exact
10003 two-argument @code{pushdef} call sequence needed, so that we are no
10004 longer passing a builtin token through a text macro.
10006 @deffn Composite stack_foreach_sep (@var{macro}, @var{pre}, @var{post}, @
10007   @var{sep})
10008 @deffnx Composite stack_foreach_sep_lifo (@var{macro}, @var{pre}, @
10009   @var{post}, @var{sep})
10010 For each of the @code{pushdef} definitions associated with @var{macro},
10011 expand the sequence @samp{@var{pre}`'definition`'@var{post}}.
10012 Additionally, expand @var{sep} between definitions.
10013 @code{stack_foreach_sep} visits the oldest definition first, while
10014 @code{stack_foreach_sep_lifo} visits the current definition first.  The
10015 expansion may dereference @var{macro}, but should not modify it.  There
10016 are a few special macros, such as @code{defn}, which cannot be used as
10017 the @var{macro} parameter.
10018 @end deffn
10020 Note that @code{stack_foreach(`@var{macro}', `@var{action}')} is
10021 equivalent to @code{stack_foreach_sep(`@var{macro}', `@var{action}(',
10022 `)')}.  By supplying explicit parentheses, split among the @var{pre} and
10023 @var{post} arguments to @code{stack_foreach_sep}, it is now possible to
10024 construct macro calls with more than one argument, without passing
10025 builtin tokens through a macro call.  It is likewise possible to
10026 directly reference the stack definitions without a macro call, by
10027 leaving @var{pre} and @var{post} empty.  Thus, in addition to fixing
10028 @code{copy} on builtin tokens, it also executes with fewer macro
10029 invocations.
10031 The new macro also adds a separator that is only output after the first
10032 iteration of the helper @code{_stack_reverse_sep}, implemented by
10033 prepending the original @var{sep} to @var{pre} and omitting a @var{sep}
10034 argument in subsequent iterations.  Note that the empty string that
10035 separates @var{sep} from @var{pre} is provided as part of the fourth
10036 argument when originally calling @code{_stack_reverse_sep}, and not by
10037 writing @code{$4`'$3} as the third argument in the recursive call; while
10038 the other approach would give the same output, it does so at the expense
10039 of increasing the argument size on each iteration of
10040 @code{_stack_reverse_sep}, which results in quadratic instead of linear
10041 execution time.  The improved stack walking macros are available in
10042 @file{m4-@value{VERSION}/@/examples/@/stack_sep.m4}:
10044 @comment examples
10045 @example
10046 $ @kbd{m4 -I examples}
10047 include(`stack_sep.m4')
10048 @result{}
10049 define(`copy', `ifdef(`$2', `errprint(`$2 already defined
10050 ')m4exit(`1')',
10051    `stack_foreach_sep(`$1', `pushdef(`$2',', `)')')')dnl
10052 pushdef(`a', `1')pushdef(`a', defn(`divnum'))
10053 @result{}
10054 copy(`a', `b')
10055 @result{}
10057 @result{}0
10058 popdef(`b')
10059 @result{}
10061 @result{}1
10062 pushdef(`c', `1')pushdef(`c', `2')
10063 @result{}
10064 stack_foreach_sep_lifo(`c', `', `', `, ')
10065 @result{}2, 1
10066 undivert(`stack_sep.m4')dnl
10067 @result{}divert(`-1')
10068 @result{}# stack_foreach_sep(macro, pre, post, sep)
10069 @result{}# Invoke PRE`'defn`'POST with a single argument of each definition
10070 @result{}# from the definition stack of MACRO, starting with the oldest, and
10071 @result{}# separated by SEP between definitions.
10072 @result{}define(`stack_foreach_sep',
10073 @result{}`_stack_reverse_sep(`$1', `tmp-$1')'dnl
10074 @result{}`_stack_reverse_sep(`tmp-$1', `$1', `$2`'defn(`$1')$3', `$4`'')')
10075 @result{}# stack_foreach_sep_lifo(macro, pre, post, sep)
10076 @result{}# Like stack_foreach_sep, but starting with the newest definition.
10077 @result{}define(`stack_foreach_sep_lifo',
10078 @result{}`_stack_reverse_sep(`$1', `tmp-$1', `$2`'defn(`$1')$3', `$4`'')'dnl
10079 @result{}`_stack_reverse_sep(`tmp-$1', `$1')')
10080 @result{}define(`_stack_reverse_sep',
10081 @result{}`ifdef(`$1', `pushdef(`$2', defn(`$1'))$3`'popdef(`$1')$0(
10082 @result{}  `$1', `$2', `$4$3')')')
10083 @result{}divert`'dnl
10084 @end example
10086 @node Improved m4wrap
10087 @section Solution for @code{m4wrap}
10089 The replacement @code{m4wrap} versions presented above, designed to
10090 guarantee FIFO or LIFO order regardless of the underlying M4
10091 implementation, share a bug when dealing with wrapped text that looks
10092 like parameter expansion.  Note how the invocation of
10093 @code{m4wrap@var{n}} interprets these parameters, while using the
10094 builtin preserves them for their intended use.
10096 @comment examples
10097 @example
10098 $ @kbd{m4 -I examples}
10099 include(`wraplifo.m4')
10100 @result{}
10101 m4wrap(`define(`foo', ``$0:'-$1-$*-$#-')foo(`a', `b')
10103 @result{}
10104 builtin(`m4wrap', ``'define(`bar', ``$0:'-$1-$*-$#-')bar(`a', `b')
10106 @result{}
10108 @result{}m4wrap0:---0-
10109 @result{}bar:-a-a,b-2-
10110 @end example
10112 Additionally, the computation of @code{_m4wrap_level} and creation of
10113 multiple @code{m4wrap@var{n}} placeholders in the original examples is
10114 more expensive in time and memory than strictly necessary.  Notice how
10115 the improved version grabs the wrapped text via @code{defn} to avoid
10116 parameter expansion, then undefines @code{_m4wrap_text}, before
10117 stripping a level of quotes with @code{_arg1} to expand the text.  That
10118 way, each level of wrapping reuses the single placeholder, which starts
10119 each nesting level in an undefined state.
10121 Finally, it is worth emulating the GNU M4 extension of saving
10122 all arguments to @code{m4wrap}, separated by a space, rather than saving
10123 just the first argument.  This is done with the @code{join} macro
10124 documented previously (@pxref{Shift}).  The improved LIFO example is
10125 shipped as @file{m4-@value{VERSION}/@/examples/@/wraplifo2.m4}, and can
10126 easily be converted to a FIFO solution by swapping the adjacent
10127 invocations of @code{joinall} and @code{defn}.
10129 @comment examples
10130 @example
10131 $ @kbd{m4 -I examples}
10132 include(`wraplifo2.m4')
10133 @result{}
10134 undivert(`wraplifo2.m4')dnl
10135 @result{}dnl Redefine m4wrap to have LIFO semantics, improved example.
10136 @result{}include(`join.m4')dnl
10137 @result{}define(`_m4wrap', defn(`m4wrap'))dnl
10138 @result{}define(`_arg1', `$1')dnl
10139 @result{}define(`m4wrap',
10140 @result{}`ifdef(`_$0_text',
10141 @result{}       `define(`_$0_text', joinall(` ', $@@)defn(`_$0_text'))',
10142 @result{}       `_$0(`_arg1(defn(`_$0_text')undefine(`_$0_text'))')dnl
10143 @result{}define(`_$0_text', joinall(` ', $@@))')')dnl
10144 m4wrap(`define(`foo', ``$0:'-$1-$*-$#-')foo(`a', `b')
10146 @result{}
10147 m4wrap(`lifo text
10148 m4wrap(`nested', `', `$@@
10149 ')')
10150 @result{}
10152 @result{}lifo text
10153 @result{}foo:-a-a,b-2-
10154 @result{}nested  $@@
10155 @end example
10157 @node Improved cleardivert
10158 @section Solution for @code{cleardivert}
10160 The @code{cleardivert} macro (@pxref{Cleardivert}) cannot, as it stands, be
10161 called without arguments to clear all pending diversions.  That is
10162 because using undivert with an empty string for an argument is different
10163 than using it with no arguments at all.  Compare the earlier definition
10164 with one that takes the number of arguments into account:
10166 @example
10167 define(`cleardivert',
10168   `pushdef(`_n', divnum)divert(`-1')undivert($@@)divert(_n)popdef(`_n')')
10169 @result{}
10170 divert(`1')one
10171 divert
10172 @result{}
10173 cleardivert
10174 @result{}
10175 undivert
10176 @result{}one
10177 @result{}
10178 define(`cleardivert',
10179   `pushdef(`_num', divnum)divert(`-1')ifelse(`$#', `0',
10180     `undivert`'', `undivert($@@)')divert(_num)popdef(`_num')')
10181 @result{}
10182 divert(`2')two
10183 divert
10184 @result{}
10185 cleardivert
10186 @result{}
10187 undivert
10188 @result{}
10189 @end example
10191 @node Improved capitalize
10192 @section Solution for @code{capitalize}
10194 The @code{capitalize} macro (@pxref{Patsubst}) as presented earlier does
10195 not allow clients to follow the quoting rule of thumb.  Consider the
10196 three macros @code{active}, @code{Active}, and @code{ACTIVE}, and the
10197 difference between calling @code{capitalize} with the expansion of a
10198 macro, expanding the result of a case change, and changing the case of a
10199 double-quoted string:
10201 @comment examples
10202 @example
10203 $ @kbd{m4 -I examples}
10204 include(`capitalize.m4')dnl
10205 define(`active', `act1, ive')dnl
10206 define(`Active', `Act2, Ive')dnl
10207 define(`ACTIVE', `ACT3, IVE')dnl
10208 upcase(active)
10209 @result{}ACT1,IVE
10210 upcase(`active')
10211 @result{}ACT3, IVE
10212 upcase(``active'')
10213 @result{}ACTIVE
10214 downcase(ACTIVE)
10215 @result{}act3,ive
10216 downcase(`ACTIVE')
10217 @result{}act1, ive
10218 downcase(``ACTIVE'')
10219 @result{}active
10220 capitalize(active)
10221 @result{}Act1
10222 capitalize(`active')
10223 @result{}Active
10224 capitalize(``active'')
10225 @result{}_capitalize(`active')
10226 define(`A', `OOPS')
10227 @result{}
10228 capitalize(active)
10229 @result{}OOPSct1
10230 capitalize(`active')
10231 @result{}OOPSctive
10232 @end example
10234 First, when @code{capitalize} is called with more than one argument, it
10235 was throwing away later arguments, whereas @code{upcase} and
10236 @code{downcase} used @samp{$*} to collect them all.  The fix is simple:
10237 use @samp{$*} consistently.
10239 Next, with single-quoting, @code{capitalize} outputs a single character,
10240 a set of quotes, then the rest of the characters, making it impossible
10241 to invoke @code{Active} after the fact, and allowing the alternate macro
10242 @code{A} to interfere.  Here, the solution is to use additional quoting
10243 in the helper macros, then pass the final over-quoted output string
10244 through @code{_arg1} to remove the extra quoting and finally invoke the
10245 concatenated portions as a single string.
10247 Finally, when passed a double-quoted string, the nested macro
10248 @code{_capitalize} is never invoked because it ended up nested inside
10249 quotes.  This one is the toughest to fix.  In short, we have no idea how
10250 many levels of quotes are in effect on the substring being altered by
10251 @code{patsubst}.  If the replacement string cannot be expressed entirely
10252 in terms of literal text and backslash substitutions, then we need a
10253 mechanism to guarantee that the helper macros are invoked outside of
10254 quotes.  In other words, this sounds like a job for @code{changequote}
10255 (@pxref{Changequote}).  By changing the active quoting characters, we
10256 can guarantee that replacement text injected by @code{patsubst} always
10257 occurs in the middle of a string that has exactly one level of
10258 over-quoting using alternate quotes; so the replacement text closes the
10259 quoted string, invokes the helper macros, then reopens the quoted
10260 string.  In turn, that means the replacement text has unbalanced quotes,
10261 necessitating another round of @code{changequote}.
10263 In the fixed version below, (also shipped as
10264 @file{m4-@value{VERSION}/@/examples/@/capitalize.m4}), @code{capitalize}
10265 uses the alternate quotes of @samp{<<[} and @samp{]>>} (the longer
10266 strings are chosen so as to be less likely to appear in the text being
10267 converted).  The helpers @code{_to_alt} and @code{_from_alt} merely
10268 reduce the number of characters required to perform a
10269 @code{changequote}, since the definition changes twice.  The outermost
10270 pair means that @code{patsubst} and @code{_capitalize_alt} are invoked
10271 with alternate quoting; the innermost pair is used so that the third
10272 argument to @code{patsubst} can contain an unbalanced
10273 @samp{]>>}/@samp{<<[} pair.  Note that @code{upcase} and @code{downcase}
10274 must be redefined as @code{_upcase_alt} and @code{_downcase_alt}, since
10275 they contain nested quotes but are invoked with the alternate quoting
10276 scheme in effect.
10278 @comment examples
10279 @example
10280 $ @kbd{m4 -I examples}
10281 include(`capitalize2.m4')dnl
10282 define(`active', `act1, ive')dnl
10283 define(`Active', `Act2, Ive')dnl
10284 define(`ACTIVE', `ACT3, IVE')dnl
10285 define(`A', `OOPS')dnl
10286 capitalize(active; `active'; ``active''; ```actIVE''')
10287 @result{}Act1,Ive; Act2, Ive; Active; `Active'
10288 undivert(`capitalize2.m4')dnl
10289 @result{}divert(`-1')
10290 @result{}# upcase(text)
10291 @result{}# downcase(text)
10292 @result{}# capitalize(text)
10293 @result{}#   change case of text, improved version
10294 @result{}define(`upcase', `translit(`$*', `a-z', `A-Z')')
10295 @result{}define(`downcase', `translit(`$*', `A-Z', `a-z')')
10296 @result{}define(`_arg1', `$1')
10297 @result{}define(`_to_alt', `changequote(`<<[', `]>>')')
10298 @result{}define(`_from_alt', `changequote(<<[`]>>, <<[']>>)')
10299 @result{}define(`_upcase_alt', `translit(<<[$*]>>, <<[a-z]>>, <<[A-Z]>>)')
10300 @result{}define(`_downcase_alt', `translit(<<[$*]>>, <<[A-Z]>>, <<[a-z]>>)')
10301 @result{}define(`_capitalize_alt',
10302 @result{}  `regexp(<<[$1]>>, <<[^\(\w\)\(\w*\)]>>,
10303 @result{}    <<[_upcase_alt(<<[<<[\1]>>]>>)_downcase_alt(<<[<<[\2]>>]>>)]>>)')
10304 @result{}define(`capitalize',
10305 @result{}  `_arg1(_to_alt()patsubst(<<[<<[$*]>>]>>, <<[\w+]>>,
10306 @result{}    _from_alt()`]>>_$0_alt(<<[\&]>>)<<['_to_alt())_from_alt())')
10307 @result{}divert`'dnl
10308 @end example
10310 @node Improved fatal_error
10311 @section Solution for @code{fatal_error}
10313 The @code{fatal_error} macro (@pxref{M4exit}) is not robust to versions
10314 of GNU M4 earlier than 1.4.8, where invoking @code{@w{__file__}}
10315 (@pxref{Location}) inside @code{m4wrap} would result in an empty string,
10316 and @code{@w{__line__}} resulted in @samp{0} even though all files start
10317 at line 1.  Furthermore, versions earlier than 1.4.6 did not support the
10318 @code{@w{__program__}} macro.  If you want @code{fatal_error} to work
10319 across the entire 1.4.x release series, a better implementation would
10322 @comment status: 1
10323 @example
10324 define(`fatal_error',
10325   `errprint(ifdef(`__program__', `__program__', ``m4'')'dnl
10326 `:ifelse(__line__, `0', `',
10327     `__file__:__line__:')` fatal error: $*
10328 ')m4exit(`1')')
10329 @result{}
10330 m4wrap(`divnum(`demo of internal message')
10331 fatal_error(`inside wrapped text')')
10332 @result{}
10334 @error{}m4:stdin:6: warning: divnum: extra arguments ignored: 1 > 0
10335 @result{}0
10336 @error{}m4:stdin:6: fatal error: inside wrapped text
10337 @end example
10339 @c ========================================================== Appendices
10341 @node Copying This Package
10342 @appendix How to make copies of the overall M4 package
10343 @cindex License, code
10345 This appendix covers the license for copying the source code of the
10346 overall M4 package.  This manual is under a different set of
10347 restrictions, covered later (@pxref{Copying This Manual}).
10349 @menu
10350 * GNU General Public License::  License for copying the M4 package
10351 @end menu
10353 @node GNU General Public License
10354 @appendixsec License for copying the M4 package
10355 @cindex GPL, GNU General Public License
10356 @cindex GNU General Public License
10357 @cindex General Public License (GPL), GNU
10358 @include gpl-3.0.texi
10360 @node Copying This Manual
10361 @appendix How to make copies of this manual
10362 @cindex License, manual
10364 This appendix covers the license for copying this manual.  Note that
10365 some of the longer examples in this manual are also distributed in the
10366 directory @file{m4-@value{VERSION}/@/examples/}, where a more
10367 permissive license is in effect when copying just the examples.
10369 @menu
10370 * GNU Free Documentation License::  License for copying this manual
10371 @end menu
10373 @node GNU Free Documentation License
10374 @appendixsec License for copying this manual
10375 @cindex FDL, GNU Free Documentation License
10376 @cindex GNU Free Documentation License
10377 @cindex Free Documentation License (FDL), GNU
10378 @include fdl-1.3.texi
10380 @node Indices
10381 @appendix Indices of concepts and macros
10383 @menu
10384 * Macro index::                 Index for all @code{m4} macros
10385 * Concept index::               Index for many concepts
10386 @end menu
10388 @node Macro index
10389 @appendixsec Index for all @code{m4} macros
10391 This index covers all @code{m4} builtins, as well as several useful
10392 composite macros.  References are exclusively to the places where a
10393 macro is introduced the first time.
10395 @printindex fn
10397 @node Concept index
10398 @appendixsec Index for many concepts
10400 @printindex cp
10402 @bye
10404 @c Local Variables:
10405 @c fill-column: 72
10406 @c ispell-local-dictionary: "american"
10407 @c indent-tabs-mode: nil
10408 @c whitespace-check-buffer-indent: nil
10409 @c End: