Document join, in order to fix bug in m4wrap example.
[m4/ericb.git] / doc / m4.texinfo
blobf0fbb96cc3807a314aa9a956efdd00856688047b
1 \input texinfo @c -*- texinfo -*-
2 @comment ========================================================
3 @comment %**start of header
4 @setfilename m4.info
5 @include version.texi
6 @settitle GNU M4 @value{VERSION} macro processor
7 @setchapternewpage odd
8 @ifnothtml
9 @setcontentsaftertitlepage
10 @end ifnothtml
11 @finalout
13 @c @tabchar{}
14 @c ----------
15 @c The testsuite expects literal tab output in some examples, but
16 @c literal tabs in texinfo lead to formatting issues.
17 @macro tabchar
18 @       @c
19 @end macro
21 @c @ovar{ARG}
22 @c -------------------
23 @c The ARG is an optional argument.  To be used for macro arguments in
24 @c their documentation.
25 @macro ovar{varname}
26 @r{[}@var{\varname\}@r{]}
27 @end macro
29 @c @dvar{ARG, DEFAULT}
30 @c -------------------
31 @c The ARG is an optional argument, defaulting to DEFAULT.  To be used
32 @c for macro arguments in their documentation.
33 @macro dvar{varname, default}
34 @r{[}@var{\varname\} = @samp{\default\}@r{]}
35 @end macro
37 @comment %**end of header
38 @comment ========================================================
40 @copying
42 This manual is for @acronym{GNU} M4 (version @value{VERSION}, @value{UPDATED}),
43 a package containing an implementation of the m4 macro language.
45 Copyright @copyright{} 1989, 1990, 1991, 1992, 1993, 1994, 2004, 2005,
46 2006, 2007, 2008 Free Software Foundation, Inc.
48 @quotation
49 Permission is granted to copy, distribute and/or modify this document
50 under the terms of the @acronym{GNU} Free Documentation License,
51 Version 1.2 or any later version published by the Free Software
52 Foundation; with no Invariant Sections, no Front-Cover Texts, and no
53 Back-Cover Texts.  A copy of the license is included in the section
54 entitled ``@acronym{GNU} Free Documentation License.''
55 @end quotation
56 @end copying
58 @dircategory Text creation and manipulation
59 @direntry
60 * M4: (m4).                     A powerful macro processor.
61 @end direntry
63 @titlepage
64 @title GNU M4, version @value{VERSION}
65 @subtitle A powerful macro processor
66 @subtitle Edition @value{EDITION}, @value{UPDATED}
67 @author by Ren@'e Seindal, Fran@,{c}ois Pinard,
68 @author Gary V. Vaughan, and Eric Blake
69 @author (@email{bug-m4@@gnu.org})
71 @page
72 @vskip 0pt plus 1filll
73 @insertcopying
74 @end titlepage
76 @contents
78 @ifnottex
79 @node Top
80 @top GNU M4
81 @insertcopying
82 @end ifnottex
84 @acronym{GNU} @code{m4} is an implementation of the traditional UNIX macro
85 processor.  It is mostly SVR4 compatible, although it has some
86 extensions (for example, handling more than 9 positional parameters
87 to macros).  @code{m4} also has builtin functions for including
88 files, running shell commands, doing arithmetic, etc.  Autoconf needs
89 @acronym{GNU} @code{m4} for generating @file{configure} scripts, but not for
90 running them.
92 @acronym{GNU} @code{m4} was originally written by Ren@'e Seindal, with
93 subsequent changes by Fran@,{c}ois Pinard and other volunteers
94 on the Internet.  All names and email addresses can be found in the
95 files @file{m4-@value{VERSION}/@/AUTHORS} and
96 @file{m4-@value{VERSION}/@/THANKS} from the @acronym{GNU} M4
97 distribution.
99 This is release @value{VERSION}.  It is now considered stable:  future
100 releases in the 1.4.x series are only meant to fix bugs, increase speed,
101 or improve documentation.  However@dots{}
103 An experimental feature, which would improve @code{m4} usefulness,
104 allows for changing the syntax for what is a @dfn{word} in @code{m4}.
105 You should use:
106 @comment ignore
107 @example
108 ./configure --enable-changeword
109 @end example
110 @noindent
111 if you want this feature compiled in.  The current implementation
112 slows down @code{m4} considerably and is hardly acceptable.  In the
113 future, @code{m4} 2.0 will come with a different set of new features
114 that provide similar capabilities, but without the inefficiencies, so
115 changeword will go away and @emph{you should not count on it}.
117 @menu
118 * Preliminaries::               Introduction and preliminaries
119 * Invoking m4::                 Invoking @code{m4}
120 * Syntax::                      Lexical and syntactic conventions
122 * Macros::                      How to invoke macros
123 * Definitions::                 How to define new macros
124 * Conditionals::                Conditionals, loops, and recursion
126 * Debugging::                   How to debug macros and input
128 * Input Control::               Input control
129 * File Inclusion::              File inclusion
130 * Diversions::                  Diverting and undiverting output
132 * Text handling::               Macros for text handling
133 * Arithmetic::                  Macros for doing arithmetic
134 * Shell commands::              Macros for running shell commands
135 * Miscellaneous::               Miscellaneous builtin macros
136 * Frozen files::                Fast loading of frozen state
138 * Compatibility::               Compatibility with other versions of @code{m4}
139 * Answers::                     Correct version of some examples
141 * Copying This Package::        How to make copies of the overall M4 package
142 * Copying This Manual::         How to make copies of this manual
143 * Indices::                     Indices of concepts and macros
145 @detailmenu
146  --- The Detailed Node Listing ---
148 Introduction and preliminaries
150 * Intro::                       Introduction to @code{m4}
151 * History::                     Historical references
152 * Bugs::                        Problems and bugs
153 * Manual::                      Using this manual
155 Invoking @code{m4}
157 * Operation modes::             Command line options for operation modes
158 * Preprocessor features::       Command line options for preprocessor features
159 * Limits control::              Command line options for limits control
160 * Frozen state::                Command line options for frozen state
161 * Debugging options::           Command line options for debugging
162 * Command line files::          Specifying input files on the command line
164 Lexical and syntactic conventions
166 * Names::                       Macro names
167 * Quoted strings::              Quoting input to @code{m4}
168 * Comments::                    Comments in @code{m4} input
169 * Other tokens::                Other kinds of input tokens
170 * Input processing::            How @code{m4} copies input to output
172 How to invoke macros
174 * Invocation::                  Macro invocation
175 * Inhibiting Invocation::       Preventing macro invocation
176 * Macro Arguments::             Macro arguments
177 * Quoting Arguments::           On Quoting Arguments to macros
178 * Macro expansion::             Expanding macros
180 How to define new macros
182 * Define::                      Defining a new macro
183 * Arguments::                   Arguments to macros
184 * Pseudo Arguments::            Special arguments to macros
185 * Undefine::                    Deleting a macro
186 * Defn::                        Renaming macros
187 * Pushdef::                     Temporarily redefining macros
189 * Indir::                       Indirect call of macros
190 * Builtin::                     Indirect call of builtins
192 Conditionals, loops, and recursion
194 * Ifdef::                       Testing if a macro is defined
195 * Ifelse::                      If-else construct, or multibranch
196 * Shift::                       Recursion in @code{m4}
197 * Forloop::                     Iteration by counting
198 * Foreach::                     Iteration by list contents
200 How to debug macros and input
202 * Dumpdef::                     Displaying macro definitions
203 * Trace::                       Tracing macro calls
204 * Debug Levels::                Controlling debugging output
205 * Debug Output::                Saving debugging output
207 Input control
209 * Dnl::                         Deleting whitespace in input
210 * Changequote::                 Changing the quote characters
211 * Changecom::                   Changing the comment delimiters
212 * Changeword::                  Changing the lexical structure of words
213 * M4wrap::                      Saving text until end of input
215 File inclusion
217 * Include::                     Including named files
218 * Search Path::                 Searching for include files
220 Diverting and undiverting output
222 * Divert::                      Diverting output
223 * Undivert::                    Undiverting output
224 * Divnum::                      Diversion numbers
225 * Cleardivert::                 Discarding diverted text
227 Macros for text handling
229 * Len::                         Calculating length of strings
230 * Index macro::                 Searching for substrings
231 * Regexp::                      Searching for regular expressions
232 * Substr::                      Extracting substrings
233 * Translit::                    Translating characters
234 * Patsubst::                    Substituting text by regular expression
235 * Format::                      Formatting strings (printf-like)
237 Macros for doing arithmetic
239 * Incr::                        Decrement and increment operators
240 * Eval::                        Evaluating integer expressions
242 Macros for running shell commands
244 * Platform macros::             Determining the platform
245 * Syscmd::                      Executing simple commands
246 * Esyscmd::                     Reading the output of commands
247 * Sysval::                      Exit status
248 * Mkstemp::                     Making temporary files
250 Miscellaneous builtin macros
252 * Errprint::                    Printing error messages
253 * Location::                    Printing current location
254 * M4exit::                      Exiting from @code{m4}
256 Fast loading of frozen state
258 * Using frozen files::          Using frozen files
259 * Frozen file format::          Frozen file format
261 Compatibility with other versions of @code{m4}
263 * Extensions::                  Extensions in @acronym{GNU} M4
264 * Incompatibilities::           Facilities in System V m4 not in GNU M4
265 * Other Incompatibilities::     Other incompatibilities
267 Correct version of some examples
269 * Improved exch::               Solution for @code{exch}
270 * Improved forloop::            Solution for @code{forloop}
271 * Improved foreach::            Solution for @code{foreach}
272 * Improved m4wrap::             Solution for @code{m4wrap}
273 * Improved cleardivert::        Solution for @code{cleardivert}
274 * Improved capitalize::         Solution for @code{capitalize}
275 * Improved fatal_error::        Solution for @code{fatal_error}
277 How to make copies of the overall M4 package
279 * GNU General Public License::  License for copying the M4 package
281 How to make copies of this manual
283 * GNU Free Documentation License::  License for copying this manual
285 Indices of concepts and macros
287 * Macro index::                 Index for all @code{m4} macros
288 * Concept index::               Index for many concepts
290 @end detailmenu
291 @end menu
293 @node Preliminaries
294 @chapter Introduction and preliminaries
296 This first chapter explains what @acronym{GNU} @code{m4} is, where @code{m4}
297 comes from, how to read and use this documentation, how to call the
298 @code{m4} program, and how to report bugs about it.  It concludes by
299 giving tips for reading the remainder of the manual.
301 The following chapters then detail all the features of the @code{m4}
302 language.
304 @menu
305 * Intro::                       Introduction to @code{m4}
306 * History::                     Historical references
307 * Bugs::                        Problems and bugs
308 * Manual::                      Using this manual
309 @end menu
311 @node Intro
312 @section Introduction to @code{m4}
314 @cindex overview of @code{m4}
315 @code{m4} is a macro processor, in the sense that it copies its
316 input to the output, expanding macros as it goes.  Macros are either
317 builtin or user-defined, and can take any number of arguments.
318 Besides just doing macro expansion, @code{m4} has builtin functions
319 for including named files, running shell commands, doing integer
320 arithmetic, manipulating text in various ways, performing recursion,
321 etc.@dots{}  @code{m4} can be used either as a front-end to a compiler,
322 or as a macro processor in its own right.
324 The @code{m4} macro processor is widely available on all UNIXes, and has
325 been standardized by @acronym{POSIX}.
326 Usually, only a small percentage of users are aware of its existence.
327 However, those who find it often become committed users.  The
328 popularity of @acronym{GNU} Autoconf, which requires @acronym{GNU}
329 @code{m4} for @emph{generating} @file{configure} scripts, is an incentive
330 for many to install it, while these people will not themselves
331 program in @code{m4}.  @acronym{GNU} @code{m4} is mostly compatible with the
332 System V, Release 3 version, except for some minor differences.
333 @xref{Compatibility}, for more details.
335 Some people find @code{m4} to be fairly addictive.  They first use
336 @code{m4} for simple problems, then take bigger and bigger challenges,
337 learning how to write complex sets of @code{m4} macros along the way.
338 Once really addicted, users pursue writing of sophisticated @code{m4}
339 applications even to solve simple problems, devoting more time
340 debugging their @code{m4} scripts than doing real work.  Beware that
341 @code{m4} may be dangerous for the health of compulsive programmers.
343 @node History
344 @section Historical references
346 @cindex history of @code{m4}
347 @cindex @acronym{GNU} M4, history of
348 @code{GPM} was an important ancestor of @code{m4}.  See
349 C. Stratchey: ``A General Purpose Macro generator'', Computer Journal
350 8,3 (1965), pp.@: 225 ff.  @code{GPM} is also succinctly described into
351 David Gries classic ``Compiler Construction for Digital Computers''.
353 The classic B. Kernighan and P.J. Plauger: ``Software Tools'',
354 Addison-Wesley, Inc.@: (1976) describes and implements a Unix
355 macro-processor language, which inspired Dennis Ritchie to write
356 @code{m3}, a macro processor for the AP-3 minicomputer.
358 Kernighan and Ritchie then joined forces to develop the original
359 @code{m4}, as described in ``The M4 Macro Processor'', Bell
360 Laboratories (1977).  It had only 21 builtin macros.
362 While @code{GPM} was more @emph{pure}, @code{m4} is meant to deal with
363 the true intricacies of real life: macros can be recognized without
364 being pre-announced, skipping whitespace or end-of-lines is easier,
365 more constructs are builtin instead of derived, etc.
367 Originally, the Kernighan and Plauger macro-processor, and then
368 @code{m3}, formed the engine for the Rational FORTRAN preprocessor,
369 that is, the @code{Ratfor} equivalent of @code{cpp}.  Later, @code{m4}
370 was used as a front-end for @code{Ratfor}, @code{C} and @code{Cobol}.
372 Ren@'e Seindal released his implementation of @code{m4}, @acronym{GNU}
373 @code{m4},
374 in 1990, with the aim of removing the artificial limitations in many
375 of the traditional @code{m4} implementations, such as maximum line
376 length, macro size, or number of macros.
378 The late Professor A. Dain Samples described and implemented a further
379 evolution in the form of @code{M5}: ``User's Guide to the M5 Macro
380 Language: 2nd edition'', Electronic Announcement on comp.compilers
381 newsgroup (1992).
383 Fran@,{c}ois Pinard took over maintenance of @acronym{GNU} @code{m4} in
384 1992, until 1994 when he released @acronym{GNU} @code{m4} 1.4, which was
385 the stable release for 10 years.  It was at this time that @acronym{GNU}
386 Autoconf decided to require @acronym{GNU} @code{m4} as its underlying
387 engine, since all other implementations of @code{m4} had too many
388 limitations.
390 More recently, in 2004, Paul Eggert released 1.4.1 and 1.4.2 which
391 addressed some long standing bugs in the venerable 1.4 release.  Then in
392 2005, Gary V. Vaughan collected together the many patches to
393 @acronym{GNU} @code{m4} 1.4 that were floating around the net and
394 released 1.4.3 and 1.4.4.  And in 2006, Eric Blake joined the team and
395 prepared patches for the release of 1.4.5, 1.4.6, 1.4.7, and 1.4.8.
396 More bug fixes were incorporated in 2007, with releases 1.4.9 and
397 1.4.10.  In 2008, Eric additionally rewrote the scanning engine to
398 reduce recursive evaluation from quadratic to linear complexity for
399 1.4.11.  The 1.4.x branch remains open for bug fixes.
401 Meanwhile, development has continued on new features for @code{m4}, such
402 as dynamic module loading and additional builtins.  When complete,
403 @acronym{GNU} @code{m4} 2.0 will start a new series of releases.
405 @node Bugs
406 @section Problems and bugs
408 @cindex reporting bugs
409 @cindex bug reports
410 @cindex suggestions, reporting
411 If you have problems with @acronym{GNU} M4 or think you've found a bug,
412 please report it.  Before reporting a bug, make sure you've actually
413 found a real bug.  Carefully reread the documentation and see if it
414 really says you can do what you're trying to do.  If it's not clear
415 whether you should be able to do something or not, report that too; it's
416 a bug in the documentation!
418 Before reporting a bug or trying to fix it yourself, try to isolate it
419 to the smallest possible input file that reproduces the problem.  Then
420 send us the input file and the exact results @code{m4} gave you.  Also
421 say what you expected to occur; this will help us decide whether the
422 problem was really in the documentation.
424 Once you've got a precise problem, send e-mail to
425 @email{bug-m4@@gnu.org}.  Please include the version number of @code{m4}
426 you are using.  You can get this information with the command
427 @kbd{m4 --version}.  Also provide details about the platform you are
428 executing on.
430 Non-bug suggestions are always welcome as well.  If you have questions
431 about things that are unclear in the documentation or are just obscure
432 features, please report them too.
434 @node Manual
435 @section Using this manual
437 @cindex examples, understanding
438 This manual contains a number of examples of @code{m4} input and output,
439 and a simple notation is used to distinguish input, output and error
440 messages from @code{m4}.  Examples are set out from the normal text, and
441 shown in a fixed width font, like this
443 @comment ignore
444 @example
445 This is an example of an example!
446 @end example
448 To distinguish input from output, all output from @code{m4} is prefixed
449 by the string @samp{@result{}}, and all error messages by the string
450 @samp{@error{}}.  When showing how command line options affect matters,
451 the command line is shown with a prompt @samp{$ @kbd{like this}},
452 otherwise, you can assume that a simple @kbd{m4} invocation will work.
453 Thus:
455 @comment ignore
456 @example
457 $ @kbd{command line to invoke m4}
458 Example of input line
459 @result{}Output line from m4
460 @error{}and an error message
461 @end example
463 The sequence @samp{^D} in an example indicates the end of the input
464 file.  The sequence @samp{@key{NL}} refers to the newline character.
465 The majority of these examples are self-contained, and you can run them
466 with similar results by invoking @kbd{m4 -d}.  In fact, the testsuite
467 that is bundled in the @acronym{GNU} M4 package consists of the examples
468 in this document!  Some of the examples assume that your current
469 directory is located where you unpacked the installation, so if you plan
470 on following along, you may find it helpful to do this now:
472 @comment ignore
473 @example
474 $ @kbd{cd m4-@value{VERSION}}
475 @end example
477 As each of the predefined macros in @code{m4} is described, a prototype
478 call of the macro will be shown, giving descriptive names to the
479 arguments, e.g.,
481 @deffn Composite example (@var{string}, @dvar{count, 1}, @
482   @ovar{argument}@dots{})
483 This is a sample prototype.  There is not really a macro named
484 @code{example}, but this documents that if there were, it would be a
485 Composite macro, rather than a Builtin.  It requires at least one
486 argument, @var{string}.  Remember that in @code{m4}, there must not be a
487 space between the macro name and the opening parenthesis, unless it was
488 intended to call the macro without any arguments.  The brackets around
489 @var{count} and @var{argument} show that these arguments are optional.
490 If @var{count} is omitted, the macro behaves as if count were @samp{1},
491 whereas if @var{argument} is omitted, the macro behaves as if it were
492 the empty string.  A blank argument is not the same as an omitted
493 argument.  For example, @samp{example(`a')}, @samp{example(`a',`1')},
494 and @samp{example(`a',`1',)} would behave identically with @var{count}
495 set to @samp{1}; while @samp{example(`a',)} and @samp{example(`a',`')}
496 would explicitly pass the empty string for @var{count}.  The ellipses
497 (@samp{@dots{}}) show that the macro processes additional arguments
498 after @var{argument}, rather than ignoring them.
499 @end deffn
501 @cindex numbers
502 All macro arguments in @code{m4} are strings, but some are given
503 special interpretation, e.g., as numbers, file names, regular
504 expressions, etc.  The documentation for each macro will state how the
505 parameters are interpreted, and what happens if the argument cannot be
506 parsed according to the desired interpretation.  Unless specified
507 otherwise, a parameter specified to be a number is parsed as a decimal,
508 even if the argument has leading zeros; and parsing the empty string as
509 a number results in 0 rather than an error, although a warning will be
510 issued.
512 This document consistently writes and uses @dfn{builtin}, without a
513 hyphen, as if it were an English word.  This is how the @code{builtin}
514 primitive is spelled within @code{m4}.
516 @node Invoking m4
517 @chapter Invoking @code{m4}
519 @cindex command line
520 @cindex invoking @code{m4}
521 The format of the @code{m4} command is:
523 @comment ignore
524 @example
525 @code{m4} @r{[}@var{option}@dots{}@r{]} @r{[}@var{file}@dots{}@r{]}
526 @end example
528 @cindex command line, options
529 @cindex options, command line
530 @cindex @env{POSIXLY_CORRECT}
531 All options begin with @samp{-}, or if long option names are used, with
532 @samp{--}.  A long option name need not be written completely, any
533 unambiguous prefix is sufficient.  @acronym{POSIX} requires @code{m4} to
534 recognize arguments intermixed with files, even when
535 @env{POSIXLY_CORRECT} is set in the environment.  Most options take
536 effect at startup regardless of their position, but some are documented
537 below as taking effect after any files that occurred earlier in the
538 command line.  The argument @option{--} is a marker to denote the end of
539 options.
541 @comment FIXME option -d+f only works on head right now...
542 With short options, options that do not take arguments may be combined
543 into a single command line argument with subsequent options, options
544 with mandatory arguments may be provided either as a single command line
545 argument or as two arguments, and options with optional arguments must
546 be provided as a single argument.  In other words,
547 @kbd{m4 -QPDfoo -d a -d+f} is equivalent to
548 @kbd{m4 -Q -P -D foo -d -d+f -- ./a}, although the latter form is
549 considered canonical.
551 With long options, options with mandatory arguments may be provided with
552 an equal sign (@samp{=}) in a single argument, or as two arguments, and
553 options with optional arguments must be provided as a single argument.
554 In other words, @kbd{m4 --def foo --debug a} is equivalent to
555 @kbd{m4 --define=foo --debug= -- ./a}, although the latter form is
556 considered canonical (not to mention more robust, in case a future
557 version of @code{m4} introduces an option named @option{--default}).
559 @code{m4} understands the following options, grouped by functionality.
561 @menu
562 * Operation modes::             Command line options for operation modes
563 * Preprocessor features::       Command line options for preprocessor features
564 * Limits control::              Command line options for limits control
565 * Frozen state::                Command line options for frozen state
566 * Debugging options::           Command line options for debugging
567 * Command line files::          Specifying input files on the command line
568 @end menu
570 @node Operation modes
571 @section Command line options for operation modes
573 Several options control the overall operation of @code{m4}:
575 @table @code
576 @item --help
577 Print a help summary on standard output, then immediately exit
578 @code{m4} without reading any input files or performing any other
579 actions.
581 @item --version
582 Print the version number of the program on standard output, then
583 immediately exit @code{m4} without reading any input files or
584 performing any other actions.
586 @item -E
587 @itemx --fatal-warnings
588 @cindex errors, fatal
589 @cindex fatal errors
590 Controls the effect of warnings.  If unspecified, then execution
591 continues and exit status is unaffected when a warning is printed.  If
592 specified exactly once, warnings become fatal; when one is issued,
593 execution continues, but the exit status will be non-zero.  If specified
594 multiple times, then execution halts with non-zero status the first time
595 a warning is issued.  The introduction of behavior levels is new to M4
596 1.4.9; for behavior consistent with earlier versions, you should specify
597 @option{-E} twice.
599 @item -i
600 @itemx --interactive
601 @itemx -e
602 Makes this invocation of @code{m4} interactive.  This means that all
603 output will be unbuffered, and interrupts will be ignored.  The
604 spelling @option{-e} exists for compatibility with other @code{m4}
605 implementations, and issues a warning because it may be withdrawn in a
606 future version of @acronym{GNU} M4.
608 @item -P
609 @itemx --prefix-builtins
610 Internally modify @emph{all} builtin macro names so they all start with
611 the prefix @samp{m4_}.  For example, using this option, one should write
612 @samp{m4_define} instead of @samp{define}, and @samp{m4___file__}
613 instead of @samp{__file__}.  This option has no effect if @option{-R}
614 is also specified.
616 @item -Q
617 @itemx --quiet
618 @itemx --silent
619 Suppress warnings, such as missing or superfluous arguments in macro
620 calls, or treating the empty string as zero.
622 @item --warn-macro-sequence@r{[}=@var{REGEXP}@r{]}
623 Issue a warning if the regular expression @var{REGEXP} has a non-empty
624 match in any macro definition (either by @code{define} or
625 @code{pushdef}).  Empty matches are ignored; therefore, supplying the
626 empty string as @var{REGEXP} disables any warning.  If the optional
627 @var{REGEXP} is not supplied, then the default regular expression is
628 @samp{\$\(@{[^@}]*@}\|[0-9][0-9]+\)} (a literal @samp{$} followed by
629 multiple digits or by an open brace), since these sequences will
630 change semantics in the default operation of @acronym{GNU} M4 2.0 (due
631 to a change in how more than 9 arguments in a macro definition will be
632 handled, @pxref{Arguments}).  Providing an alternate regular
633 expression can provide a useful reverse lookup feature of finding
634 where a macro is defined to have a given definition.
636 @item -W @var{REGEXP}
637 @itemx --word-regexp=@var{REGEXP}
638 Use @var{REGEXP} as an alternative syntax for macro names.  This
639 experimental option will not be present in all @acronym{GNU} @code{m4}
640 implementations (@pxref{Changeword}).
641 @end table
643 @node Preprocessor features
644 @section Command line options for preprocessor features
646 @cindex macro definitions, on the command line
647 @cindex command line, macro definitions on the
648 @cindex preprocessor features
649 Several options allow @code{m4} to behave more like a preprocessor.
650 Macro definitions and deletions can be made on the command line, the
651 search path can be altered, and the output file can track where the
652 input came from.  These features occur with the following options:
654 @table @code
655 @item -D @var{NAME}@r{[}=@var{VALUE}@r{]}
656 @itemx --define=@var{NAME}@r{[}=@var{VALUE}@r{]}
657 This enters @var{NAME} into the symbol table.  If @samp{=@var{VALUE}} is
658 missing, the value is taken to be the empty string.  The @var{VALUE} can
659 be any string, and the macro can be defined to take arguments, just as
660 if it was defined from within the input.  This option may be given more
661 than once; order with respect to file names is significant, and
662 redefining the same @var{NAME} loses the previous value.
664 @item -I @var{DIRECTORY}
665 @itemx --include=@var{DIRECTORY}
666 Make @code{m4} search @var{DIRECTORY} for included files that are not
667 found in the current working directory.  @xref{Search Path}, for more
668 details.  This option may be given more than once.
670 @item -s
671 @itemx --synclines
672 @cindex synchronization lines
673 @cindex location, input
674 @cindex input location
675 Generate synchronization lines, for use by the C preprocessor or other
676 similar tools.  Order is significant with respect to file names.  This
677 option is useful, for example, when @code{m4} is used as a
678 front end to a compiler.  Source file name and line number information
679 is conveyed by directives of the form @samp{#line @var{linenum}
680 "@var{file}"}, which are inserted as needed into the middle of the
681 output.  Such directives mean that the following line originated or was
682 expanded from the contents of input file @var{file} at line
683 @var{linenum}.  The @samp{"@var{file}"} part is often omitted when
684 the file name did not change from the previous directive.
686 Synchronization directives are always given on complete lines by
687 themselves.  When a synchronization discrepancy occurs in the middle of
688 an output line, the associated synchronization directive is delayed
689 until the next newline that does not occur in the middle of a quoted
690 string or comment.
692 @comment options: -s
693 @example
694 define(`twoline', `1
696 @result{}#line 2 "stdin"
697 @result{}
698 changecom(`/*', `*/')
699 @result{}
700 define(`comment', `/*1
701 2*/')
702 @result{}#line 5
703 @result{}
704 dnl no line
705 hello
706 @result{}#line 7
707 @result{}hello
708 twoline
709 @result{}1
710 @result{}#line 8
711 @result{}2
712 comment
713 @result{}/*1
714 @result{}2*/
715 one comment `two
716 three'
717 @result{}#line 10
718 @result{}one /*1
719 @result{}2*/ two
720 @result{}three
721 goodbye
722 @result{}#line 12
723 @result{}goodbye
724 @end example
726 @item -U @var{NAME}
727 @itemx --undefine=@var{NAME}
728 This deletes any predefined meaning @var{NAME} might have.  Obviously,
729 only predefined macros can be deleted in this way.  This option may be
730 given more than once; undefining a @var{NAME} that does not have a
731 definition is silently ignored.  Order is significant with respect to
732 file names.
733 @end table
735 @node Limits control
736 @section Command line options for limits control
738 There are some limits within @code{m4} that can be tuned.  For
739 compatibility, @code{m4} also accepts some options that control limits
740 in other implementations, but which are automatically unbounded (limited
741 only by your hardware and operating system constraints) in @acronym{GNU}
742 @code{m4}.
744 @table @code
745 @item -G
746 @itemx --traditional
747 Suppress all the extensions made in this implementation, compared to the
748 System V version.  @xref{Compatibility}, for a list of these.
750 @item -H @var{NUM}
751 @itemx --hashsize=@var{NUM}
752 Make the internal hash table for symbol lookup be @var{NUM} entries big.
753 For better performance, the number should be prime, but this is not
754 checked.  The default is 509 entries.  It should not be necessary to
755 increase this value, unless you define an excessive number of macros.
757 @item -L @var{NUM}
758 @itemx --nesting-limit=@var{NUM}
759 @cindex nesting limit
760 @cindex limit, nesting
761 Artificially limit the nesting of macro calls to @var{NUM} levels,
762 stopping program execution if this limit is ever exceeded.  When not
763 specified, nesting is limited to 1024 levels.  A value of zero means
764 unlimited; but then heavily nested code could potentially cause a stack
765 overflow.
767 The precise effect of this option might be more correctly associated
768 with textual nesting than dynamic recursion.  It has been useful
769 when some complex @code{m4} input was generated by mechanical means.
770 Most users would never need this option.  If shown to be obtrusive,
771 this option (which is still experimental) might well disappear.
773 @cindex rescanning
774 This option does @emph{not} have the ability to break endless
775 rescanning loops, since these do not necessarily consume much memory
776 or stack space.  Through clever usage of rescanning loops, one can
777 request complex, time-consuming computations from @code{m4} with useful
778 results.  Putting limitations in this area would break @code{m4} power.
779 There are many pathological cases: @w{@samp{define(`a', `a')a}} is
780 only the simplest example (but @pxref{Compatibility}).  Expecting @acronym{GNU}
781 @code{m4} to detect these would be a little like expecting a compiler
782 system to detect and diagnose endless loops: it is a quite @emph{hard}
783 problem in general, if not undecidable!
785 @item -B @var{NUM}
786 @itemx -S @var{NUM}
787 @itemx -T @var{NUM}
788 These options are present for compatibility with System V @code{m4}, but
789 do nothing in this implementation.  They may disappear in future
790 releases, and issue a warning to that effect.
792 @item -N @var{NUM}
793 @itemx --diversions=@var{NUM}
794 These options are present only for compatibility with previous
795 versions of @acronym{GNU} @code{m4}, and were controlling the number of
796 possible diversions which could be used at the same time.  They do nothing,
797 because there is no fixed limit anymore.  They may disappear in future
798 releases, and issue a warning to that effect.
799 @end table
801 @node Frozen state
802 @section Command line options for frozen state
804 @acronym{GNU} @code{m4} comes with a feature of freezing internal state
805 (@pxref{Frozen files}).  This can be used to speed up @code{m4}
806 execution when reusing a common initialization script.
808 @table @code
809 @item -F @var{FILE}
810 @itemx --freeze-state=@var{FILE}
811 Once execution is finished, write out the frozen state on the specified
812 @var{FILE}.  It is conventional, but not required, for @var{FILE} to end
813 in @samp{.m4f}.
815 @item -R @var{FILE}
816 @itemx --reload-state=@var{FILE}
817 Before execution starts, recover the internal state from the specified
818 frozen @var{FILE}.  The options @option{-D}, @option{-U}, and
819 @option{-t} take effect after state is reloaded, but before the input
820 files are read.
821 @end table
823 @node Debugging options
824 @section Command line options for debugging
826 Finally, there are several options for aiding in debugging @code{m4}
827 scripts.
829 @table @code
830 @item -d@r{[}@var{FLAGS}@r{]}
831 @itemx --debug@r{[}=@var{FLAGS}@r{]}
832 Set the debug-level according to the flags @var{FLAGS}.  The debug-level
833 controls the format and amount of information presented by the debugging
834 functions.  @xref{Debug Levels}, for more details on the format and
835 meaning of @var{FLAGS}.  If omitted, @var{FLAGS} defaults to @samp{aeq}.
837 @item --debugfile=@var{FILE}
838 @itemx -o @var{FILE}
839 @itemx --error-output=@var{FILE}
840 Redirect @code{dumpdef} output, debug messages, and trace output to the
841 named @var{FILE}.  Warnings, error messages, and @code{errprint} output
842 are still printed to standard error.  If unspecified, debug output goes
843 to standard error; if empty, debug output is discarded.  @xref{Debug
844 Output}, for more details.  The spellings @option{-o} and
845 @option{--error-output} are misleading and inconsistent with other
846 @acronym{GNU} tools; for now they are silently accepted as synonyms of
847 @option{--debugfile}, but in a future version of M4, using them will
848 cause a warning to be issued.
850 @item -l @var{NUM}
851 @itemx --arglength=@var{NUM}
852 Restrict the size of the output generated by macro tracing to @var{NUM}
853 characters per trace line.  If unspecified or zero, output is
854 unlimited.  @xref{Debug Levels}, for more details.
856 @item -t @var{NAME}
857 @itemx --trace=@var{NAME}
858 This enables tracing for the macro @var{NAME}, at any point where it is
859 defined.  @var{NAME} need not be defined when this option is given.
860 This option may be given more than once, and order is significant with
861 respect to file names.  @xref{Trace}, for more details.
862 @end table
864 @node Command line files
865 @section Specifying input files on the command line
867 @cindex command line, file names on the
868 @cindex file names, on the command line
869 The remaining arguments on the command line are taken to be input file
870 names.  If no names are present, standard input is read.  A file
871 name of @file{-} is taken to mean standard input.  It is
872 conventional, but not required, for input files to end in @samp{.m4}.
874 The input files are read in the sequence given.  Standard input can be
875 read more than once, so the file name @file{-} may appear multiple times
876 on the command line; this makes a difference when input is from a
877 terminal or other special file type.  It is an error if an input file
878 ends in the middle of argument collection, a comment, or a quoted
879 string.
881 The options @option{--define} (@option{-D}), @option{--undefine}
882 (@option{-U}), @option{--synclines} (@option{-s}), and @option{--trace}
883 (@option{-t}) only take effect after processing input from any file
884 names that occur earlier on the command line.  For example, assume the
885 file @file{foo} contains:
887 @comment ignore
888 @example
889 $ @kbd{cat foo}
891 @end example
893 The text @samp{bar} can then be redefined over multiple uses of
894 @file{foo}:
896 @comment options: -Dbar=hello foo -Dbar=world foo
897 @example
898 $ @kbd{m4 -Dbar=hello foo -Dbar=world foo}
899 @result{}hello
900 @result{}world
901 @end example
903 If none of the input files invoked @code{m4exit} (@pxref{M4exit}), the
904 exit status of @code{m4} will be 0 for success, 1 for general failure
905 (such as problems with reading an input file), and 63 for version
906 mismatch (@pxref{Using frozen files}).
908 If you need to read a file whose name starts with a @file{-}, you can
909 specify it as @samp{./-file}, or use @option{--} to mark the end of
910 options.
912 @node Syntax
913 @chapter Lexical and syntactic conventions
915 @cindex input tokens
916 @cindex tokens
917 As @code{m4} reads its input, it separates it into @dfn{tokens}.  A
918 token is either a name, a quoted string, or any single character, that
919 is not a part of either a name or a string.  Input to @code{m4} can also
920 contain comments.  @acronym{GNU} @code{m4} does not yet understand
921 multibyte locales; all operations are byte-oriented rather than
922 character-oriented (although if your locale uses a single byte
923 encoding, such as @sc{ISO-8859-1}, you will not notice a difference).
924 However, @code{m4} is eight-bit clean, so you can
925 use non-@sc{ascii} characters in quoted strings (@pxref{Changequote}),
926 comments (@pxref{Changecom}), and macro names (@pxref{Indir}), with the
927 exception of the @sc{nul} character (the zero byte @samp{'\0'}).
929 @ignore
930 @comment FIXME - each builtin needs to document how it handles NUL, then
931 @comment update the above paragraph to mention that NUL is now handled
932 @comment transparently.  Meanwhile, test that we don't regress.
934 @comment xout: null.out
935 @comment xerr: null.err
936 @example
937 define(`m4exit')include(`null.m4')dnl
938 @end example
940 @comment status: 2
941 @example
942 include(`null.m4')
943 @result{}# This file tests m4 behavior on NUL bytes.
944 @end example
945 @end ignore
947 @menu
948 * Names::                       Macro names
949 * Quoted strings::              Quoting input to @code{m4}
950 * Comments::                    Comments in @code{m4} input
951 * Other tokens::                Other kinds of input tokens
952 * Input processing::            How @code{m4} copies input to output
953 @end menu
955 @node Names
956 @section Macro names
958 @cindex names
959 @cindex words
960 A name is any sequence of letters, digits, and the character @samp{_}
961 (underscore), where the first character is not a digit.  @code{m4} will
962 use the longest such sequence found in the input.  If a name has a
963 macro definition, it will be subject to macro expansion
964 (@pxref{Macros}).  Names are case-sensitive.
966 Examples of legal names are: @samp{foo}, @samp{_tmp}, and @samp{name01}.
968 @node Quoted strings
969 @section Quoting input to @code{m4}
971 @cindex quoted string
972 @cindex string, quoted
973 A quoted string is a sequence of characters surrounded by quote
974 strings, defaulting to
975 @samp{`} and @samp{'}, where the nested begin and end quotes within the
976 string are balanced.  The value of a string token is the text, with one
977 level of quotes stripped off.  Thus
979 @comment ignore
980 @example
982 @result{}
983 @end example
985 @noindent
986 is the empty string, and double-quoting turns into single-quoting.
988 @comment ignore
989 @example
990 ``quoted''
991 @result{}`quoted'
992 @end example
994 The quote characters can be changed at any time, using the builtin macro
995 @code{changequote}.  @xref{Changequote}, for more information.
997 @node Comments
998 @section Comments in @code{m4} input
1000 @cindex comments
1001 Comments in @code{m4} are normally delimited by the characters @samp{#}
1002 and newline.  All characters between the comment delimiters are ignored,
1003 but the entire comment (including the delimiters) is passed through to
1004 the output---comments are @emph{not} discarded by @code{m4}.
1006 Comments cannot be nested, so the first newline after a @samp{#} ends
1007 the comment.  The commenting effect of the begin-comment string
1008 can be inhibited by quoting it.
1010 @example
1011 $ @kbd{m4}
1012 `quoted text' # `commented text'
1013 @result{}quoted text # `commented text'
1014 `quoting inhibits' `#' `comments'
1015 @result{}quoting inhibits # comments
1016 @end example
1018 The comment delimiters can be changed to any string at any time, using
1019 the builtin macro @code{changecom}.  @xref{Changecom}, for more
1020 information.
1022 @node Other tokens
1023 @section Other kinds of input tokens
1025 @cindex tokens, special
1026 Any character, that is neither a part of a name, nor of a quoted string,
1027 nor a comment, is a token by itself.  When not in the context of macro
1028 expansion, all of these tokens are just copied to output.  However,
1029 during macro expansion, whitespace characters (space, tab, newline,
1030 formfeed, carriage return, vertical tab), parentheses (@samp{(} and
1031 @samp{)}), comma (@samp{,}), and dollar (@samp{$}) have additional
1032 roles, explained later.
1034 @node Input processing
1035 @section How @code{m4} copies input to output
1037 As @code{m4} reads the input token by token, it will copy each token
1038 directly to the output immediately.
1040 The exception is when it finds a word with a macro definition.  In that
1041 case @code{m4} will calculate the macro's expansion, possibly reading
1042 more input to get the arguments.  It then inserts the expansion in front
1043 of the remaining input.  In other words, the resulting text from a macro
1044 call will be read and parsed into tokens again.
1046 @code{m4} expands a macro as soon as possible.  If it finds a macro call
1047 when collecting the arguments to another, it will expand the second call
1048 first.  This process continues until there are no more macro calls to
1049 expand and all the input has been consumed.
1051 For a running example, examine how @code{m4} handles this input:
1053 @comment ignore
1054 @example
1055 format(`Result is %d', eval(`2**15'))
1056 @end example
1058 @noindent
1059 First, @code{m4} sees that the token @samp{format} is a macro name, so
1060 it collects the tokens @samp{(}, @samp{`Result is %d'}, @samp{,},
1061 and @samp{@w{ }}, before encountering another potential macro.  Sure
1062 enough, @samp{eval} is a macro name, so the nested argument collection
1063 picks up @samp{(}, @samp{`2**15'}, and @samp{)}, invoking the eval macro
1064 with the lone argument of @samp{2**15}.  The expansion of
1065 @samp{eval(2**15)} is @samp{32768}, which is then rescanned as the five
1066 tokens @samp{3}, @samp{2}, @samp{7}, @samp{6}, and @samp{8}; and
1067 combined with the next @samp{)}, the format macro now has all its
1068 arguments, as if the user had typed:
1070 @comment ignore
1071 @example
1072 format(`Result is %d', 32768)
1073 @end example
1075 @noindent
1076 The format macro expands to @samp{Result is 32768}, and we have another
1077 round of scanning for the tokens @samp{Result}, @samp{@w{ }},
1078 @samp{is}, @samp{@w{ }}, @samp{3}, @samp{2}, @samp{7}, @samp{6}, and
1079 @samp{8}.  None of these are macros, so the final output is
1081 @comment ignore
1082 @example
1083 @result{}Result is 32768
1084 @end example
1086 As a more complicated example, we will contrast an actual code
1087 example from the Gnulib project@footnote{Derived from a patch in
1088 @uref{http://lists.gnu.org/archive/html/bug-gnulib/@/2007-01/@/msg00389.html},
1089 and a followup patch in
1090 @uref{http://lists.gnu.org/archive/html/bug-gnulib/@/2007-02/@/msg00000.html}},
1091 showing both a buggy approach and the desired results.  The user desires
1092 to output a shell assignment statement that takes its argument and turns
1093 it into a shell variable by converting it to uppercase and prepending a
1094 prefix.  The original attempt looks like this:
1096 @example
1097 changequote([,])dnl
1098 define([gl_STRING_MODULE_INDICATOR],
1099   [
1100     dnl comment
1101     GNULIB_]translit([$1],[a-z],[A-Z])[=1
1102   ])dnl
1103   gl_STRING_MODULE_INDICATOR([strcase])
1104 @result{} @w{ }
1105 @result{}        GNULIB_strcase=1
1106 @result{} @w{ }
1107 @end example
1109 Oops -- the argument did not get capitalized.  And although the manual
1110 is not able to easily show it, both lines that appear empty actually
1111 contain two trailing spaces.  By stepping through the parse, it is easy
1112 to see what happened.  First, @code{m4} sees the token
1113 @samp{changequote}, which it recognizes as a macro, followed by
1114 @samp{(}, @samp{[}, @samp{,}, @samp{]}, and @samp{)} to form the
1115 argument list.  The macro expands to the empty string, but changes the
1116 quoting characters to something more useful for generating shell code
1117 (unbalanced @samp{`} and @samp{'} appear all the time in shell scripts,
1118 but unbalanced @samp{[]} tend to be rare).  Also in the first line,
1119 @code{m4} sees the token @samp{dnl}, which it recognizes as a builtin
1120 macro that consumes the rest of the line, resulting in no output for
1121 that line.
1123 The second line starts a macro definition.  @code{m4} sees the token
1124 @samp{define}, which it recognizes as a macro, followed by a @samp{(},
1125 @samp{[gl_STRING_MODULE_INDICATOR]}, and @samp{,}.  Because an unquoted
1126 comma was encountered, the first argument is known to be the expansion
1127 of the single-quoted string token, or @samp{gl_STRING_MODULE_INDICATOR}.
1128 Next, @code{m4} sees @samp{@key{NL}}, @samp{ }, and @samp{ }, but this
1129 whitespace is discarded as part of argument collection.  Then comes a
1130 rather lengthy single-quoted string token, @samp{[@key{NL}@ @ @ @ dnl
1131 comment@key{NL}@ @ @ @ GNULIB_]}.  This is followed by the token
1132 @samp{translit}, which @code{m4} recognizes as a macro name, so a nested
1133 macro expansion has started.
1135 The arguments to the @code{translit} are found by the tokens @samp{(},
1136 @samp{[$1]}, @samp{,}, @samp{[a-z]}, @samp{,}, @samp{[A-Z]}, and finally
1137 @samp{)}.  All three string arguments are expanded (or in other words,
1138 the quotes are stripped), and since neither @samp{$} nor @samp{1} need
1139 capitalization, the result of the macro is @samp{$1}.  This expansion is
1140 rescanned, resulting in the two literal characters @samp{$} and
1141 @samp{1}.
1143 Scanning of the outer macro resumes, and picks up with
1144 @samp{[=1@key{NL}@ @ ]}, and finally @samp{)}.  The collected pieces of
1145 expanded text are concatenated, with the end result that the macro
1146 @samp{gl_STRING_MODULE_INDICATOR} is now defined to be the sequence
1147 @samp{@key{NL}@ @ @ @ dnl comment@key{NL}@ @ @ @ GNULIB_$1=1@key{NL}@ @ }.
1148 Once again, @samp{dnl} is recognized and avoids a newline in the output.
1150 The final line is then parsed, beginning with @samp{ } and @samp{ }
1151 that are output literally.  Then @samp{gl_STRING_MODULE_INDICATOR} is
1152 recognized as a macro name, with an argument list of @samp{(},
1153 @samp{[strcase]}, and @samp{)}.  Since the definition of the macro
1154 contains the sequence @samp{$1}, that sequence is replaced with the
1155 argument @samp{strcase} prior to starting the rescan.  The rescan sees
1156 @samp{@key{NL}} and four spaces, which are output literally, then
1157 @samp{dnl}, which discards the text @samp{ comment@key{NL}}.  Next
1158 comes four more spaces, also output literally, and the token
1159 @samp{GNULIB_strcase}, which resulted from the earlier parameter
1160 substitution.  Since that is not a macro name, it is output literally,
1161 followed by the literal tokens @samp{=}, @samp{1}, @samp{@key{NL}}, and
1162 two more spaces.  Finally, the original @samp{@key{NL}} seen after the
1163 macro invocation is scanned and output literally.
1165 Now for a corrected approach.  This rearranges the use of newlines and
1166 whitespace so that less whitespace is output (which, although harmless
1167 to shell scripts, can be visually unappealing), and fixes the quoting
1168 issues so that the capitalization occurs when the macro
1169 @samp{gl_STRING_MODULE_INDICATOR} is invoked, rather then when it is
1170 defined.
1172 @example
1173 changequote([,])dnl
1174 define([gl_STRING_MODULE_INDICATOR],
1175   [dnl comment
1176   GNULIB_[]translit([$1], [a-z], [A-Z])=1dnl
1177 ])dnl
1178   gl_STRING_MODULE_INDICATOR([strcase])
1179 @result{}    GNULIB_STRCASE=1
1180 @end example
1182 The parsing of the first line is unchanged.  The second line sees the
1183 name of the macro to define, then sees the discarded @samp{@key{NL}}
1184 and two spaces, as before.  But this time, the next token is
1185 @samp{[dnl comment@key{NL}@ @ GNULIB_[]translit([$1], [a-z],
1186 [A-Z])=1dnl@key{NL}]}, which includes nested quotes, followed by
1187 @samp{)} to end the macro definition and @samp{dnl} to skip the
1188 newline.  No early expansion of @code{translit} occurs, so the entire
1189 string becomes the definition of the macro.
1191 The final line is then parsed, beginning with two spaces that are
1192 output literally, and an invocation of
1193 @code{gl_STRING_MODULE_INDICATOR} with the argument @samp{strcase}.
1194 Again, the @samp{$1} in the macro definition is substituted prior to
1195 rescanning.  Rescanning first encounters @samp{dnl}, and discards
1196 @samp{ comment@key{NL}}.  Then two spaces are output literally.  Next
1197 comes the token @samp{GNULIB_}, but that is not a macro, so it is
1198 output literally.  The token @samp{[]} is an empty string, so it does
1199 not affect output.  Then the token @samp{translit} is encountered.
1201 This time, the arguments to @code{translit} are parsed as @samp{(},
1202 @samp{[strcase]}, @samp{,}, @samp{ }, @samp{[a-z]}, @samp{,}, @samp{ },
1203 @samp{[A-Z]}, and @samp{)}.  The two spaces are discarded, and the
1204 translit results in the desired result @samp{STRCASE}.  This is
1205 rescanned, but since it is not a macro name, it is output literally.
1206 Then the scanner sees @samp{=} and @samp{1}, which are output
1207 literally, followed by @samp{dnl} which discards the rest of the
1208 definition of @code{gl_STRING_MODULE_INDICATOR}.  The newline at the
1209 end of output is the literal @samp{@key{NL}} that appeared after the
1210 invocation of the macro.
1212 The order in which @code{m4} expands the macros can be further explored
1213 using the trace facilities of @acronym{GNU} @code{m4} (@pxref{Trace}).
1215 @node Macros
1216 @chapter How to invoke macros
1218 This chapter covers macro invocation, macro arguments and how macro
1219 expansion is treated.
1221 @menu
1222 * Invocation::                  Macro invocation
1223 * Inhibiting Invocation::       Preventing macro invocation
1224 * Macro Arguments::             Macro arguments
1225 * Quoting Arguments::           On Quoting Arguments to macros
1226 * Macro expansion::             Expanding macros
1227 @end menu
1229 @node Invocation
1230 @section Macro invocation
1232 @cindex macro invocation
1233 @cindex invoking macros
1234 Macro invocations has one of the forms
1236 @comment ignore
1237 @example
1238 name
1239 @end example
1241 @noindent
1242 which is a macro invocation without any arguments, or
1244 @comment ignore
1245 @example
1246 name(arg1, arg2, @dots{}, arg@var{n})
1247 @end example
1249 @noindent
1250 which is a macro invocation with @var{n} arguments.  Macros can have any
1251 number of arguments.  All arguments are strings, but different macros
1252 might interpret the arguments in different ways.
1254 The opening parenthesis @emph{must} follow the @var{name} directly, with
1255 no spaces in between.  If it does not, the macro is called with no
1256 arguments at all.
1258 For a macro call to have no arguments, the parentheses @emph{must} be
1259 left out.  The macro call
1261 @comment ignore
1262 @example
1263 name()
1264 @end example
1266 @noindent
1267 is a macro call with one argument, which is the empty string, not a call
1268 with no arguments.
1270 @node Inhibiting Invocation
1271 @section Preventing macro invocation
1273 An innovation of the @code{m4} language, compared to some of its
1274 predecessors (like Stratchey's @code{GPM}, for example), is the ability
1275 to recognize macro calls without resorting to any special, prefixed
1276 invocation character.  While generally useful, this feature might
1277 sometimes be the source of spurious, unwanted macro calls.  So, @acronym{GNU}
1278 @code{m4} offers several mechanisms or techniques for inhibiting the
1279 recognition of names as macro calls.
1281 @cindex @acronym{GNU} extensions
1282 @cindex blind macro
1283 @cindex macro, blind
1284 First of all, many builtin macros cannot meaningfully be called without
1285 arguments.  As a @acronym{GNU} extension, for any of these macros,
1286 whenever an opening parenthesis does not immediately follow their name,
1287 the builtin macro call is not triggered.  This solves the most usual
1288 cases, like for @samp{include} or @samp{eval}.  Later in this document,
1289 the sentence ``This macro is recognized only with parameters'' refers to
1290 this specific provision of @acronym{GNU} M4, also known as a blind
1291 builtin macro.  For the builtins defined by @acronym{POSIX} that bear
1292 this disclaimer, @acronym{POSIX} specifically states that invoking those
1293 builtins without arguments is unspecified, because many other
1294 implementations simply invoke the builtin as though it were given one
1295 empty argument instead.
1297 @example
1298 $ @kbd{m4}
1299 eval
1300 @result{}eval
1301 eval(`1')
1302 @result{}1
1303 @end example
1305 There is also a command line option (@option{--prefix-builtins}, or
1306 @option{-P}, @pxref{Operation modes, , Invoking m4}) that renames all
1307 builtin macros with a prefix of @samp{m4_} at startup.  The option has
1308 no effect whatsoever on user defined macros.  For example, with this option,
1309 one has to write @code{m4_dnl} and even @code{m4_m4exit}.  It also has
1310 no effect on whether a macro requires parameters.
1312 @comment options: -P
1313 @example
1314 $ @kbd{m4 -P}
1315 eval
1316 @result{}eval
1317 eval(`1')
1318 @result{}eval(1)
1319 m4_eval
1320 @result{}m4_eval
1321 m4_eval(`1')
1322 @result{}1
1323 @end example
1325 Another alternative is to redefine problematic macros to a name less
1326 likely to cause conflicts, @xref{Definitions}.
1328 If your version of @acronym{GNU} @code{m4} has the @code{changeword} feature
1329 compiled in, it offers far more flexibility in specifying the
1330 syntax of macro names, both builtin or user-defined.  @xref{Changeword},
1331 for more information on this experimental feature.
1333 Of course, the simplest way to prevent a name from being interpreted
1334 as a call to an existing macro is to quote it.  The remainder of
1335 this section studies a little more deeply how quoting affects macro
1336 invocation, and how quoting can be used to inhibit macro invocation.
1338 Even if quoting is usually done over the whole macro name, it can also
1339 be done over only a few characters of this name (provided, of course,
1340 that the unquoted portions are not also a macro).  It is also possible
1341 to quote the empty string, but this works only @emph{inside} the name.
1342 For example:
1344 @example
1345 `divert'
1346 @result{}divert
1347 `d'ivert
1348 @result{}divert
1349 di`ver't
1350 @result{}divert
1351 div`'ert
1352 @result{}divert
1353 @end example
1355 @noindent
1356 all yield the string @samp{divert}.  While in both:
1358 @example
1359 `'divert
1360 @result{}
1361 divert`'
1362 @result{}
1363 @end example
1365 @noindent
1366 the @code{divert} builtin macro will be called, which expands to the
1367 empty string.
1369 @cindex rescanning
1370 The output of macro evaluations is always rescanned.  In the following
1371 example, the input @samp{x`'y} yields the string @samp{bCD}, exactly as
1372 if @code{m4}
1373 has been given @w{@samp{substr(ab`'cde, `1', `3')}} as input:
1375 @example
1376 define(`cde', `CDE')
1377 @result{}
1378 define(`x', `substr(ab')
1379 @result{}
1380 define(`y', `cde, `1', `3')')
1381 @result{}
1382 x`'y
1383 @result{}bCD
1384 @end example
1386 @ignore
1387 @comment Similar, but with argument references, to ensure good test
1388 @comment coverage.
1389 @example
1390 define(`x1', `len(`$1'')
1391 @result{}
1392 define(`y1', ``$1')')
1393 @result{}
1394 x1(`01234567890123456789')y1(`98765432109876543210')
1395 @result{}40
1396 @end example
1397 @end ignore
1399 Unquoted strings on either side of a quoted string are subject to
1400 being recognized as macro names.  In the following example, quoting the
1401 empty string allows for the second @code{macro} to be recognized as such:
1403 @example
1404 define(`macro', `m')
1405 @result{}
1406 macro(`m')macro
1407 @result{}mmacro
1408 macro(`m')`'macro
1409 @result{}mm
1410 @end example
1412 Quoting may prevent recognizing as a macro name the concatenation of a
1413 macro expansion with the surrounding characters.  In this example:
1415 @example
1416 define(`macro', `di$1')
1417 @result{}
1418 macro(`v')`ert'
1419 @result{}divert
1420 macro(`v')ert
1421 @result{}
1422 @end example
1424 @noindent
1425 the input will produce the string @samp{divert}.  When the quotes were
1426 removed, the @code{divert} builtin was called instead.
1428 @node Macro Arguments
1429 @section Macro arguments
1431 @cindex macros, arguments to
1432 @cindex arguments to macros
1433 When a name is seen, and it has a macro definition, it will be expanded
1434 as a macro.
1436 If the name is followed by an opening parenthesis, the arguments will be
1437 collected before the macro is called.  If too few arguments are
1438 supplied, the missing arguments are taken to be the empty string.
1439 However, some builtins are documented to behave differently for a
1440 missing optional argument than for an explicit empty string.  If there
1441 are too many arguments, the excess arguments are ignored.  Unquoted
1442 leading whitespace is stripped off all arguments, but whitespace
1443 generated by a macro expansion or occurring after a macro that expanded
1444 to an empty string remains intact.  Whitespace includes space, tab,
1445 newline, carriage return, vertical tab, and formfeed.
1447 @example
1448 define(`macro', `$1')
1449 @result{}
1450 macro( unquoted leading space lost)
1451 @result{}unquoted leading space lost
1452 macro(` quoted leading space kept')
1453 @result{} quoted leading space kept
1454 macro(
1455  divert `unquoted space kept after expansion')
1456 @result{} unquoted space kept after expansion
1457 macro(macro(`
1458 ')`whitespace from expansion kept')
1459 @result{}
1460 @result{}whitespace from expansion kept
1461 macro(`unquoted trailing whitespace kept'
1463 @result{}unquoted trailing whitespace kept
1464 @result{}
1465 @end example
1467 @cindex warnings, suppressing
1468 @cindex suppressing warnings
1469 Normally @code{m4} will issue warnings if a builtin macro is called
1470 with an inappropriate number of arguments, but it can be suppressed with
1471 the @option{--quiet} command line option (or @option{--silent}, or
1472 @option{-Q}, @pxref{Operation modes, , Invoking m4}).  For user
1473 defined macros, there is no check of the number of arguments given.
1475 @example
1476 $ @kbd{m4}
1477 index(`abc')
1478 @error{}m4:stdin:1: Warning: index: too few arguments: 1 < 2
1479 @result{}0
1480 index(`abc',)
1481 @result{}0
1482 index(`abc', `b', `ignored')
1483 @error{}m4:stdin:3: Warning: index: extra arguments ignored: 3 > 2
1484 @result{}1
1485 @end example
1487 @comment options: -Q
1488 @example
1489 $ @kbd{m4 -Q}
1490 index(`abc')
1491 @result{}0
1492 index(`abc',)
1493 @result{}0
1494 index(`abc', `b', `ignored')
1495 @result{}1
1496 @end example
1498 Macros are expanded normally during argument collection, and whatever
1499 commas, quotes and parentheses that might show up in the resulting
1500 expanded text will serve to define the arguments as well.  Thus, if
1501 @var{foo} expands to @samp{, b, c}, the macro call
1503 @comment ignore
1504 @example
1505 bar(a foo, d)
1506 @end example
1508 @noindent
1509 is a macro call with four arguments, which are @samp{a }, @samp{b},
1510 @samp{c} and @samp{d}.  To understand why the first argument contains
1511 whitespace, remember that unquoted leading whitespace is never part
1512 of an argument, but trailing whitespace always is.
1514 It is possible for a macro's definition to change during argument
1515 collection, in which case the expansion uses the definition that was in
1516 effect at the time the opening @samp{(} was seen.
1518 @example
1519 define(`f', `1')
1520 @result{}
1521 f(define(`f', `2'))
1522 @result{}1
1524 @result{}2
1525 @end example
1527 It is an error if the end of file occurs while collecting arguments.
1529 @comment status: 1
1530 @example
1531 hello world
1532 @result{}hello world
1533 define(
1535 @error{}m4:stdin:2: define: end of file in argument list
1536 @end example
1538 @node Quoting Arguments
1539 @section On Quoting Arguments to macros
1541 @cindex quoted macro arguments
1542 @cindex macros, quoted arguments to
1543 @cindex arguments, quoted macro
1544 Each argument has unquoted leading whitespace removed.  Within each
1545 argument, all unquoted parentheses must match.  For example, if
1546 @var{foo} is a macro,
1548 @comment ignore
1549 @example
1550 foo(() (`(') `(')
1551 @end example
1553 @noindent
1554 is a macro call, with one argument, whose value is @samp{() (() (}.
1555 Commas separate arguments, except when they occur inside quotes,
1556 comments, or unquoted parentheses.  @xref{Pseudo Arguments}, for
1557 examples.
1559 It is common practice to quote all arguments to macros, unless you are
1560 sure you want the arguments expanded.  Thus, in the above
1561 example with the parentheses, the `right' way to do it is like this:
1563 @comment ignore
1564 @example
1565 foo(`() (() (')
1566 @end example
1568 @cindex quoting rule of thumb
1569 @cindex rule of thumb, quoting
1570 It is, however, in certain cases necessary (because nested expansion
1571 must occur to create the arguments for the outer macro) or convenient
1572 (because it uses fewer characters) to leave out quotes for some
1573 arguments, and there is nothing wrong in doing it.  It just makes life a
1574 bit harder, if you are not careful to follow a consistent quoting style.
1575 For consistency, this manual follows the rule of thumb that each layer
1576 of parentheses introduces another layer of single quoting, except when
1577 showing the consequences of quoting rules.  This is done even when the
1578 quoted string cannot be a macro, such as with integers when you have not
1579 changed the syntax via @code{changeword} (@pxref{Changeword}).
1581 The quoting rule of thumb of one level of quoting per parentheses has a
1582 nice property: when a macro name appears inside parentheses, you can
1583 determine when it will be expanded.  If it is not quoted, it will be
1584 expanded prior to the outer macro, so that its expansion becomes the
1585 argument.  If it is single-quoted, it will be expanded after the outer
1586 macro.  And if it is double-quoted, it will be used as literal text
1587 instead of a macro name.
1589 @example
1590 define(`active', `ACT, IVE')
1591 @result{}
1592 define(`show', `$1 $1')
1593 @result{}
1594 show(active)
1595 @result{}ACT ACT
1596 show(`active')
1597 @result{}ACT, IVE ACT, IVE
1598 show(``active'')
1599 @result{}active active
1600 @end example
1602 @node Macro expansion
1603 @section Macro expansion
1605 @cindex macros, expansion of
1606 @cindex expansion of macros
1607 When the arguments, if any, to a macro call have been collected, the
1608 macro is expanded, and the expansion text is pushed back onto the input
1609 (unquoted), and reread.  The expansion text from one macro call might
1610 therefore result in more macros being called, if the calls are included,
1611 completely or partially, in the first macro calls' expansion.
1613 Taking a very simple example, if @var{foo} expands to @samp{bar}, and
1614 @var{bar} expands to @samp{Hello}, the input
1616 @comment options: -Dbar=Hello -Dfoo=bar
1617 @example
1618 $ @kbd{m4 -Dbar=Hello -Dfoo=bar}
1620 @result{}Hello
1621 @end example
1623 @noindent
1624 will expand first to @samp{bar}, and when this is reread and
1625 expanded, into @samp{Hello}.
1627 @ignore
1628 @comment not worth documenting, but test that the command line can
1629 @comment define macros that take parameters
1631 @comment options: -Dfoo -Decho=$@
1632 @example
1633 $ @kbd{m4 -Dfoo -Decho='$@'}
1635 @result{}
1636 foo(`silently ignored')
1637 @result{}
1638 echo(`1', `2')
1639 @result{}1,2
1640 @end example
1641 @end ignore
1643 @node Definitions
1644 @chapter How to define new macros
1646 @cindex macros, how to define new
1647 @cindex defining new macros
1648 Macros can be defined, redefined and deleted in several different ways.
1649 Also, it is possible to redefine a macro without losing a previous
1650 value, and bring back the original value at a later time.
1652 @menu
1653 * Define::                      Defining a new macro
1654 * Arguments::                   Arguments to macros
1655 * Pseudo Arguments::            Special arguments to macros
1656 * Undefine::                    Deleting a macro
1657 * Defn::                        Renaming macros
1658 * Pushdef::                     Temporarily redefining macros
1660 * Indir::                       Indirect call of macros
1661 * Builtin::                     Indirect call of builtins
1662 @end menu
1664 @node Define
1665 @section Defining a macro
1667 The normal way to define or redefine macros is to use the builtin
1668 @code{define}:
1670 @deffn Builtin define (@var{name}, @ovar{expansion})
1671 Defines @var{name} to expand to @var{expansion}.  If
1672 @var{expansion} is not given, it is taken to be empty.
1674 The expansion of @code{define} is void.
1675 The macro @code{define} is recognized only with parameters.
1676 @end deffn
1678 The following example defines the macro @var{foo} to expand to the text
1679 @samp{Hello World.}.
1681 @example
1682 define(`foo', `Hello world.')
1683 @result{}
1685 @result{}Hello world.
1686 @end example
1688 The empty line in the output is there because the newline is not
1689 a part of the macro definition, and it is consequently copied to
1690 the output.  This can be avoided by use of the macro @code{dnl}.
1691 @xref{Dnl}, for details.
1693 The first argument to @code{define} should be quoted; otherwise, if the
1694 macro is already defined, you will be defining a different macro.  This
1695 example shows the problems with underquoting, since we did not want to
1696 redefine @code{one}:
1698 @example
1699 define(foo, one)
1700 @result{}
1701 define(foo, two)
1702 @result{}
1704 @result{}two
1705 @end example
1707 @cindex @acronym{GNU} extensions
1708 @acronym{GNU} @code{m4} normally replaces only the @emph{topmost}
1709 definition of a macro if it has several definitions from @code{pushdef}
1710 (@pxref{Pushdef}).  Some other implementations of @code{m4} replace all
1711 definitions of a macro with @code{define}.  @xref{Incompatibilities},
1712 for more details.
1714 As a @acronym{GNU} extension, the first argument to @code{define} does
1715 not have to be a simple word.
1716 It can be any text string, even the empty string.  A macro with a
1717 non-standard name cannot be invoked in the normal way, as the name is
1718 not recognized.  It can only be referenced by the builtins @code{indir}
1719 (@pxref{Indir}) and @code{defn} (@pxref{Defn}).
1721 @cindex arrays
1722 Arrays and associative arrays can be simulated by using non-standard
1723 macro names.
1725 @deffn Composite array (@var{index})
1726 @deffnx Composite array_set (@var{index}, @ovar{value})
1727 Provide access to entries within an array.  @code{array} reads the entry
1728 at location @var{index}, and @code{array_set} assigns @var{value} to
1729 location @var{index}.
1730 @end deffn
1732 @example
1733 define(`array', `defn(format(``array[%d]'', `$1'))')
1734 @result{}
1735 define(`array_set', `define(format(``array[%d]'', `$1'), `$2')')
1736 @result{}
1737 array_set(`4', `array element no. 4')
1738 @result{}
1739 array_set(`17', `array element no. 17')
1740 @result{}
1741 array(`4')
1742 @result{}array element no. 4
1743 array(eval(`10 + 7'))
1744 @result{}array element no. 17
1745 @end example
1747 Change the @samp{%d} to @samp{%s} and it is an associative array.
1749 @node Arguments
1750 @section Arguments to macros
1752 @cindex macros, arguments to
1753 @cindex arguments to macros
1754 Macros can have arguments.  The @var{n}th argument is denoted by
1755 @code{$n} in the expansion text, and is replaced by the @var{n}th actual
1756 argument, when the macro is expanded.  Replacement of arguments happens
1757 before rescanning, regardless of how many nesting levels of quoting
1758 appear in the expansion.  Here is an example of a macro with
1759 two arguments.
1761 @deffn Composite exch (@var{arg1}, @var{arg2})
1762 Expands to @var{arg2} followed by @var{arg1}, effectively exchanging
1763 their order.
1764 @end deffn
1766 @example
1767 define(`exch', `$2, $1')
1768 @result{}
1769 exch(`arg1', `arg2')
1770 @result{}arg2, arg1
1771 @end example
1773 This can be used, for example, if you like the arguments to
1774 @code{define} to be reversed.
1776 @example
1777 define(`exch', `$2, $1')
1778 @result{}
1779 define(exch(``expansion text'', ``macro''))
1780 @result{}
1781 macro
1782 @result{}expansion text
1783 @end example
1785 @xref{Quoting Arguments}, for an explanation of the double quotes.
1786 (You should try and improve this example so that clients of @code{exch}
1787 do not have to double quote; or @pxref{Improved exch, , Answers}).
1789 As a special case, the zeroth argument, @code{$0}, is always the name
1790 of the macro being expanded.
1792 @example
1793 define(`test', ``Macro name: $0'')
1794 @result{}
1795 test
1796 @result{}Macro name: test
1797 @end example
1799 If you want quoted text to appear as part of the expansion text,
1800 remember that quotes can be nested in quoted strings.  Thus, in
1802 @example
1803 define(`foo', `This is macro `foo'.')
1804 @result{}
1806 @result{}This is macro foo.
1807 @end example
1809 @noindent
1810 The @samp{foo} in the expansion text is @emph{not} expanded, since it is
1811 a quoted string, and not a name.
1813 @cindex @acronym{GNU} extensions
1814 @cindex nine arguments, more than
1815 @cindex more than nine arguments
1816 @cindex arguments, more than nine
1817 @cindex positional parameters, more than nine
1818 @acronym{GNU} @code{m4} allows the number following the @samp{$} to
1819 consist of one or more digits, allowing macros to have any number of
1820 arguments.  The extension of accepting multiple digits is incompatible
1821 with @acronym{POSIX}, and is different than traditional implementations
1822 of @code{m4}, which only recognize one digit.  Therefore, future
1823 versions of @acronym{GNU} M4 will phase out this feature.  To portably
1824 access beyond the ninth argument, you can use the @code{argn} macro
1825 documented later (@pxref{Shift}).
1827 @acronym{POSIX} also states that @samp{$} followed immediately by
1828 @samp{@{} in a macro definition is implementation-defined.  This version
1829 of M4 passes the literal characters @samp{$@{} through unchanged, but M4
1830 2.0 will implement an optional feature similar to @command{sh}, where
1831 @samp{$@{11@}} expands to the eleventh argument, to replace the current
1832 recognition of @samp{$11}.  Meanwhile, if you want to guarantee that you
1833 will get a literal @samp{$@{} in output when expanding a macro, even
1834 when you upgrade to M4 2.0, you can use nested quoting to your
1835 advantage:
1837 @example
1838 define(`foo', `single quoted $`'@{1@} output')
1839 @result{}
1840 define(`bar', ``double quoted $'`@{2@} output'')
1841 @result{}
1842 foo(`a', `b')
1843 @result{}single quoted $@{1@} output
1844 bar(`a', `b')
1845 @result{}double quoted $@{2@} output
1846 @end example
1848 To help you detect places in your M4 input files that might change in
1849 behavior due to the changed behavior of M4 2.0, you can use the
1850 @option{--warn-macro-sequence} command-line option (@pxref{Operation
1851 modes, , Invoking m4}) with the default regular expression.  This will
1852 add a warning any time a macro definition includes @samp{$} followed by
1853 multiple digits, or by @samp{@{}.  The warning is not enabled by
1854 default, because it triggers a number of warnings in Autoconf 2.61 (and
1855 Autoconf uses @option{-E} to treat warnings as errors), and because it
1856 will still be possible to restore older behavior in M4 2.0.
1858 @comment options: --warn-macro-sequence
1859 @example
1860 $ @kbd{m4 --warn-macro-sequence}
1861 define(`foo', `$001 $@{1@} $1')
1862 @error{}m4:stdin:1: Warning: definition of `foo' contains sequence `$001'
1863 @error{}m4:stdin:1: Warning: definition of `foo' contains sequence `$@{1@}'
1864 @result{}
1865 foo(`bar')
1866 @result{}bar $@{1@} bar
1867 @end example
1869 @node Pseudo Arguments
1870 @section Special arguments to macros
1872 @cindex special arguments to macros
1873 @cindex macros, special arguments to
1874 @cindex arguments to macros, special
1875 There is a special notation for the number of actual arguments supplied,
1876 and for all the actual arguments.
1878 The number of actual arguments in a macro call is denoted by @code{$#}
1879 in the expansion text.
1881 @deffn Composite nargs (@dots{})
1882 Expands to a count of the number of arguments supplied.
1883 @end deffn
1885 @example
1886 define(`nargs', `$#')
1887 @result{}
1888 nargs
1889 @result{}0
1890 nargs()
1891 @result{}1
1892 nargs(`arg1', `arg2', `arg3')
1893 @result{}3
1894 nargs(`commas can be quoted, like this')
1895 @result{}1
1896 nargs(arg1#inside comments, commas do not separate arguments
1897 still arg1)
1898 @result{}1
1899 nargs((unquoted parentheses, like this, group arguments))
1900 @result{}1
1901 @end example
1903 Remember that @samp{#} defaults to the comment character; if you forget
1904 quotes to inhibit the comment behavior, your macro definition may not
1905 end where you expected.
1907 @example
1908 dnl Attempt to define a macro to just `$#'
1909 define(underquoted, $#)
1910 oops)
1911 @result{}
1912 underquoted
1913 @result{}0)
1914 @result{}oops
1915 @end example
1917 The notation @code{$*} can be used in the expansion text to denote all
1918 the actual arguments, unquoted, with commas in between.  For example
1920 @example
1921 define(`echo', `$*')
1922 @result{}
1923 echo(arg1,    arg2, arg3 , arg4)
1924 @result{}arg1,arg2,arg3 ,arg4
1925 @end example
1927 Often each argument should be quoted, and the notation @code{$@@} handles
1928 that.  It is just like @code{$*}, except that it quotes each argument.
1929 A simple example of that is:
1931 @example
1932 define(`echo', `$@@')
1933 @result{}
1934 echo(arg1,    arg2, arg3 , arg4)
1935 @result{}arg1,arg2,arg3 ,arg4
1936 @end example
1938 Where did the quotes go?  Of course, they were eaten, when the expanded
1939 text were reread by @code{m4}.  To show the difference, try
1941 @example
1942 define(`echo1', `$*')
1943 @result{}
1944 define(`echo2', `$@@')
1945 @result{}
1946 define(`foo', `This is macro `foo'.')
1947 @result{}
1948 echo1(foo)
1949 @result{}This is macro This is macro foo..
1950 echo1(`foo')
1951 @result{}This is macro foo.
1952 echo2(foo)
1953 @result{}This is macro foo.
1954 echo2(`foo')
1955 @result{}foo
1956 @end example
1958 @noindent
1959 @xref{Trace}, if you do not understand this.  As another example of the
1960 difference, remember that comments encountered in arguments are passed
1961 untouched to the macro, and that quoting disables comments.
1963 @example
1964 define(`echo1', `$*')
1965 @result{}
1966 define(`echo2', `$@@')
1967 @result{}
1968 define(`foo', `bar')
1969 @result{}
1970 echo1(#foo'foo
1971 foo)
1972 @result{}#foo'foo
1973 @result{}bar
1974 echo2(#foo'foo
1975 foo)
1976 @result{}#foobar
1977 @result{}bar'
1978 @end example
1980 @ignore
1981 @comment Not worth putting in the manual, but this example is needed for
1982 @comment good test coverage of copying large strings across recursion
1983 @comment levels.
1985 @example
1986 define(`echo', `$@@')dnl
1987 echo(echo(`01234567890123456789', `01234567890123456789')
1988 echo(`98765432109876543210', `98765432109876543210'))
1989 @result{}01234567890123456789,01234567890123456789
1990 @result{}98765432109876543210,98765432109876543210
1991 len((echo(`01234567890123456789',
1992           `01234567890123456789')echo(`98765432109876543210',
1993                                       `98765432109876543210')))
1994 @result{}84
1995 indir(`echo', indir(`echo', `01234567890123456789',
1996                             `01234567890123456789')
1997 indir(`echo', `98765432109876543210', `98765432109876543210'))
1998 @result{}01234567890123456789,01234567890123456789
1999 @result{}98765432109876543210,98765432109876543210
2000 define(`argn', `$#')dnl
2001 define(`echo1', `-$@@-')define(`echo2', `,$@@,')dnl
2002 echo1(`1', `2', `3') argn(echo1(`1', `2', `3'))
2003 @result{}-1,2,3- 3
2004 echo2(`1', `2', `3') argn(echo2(`1', `2', `3'))
2005 @result{},1,2,3, 5
2006 @end example
2007 @end ignore
2009 A @samp{$} sign in the expansion text, that is not followed by anything
2010 @code{m4} understands, is simply copied to the macro expansion, as any
2011 other text is.
2013 @example
2014 define(`foo', `$$$ hello $$$')
2015 @result{}
2017 @result{}$$$ hello $$$
2018 @end example
2020 @cindex rescanning
2021 @cindex literal output
2022 @cindex output, literal
2023 If you want a macro to expand to something like @samp{$12}, the
2024 judicious use of nested quoting can put a safe character between the
2025 @code{$} and the next character, relying on the rescanning to remove the
2026 nested quote.  This will prevent @code{m4} from interpreting the
2027 @code{$} sign as a reference to an argument.
2029 @example
2030 define(`foo', `no nested quote: $1')
2031 @result{}
2032 foo(`arg')
2033 @result{}no nested quote: arg
2034 define(`foo', `nested quote around $: `$'1')
2035 @result{}
2036 foo(`arg')
2037 @result{}nested quote around $: $1
2038 define(`foo', `nested empty quote after $: $`'1')
2039 @result{}
2040 foo(`arg')
2041 @result{}nested empty quote after $: $1
2042 define(`foo', `nested quote around next character: $`1'')
2043 @result{}
2044 foo(`arg')
2045 @result{}nested quote around next character: $1
2046 define(`foo', `nested quote around both: `$1'')
2047 @result{}
2048 foo(`arg')
2049 @result{}nested quote around both: arg
2050 @end example
2052 @node Undefine
2053 @section Deleting a macro
2055 @cindex macros, how to delete
2056 @cindex deleting macros
2057 @cindex undefining macros
2058 A macro definition can be removed with @code{undefine}:
2060 @deffn Builtin undefine (@var{name}@dots{})
2061 For each argument, remove the macro @var{name}.  The macro names must
2062 necessarily be quoted, since they will be expanded otherwise.
2064 The expansion of @code{undefine} is void.
2065 The macro @code{undefine} is recognized only with parameters.
2066 @end deffn
2068 @example
2069 foo bar blah
2070 @result{}foo bar blah
2071 define(`foo', `some')define(`bar', `other')define(`blah', `text')
2072 @result{}
2073 foo bar blah
2074 @result{}some other text
2075 undefine(`foo')
2076 @result{}
2077 foo bar blah
2078 @result{}foo other text
2079 undefine(`bar', `blah')
2080 @result{}
2081 foo bar blah
2082 @result{}foo bar blah
2083 @end example
2085 Undefining a macro inside that macro's expansion is safe; the macro
2086 still expands to the definition that was in effect at the @samp{(}.
2088 @example
2089 define(`f', ``$0':$1')
2090 @result{}
2091 f(f(f(undefine(`f')`hello world')))
2092 @result{}f:f:f:hello world
2093 f(`bye')
2094 @result{}f(bye)
2095 @end example
2097 It is not an error for @var{name} to have no macro definition.  In that
2098 case, @code{undefine} does nothing.
2100 @node Defn
2101 @section Renaming macros
2103 @cindex macros, how to rename
2104 @cindex renaming macros
2105 @cindex macros, displaying definitions
2106 @cindex definitions, displaying macro
2107 It is possible to rename an already defined macro.  To do this, you need
2108 the builtin @code{defn}:
2110 @deffn Builtin defn (@var{name}@dots{})
2111 Expands to the @emph{quoted definition} of each @var{name}.  If an
2112 argument is not a defined macro, the expansion for that argument is
2113 empty.
2115 If @var{name} is a user-defined macro, the quoted definition is simply
2116 the quoted expansion text.  If, instead, there is only one @var{name}
2117 and it is a builtin, the
2118 expansion is a special token, which points to the builtin's internal
2119 definition.  This token is only meaningful as the second argument to
2120 @code{define} (and @code{pushdef}), and is silently converted to an
2121 empty string in most other contexts.  Using multiple @var{name} to
2122 combine a builtin with anything else is not supported; a warning is
2123 issued and the builtin is omitted from the final expansion.
2125 The macro @code{defn} is recognized only with parameters.
2126 @end deffn
2128 Its normal use is best understood through an example, which shows how to
2129 rename @code{undefine} to @code{zap}:
2131 @example
2132 define(`zap', defn(`undefine'))
2133 @result{}
2134 zap(`undefine')
2135 @result{}
2136 undefine(`zap')
2137 @result{}undefine(zap)
2138 @end example
2140 In this way, @code{defn} can be used to copy macro definitions, and also
2141 definitions of builtin macros.  Even if the original macro is removed,
2142 the other name can still be used to access the definition.
2144 The fact that macro definitions can be transferred also explains why you
2145 should use @code{$0}, rather than retyping a macro's name in its
2146 definition:
2148 @example
2149 define(`foo', `This is `$0'')
2150 @result{}
2151 define(`bar', defn(`foo'))
2152 @result{}
2154 @result{}This is bar
2155 @end example
2157 Macros used as string variables should be referred through @code{defn},
2158 to avoid unwanted expansion of the text:
2160 @example
2161 define(`string', `The macro dnl is very useful
2163 @result{}
2164 string
2165 @result{}The macro@w{ }
2166 defn(`string')
2167 @result{}The macro dnl is very useful
2168 @result{}
2169 @end example
2171 @cindex rescanning
2172 However, it is important to remember that @code{m4} rescanning is purely
2173 textual.  If an unbalanced end-quote string occurs in a macro
2174 definition, the rescan will see that embedded quote as the termination
2175 of the quoted string, and the remainder of the macro's definition will
2176 be rescanned unquoted.  Thus it is a good idea to avoid unbalanced
2177 end-quotes in macro definitions or arguments to macros.
2179 @example
2180 define(`foo', a'a)
2181 @result{}
2182 define(`a', `A')
2183 @result{}
2184 define(`echo', `$@@')
2185 @result{}
2187 @result{}A'A
2188 defn(`foo')
2189 @result{}aA'
2190 echo(foo)
2191 @result{}AA'
2192 @end example
2194 On the other hand, it is possible to exploit the fact that @code{defn}
2195 can concatenate multiple macros prior to the rescanning phase, in order
2196 to join the definitions of macros that, in isolation, have unbalanced
2197 quotes.  This is particularly useful when one has used several macros to
2198 accumulate text that M4 should rescan as a whole.  In the example below,
2199 note how the use of @code{defn} on @code{l} in isolation opens a string,
2200 which is not closed until the next line; but used on @code{l} and
2201 @code{r} together results in nested quoting.
2203 @example
2204 define(`l', `<[>')define(`r', `<]>')
2205 @result{}
2206 changequote(`[', `]')
2207 @result{}
2208 defn([l])defn([r])
2210 @result{}<[>]defn([r])
2211 @result{})
2212 defn([l], [r])
2213 @result{}<[>][<]>
2214 @end example
2216 @cindex builtins, special tokens
2217 @cindex tokens, builtin macro
2218 Using @code{defn} to generate special tokens for builtin macros will
2219 generate a warning in contexts where a macro name is expected.  But in
2220 contexts that operate on text, the builtin token is just silently
2221 converted to an empty string.  As of M4 1.4.11, expansion of user macros
2222 will also preserve builtin tokens.  However, any use of builtin tokens
2223 outside of the second argument to @code{define} and @code{pushdef} is
2224 generally not portable, since earlier @acronym{GNU} M4 versions, as well
2225 as other @code{m4} implementations, vary on how such tokens are treated.
2227 @example
2228 $ @kbd{m4 -d}
2229 defn(`defn')
2230 @result{}
2231 define(defn(`divnum'), `cannot redefine a builtin token')
2232 @error{}m4:stdin:2: Warning: define: invalid macro name ignored
2233 @result{}
2234 divnum
2235 @result{}0
2236 len(defn(`divnum'))
2237 @result{}0
2238 define(`echo', `$@@')
2239 @result{}
2240 define(`mydivnum', shift(echo(`', defn(`divnum'))))
2241 @result{}
2242 mydivnum
2243 @result{}0
2244 define(`', `empty-$1')
2245 @result{}
2246 defn(defn(`divnum'))
2247 @error{}m4:stdin:9: Warning: defn: invalid macro name ignored
2248 @result{}
2249 pushdef(defn(`divnum'), `oops')
2250 @error{}m4:stdin:10: Warning: pushdef: invalid macro name ignored
2251 @result{}
2252 traceon(defn(`divnum'))
2253 @error{}m4:stdin:11: Warning: traceon: invalid macro name ignored
2254 @result{}
2255 indir(defn(`divnum'), `string')
2256 @error{}m4:stdin:12: Warning: indir: invalid macro name ignored
2257 @result{}
2258 indir(`', `string')
2259 @result{}empty-string
2260 traceoff(defn(`divnum'))
2261 @error{}m4:stdin:14: Warning: traceoff: invalid macro name ignored
2262 @result{}
2263 popdef(defn(`divnum'))
2264 @error{}m4:stdin:15: Warning: popdef: invalid macro name ignored
2265 @result{}
2266 dumpdef(defn(`divnum'))
2267 @error{}m4:stdin:16: Warning: dumpdef: invalid macro name ignored
2268 @result{}
2269 undefine(defn(`divnum'))
2270 @error{}m4:stdin:17: Warning: undefine: invalid macro name ignored
2271 @result{}
2272 dumpdef(`')
2273 @error{}:@tabchar{}`empty-$1'
2274 @result{}
2275 define(`foo', `define(`$1', $2)')dnl
2276 foo(`bar', defn(`divnum'))
2277 @result{}
2279 @result{}0
2280 @end example
2282 Also note that @code{defn} with multiple arguments can only join text
2283 macros, not builtins.  Likewise, when collecting macro arguments, a
2284 builtin token is preserved only when it occurs in isolation.  A future
2285 version of @acronym{GNU} M4 may lift these restrictions.
2287 @example
2288 $ @kbd{m4 -d}
2289 define(`a', `A')define(`AA', `b')
2290 @result{}
2291 traceon(`defn', `define')
2292 @result{}
2293 defn(`a', `divnum', `a')
2294 @error{}m4:stdin:3: Warning: defn: cannot concatenate builtin `divnum'
2295 @error{}m4trace: -1- defn(`a', `divnum', `a') -> ``A'`A''
2296 @result{}AA
2297 define(`mydivnum', defn(`divnum', `divnum'))mydivnum
2298 @error{}m4:stdin:4: Warning: defn: cannot concatenate builtin `divnum'
2299 @error{}m4:stdin:4: Warning: defn: cannot concatenate builtin `divnum'
2300 @error{}m4trace: -2- defn(`divnum', `divnum')
2301 @error{}m4trace: -1- define(`mydivnum', `')
2302 @result{}
2303 traceoff(`defn', `define')
2304 @result{}
2305 define(`mydivnum', defn(`divnum')defn(`divnum'))mydivnum
2306 @error{}m4:stdin:6: Warning: define: cannot concatenate builtin `divnum'
2307 @error{}m4:stdin:6: Warning: define: cannot concatenate builtin `divnum'
2308 @result{}
2309 define(`mydivnum', defn(`divnum')`a')mydivnum
2310 @error{}m4:stdin:7: Warning: define: cannot concatenate builtin `divnum'
2311 @result{}A
2312 define(`mydivnum', `a'defn(`divnum'))mydivnum
2313 @error{}m4:stdin:8: Warning: define: cannot concatenate builtin `divnum'
2314 @result{}A
2315 define(`q', ``$@@'')
2316 @result{}
2317 define(`foo', q(`a', defn(`divnum')))foo
2318 @error{}m4:stdin:10: Warning: define: cannot quote builtin
2319 @result{}a,
2320 ifdef(`foo', `yes', `no')
2321 @result{}yes
2322 @end example
2324 @node Pushdef
2325 @section Temporarily redefining macros
2327 @cindex macros, temporary redefinition of
2328 @cindex temporary redefinition of macros
2329 @cindex redefinition of macros, temporary
2330 @cindex definition stack
2331 @cindex stack, macro definition
2332 It is possible to redefine a macro temporarily, reverting to the
2333 previous definition at a later time.  This is done with the builtins
2334 @code{pushdef} and @code{popdef}:
2336 @deffn Builtin pushdef (@var{name}, @ovar{expansion})
2337 @deffnx Builtin popdef (@var{name}@dots{})
2338 Analogous to @code{define} and @code{undefine}.
2340 These macros work in a stack-like fashion.  A macro is temporarily
2341 redefined with @code{pushdef}, which replaces an existing definition of
2342 @var{name}, while saving the previous definition, before the new one is
2343 installed.  If there is no previous definition, @code{pushdef} behaves
2344 exactly like @code{define}.
2346 If a macro has several definitions (of which only one is accessible),
2347 the topmost definition can be removed with @code{popdef}.  If there is
2348 no previous definition, @code{popdef} behaves like @code{undefine}.
2350 The expansion of both @code{pushdef} and @code{popdef} is void.
2351 The macros @code{pushdef} and @code{popdef} are recognized only with
2352 parameters.
2353 @end deffn
2355 @example
2356 define(`foo', `Expansion one.')
2357 @result{}
2359 @result{}Expansion one.
2360 pushdef(`foo', `Expansion two.')
2361 @result{}
2363 @result{}Expansion two.
2364 pushdef(`foo', `Expansion three.')
2365 @result{}
2366 pushdef(`foo', `Expansion four.')
2367 @result{}
2368 popdef(`foo')
2369 @result{}
2371 @result{}Expansion three.
2372 popdef(`foo', `foo')
2373 @result{}
2375 @result{}Expansion one.
2376 popdef(`foo')
2377 @result{}
2379 @result{}foo
2380 @end example
2382 If a macro with several definitions is redefined with @code{define}, the
2383 topmost definition is @emph{replaced} with the new definition.  If it is
2384 removed with @code{undefine}, @emph{all} the definitions are removed,
2385 and not only the topmost one.  However, @acronym{POSIX} allows other
2386 implementations that treat @code{define} as replacing an entire stack
2387 of definitions with a single new definition, so to be portable to other
2388 implementations, it may be worth explicitly using @code{popdef} and
2389 @code{pushdef} rather than relying on the @acronym{GNU} behavior of
2390 @code{define}.
2392 @example
2393 define(`foo', `Expansion one.')
2394 @result{}
2396 @result{}Expansion one.
2397 pushdef(`foo', `Expansion two.')
2398 @result{}
2400 @result{}Expansion two.
2401 define(`foo', `Second expansion two.')
2402 @result{}
2404 @result{}Second expansion two.
2405 undefine(`foo')
2406 @result{}
2408 @result{}foo
2409 @end example
2411 @cindex local variables
2412 @cindex variables, local
2413 Local variables within macros are made with @code{pushdef} and
2414 @code{popdef}.  At the start of the macro a new definition is pushed,
2415 within the macro it is manipulated and at the end it is popped,
2416 revealing the former definition.
2418 It is possible to temporarily redefine a builtin with @code{pushdef}
2419 and @code{defn}.
2421 @node Indir
2422 @section Indirect call of macros
2424 @cindex indirect call of macros
2425 @cindex call of macros, indirect
2426 @cindex macros, indirect call of
2427 @cindex @acronym{GNU} extensions
2428 Any macro can be called indirectly with @code{indir}:
2430 @deffn Builtin indir (@var{name}, @ovar{args@dots{}})
2431 Results in a call to the macro @var{name}, which is passed the
2432 rest of the arguments @var{args}.  If @var{name} is not defined, an
2433 error message is printed, and the expansion is void.
2435 The macro @code{indir} is recognized only with parameters.
2436 @end deffn
2438 This can be used to call macros with computed or ``invalid''
2439 names (@code{define} allows such names to be defined):
2441 @example
2442 define(`$$internal$macro', `Internal macro (name `$0')')
2443 @result{}
2444 $$internal$macro
2445 @result{}$$internal$macro
2446 indir(`$$internal$macro')
2447 @result{}Internal macro (name $$internal$macro)
2448 @end example
2450 The point is, here, that larger macro packages can have private macros
2451 defined, that will not be called by accident.  They can @emph{only} be
2452 called through the builtin @code{indir}.
2454 One other point to observe is that argument collection occurs before
2455 @code{indir} invokes @var{name}, so if argument collection changes the
2456 value of @var{name}, that will be reflected in the final expansion.
2457 This is different than the behavior when invoking macros directly,
2458 where the definition that was in effect before argument collection is
2459 used.
2461 @example
2462 $ @kbd{m4 -d}
2463 define(`f', `1')
2464 @result{}
2465 f(define(`f', `2'))
2466 @result{}1
2467 indir(`f', define(`f', `3'))
2468 @result{}3
2469 indir(`f', undefine(`f'))
2470 @error{}m4:stdin:4: Warning: indir: undefined macro `f'
2471 @result{}
2472 @end example
2474 When handed the result of @code{defn} (@pxref{Defn}) as one of its
2475 arguments, @code{indir} defers to the invoked @var{name} for whether a
2476 token representing a builtin is recognized or flattened to the empty
2477 string.
2479 @example
2480 $ @kbd{m4 -d}
2481 indir(defn(`defn'), `divnum')
2482 @error{}m4:stdin:1: Warning: indir: invalid macro name ignored
2483 @result{}
2484 indir(`define', defn(`defn'), `divnum')
2485 @error{}m4:stdin:2: Warning: define: invalid macro name ignored
2486 @result{}
2487 indir(`define', `foo', defn(`divnum'))
2488 @result{}
2490 @result{}0
2491 indir(`divert', defn(`foo'))
2492 @error{}m4:stdin:5: Warning: divert: empty string treated as 0
2493 @result{}
2494 @end example
2496 Warning messages issued on behalf of an indirect macro use an
2497 unambiguous representation of the macro name, using escape sequences
2498 similar to C strings, and with colons also quoted.
2500 @example
2501 define(`%%:\
2502 odd', defn(`divnum'))
2503 @result{}
2504 indir(`%%:\
2505 odd', `extra')
2506 @error{}m4:stdin:3: Warning: %%\:\\\nodd: extra arguments ignored: 1 > 0
2507 @result{}0
2508 @end example
2510 @node Builtin
2511 @section Indirect call of builtins
2513 @cindex indirect call of builtins
2514 @cindex call of builtins, indirect
2515 @cindex builtins, indirect call of
2516 @cindex @acronym{GNU} extensions
2517 Builtin macros can be called indirectly with @code{builtin}:
2519 @deffn Builtin builtin (@var{name}, @ovar{args@dots{}})
2520 Results in a call to the builtin @var{name}, which is passed the
2521 rest of the arguments @var{args}.  If @var{name} does not name a
2522 builtin, an error message is printed, and the expansion is void.
2524 The macro @code{builtin} is recognized only with parameters.
2525 @end deffn
2527 This can be used even if @var{name} has been given another definition
2528 that has covered the original, or been undefined so that no macro
2529 maps to the builtin.
2531 @example
2532 pushdef(`define', `hidden')
2533 @result{}
2534 undefine(`undefine')
2535 @result{}
2536 define(`foo', `bar')
2537 @result{}hidden
2539 @result{}foo
2540 builtin(`define', `foo', defn(`divnum'))
2541 @result{}
2543 @result{}0
2544 builtin(`define', `foo', `BAR')
2545 @result{}
2547 @result{}BAR
2548 undefine(`foo')
2549 @result{}undefine(foo)
2551 @result{}BAR
2552 builtin(`undefine', `foo')
2553 @result{}
2555 @result{}foo
2556 @end example
2558 The @var{name} argument only matches the original name of the builtin,
2559 even when the @option{--prefix-builtins} option (or @option{-P},
2560 @pxref{Operation modes, , Invoking m4}) is in effect.  This is different
2561 from @code{indir}, which only tracks current macro names.
2563 @comment options: -P
2564 @example
2565 $ @kbd{m4 -P}
2566 m4_builtin(`divnum')
2567 @result{}0
2568 m4_builtin(`m4_divnum')
2569 @error{}m4:stdin:2: Warning: m4_builtin: undefined builtin `m4_divnum'
2570 @result{}
2571 m4_indir(`divnum')
2572 @error{}m4:stdin:3: Warning: m4_indir: undefined macro `divnum'
2573 @result{}
2574 m4_indir(`m4_divnum')
2575 @result{}0
2576 @end example
2578 Note that @code{indir} and @code{builtin} can be used to invoke builtins
2579 without arguments, even when they normally require parameters to be
2580 recognized; but it will provoke a warning, and result in a void expansion.
2582 @example
2583 builtin
2584 @result{}builtin
2585 builtin()
2586 @error{}m4:stdin:2: Warning: builtin: undefined builtin `'
2587 @result{}
2588 builtin(`builtin')
2589 @error{}m4:stdin:3: Warning: builtin: too few arguments: 0 < 1
2590 @result{}
2591 builtin(`builtin',)
2592 @error{}m4:stdin:4: Warning: builtin: undefined builtin `'
2593 @result{}
2594 @end example
2596 @ignore
2597 @comment This example is not worth putting in the manual, but it is
2598 @comment needed for full coverage.  Autoconf's m4_include relies heavily
2599 @comment on this feature.
2601 @example
2602 builtin(`include', `foo')dnl
2603 @result{}bar
2604 @end example
2606 @comment And this example triggers a regression present in 1.4.10b.
2608 @example
2609 define(`s', `builtin(`shift', $@@)')dnl
2610 define(`loop', `ifelse(`$2', `', `-', `$1$2: $0(`$1', s(s($@@)))')')dnl
2611 loop(`1')
2612 @result{}-
2613 loop(`1', `2')
2614 @result{}12: -
2615 loop(`1', `2', `3')
2616 @result{}12: 13: -
2617 loop(`1', `2', `3', `4')
2618 @result{}12: 13: 14: -
2619 loop(`1', `2', `3', `4', `5')
2620 @result{}12: 13: 14: 15: -
2621 @end example
2622 @end ignore
2624 @node Conditionals
2625 @chapter Conditionals, loops, and recursion
2627 Macros, expanding to plain text, perhaps with arguments, are not quite
2628 enough.  We would like to have macros expand to different things, based
2629 on decisions taken at run-time.  For that, we need some kind of conditionals.
2630 Also, we would like to have some kind of loop construct, so we could do
2631 something a number of times, or while some condition is true.
2633 @menu
2634 * Ifdef::                       Testing if a macro is defined
2635 * Ifelse::                      If-else construct, or multibranch
2636 * Shift::                       Recursion in @code{m4}
2637 * Forloop::                     Iteration by counting
2638 * Foreach::                     Iteration by list contents
2639 @end menu
2641 @node Ifdef
2642 @section Testing if a macro is defined
2644 @cindex conditionals
2645 There are two different builtin conditionals in @code{m4}.  The first is
2646 @code{ifdef}:
2648 @deffn Builtin ifdef (@var{name}, @var{string-1}, @ovar{string-2})
2649 If @var{name} is defined as a macro, @code{ifdef} expands to
2650 @var{string-1}, otherwise to @var{string-2}.  If @var{string-2} is
2651 omitted, it is taken to be the empty string (according to the normal
2652 rules).
2654 The macro @code{ifdef} is recognized only with parameters.
2655 @end deffn
2657 @example
2658 ifdef(`foo', ``foo' is defined', ``foo' is not defined')
2659 @result{}foo is not defined
2660 define(`foo', `')
2661 @result{}
2662 ifdef(`foo', ``foo' is defined', ``foo' is not defined')
2663 @result{}foo is defined
2664 ifdef(`no_such_macro', `yes', `no', `extra argument')
2665 @error{}m4:stdin:4: Warning: ifdef: extra arguments ignored: 4 > 3
2666 @result{}no
2667 @end example
2669 As of M4 1.4.11, @code{ifdef} transparently handles builtin tokens
2670 generated by @code{defn} (@pxref{Defn}) that occur in either
2671 @var{string}, although a warning is issued for invalid macro names.
2673 @example
2674 define(`', `empty')
2675 @result{}
2676 ifdef(defn(`defn'), `yes', `no')
2677 @error{}m4:stdin:2: Warning: ifdef: invalid macro name ignored
2678 @result{}no
2679 define(`foo', ifdef(`divnum', defn(`divnum'), `undefined'))
2680 @result{}
2682 @result{}0
2683 @end example
2685 @node Ifelse
2686 @section If-else construct, or multibranch
2688 @cindex comparing strings
2689 @cindex discarding input
2690 @cindex input, discarding
2691 The other conditional, @code{ifelse}, is much more powerful.  It can be
2692 used as a way to introduce a long comment, as an if-else construct, or
2693 as a multibranch, depending on the number of arguments supplied:
2695 @deffn Builtin ifelse (@var{comment})
2696 @deffnx Builtin ifelse (@var{string-1}, @var{string-2}, @var{equal}, @
2697   @ovar{not-equal})
2698 @deffnx Builtin ifelse (@var{string-1}, @var{string-2}, @var{equal-1}, @
2699   @var{string-3}, @var{string-4}, @var{equal-2}, @dots{}, @ovar{not-equal})
2700 Used with only one argument, the @code{ifelse} simply discards it and
2701 produces no output.
2703 If called with three or four arguments, @code{ifelse} expands into
2704 @var{equal}, if @var{string-1} and @var{string-2} are equal (character
2705 for character), otherwise it expands to @var{not-equal}.  A final fifth
2706 argument is ignored, after triggering a warning.
2708 If called with six or more arguments, and @var{string-1} and
2709 @var{string-2} are equal, @code{ifelse} expands into @var{equal-1},
2710 otherwise the first three arguments are discarded and the processing
2711 starts again.
2713 The macro @code{ifelse} is recognized only with parameters.
2714 @end deffn
2716 Using only one argument is a common @code{m4} idiom for introducing a
2717 block comment, as an alternative to repeatedly using @code{dnl}.  This
2718 special usage is recognized by @acronym{GNU} @code{m4}, so that in this
2719 case, the warning about missing arguments is never triggered.
2721 @example
2722 ifelse(`some comments')
2723 @result{}
2724 ifelse(`foo', `bar')
2725 @error{}m4:stdin:2: Warning: ifelse: too few arguments: 2 < 3
2726 @result{}
2727 @end example
2729 Using three or four arguments provides decision points.
2731 @example
2732 ifelse(`foo', `bar', `true')
2733 @result{}
2734 ifelse(`foo', `foo', `true')
2735 @result{}true
2736 define(`foo', `bar')
2737 @result{}
2738 ifelse(foo, `bar', `true', `false')
2739 @result{}true
2740 ifelse(foo, `foo', `true', `false')
2741 @result{}false
2742 @end example
2744 @cindex macro, blind
2745 @cindex blind macro
2746 Notice how the first argument was used unquoted; it is common to compare
2747 the expansion of a macro with a string.  With this macro, you can now
2748 reproduce the behavior of blind builtins, where the macro is recognized
2749 only with arguments.
2751 @example
2752 define(`foo', `ifelse(`$#', `0', ``$0'', `arguments:$#')')
2753 @result{}
2755 @result{}foo
2756 foo()
2757 @result{}arguments:1
2758 foo(`a', `b', `c')
2759 @result{}arguments:3
2760 @end example
2762 @cindex multibranches
2763 @cindex switch statement
2764 @cindex case statement
2765 However, @code{ifelse} can take more than four arguments.  If given more
2766 than four arguments, @code{ifelse} works like a @code{case} or @code{switch}
2767 statement in traditional programming languages.  If @var{string-1} and
2768 @var{string-2} are equal, @code{ifelse} expands into @var{equal-1}, otherwise
2769 the procedure is repeated with the first three arguments discarded.  This
2770 calls for an example:
2772 @example
2773 ifelse(`foo', `bar', `third', `gnu', `gnats')
2774 @error{}m4:stdin:1: Warning: ifelse: extra arguments ignored: 5 > 4
2775 @result{}gnu
2776 ifelse(`foo', `bar', `third', `gnu', `gnats', `sixth')
2777 @result{}
2778 ifelse(`foo', `bar', `third', `gnu', `gnats', `sixth', `seventh')
2779 @result{}seventh
2780 ifelse(`foo', `bar', `3', `gnu', `gnats', `6', `7', `8')
2781 @error{}m4:stdin:4: Warning: ifelse: extra arguments ignored: 8 > 7
2782 @result{}7
2783 @end example
2785 As of M4 1.4.11, @code{ifelse} transparently handles builtin tokens
2786 generated by @code{defn} (@pxref{Defn}).  Because of this, it is always
2787 safe to compare two macro definitions, without worrying whether the
2788 macro might be a builtin.
2790 @example
2791 ifelse(defn(`defn'), `', `yes', `no')
2792 @result{}no
2793 ifelse(defn(`defn'), defn(`divnum'), `yes', `no')
2794 @result{}no
2795 ifelse(defn(`defn'), defn(`defn'), `yes', `no')
2796 @result{}yes
2797 define(`foo', ifelse(`', `', defn(`divnum')))
2798 @result{}
2800 @result{}0
2801 @end example
2803 @ignore
2804 @comment Stress tests, not worth documenting.
2806 @comment Ensure that references compared to strings work regardless of
2807 @comment similar prefixes.
2808 @example
2809 define(`e', `$@@')define(`long', `01234567890123456789')
2810 @result{}
2811 ifelse(long, `01234567890123456789', `yes', `no')
2812 @result{}yes
2813 ifelse(`01234567890123456789', long, `yes', `no')
2814 @result{}yes
2815 ifelse(long, `01234567890123456789-', `yes', `no')
2816 @result{}no
2817 ifelse(`01234567890123456789-', long, `yes', `no')
2818 @result{}no
2819 ifelse(e(long), `01234567890123456789', `yes', `no')
2820 @result{}yes
2821 ifelse(`01234567890123456789', e(long), `yes', `no')
2822 @result{}yes
2823 ifelse(e(long), `01234567890123456789-', `yes', `no')
2824 @result{}no
2825 ifelse(`01234567890123456789-', e(long), `yes', `no')
2826 @result{}no
2827 ifelse(-e(long), `-01234567890123456789', `yes', `no')
2828 @result{}yes
2829 ifelse(-`01234567890123456789', -e(long), `yes', `no')
2830 @result{}yes
2831 ifelse(-e(long), `-01234567890123456789-', `yes', `no')
2832 @result{}no
2833 ifelse(`-01234567890123456789-', -e(long), `yes', `no')
2834 @result{}no
2835 ifelse(-e(long)-, `-01234567890123456789-', `yes', `no')
2836 @result{}yes
2837 ifelse(-`01234567890123456789-', -e(long)-, `yes', `no')
2838 @result{}yes
2839 ifelse(-e(long)-, `-01234567890123456789', `yes', `no')
2840 @result{}no
2841 ifelse(`-01234567890123456789', -e(long)-, `yes', `no')
2842 @result{}no
2843 ifelse(`-'e(long), `-01234567890123456789', `yes', `no')
2844 @result{}yes
2845 ifelse(-`01234567890123456789', `-'e(long), `yes', `no')
2846 @result{}yes
2847 ifelse(`-'e(long), `-01234567890123456789-', `yes', `no')
2848 @result{}no
2849 ifelse(`-01234567890123456789-', `-'e(long), `yes', `no')
2850 @result{}no
2851 ifelse(`-'e(long)`-', `-01234567890123456789-', `yes', `no')
2852 @result{}yes
2853 ifelse(-`01234567890123456789-', `-'e(long)`-', `yes', `no')
2854 @result{}yes
2855 ifelse(`-'e(long)`-', `-01234567890123456789', `yes', `no')
2856 @result{}no
2857 ifelse(`-01234567890123456789', `-'e(long)`-', `yes', `no')
2858 @result{}no
2859 @end example
2861 @comment It would be nice to pass builtin tokens through m4wrap, as well
2862 @comment as allowing concatenation of builtins in ifelse and user macros.
2863 @example
2864 define(`e', `$@@')define(`q', ``$@@'')define(`u', `$*')
2865 @result{}
2866 define(`cmp', `ifelse($1, $2, `yes', `no')')define(`d', defn(`defn'))
2867 @result{}
2868 cmp(`defn(`defn')', `defn(`d')')
2869 @result{}yes
2870 cmp(`defn(`defn')', ``<defn>'')
2871 @result{}no
2872 cmp(`q(defn(`defn'))', `q(defn(`d'))')-fixme
2873 @error{}m4:stdin:5: Warning: ifelse: cannot quote builtin
2874 @error{}m4:stdin:5: Warning: ifelse: cannot quote builtin
2875 @result{}yes-fixme
2876 cmp(`q(defn(`defn'))', `q(`<defn>')')-fixme
2877 @error{}m4:stdin:6: Warning: ifelse: cannot quote builtin
2878 @result{}no-fixme
2879 cmp(`q(defn(`defn'))', ``'')-fixme
2880 @error{}m4:stdin:7: Warning: ifelse: cannot quote builtin
2881 @result{}no-fixme
2882 cmp(`q(`1', `2', defn(`defn'))', `q(`1', `2', defn(`d'))')-fixme
2883 @error{}m4:stdin:8: Warning: ifelse: cannot quote builtin
2884 @error{}m4:stdin:8: Warning: ifelse: cannot quote builtin
2885 @result{}yes-fixme
2886 cmp(`q(`1', `2', defn(`defn'))', `q(`1', `2', `<defn>')')-fixme
2887 @error{}m4:stdin:9: Warning: ifelse: cannot quote builtin
2888 @result{}no-fixme
2889 cmp(`q(`1', `2', defn(`defn'))', ```1',`2',<defn>'')-fixme
2890 @error{}m4:stdin:10: Warning: ifelse: cannot quote builtin
2891 @result{}no-fixme
2892 cmp(`q(`1', `2', defn(`defn'))', ```1',`2',`''')-fixme
2893 @error{}m4:stdin:11: Warning: ifelse: cannot quote builtin
2894 @result{}yes-fixme
2895 define(`cat', `$1`'ifelse(`$#', `1', `', `$0(shift($@@))')')
2896 @result{}
2897 cat(`define(`foo',', defn(`divnum'), `)foo')-fixme
2898 @error{}m4:stdin:13: Warning: ifelse: cannot quote builtin
2899 @result{}-fixme
2900 cat(e(`define(`bar',', defn(`divnum'), `)bar'))-fixme
2901 @error{}m4:stdin:14: Warning: ifelse: cannot quote builtin
2902 @result{}-fixme
2903 m4wrap(`u('q(`cat(`define(`baz','', defn(`divnum'), ``)baz')')`)-fixme
2905 @error{}m4:stdin:15: Warning: m4wrap: cannot quote builtin
2906 @result{}
2908 @result{}-fixme
2909 @end example
2910 @end ignore
2912 Naturally, the normal case will be slightly more advanced than these
2913 examples.  A common use of @code{ifelse} is in macros implementing loops
2914 of various kinds.
2916 @node Shift
2917 @section Recursion in @code{m4}
2919 @cindex recursive macros
2920 @cindex macros, recursive
2921 There is no direct support for loops in @code{m4}, but macros can be
2922 recursive.  There is no limit on the number of recursion levels, other
2923 than those enforced by your hardware and operating system.
2925 @cindex loops
2926 Loops can be programmed using recursion and the conditionals described
2927 previously.
2929 There is a builtin macro, @code{shift}, which can, among other things,
2930 be used for iterating through the actual arguments to a macro:
2932 @deffn Builtin shift (@var{arg1}, @dots{})
2933 Takes any number of arguments, and expands to all its arguments except
2934 @var{arg1}, separated by commas, with each argument quoted.
2936 The macro @code{shift} is recognized only with parameters.
2937 @end deffn
2939 @example
2940 shift
2941 @result{}shift
2942 shift(`bar')
2943 @result{}
2944 shift(`foo', `bar', `baz')
2945 @result{}bar,baz
2946 @end example
2948 An example of the use of @code{shift} is this macro:
2950 @cindex reversing arguments
2951 @cindex arguments, reversing
2952 @deffn Composite reverse (@dots{})
2953 Takes any number of arguments, and reverses their order.
2954 @end deffn
2956 It is implemented as:
2958 @example
2959 define(`reverse', `ifelse(`$#', `0', , `$#', `1', ``$1'',
2960                           `reverse(shift($@@)), `$1'')')
2961 @result{}
2962 reverse
2963 @result{}
2964 reverse(`foo')
2965 @result{}foo
2966 reverse(`foo', `bar', `gnats', `and gnus')
2967 @result{}and gnus, gnats, bar, foo
2968 @end example
2970 While not a very interesting macro, it does show how simple loops can be
2971 made with @code{shift}, @code{ifelse} and recursion.  It also shows
2972 that @code{shift} is usually used with @samp{$@@}.  Another example of
2973 this is an implementation of a short-circuiting conditional operator.
2975 @cindex short-circuiting conditional
2976 @cindex conditional, short-circuiting
2977 @deffn Composite cond (@var{test-1}, @var{string-1}, @var{equal-1}, @
2978   @ovar{test-2}, @ovar{string-2}, @ovar{equal-2}, @dots{}, @ovar{not-equal})
2979 Similar to @code{ifelse}, where an equal comparison between the first
2980 two strings results in the third, otherwise the first three arguments
2981 are discarded and the process repeats.  The difference is that each
2982 @var{test-<n>} is expanded only when it is encountered.  This means that
2983 every third argument to @code{cond} is normally given one more level of
2984 quoting than the corresponding argument to @code{ifelse}.
2985 @end deffn
2987 Here is the implementation of @code{cond}, along with a demonstration of
2988 how it can short-circuit the side effects in @code{side}.  Notice how
2989 all the unquoted side effects happen regardless of how many comparisons
2990 are made with @code{ifelse}, compared with only the relevant effects
2991 with @code{cond}.
2993 @example
2994 define(`cond',
2995 `ifelse(`$#', `1', `$1',
2996         `ifelse($1, `$2', `$3',
2997                 `$0(shift(shift(shift($@@))))')')')dnl
2998 define(`side', `define(`counter', incr(counter))$1')dnl
2999 define(`example1',
3000 `define(`counter', `0')dnl
3001 ifelse(side(`$1'), `yes', `one comparison: ',
3002        side(`$1'), `no', `two comparisons: ',
3003        side(`$1'), `maybe', `three comparisons: ',
3004        `side(`default answer: ')')counter')dnl
3005 define(`example2',
3006 `define(`counter', `0')dnl
3007 cond(`side(`$1')', `yes', `one comparison: ',
3008      `side(`$1')', `no', `two comparisons: ',
3009      `side(`$1')', `maybe', `three comparisons: ',
3010      `side(`default answer: ')')counter')dnl
3011 example1(`yes')
3012 @result{}one comparison: 3
3013 example1(`no')
3014 @result{}two comparisons: 3
3015 example1(`maybe')
3016 @result{}three comparisons: 3
3017 example1(`feeling rather indecisive today')
3018 @result{}default answer: 4
3019 example2(`yes')
3020 @result{}one comparison: 1
3021 example2(`no')
3022 @result{}two comparisons: 2
3023 example2(`maybe')
3024 @result{}three comparisons: 3
3025 example2(`feeling rather indecisive today')
3026 @result{}default answer: 4
3027 @end example
3029 @cindex joining arguments
3030 @cindex arguments, joining
3031 @cindex concatenating arguments
3032 Another common task that requires iteration is joining a list of
3033 arguments into a single string.
3035 @deffn Composite join (@ovar{separator}, @ovar{args@dots{}})
3036 @deffnx Composite joinall (@ovar{separator}, @ovar{args@dots{}})
3037 Generate a single-quoted string, consisting of each @var{arg} separated
3038 by @var{separator}.  While @code{joinall} always outputs a
3039 @var{separator} between arguments, @code{join} avoids the
3040 @var{separator} for an empty @var{arg}.
3041 @end deffn
3043 Here are some examples of its usage, based on the implementation
3044 @file{m4-@value{VERSION}/@/examples/@/join.m4} distributed in this
3045 package:
3047 @comment examples
3048 @example
3049 $ @kbd{m4 -I examples}
3050 include(`join.m4')
3051 @result{}
3052 join,join(`-'),join(`-', `'),join(`-', `', `')
3053 @result{},,,
3054 joinall,joinall(`-'),joinall(`-', `'),joinall(`-', `', `')
3055 @result{},,,-
3056 join(`-', `1')
3057 @result{}1
3058 join(`-', `1', `2', `3')
3059 @result{}1-2-3
3060 join(`', `1', `2', `3')
3061 @result{}123
3062 join(`-', `', `1', `', `', `2', `')
3063 @result{}1-2
3064 joinall(`-', `', `1', `', `', `2', `')
3065 @result{}-1---2-
3066 join(`,', `1', `2', `3')
3067 @result{}1,2,3
3068 define(`nargs', `$#')dnl
3069 nargs(join(`,', `1', `2', `3'))
3070 @result{}1
3071 @end example
3073 Examining the implementation shows some interesting points about several
3074 m4 programming idioms.
3076 @comment examples
3077 @example
3078 $ @kbd{m4 -I examples}
3079 undivert(`join.m4')dnl
3080 @result{}divert(`-1')
3081 @result{}# join(sep, args) - join each non-empty ARG into a single
3082 @result{}# string, with each element separated by SEP
3083 @result{}define(`join',
3084 @result{}`ifelse(`$#', `2', ``$2'',
3085 @result{}  `ifelse(`$2', `', `', ``$2'_')$0(`$1', shift(shift($@@)))')')
3086 @result{}define(`_join',
3087 @result{}`ifelse(`$#$2', `2', `',
3088 @result{}  `ifelse(`$2', `', `', ``$1$2'')$0(`$1', shift(shift($@@)))')')
3089 @result{}# joinall(sep, args) - join each ARG, including empty ones,
3090 @result{}# into a single string, with each element separated by SEP
3091 @result{}define(`joinall', ``$2'_$0(`$1', shift($@@))')
3092 @result{}define(`_joinall',
3093 @result{}`ifelse(`$#', `2', `', ``$1$3'$0(`$1', shift(shift($@@)))')')
3094 @result{}divert`'dnl
3095 @end example
3097 First, notice that this implementation creates helper macros
3098 @code{_join} and @code{_joinall}.  This division of labor makes it
3099 easier to output the correct number of @var{separator} instances:
3100 @code{join} and @code{joinall} are responsible for the first argument,
3101 without a separator, while @code{_join} and @code{_joinall} are
3102 responsible for all remaining arguments, always outputting a separator
3103 when outputting an argument.
3105 Next, observe how @code{join} decides to iterate to itself, because the
3106 first @var{arg} was empty, or to output the argument and swap over to
3107 @code{_join}.  If the argument is non-empty, then the nested
3108 @code{ifelse} results in an unquoted @samp{_}, which is concatenated
3109 with the @samp{$0} to form the next macro name to invoke.  The
3110 @code{joinall} implementation is simpler since it does not have to
3111 suppress empty @var{arg}; it always executes once then defers to
3112 @code{_joinall}.
3114 Another important idiom is the idea that @var{separator} is reused for
3115 each iteration.  Each iteration has one less argument, but rather than
3116 discarding @samp{$1} by iterating with @code{$0(shift($@@))}, the macro
3117 discards @samp{$2} by using @code{$0(`$1', shift(shift($@@)))}.
3119 Next, notice that it is possible to compare more than one condition in a
3120 single @code{ifelse} test.  The test of @samp{$#$2} against @samp{2}
3121 allows @code{_join} to iterate for two separate reasons---either there
3122 are still more than two arguments, or there are exactly two arguments
3123 but the last argument is not empty.
3125 Finally, notice that these macros require exactly two arguments to
3126 terminate recursion, but that they still correctly result in empty
3127 output when given no @var{args} (i.e., zero or one macro argument).  On
3128 the first pass when there are too few arguments, the @code{shift}
3129 results in no output, but leaves an empty string to serve as the
3130 required second argument for the second pass.  Put another way,
3131 @samp{`$1', shift($@@)} is not the same as @samp{$@@}, since only the
3132 former guarantees at least two arguments.
3134 @cindex quote manipulation
3135 @cindex manipulating quotes
3136 Sometimes, a recursive algorithm requires adding quotes to each element,
3137 or treating multiple arguments as a single element:
3139 @deffn Composite quote (@dots{})
3140 @deffnx Composite dquote (@dots{})
3141 @deffnx Composite dquote_elt (@dots{})
3142 Takes any number of arguments, and adds quoting.  With @code{quote},
3143 only one level of quoting is added, effectively removing whitespace
3144 after commas and turning multiple arguments into a single string.  With
3145 @code{dquote}, two levels of quoting are added, one around each element,
3146 and one around the list.  And with @code{dquote_elt}, two levels of
3147 quoting are added around each element.
3148 @end deffn
3150 An actual implementation of these three macros is distributed as
3151 @file{m4-@value{VERSION}/@/examples/@/quote.m4} in this package.  First,
3152 let's examine their usage:
3154 @comment examples
3155 @example
3156 $ @kbd{m4 -I examples}
3157 include(`quote.m4')
3158 @result{}
3159 -quote-dquote-dquote_elt-
3160 @result{}----
3161 -quote()-dquote()-dquote_elt()-
3162 @result{}--`'-`'-
3163 -quote(`1')-dquote(`1')-dquote_elt(`1')-
3164 @result{}-1-`1'-`1'-
3165 -quote(`1', `2')-dquote(`1', `2')-dquote_elt(`1', `2')-
3166 @result{}-1,2-`1',`2'-`1',`2'-
3167 define(`n', `$#')dnl
3168 -n(quote(`1', `2'))-n(dquote(`1', `2'))-n(dquote_elt(`1', `2'))-
3169 @result{}-1-1-2-
3170 dquote(dquote_elt(`1', `2'))
3171 @result{}``1'',``2''
3172 dquote_elt(dquote(`1', `2'))
3173 @result{}``1',`2''
3174 @end example
3176 The last two lines show that when given two arguments, @code{dquote}
3177 results in one string, while @code{dquote_elt} results in two.  Now,
3178 examine the implementation.  Note that @code{quote} and
3179 @code{dquote_elt} make decisions based on their number of arguments, so
3180 that when called without arguments, they result in nothing instead of a
3181 quoted empty string; this is so that it is possible to distinguish
3182 between no arguments and an empty first argument.  @code{dquote}, on the
3183 other hand, results in a string no matter what, since it is still
3184 possible to tell whether it was invoked without arguments based on the
3185 resulting string.
3187 @comment examples
3188 @example
3189 $ @kbd{m4 -I examples}
3190 undivert(`quote.m4')dnl
3191 @result{}divert(`-1')
3192 @result{}# quote(args) - convert args to single-quoted string
3193 @result{}define(`quote', `ifelse(`$#', `0', `', ``$*'')')
3194 @result{}# dquote(args) - convert args to quoted list of quoted strings
3195 @result{}define(`dquote', ``$@@'')
3196 @result{}# dquote_elt(args) - convert args to list of double-quoted strings
3197 @result{}define(`dquote_elt', `ifelse(`$#', `0', `', `$#', `1', ```$1''',
3198 @result{}                             ```$1'',$0(shift($@@))')')
3199 @result{}divert`'dnl
3200 @end example
3202 It is worth pointing out that @samp{quote(@var{args})} is more efficient
3203 than @samp{joinall(`,', @var{args})} for producing the same output.
3205 @cindex nine arguments, more than
3206 @cindex more than nine arguments
3207 @cindex arguments, more than nine
3208 One more useful macro based on @code{shift} allows portably selecting
3209 an arbitrary argument (usually greater than the ninth argument), without
3210 relying on the @acronym{GNU} extension of multi-digit arguments
3211 (@pxref{Arguments}).
3213 @deffn Composite argn (@var{n}, @dots{})
3214 Expands to argument @var{n} out of the remaining arguments.  @var{n}
3215 must be a positive number.  Usually invoked as
3216 @samp{argn(`@var{n}',$@@)}.
3217 @end deffn
3219 It is implemented as:
3221 @example
3222 define(`argn', `ifelse(`$1', 1, ``$2'',
3223   `argn(decr(`$1'), shift(shift($@@)))')')
3224 @result{}
3225 argn(`1', `a')
3226 @result{}a
3227 define(`foo', `argn(`11', $@@)')
3228 @result{}
3229 foo(`a', `b', `c', `d', `e', `f', `g', `h', `i', `j', `k', `l')
3230 @result{}k
3231 @end example
3233 @node Forloop
3234 @section Iteration by counting
3236 @cindex for loops
3237 @cindex loops, counting
3238 @cindex counting loops
3239 Here is an example of a loop macro that implements a simple for loop.
3241 @deffn Composite forloop (@var{iterator}, @var{start}, @var{end}, @var{text})
3242 Takes the name in @var{iterator}, which must be a valid macro name, and
3243 successively assign it each integer value from @var{start} to @var{end},
3244 inclusive.  For each assignment to @var{iterator}, append @var{text} to
3245 the expansion of the @code{forloop}.  @var{text} may refer to
3246 @var{iterator}.  Any definition of @var{iterator} prior to this
3247 invocation is restored.
3248 @end deffn
3250 It can, for example, be used for simple counting:
3252 @comment examples
3253 @example
3254 $ @kbd{m4 -I examples}
3255 include(`forloop.m4')
3256 @result{}
3257 forloop(`i', `1', `8', `i ')
3258 @result{}1 2 3 4 5 6 7 8@w{ }
3259 @end example
3261 For-loops can be nested, like:
3263 @comment examples
3264 @example
3265 $ @kbd{m4 -I examples}
3266 include(`forloop.m4')
3267 @result{}
3268 forloop(`i', `1', `4', `forloop(`j', `1', `8', ` (i, j)')
3270 @result{} (1, 1) (1, 2) (1, 3) (1, 4) (1, 5) (1, 6) (1, 7) (1, 8)
3271 @result{} (2, 1) (2, 2) (2, 3) (2, 4) (2, 5) (2, 6) (2, 7) (2, 8)
3272 @result{} (3, 1) (3, 2) (3, 3) (3, 4) (3, 5) (3, 6) (3, 7) (3, 8)
3273 @result{} (4, 1) (4, 2) (4, 3) (4, 4) (4, 5) (4, 6) (4, 7) (4, 8)
3274 @result{}
3275 @end example
3277 The implementation of the @code{forloop} macro is fairly
3278 straightforward.  The @code{forloop} macro itself is simply a wrapper,
3279 which saves the previous definition of the first argument, calls the
3280 internal macro @code{@w{_forloop}}, and re-establishes the saved
3281 definition of the first argument.
3283 The macro @code{@w{_forloop}} expands the fourth argument once, and
3284 tests to see if the iterator has reached the final value.  If it has
3285 not finished, it increments the iterator (using the predefined macro
3286 @code{incr}, @pxref{Incr}), and recurses.
3288 Here is an actual implementation of @code{forloop}, distributed as
3289 @file{m4-@value{VERSION}/@/examples/@/forloop.m4} in this package:
3291 @comment examples
3292 @example
3293 $ @kbd{m4 -I examples}
3294 undivert(`forloop.m4')dnl
3295 @result{}divert(`-1')
3296 @result{}# forloop(var, from, to, stmt) - simple version
3297 @result{}define(`forloop', `pushdef(`$1', `$2')_forloop($@@)popdef(`$1')')
3298 @result{}define(`_forloop',
3299 @result{}       `$4`'ifelse($1, `$3', `', `define(`$1', incr($1))$0($@@)')')
3300 @result{}divert`'dnl
3301 @end example
3303 Notice the careful use of quotes.  Certain macro arguments are left
3304 unquoted, each for its own reason.  Try to find out @emph{why} these
3305 arguments are left unquoted, and see what happens if they are quoted.
3306 (As presented, these two macros are useful but not very robust for
3307 general use.  They lack even basic error handling for cases like
3308 @var{start} less than @var{end}, @var{end} not numeric, or
3309 @var{iterator} not being a macro name.  See if you can improve these
3310 macros; or @pxref{Improved forloop, , Answers}).
3312 @node Foreach
3313 @section Iteration by list contents
3315 @cindex for each loops
3316 @cindex loops, list iteration
3317 @cindex iterating over lists
3318 Here is an example of a loop macro that implements list iteration.
3320 @deffn Composite foreach (@var{iterator}, @var{paren-list}, @var{text})
3321 @deffnx Composite foreachq (@var{iterator}, @var{quote-list}, @var{text})
3322 Takes the name in @var{iterator}, which must be a valid macro name, and
3323 successively assign it each value from @var{paren-list} or
3324 @var{quote-list}.  In @code{foreach}, @var{paren-list} is a
3325 comma-separated list of elements contained in parentheses.  In
3326 @code{foreachq}, @var{quote-list} is a comma-separated list of elements
3327 contained in a quoted string.  For each assignment to @var{iterator},
3328 append @var{text} to the overall expansion.  @var{text} may refer to
3329 @var{iterator}.  Any definition of @var{iterator} prior to this
3330 invocation is restored.
3331 @end deffn
3333 As an example, this displays each word in a list inside of a sentence,
3334 using an implementation of @code{foreach} distributed as
3335 @file{m4-@value{VERSION}/@/examples/@/foreach.m4}, and @code{foreachq}
3336 in @file{m4-@value{VERSION}/@/examples/@/foreachq.m4}.
3338 @comment examples
3339 @example
3340 $ @kbd{m4 -I examples}
3341 include(`foreach.m4')
3342 @result{}
3343 foreach(`x', (foo, bar, foobar), `Word was: x
3344 ')dnl
3345 @result{}Word was: foo
3346 @result{}Word was: bar
3347 @result{}Word was: foobar
3348 include(`foreachq.m4')
3349 @result{}
3350 foreachq(`x', `foo, bar, foobar', `Word was: x
3351 ')dnl
3352 @result{}Word was: foo
3353 @result{}Word was: bar
3354 @result{}Word was: foobar
3355 @end example
3357 It is possible to be more complex; each element of the @var{paren-list}
3358 or @var{quote-list} can itself be a list, to pass as further arguments
3359 to a helper macro.  This example generates a shell case statement:
3361 @comment examples
3362 @example
3363 $ @kbd{m4 -I examples}
3364 include(`foreach.m4')
3365 @result{}
3366 define(`_case', `  $1)
3367     $2=" $1";;
3368 ')dnl
3369 define(`_cat', `$1$2')dnl
3370 case $`'1 in
3371 @result{}case $1 in
3372 foreach(`x', `(`(`a', `vara')', `(`b', `varb')', `(`c', `varc')')',
3373         `_cat(`_case', x)')dnl
3374 @result{}  a)
3375 @result{}    vara=" a";;
3376 @result{}  b)
3377 @result{}    varb=" b";;
3378 @result{}  c)
3379 @result{}    varc=" c";;
3380 esac
3381 @result{}esac
3382 @end example
3384 The implementation of the @code{foreach} macro is a bit more involved;
3385 it is a wrapper around two helper macros.  First, @code{@w{_arg1}} is
3386 needed to grab the first element of a list.  Second,
3387 @code{@w{_foreach}} implements the recursion, successively walking
3388 through the original list.  Here is a simple implementation of
3389 @code{foreach}:
3391 @comment examples
3392 @example
3393 $ @kbd{m4 -I examples}
3394 undivert(`foreach.m4')dnl
3395 @result{}divert(`-1')
3396 @result{}# foreach(x, (item_1, item_2, ..., item_n), stmt)
3397 @result{}#   parenthesized list, simple version
3398 @result{}define(`foreach', `pushdef(`$1')_foreach($@@)popdef(`$1')')
3399 @result{}define(`_arg1', `$1')
3400 @result{}define(`_foreach', `ifelse(`$2', `()', `',
3401 @result{}  `define(`$1', _arg1$2)$3`'$0(`$1', (shift$2), `$3')')')
3402 @result{}divert`'dnl
3403 @end example
3405 Unfortunately, that implementation is not robust to macro names as list
3406 elements.  Each iteration of @code{@w{_foreach}} is stripping another
3407 layer of quotes, leading to erratic results if list elements are not
3408 already fully expanded.  The first cut at implementing @code{foreachq}
3409 takes this into account.  Also, when using quoted elements in a
3410 @var{paren-list}, the overall list must be quoted.  A @var{quote-list}
3411 has the nice property of requiring fewer characters to create a list
3412 containing the same quoted elements.  To see the difference between the
3413 two macros, we attempt to pass double-quoted macro names in a list,
3414 expecting the macro name on output after one layer of quotes is removed
3415 during list iteration and the final layer removed during the final
3416 rescan:
3418 @comment examples
3419 @example
3420 $ @kbd{m4 -I examples}
3421 define(`a', `1')define(`b', `2')define(`c', `3')
3422 @result{}
3423 include(`foreach.m4')
3424 @result{}
3425 include(`foreachq.m4')
3426 @result{}
3427 foreach(`x', `(``a'', ``(b'', ``c)'')', `x
3429 @result{}1
3430 @result{}(2)1
3431 @result{}
3432 @result{}, x
3433 @result{})
3434 foreachq(`x', ```a'', ``(b'', ``c)''', `x
3435 ')dnl
3436 @result{}a
3437 @result{}(b
3438 @result{}c)
3439 @end example
3441 Obviously, @code{foreachq} did a better job; here is its implementation:
3443 @comment examples
3444 @example
3445 $ @kbd{m4 -I examples}
3446 undivert(`foreachq.m4')dnl
3447 @result{}include(`quote.m4')dnl
3448 @result{}divert(`-1')
3449 @result{}# foreachq(x, `item_1, item_2, ..., item_n', stmt)
3450 @result{}#   quoted list, simple version
3451 @result{}define(`foreachq', `pushdef(`$1')_foreachq($@@)popdef(`$1')')
3452 @result{}define(`_arg1', `$1')
3453 @result{}define(`_foreachq', `ifelse(quote($2), `', `',
3454 @result{}  `define(`$1', `_arg1($2)')$3`'$0(`$1', `shift($2)', `$3')')')
3455 @result{}divert`'dnl
3456 @end example
3458 Notice that @code{@w{_foreachq}} had to use the helper macro
3459 @code{quote} defined earlier (@pxref{Shift}), to ensure that the
3460 embedded @code{ifelse} call does not go haywire if a list element
3461 contains a comma.  Unfortunately, this implementation of @code{foreachq}
3462 has its own severe flaw.  Whereas the @code{foreach} implementation was
3463 linear, this macro is quadratic in the number of list elements, and is
3464 much more likely to trip up the limit set by the command line option
3465 @option{--nesting-limit} (or @option{-L}, @pxref{Limits control, ,
3466 Invoking m4}).  Additionally, this implementation does not expand
3467 @samp{defn(`@var{iterator}')} very well, when compared with
3468 @code{foreach}.
3470 @comment examples
3471 @example
3472 $ @kbd{m4 -I examples}
3473 include(`foreach.m4')include(`foreachq.m4')
3474 @result{}
3475 foreach(`name', `(`a', `b')', ` defn(`name')')
3476 @result{} a b
3477 foreachq(`name', ``a', `b'', ` defn(`name')')
3478 @result{} _arg1(`a', `b') _arg1(shift(`a', `b'))
3479 @end example
3481 It is possible to have robust iteration with linear behavior and sane
3482 @var{iterator} contents for either list style.  See if you can learn
3483 from the best elements of both of these implementations to create robust
3484 macros (or @pxref{Improved foreach, , Answers}).
3486 @node Debugging
3487 @chapter How to debug macros and input
3489 @cindex debugging macros
3490 @cindex macros, debugging
3491 When writing macros for @code{m4}, they often do not work as intended on
3492 the first try (as is the case with most programming languages).
3493 Fortunately, there is support for macro debugging in @code{m4}.
3495 @menu
3496 * Dumpdef::                     Displaying macro definitions
3497 * Trace::                       Tracing macro calls
3498 * Debug Levels::                Controlling debugging output
3499 * Debug Output::                Saving debugging output
3500 @end menu
3502 @node Dumpdef
3503 @section Displaying macro definitions
3505 @cindex displaying macro definitions
3506 @cindex macros, displaying definitions
3507 @cindex definitions, displaying macro
3508 @cindex standard error, output to
3509 If you want to see what a name expands into, you can use the builtin
3510 @code{dumpdef}:
3512 @deffn Builtin dumpdef (@ovar{names@dots{}})
3513 Accepts any number of arguments.  If called without any arguments,
3514 it displays the definitions of all known names, otherwise it displays
3515 the definitions of the @var{names} given.  The output is printed to the
3516 current debug file (usually standard error), and is sorted by name.  If
3517 an unknown name is encountered, a warning is printed.
3519 The expansion of @code{dumpdef} is void.
3520 @end deffn
3522 @example
3523 $ @kbd{m4 -d}
3524 define(`foo', `Hello world.')
3525 @result{}
3526 dumpdef(`foo')
3527 @error{}foo:@tabchar{}`Hello world.'
3528 @result{}
3529 dumpdef(`define')
3530 @error{}define:@tabchar{}<define>
3531 @result{}
3532 @end example
3534 The last example shows how builtin macros definitions are displayed.
3535 The definition that is dumped corresponds to what would occur if the
3536 macro were to be called at that point, even if other definitions are
3537 still live due to redefining a macro during argument collection.
3539 @example
3540 $ @kbd{m4 -d}
3541 pushdef(`f', ``$0'1')pushdef(`f', ``$0'2')
3542 @result{}
3543 f(popdef(`f')dumpdef(`f'))
3544 @error{}f:@tabchar{}``$0'1'
3545 @result{}f2
3546 f(popdef(`f')dumpdef(`f'))
3547 @error{}m4:stdin:3: Warning: dumpdef: undefined macro `f'
3548 @result{}f1
3549 @end example
3551 @xref{Debug Levels}, for information on controlling the details of the
3552 display.
3554 @node Trace
3555 @section Tracing macro calls
3557 @cindex tracing macro expansion
3558 @cindex macro expansion, tracing
3559 @cindex expansion, tracing macro
3560 @cindex standard error, output to
3561 It is possible to trace macro calls and expansions through the builtins
3562 @code{traceon} and @code{traceoff}:
3564 @deffn Builtin traceon (@ovar{names@dots{}})
3565 @deffnx Builtin traceoff (@ovar{names@dots{}})
3566 When called without any arguments, @code{traceon} and @code{traceoff}
3567 will turn tracing on and off, respectively, for all currently defined
3568 macros.
3570 When called with arguments, only the macros listed in @var{names} are
3571 affected, whether or not they are currently defined.
3573 The expansion of @code{traceon} and @code{traceoff} is void.
3574 @end deffn
3576 Whenever a traced macro is called and the arguments have been collected,
3577 the call is displayed.  If the expansion of the macro call is not void,
3578 the expansion can be displayed after the call.  The output is printed
3579 to the current debug file (defaulting to standard error, @pxref{Debug
3580 Output}).
3582 @example
3583 $ @kbd{m4 -d}
3584 define(`foo', `Hello World.')
3585 @result{}
3586 define(`echo', `$@@')
3587 @result{}
3588 traceon(`foo', `echo')
3589 @result{}
3591 @error{}m4trace: -1- foo -> `Hello World.'
3592 @result{}Hello World.
3593 echo(`gnus', `and gnats')
3594 @error{}m4trace: -1- echo(`gnus', `and gnats') -> ``gnus',`and gnats''
3595 @result{}gnus,and gnats
3596 @end example
3598 The number between dashes is the depth of the expansion.  It is one most
3599 of the time, signifying an expansion at the outermost level, but it
3600 increases when macro arguments contain unquoted macro calls.  The
3601 maximum number that will appear between dashes is controlled by the
3602 option @option{--nesting-limit} (or @option{-L}, @pxref{Limits control,
3603 , Invoking m4}).  Additionally, the option @option{--trace} (or
3604 @option{-t}) can be used to invoke @code{traceon(@var{name})} before
3605 parsing input.
3607 @comment The explicit -dp neutralizes the testsuite default of -d.
3608 @comment options: -dp -L3 -tifelse
3609 @comment status: 1
3610 @example
3611 $ @kbd{m4 -L 3 -t ifelse}
3612 ifelse(`one level')
3613 @error{}m4trace: -1- ifelse
3614 @result{}
3615 ifelse(ifelse(ifelse(`three levels')))
3616 @error{}m4trace: -3- ifelse
3617 @error{}m4trace: -2- ifelse
3618 @error{}m4trace: -1- ifelse
3619 @result{}
3620 ifelse(ifelse(ifelse(ifelse(`four levels'))))
3621 @error{}m4:stdin:3: recursion limit of 3 exceeded, use -L<N> to change it
3622 @end example
3624 Tracing by name is an attribute that is preserved whether the macro is
3625 defined or not.  This allows the selection of macros to trace before
3626 those macros are defined.
3628 @example
3629 $ @kbd{m4 -d}
3630 traceoff(`foo')
3631 @result{}
3632 traceon(`foo')
3633 @result{}
3635 @result{}foo
3636 define(`foo', `bar')
3637 @result{}
3639 @error{}m4trace: -1- foo -> `bar'
3640 @result{}bar
3641 undefine(`foo')
3642 @result{}
3643 ifdef(`foo', `yes', `no')
3644 @result{}no
3645 indir(`foo')
3646 @error{}m4:stdin:8: Warning: indir: undefined macro `foo'
3647 @result{}
3648 define(`foo', `blah')
3649 @result{}
3651 @error{}m4trace: -1- foo -> `blah'
3652 @result{}blah
3653 traceoff
3654 @result{}
3656 @result{}blah
3657 @end example
3659 Tracing even works on builtins.  However, @code{defn} (@pxref{Defn})
3660 does not transfer tracing status.
3662 @example
3663 $ @kbd{m4 -d}
3664 traceon(`eval', `m4_divnum')
3665 @result{}
3666 define(`m4_eval', defn(`eval'))
3667 @result{}
3668 define(`m4_divnum', defn(`divnum'))
3669 @result{}
3670 eval(divnum)
3671 @error{}m4trace: -1- eval(`0') -> `0'
3672 @result{}0
3673 m4_eval(m4_divnum)
3674 @error{}m4trace: -2- m4_divnum -> `0'
3675 @result{}0
3676 @end example
3678 @xref{Debug Levels}, for information on controlling the details of the
3679 display.
3681 @node Debug Levels
3682 @section Controlling debugging output
3684 @cindex controlling debugging output
3685 @cindex debugging output, controlling
3686 The @option{-d} option to @code{m4} (or @option{--debug},
3687 @pxref{Debugging options, , Invoking m4}) controls the amount of details
3688 presented in three
3689 categories of output.  Trace output is requested by @code{traceon}
3690 (@pxref{Trace}), and each line is prefixed by @samp{m4trace:} in
3691 relation to a macro invocation.  Debug output tracks useful events not
3692 associated with a macro invocation, and each line is prefixed by
3693 @samp{m4debug:}.  Finally, @code{dumpdef} (@pxref{Dumpdef}) output is
3694 affected, with no prefix added to the output lines.
3696 The @var{flags} following the option can be one or more of the
3697 following:
3699 @table @code
3700 @item a
3701 In trace output, show the actual arguments that were collected before
3702 invoking the macro.  This applies to all macro calls if the @samp{t}
3703 flag is used, otherwise only the macros covered by calls of
3704 @code{traceon}.  Arguments are subject to length truncation specified by
3705 the command line option @option{--arglength} (or @option{-l}).
3707 @item c
3708 In trace output, show several trace lines for each macro call.  A line
3709 is shown when the macro is seen, but before the arguments are collected;
3710 a second line when the arguments have been collected and a third line
3711 after the call has completed.
3713 @item e
3714 In trace output, show the expansion of each macro call, if it is not
3715 void.  This applies to all macro calls if the @samp{t} flag is used,
3716 otherwise only the macros covered by calls of @code{traceon}.  The
3717 expansion is subject to length truncation specified by the command line
3718 option @option{--arglength} (or @option{-l}).
3720 @item f
3721 In debug and trace output, include the name of the current input file in
3722 the output line.
3724 @item i
3725 In debug output, print a message each time the current input file is
3726 changed.
3728 @item l
3729 In debug and trace output, include the current input line number in the
3730 output line.
3732 @item p
3733 In debug output, print a message when a named file is found through the
3734 path search mechanism (@pxref{Search Path}), giving the actual file name
3735 used.
3737 @item q
3738 In trace and dumpdef output, quote actual arguments and macro expansions
3739 in the display with the current quotes.  This is useful in connection
3740 with the @samp{a} and @samp{e} flags above.
3742 @item t
3743 In trace output, trace all macro calls made in this invocation of
3744 @code{m4}, regardless of the settings of @code{traceon}.
3746 @item x
3747 In trace output, add a unique `macro call id' to each line of the trace
3748 output.  This is useful in connection with the @samp{c} flag above.
3750 @item V
3751 A shorthand for all of the above flags.
3752 @end table
3754 If no flags are specified with the @option{-d} option, the default is
3755 @samp{aeq}.  The examples throughout this manual assume the default
3756 flags.
3758 @cindex @acronym{GNU} extensions
3759 There is a builtin macro @code{debugmode}, which allows on-the-fly control of
3760 the debugging output format:
3762 @deffn Builtin debugmode (@ovar{flags})
3763 The argument @var{flags} should be a subset of the letters listed above.
3764 As special cases, if the argument starts with a @samp{+}, the flags are
3765 added to the current debug flags, and if it starts with a @samp{-}, they
3766 are removed.  If no argument is present, all debugging flags are cleared
3767 (as if no @option{-d} was given), and with an empty argument the flags
3768 are reset to the default of @samp{aeq}.
3770 The expansion of @code{debugmode} is void.
3771 @end deffn
3773 @comment The explicit -dp neutralizes the testsuite default of -d.
3774 @comment options: -dp
3775 @example
3776 $ @kbd{m4}
3777 define(`foo', `FOO')
3778 @result{}
3779 traceon(`foo')
3780 @result{}
3781 debugmode()
3782 @result{}
3784 @error{}m4trace: -1- foo -> `FOO'
3785 @result{}FOO
3786 debugmode
3787 @result{}
3789 @error{}m4trace: -1- foo
3790 @result{}FOO
3791 debugmode(`+l')
3792 @result{}
3794 @error{}m4trace:8: -1- foo
3795 @result{}FOO
3796 @end example
3798 The following example demonstrates the behavior of length truncation,
3799 when specified on the command line.  Note that each argument and the
3800 final result are individually truncated.  Also, the special tokens for
3801 builtin functions are not truncated.
3803 @comment options: -l6
3804 @example
3805 $ @kbd{m4 -d -l 6}
3806 define(`echo', `$@@')debugmode(`+t')
3807 @result{}
3808 echo(`1', `long string')
3809 @error{}m4trace: -1- echo(`1', `long s...') -> ``1',`l...'
3810 @result{}1,long string
3811 indir(`echo', defn(`changequote'))
3812 @error{}m4trace: -2- defn(`change...')
3813 @error{}m4trace: -1- indir(`echo', <changequote>) -> ``<changequote>''
3814 @result{}
3815 @end example
3817 @node Debug Output
3818 @section Saving debugging output
3820 @cindex saving debugging output
3821 @cindex debugging output, saving
3822 @cindex output, saving debugging
3823 @cindex @acronym{GNU} extensions
3824 Debug and tracing output can be redirected to files using either the
3825 @option{--debugfile} option to @code{m4} (@pxref{Debugging options, ,
3826 Invoking m4}), or with the builtin macro @code{debugfile}:
3828 @deffn Builtin debugfile (@ovar{file})
3829 Sends all further debug and trace output to @var{file}, opened in append
3830 mode.  If @var{file} is the empty string, debug and trace output are
3831 discarded.  If @code{debugfile} is called without any arguments, debug
3832 and trace output are sent to standard error.  This does not affect
3833 warnings, error messages, or @code{errprint} output, which are
3834 always sent to standard error.  If @var{file} cannot be opened, the
3835 current debug file is unchanged, and an error is issued.
3837 The expansion of @code{debugfile} is void.
3838 @end deffn
3840 @example
3841 $ @kbd{m4 -d}
3842 traceon(`divnum')
3843 @result{}
3844 divnum(`extra')
3845 @error{}m4:stdin:2: Warning: divnum: extra arguments ignored: 1 > 0
3846 @error{}m4trace: -1- divnum(`extra') -> `0'
3847 @result{}0
3848 debugfile()
3849 @result{}
3850 divnum(`extra')
3851 @error{}m4:stdin:4: Warning: divnum: extra arguments ignored: 1 > 0
3852 @result{}0
3853 debugfile
3854 @result{}
3855 divnum
3856 @error{}m4trace: -1- divnum -> `0'
3857 @result{}0
3858 @end example
3860 @node Input Control
3861 @chapter Input control
3863 This chapter describes various builtin macros for controlling the input
3864 to @code{m4}.
3866 @menu
3867 * Dnl::                         Deleting whitespace in input
3868 * Changequote::                 Changing the quote characters
3869 * Changecom::                   Changing the comment delimiters
3870 * Changeword::                  Changing the lexical structure of words
3871 * M4wrap::                      Saving text until end of input
3872 @end menu
3874 @node Dnl
3875 @section Deleting whitespace in input
3877 @cindex deleting whitespace in input
3878 @cindex discarding input
3879 @cindex input, discarding
3880 The builtin @code{dnl} stands for ``Discard to Next Line'':
3882 @deffn Builtin dnl
3883 All characters, up to and including the next newline, are discarded
3884 without performing any macro expansion.  A warning is issued if the end
3885 of the file is encountered without a newline.
3887 The expansion of @code{dnl} is void.
3888 @end deffn
3890 It is often used in connection with @code{define}, to remove the
3891 newline that follows the call to @code{define}.  Thus
3893 @example
3894 define(`foo', `Macro `foo'.')dnl A very simple macro, indeed.
3896 @result{}Macro foo.
3897 @end example
3899 The input up to and including the next newline is discarded, as opposed
3900 to the way comments are treated (@pxref{Comments}).
3902 Usually, @code{dnl} is immediately followed by an end of line or some
3903 other whitespace.  @acronym{GNU} @code{m4} will produce a warning diagnostic if
3904 @code{dnl} is followed by an open parenthesis.  In this case, @code{dnl}
3905 will collect and process all arguments, looking for a matching close
3906 parenthesis.  All predictable side effects resulting from this
3907 collection will take place.  @code{dnl} will return no output.  The
3908 input following the matching close parenthesis up to and including the
3909 next newline, on whatever line containing it, will still be discarded.
3911 @example
3912 dnl(`args are ignored, but side effects occur',
3913 define(`foo', `like this')) while this text is ignored: undefine(`foo')
3914 @error{}m4:stdin:1: Warning: dnl: extra arguments ignored: 2 > 0
3915 See how `foo' was defined, foo?
3916 @result{}See how foo was defined, like this?
3917 @end example
3919 If the end of file is encountered without a newline character, a
3920 warning is issued and dnl stops consuming input.
3922 @example
3923 m4wrap(`m4wrap(`2 hi
3924 ')0 hi dnl 1 hi')
3925 @result{}
3926 define(`hi', `HI')
3927 @result{}
3929 @error{}m4:stdin:1: Warning: dnl: end of file treated as newline
3930 @result{}0 HI 2 HI
3931 @end example
3933 @node Changequote
3934 @section Changing the quote characters
3936 @cindex changing quote delimiters
3937 @cindex quote delimiters, changing
3938 @cindex delimiters, changing
3939 The default quote delimiters can be changed with the builtin
3940 @code{changequote}:
3942 @deffn Builtin changequote (@dvar{start, `}, @dvar{end, '})
3943 This sets @var{start} as the new begin-quote delimiter and @var{end} as
3944 the new end-quote delimiter.  If both arguments are missing, the default
3945 quotes (@code{`} and @code{'}) are used.  If @var{start} is void, then
3946 quoting is disabled.  Otherwise, if @var{end} is missing or void, the
3947 default end-quote delimiter (@code{'}) is used.  The quote delimiters
3948 can be of any length.
3950 The expansion of @code{changequote} is void.
3951 @end deffn
3953 @example
3954 changequote(`[', `]')
3955 @result{}
3956 define([foo], [Macro [foo].])
3957 @result{}
3959 @result{}Macro foo.
3960 @end example
3962 The quotation strings can safely contain eight-bit characters.
3963 @ignore
3964 @comment Yuck.  I know of no clean way to render an 8-bit character in
3965 @comment both info and dvi.  This example uses the `open-guillemot' and
3966 @comment `close-guillemot' characters of the Latin-1 character set.
3968 @example
3969 define(`a', `b')
3970 @result{}
3971 «a»
3972 @result{}«b»
3973 changequote(`«', `»')
3974 @result{}
3975 «a»
3976 @result{}a
3977 @end example
3978 @end ignore
3979 If no single character is appropriate, @var{start} and @var{end} can be
3980 of any length.  Other implementations cap the delimiter length to five
3981 characters, but @acronym{GNU} has no inherent limit.
3983 @example
3984 changequote(`[[[', `]]]')
3985 @result{}
3986 define([[[foo]]], [[[Macro [[[[[foo]]]]].]]])
3987 @result{}
3989 @result{}Macro [[foo]].
3990 @end example
3992 Calling @code{changequote} with @var{start} as the empty string will
3993 effectively disable the quoting mechanism, leaving no way to quote text.
3994 However, using an empty string is not portable, as some other
3995 implementations of @code{m4} revert to the default quoting, while others
3996 preserve the prior non-empty delimiter.  If @var{start} is not empty,
3997 then an empty @var{end} will use the default end-quote delimiter of
3998 @samp{'}, as otherwise, it would be impossible to end a quoted string.
3999 Again, this is not portable, as some other @code{m4} implementations
4000 reuse @var{start} as the end-quote delimiter, while others preserve the
4001 previous non-empty value.  Omitting both arguments restores the default
4002 begin-quote and end-quote delimiters; fortunately this behavior is
4003 portable to all implementations of @code{m4}.
4005 @example
4006 define(`foo', `Macro `FOO'.')
4007 @result{}
4008 changequote(`', `')
4009 @result{}
4011 @result{}Macro `FOO'.
4012 `foo'
4013 @result{}`Macro `FOO'.'
4014 changequote(`,)
4015 @result{}
4017 @result{}Macro FOO.
4018 @end example
4020 There is no way in @code{m4} to quote a string containing an unmatched
4021 begin-quote, except using @code{changequote} to change the current
4022 quotes.
4024 If the quotes should be changed from, say, @samp{[} to @samp{[[},
4025 temporary quote characters have to be defined.  To achieve this, two
4026 calls of @code{changequote} must be made, one for the temporary quotes
4027 and one for the new quotes.
4029 Macros are recognized in preference to the begin-quote string, so if a
4030 prefix of @var{start} can be recognized as part of a potential macro
4031 name, the quoting mechanism is effectively disabled.  Unless you use
4032 @code{changeword} (@pxref{Changeword}), this means that @var{start}
4033 should not begin with a letter, digit, or @samp{_} (underscore).
4034 However, even though quoted strings are not recognized, the quote
4035 characters can still be discerned in macro expansion and in trace
4036 output.
4038 @example
4039 define(`echo', `$@@')
4040 @result{}
4041 define(`hi', `HI')
4042 @result{}
4043 changequote(`q', `Q')
4044 @result{}
4045 q hi Q hi
4046 @result{}q HI Q HI
4047 echo(hi)
4048 @result{}qHIQ
4049 changequote
4050 @result{}
4051 changequote(`-', `EOF')
4052 @result{}
4053 - hi EOF hi
4054 @result{} hi  HI
4055 changequote
4056 @result{}
4057 changequote(`1', `2')
4058 @result{}
4059 hi1hi2
4060 @result{}hi1hi2
4061 hi 1hi2
4062 @result{}HI hi
4063 @end example
4065 Quotes are recognized in preference to argument collection.  In
4066 particular, if @var{start} is a single @samp{(}, then argument
4067 collection is effectively disabled.  For portability with other
4068 implementations, it is a good idea to avoid @samp{(}, @samp{,}, and
4069 @samp{)} as the first character in @var{start}.
4071 @example
4072 define(`echo', `$#:$@@:')
4073 @result{}
4074 define(`hi', `HI')
4075 @result{}
4076 changequote(`(',`)')
4077 @result{}
4078 echo(hi)
4079 @result{}0::hi
4080 changequote
4081 @result{}
4082 changequote(`((', `))')
4083 @result{}
4084 echo(hi)
4085 @result{}1:HI:
4086 echo((hi))
4087 @result{}0::hi
4088 changequote
4089 @result{}
4090 changequote(`,', `)')
4091 @result{}
4092 echo(hi,hi)bye)
4093 @result{}1:HIhibye:
4094 @end example
4096 However, if you are not worried about portability, using @samp{(} and
4097 @samp{)} as quoting characters has an interesting property---you can use
4098 it to compute a quoted string containing the expansion of any quoted
4099 text, as long as the expansion results in both balanced quotes and
4100 balanced parentheses.  The trick is realizing @code{expand} uses
4101 @samp{$1} unquoted, to trigger its expansion using the normal quoting
4102 characters, but uses extra parentheses to group unquoted commas that
4103 occur in the expansion without consuming whitespace following those
4104 commas.  Then @code{_expand} uses @code{changequote} to convert the
4105 extra parentheses back into quoting characters.  Note that it takes two
4106 more @code{changequote} invocations to restore the original quotes.
4107 Contrast the behavior on whitespace when using @samp{$*}, via
4108 @code{quote}, to attempt the same task.
4110 @example
4111 changequote(`[', `]')dnl
4112 define([a], [1, (b)])dnl
4113 define([b], [2])dnl
4114 define([quote], [[$*]])dnl
4115 define([expand], [_$0(($1))])dnl
4116 define([_expand],
4117   [changequote([(], [)])$1changequote`'changequote(`[', `]')])dnl
4118 expand([a, a, [a, a], [[a, a]]])
4119 @result{}1, (2), 1, (2), a, a, [a, a]
4120 quote(a, a, [a, a], [[a, a]])
4121 @result{}1,(2),1,(2),a, a,[a, a]
4122 @end example
4124 If @var{end} is a prefix of @var{start}, the end-quote will be
4125 recognized in preference to a nested begin-quote.  In particular,
4126 changing the quotes to have the same string for @var{start} and
4127 @var{end} disables nesting of quotes.  When quote nesting is disabled,
4128 it is impossible to double-quote strings across macro expansions, so
4129 using the same string is not done very often.
4131 @example
4132 define(`hi', `HI')
4133 @result{}
4134 changequote(`""', `"')
4135 @result{}
4136 ""hi"""hi"
4137 @result{}hihi
4138 ""hi" ""hi"
4139 @result{}hi hi
4140 ""hi"" "hi"
4141 @result{}hi" "HI"
4142 changequote
4143 @result{}
4144 `hi`hi'hi'
4145 @result{}hi`hi'hi
4146 changequote(`"', `"')
4147 @result{}
4148 "hi"hi"hi"
4149 @result{}hiHIhi
4150 @end example
4152 @ignore
4153 @comment And another stress test, not worth documenting in the manual.
4154 @example
4155 define(`aaaaaaaaaaaaaaaaaaaa', `A')define(`q', `"$@@"')
4156 @result{}
4157 changequote(`"', `"')
4158 @result{}
4159 q(q("aaaaaaaaaaaaaaaaaaaa", "a"))
4160 @result{}A,a
4161 @end example
4162 @end ignore
4164 It is an error if the end of file occurs within a quoted string.
4166 @comment status: 1
4167 @example
4168 `hello world'
4169 @result{}hello world
4170 `dangling quote
4172 @error{}m4:stdin:2: end of file in string
4173 @end example
4175 @comment status: 1
4176 @example
4177 ifelse(`dangling quote
4179 @error{}m4:stdin:1: ifelse: end of file in string
4180 @end example
4182 @node Changecom
4183 @section Changing the comment delimiters
4185 @cindex changing comment delimiters
4186 @cindex comment delimiters, changing
4187 @cindex delimiters, changing
4188 The default comment delimiters can be changed with the builtin
4189 macro @code{changecom}:
4191 @deffn Builtin changecom (@ovar{start}, @dvar{end, @key{NL}})
4192 This sets @var{start} as the new begin-comment delimiter and @var{end}
4193 as the new end-comment delimiter.  If both arguments are missing, or
4194 @var{start} is void, then comments are disabled.  Otherwise, if
4195 @var{end} is missing or void, the default end-comment delimiter of
4196 newline is used.  The comment delimiters can be of any length.
4198 The expansion of @code{changecom} is void.
4199 @end deffn
4201 @example
4202 define(`comment', `COMMENT')
4203 @result{}
4204 # A normal comment
4205 @result{}# A normal comment
4206 changecom(`/*', `*/')
4207 @result{}
4208 # Not a comment anymore
4209 @result{}# Not a COMMENT anymore
4210 But: /* this is a comment now */ while this is not a comment
4211 @result{}But: /* this is a comment now */ while this is not a COMMENT
4212 @end example
4214 @cindex comments, copied to output
4215 Note how comments are copied to the output, much as if they were quoted
4216 strings.  If you want the text inside a comment expanded, quote the
4217 begin-comment delimiter.
4219 Calling @code{changecom} without any arguments, or with @var{start} as
4220 the empty string, will effectively disable the commenting mechanism.  To
4221 restore the original comment start of @samp{#}, you must explicitly ask
4222 for it.  If @var{start} is not empty, then an empty @var{end} will use
4223 the default end-comment delimiter of newline, as otherwise, it would be
4224 impossible to end a comment.  However, this is not portable, as some
4225 other @code{m4} implementations preserve the previous non-empty
4226 delimiters instead.
4228 @example
4229 define(`comment', `COMMENT')
4230 @result{}
4231 changecom
4232 @result{}
4233 # Not a comment anymore
4234 @result{}# Not a COMMENT anymore
4235 changecom(`#', `')
4236 @result{}
4237 # comment again
4238 @result{}# comment again
4239 @end example
4241 The comment strings can safely contain eight-bit characters.
4242 @ignore
4243 @comment Yuck.  I know of no clean way to render an 8-bit character in
4244 @comment both info and dvi.  This example uses the `open-guillemot' and
4245 @comment `close-guillemot' characters of the Latin-1 character set.
4247 @example
4248 define(`a', `b')
4249 @result{}
4250 «a»
4251 @result{}«b»
4252 changecom(`«', `»')
4253 @result{}
4254 «a»
4255 @result{}«a»
4256 @end example
4257 @end ignore
4258 If no single character is appropriate, @var{start} and @var{end} can be
4259 of any length.  Other implementations cap the delimiter length to five
4260 characters, but @acronym{GNU} has no inherent limit.
4262 Comments are recognized in preference to macros.  However, this is not
4263 compatible with other implementations, where macros and even quoting
4264 takes precedence over comments, so it may change in a future release.
4265 For portability, this means that @var{start} should not begin with a
4266 letter, digit, or @samp{_} (underscore), and that neither the
4267 start-quote nor the start-comment string should be a prefix of the
4268 other.
4270 @example
4271 define(`hi', `HI')
4272 @result{}
4273 define(`hi1hi2', `hello')
4274 @result{}
4275 changecom(`q', `Q')
4276 @result{}
4277 q hi Q hi
4278 @result{}q hi Q HI
4279 changecom(`1', `2')
4280 @result{}
4281 hi1hi2
4282 @result{}hello
4283 hi 1hi2
4284 @result{}HI 1hi2
4285 @end example
4287 Comments are recognized in preference to argument collection.  In
4288 particular, if @var{start} is a single @samp{(}, then argument
4289 collection is effectively disabled.  For portability with other
4290 implementations, it is a good idea to avoid @samp{(}, @samp{,}, and
4291 @samp{)} as the first character in @var{start}.
4293 @example
4294 define(`echo', `$#:$*:$@@:')
4295 @result{}
4296 define(`hi', `HI')
4297 @result{}
4298 changecom(`(',`)')
4299 @result{}
4300 echo(hi)
4301 @result{}0:::(hi)
4302 changecom
4303 @result{}
4304 changecom(`((', `))')
4305 @result{}
4306 echo(hi)
4307 @result{}1:HI:HI:
4308 echo((hi))
4309 @result{}0:::((hi))
4310 changecom(`,', `)')
4311 @result{}
4312 echo(hi,hi)bye)
4313 @result{}1:HI,hi)bye:HI,hi)bye:
4314 changecom
4315 @result{}
4316 echo(hi,`,`'hi',hi)
4317 @result{}3:HI,,HI,HI:HI,,`'hi,HI:
4318 echo(hi,`,`'hi',hi`'changecom(`,,', `hi'))
4319 @result{}3:HI,,`'hi,HI:HI,,`'hi,HI:
4320 @end example
4322 It is an error if the end of file occurs within a comment.
4324 @comment status: 1
4325 @example
4326 changecom(`/*', `*/')
4327 @result{}
4328 /*dangling comment
4330 @error{}m4:stdin:2: end of file in comment
4331 @end example
4333 @comment status: 1
4334 @example
4335 changecom(`/*', `*/')
4336 @result{}
4337 len(/*dangling comment
4339 @error{}m4:stdin:2: len: end of file in comment
4340 @end example
4342 @node Changeword
4343 @section Changing the lexical structure of words
4345 @cindex lexical structure of words
4346 @cindex words, lexical structure of
4347 @cindex syntax, changing
4348 @cindex changing syntax
4349 @cindex regular expressions
4350 @quotation
4351 The macro @code{changeword} and all associated functionality is
4352 experimental.  It is only available if the @option{--enable-changeword}
4353 option was given to @code{configure}, at @acronym{GNU} @code{m4} installation
4354 time.  The functionality will go away in the future, to be replaced by
4355 other new features that are more efficient at providing the same
4356 capabilities.  @emph{Do not rely on it}.  Please direct your comments
4357 about it the same way you would do for bugs.
4358 @end quotation
4360 A file being processed by @code{m4} is split into quoted strings, words
4361 (potential macro names) and simple tokens (any other single character).
4362 Initially a word is defined by the following regular expression:
4364 @comment ignore
4365 @example
4366 [_a-zA-Z][_a-zA-Z0-9]*
4367 @end example
4369 Using @code{changeword}, you can change this regular expression:
4371 @deffn {Optional builtin} changeword (@var{regex})
4372 Changes the regular expression for recognizing macro names to be
4373 @var{regex}.  If @var{regex} is empty, use
4374 @samp{[_a-zA-Z][_a-zA-Z0-9]*}.  @var{regex} must obey the constraint
4375 that every prefix of the desired final pattern is also accepted by the
4376 regular expression.  If @var{regex} contains grouping parentheses, the
4377 macro invoked is the portion that matched the first group, rather than
4378 the entire matching string.
4380 The expansion of @code{changeword} is void.
4381 The macro @code{changeword} is recognized only with parameters.
4382 @end deffn
4384 Relaxing the lexical rules of @code{m4} might be useful (for example) if
4385 you wanted to apply translations to a file of numbers:
4387 @example
4388 ifdef(`changeword', `', `errprint(` skipping: no changeword support
4389 ')m4exit(`77')')dnl
4390 changeword(`[_a-zA-Z0-9]+')
4391 @result{}
4392 define(`1', `0')1
4393 @result{}0
4394 @end example
4396 Tightening the lexical rules is less useful, because it will generally
4397 make some of the builtins unavailable.  You could use it to prevent
4398 accidental call of builtins, for example:
4400 @example
4401 ifdef(`changeword', `', `errprint(` skipping: no changeword support
4402 ')m4exit(`77')')dnl
4403 define(`_indir', defn(`indir'))
4404 @result{}
4405 changeword(`_[_a-zA-Z0-9]*')
4406 @result{}
4407 esyscmd(`foo')
4408 @result{}esyscmd(foo)
4409 _indir(`esyscmd', `echo hi')
4410 @result{}hi
4411 @result{}
4412 @end example
4414 Because @code{m4} constructs its words a character at a time, there
4415 is a restriction on the regular expressions that may be passed to
4416 @code{changeword}.  This is that if your regular expression accepts
4417 @samp{foo}, it must also accept @samp{f} and @samp{fo}.
4419 @example
4420 ifdef(`changeword', `', `errprint(` skipping: no changeword support
4421 ')m4exit(`77')')dnl
4422 define(`foo
4423 ', `bar
4425 @result{}
4426 dnl This example wants to recognize changeword, dnl, and `foo\n'.
4427 dnl First, we check that our regexp will match.
4428 regexp(`changeword', `[cd][a-z]*\|foo[
4430 @result{}0
4431 regexp(`foo
4432 ', `[cd][a-z]*\|foo[
4434 @result{}0
4435 regexp(`f', `[cd][a-z]*\|foo[
4437 @result{}-1
4439 @result{}foo
4440 changeword(`[cd][a-z]*\|foo[
4442 @result{}
4443 dnl Even though `foo\n' matches, we forgot to allow `f'.
4445 @result{}foo
4446 changeword(`[cd][a-z]*\|fo*[
4447 ]?')
4448 @result{}
4449 dnl Now we can call `foo\n'.
4451 @result{}bar
4452 @end example
4454 @ignore
4455 @comment One more test of including newline in a macro name; but this
4456 @comment does not need to be displayed in the manual.  This ensures
4457 @comment that line numbering is correct when dnl cuts across include
4458 @comment file boundaries, and when __file__ or __line__ is the last
4459 @comment token in an include file.
4461 @example
4462 ifdef(`changeword', `', `errprint(` skipping: no changeword support
4463 ')m4exit(`77')')dnl
4464 define(`bar
4465 ', defn(`dnl'))dnl
4466 define(`baz', `dnl
4467 include(`foo') ignored
4468 dnl')dnl
4469 changeword(`\([_a-zA-Z][_a-zA-Z0-9]*\|bar
4470 \)')
4471 @result{}
4472 __file__:__line__
4473 @result{}stdin:10
4474 include(`foo') ignored
4475 __file__:__line__
4476 @result{}stdin:12
4477 baz ignored
4478 __file__:__line__
4479 @result{}stdin:14
4480 define(`bar
4481 ', defn(`__file__'))
4482 @result{}
4483 include(`foo')
4484 @result{}../examples/foo
4485 define(`bar
4486 ', defn(`__line__'))
4487 @result{}
4488 include(`foo')
4489 @result{}1
4490 __file__:__line__
4491 @result{}stdin:21
4492 @end example
4493 @end ignore
4495 @code{changeword} has another function.  If the regular expression
4496 supplied contains any grouped subexpressions, then text outside
4497 the first of these is discarded before symbol lookup.  So:
4499 @example
4500 ifdef(`changeword', `', `errprint(` skipping: no changeword support
4501 ')m4exit(`77')')dnl
4502 ifdef(`__unix__', ,
4503       `errprint(` skipping: syscmd does not have unix semantics
4504 ')m4exit(`77')')dnl
4505 changecom(`/*', `*/')dnl
4506 define(`foo', `bar')dnl
4507 changeword(`#\([_a-zA-Z0-9]*\)')
4508 @result{}
4509 #esyscmd(`echo foo \#foo')
4510 @result{}foo bar
4511 @result{}
4512 @end example
4514 @code{m4} now requires a @samp{#} mark at the beginning of every
4515 macro invocation, so one can use @code{m4} to preprocess plain
4516 text without losing various words like @samp{divert}.
4518 In @code{m4}, macro substitution is based on text, while in @TeX{}, it
4519 is based on tokens.  @code{changeword} can throw this difference into
4520 relief.  For example, here is the same idea represented in @TeX{} and
4521 @code{m4}.  First, the @TeX{} version:
4523 @comment ignore
4524 @example
4525 \def\a@{\message@{Hello@}@}
4526 \catcode`\@@=0
4527 \catcode`\\=12
4529 @@bye
4530 @result{}Hello
4531 @end example
4533 @noindent
4534 Then, the @code{m4} version:
4536 @example
4537 ifdef(`changeword', `', `errprint(` skipping: no changeword support
4538 ')m4exit(`77')')dnl
4539 define(`a', `errprint(`Hello')')dnl
4540 changeword(`@@\([_a-zA-Z0-9]*\)')
4541 @result{}
4543 @result{}errprint(Hello)
4544 @end example
4546 In the @TeX{} example, the first line defines a macro @code{a} to
4547 print the message @samp{Hello}.  The second line defines @key{@@} to
4548 be usable instead of @key{\} as an escape character.  The third line
4549 defines @key{\} to be a normal printing character, not an escape.
4550 The fourth line invokes the macro @code{a}.  So, when @TeX{} is run
4551 on this file, it displays the message @samp{Hello}.
4553 When the @code{m4} example is passed through @code{m4}, it outputs
4554 @samp{errprint(Hello)}.  The reason for this is that @TeX{} does
4555 lexical analysis of macro definition when the macro is @emph{defined}.
4556 @code{m4} just stores the text, postponing the lexical analysis until
4557 the macro is @emph{used}.
4559 You should note that using @code{changeword} will slow @code{m4} down
4560 by a factor of about seven, once it is changed to something other
4561 than the default regular expression.  You can invoke @code{changeword}
4562 with the empty string to restore the default word definition, and regain
4563 the parsing speed.
4565 @node M4wrap
4566 @section Saving text until end of input
4568 @cindex saving input
4569 @cindex input, saving
4570 @cindex deferring expansion
4571 @cindex expansion, deferring
4572 It is possible to `save' some text until the end of the normal input has
4573 been seen.  Text can be saved, to be read again by @code{m4} when the
4574 normal input has been exhausted.  This feature is normally used to
4575 initiate cleanup actions before normal exit, e.g., deleting temporary
4576 files.
4578 To save input text, use the builtin @code{m4wrap}:
4580 @deffn Builtin m4wrap (@var{string}, @dots{})
4581 Stores @var{string} in a safe place, to be reread when end of input is
4582 reached.  As a @acronym{GNU} extension, additional arguments are
4583 concatenated with a space to the @var{string}.
4585 The expansion of @code{m4wrap} is void.
4586 The macro @code{m4wrap} is recognized only with parameters.
4587 @end deffn
4589 @example
4590 define(`cleanup', `This is the `cleanup' action.
4592 @result{}
4593 m4wrap(`cleanup')
4594 @result{}
4595 This is the first and last normal input line.
4596 @result{}This is the first and last normal input line.
4598 @result{}This is the cleanup action.
4599 @end example
4601 The saved input is only reread when the end of normal input is seen, and
4602 not if @code{m4exit} is used to exit @code{m4}.
4604 @comment FIXME: this contradicts POSIX, which requires that "If the
4605 @comment m4wrap macro is used multiple times, the arguments specified
4606 @comment shall be processed in the order in which the m4wrap macros were
4607 @comment processed."
4608 It is safe to call @code{m4wrap} from saved text, but then the order in
4609 which the saved text is reread is undefined.  If @code{m4wrap} is not used
4610 recursively, the saved pieces of text are reread in the opposite order
4611 in which they were saved (LIFO---last in, first out).  However, this
4612 behavior is likely to change in a future release, to match
4613 @acronym{POSIX}, so you should not depend on this order.
4615 It is possible to emulate @acronym{POSIX} behavior even
4616 with older versions of @acronym{GNU} M4 by including the file
4617 @file{m4-@value{VERSION}/@/examples/@/wrapfifo.m4} from the
4618 distribution:
4620 @comment examples
4621 @example
4622 $ @kbd{m4 -I examples}
4623 undivert(`wrapfifo.m4')dnl
4624 @result{}dnl Redefine m4wrap to have FIFO semantics.
4625 @result{}define(`_m4wrap_level', `0')dnl
4626 @result{}define(`m4wrap',
4627 @result{}`ifdef(`m4wrap'_m4wrap_level,
4628 @result{}       `define(`m4wrap'_m4wrap_level,
4629 @result{}               defn(`m4wrap'_m4wrap_level)`$1')',
4630 @result{}       `builtin(`m4wrap', `define(`_m4wrap_level',
4631 @result{}                                  incr(_m4wrap_level))dnl
4632 @result{}m4wrap'_m4wrap_level)dnl
4633 @result{}define(`m4wrap'_m4wrap_level, `$1')')')dnl
4634 include(`wrapfifo.m4')
4635 @result{}
4636 m4wrap(`a`'m4wrap(`c
4637 ', `d')')m4wrap(`b')
4638 @result{}
4640 @result{}abc
4641 @end example
4643 It is likewise possible to emulate LIFO behavior without resorting to
4644 the @acronym{GNU} M4 extension of @code{builtin}, by including the file
4645 @file{m4-@value{VERSION}/@/examples/@/wraplifo.m4} from the
4646 distribution.  (Unfortunately, both examples shown here share some
4647 subtle bugs.  See if you can find and correct them; or @pxref{Improved
4648 m4wrap, , Answers}).
4650 @comment examples
4651 @example
4652 $ @kbd{m4 -I examples}
4653 undivert(`wraplifo.m4')dnl
4654 @result{}dnl Redefine m4wrap to have LIFO semantics.
4655 @result{}define(`_m4wrap_level', `0')dnl
4656 @result{}define(`_m4wrap', defn(`m4wrap'))dnl
4657 @result{}define(`m4wrap',
4658 @result{}`ifdef(`m4wrap'_m4wrap_level,
4659 @result{}       `define(`m4wrap'_m4wrap_level,
4660 @result{}               `$1'defn(`m4wrap'_m4wrap_level))',
4661 @result{}       `_m4wrap(`define(`_m4wrap_level', incr(_m4wrap_level))dnl
4662 @result{}m4wrap'_m4wrap_level)dnl
4663 @result{}define(`m4wrap'_m4wrap_level, `$1')')')dnl
4664 include(`wraplifo.m4')
4665 @result{}
4666 m4wrap(`a`'m4wrap(`c
4667 ', `d')')m4wrap(`b')
4668 @result{}
4670 @result{}bac
4671 @end example
4673 Here is an example of implementing a factorial function using
4674 @code{m4wrap}:
4676 @example
4677 define(`f', `ifelse(`$1', `0', `Answer: 0!=1
4678 ', eval(`$1>1'), `0', `Answer: $2$1=eval(`$2$1')
4679 ', `m4wrap(`f(decr(`$1'), `$2$1*')')')')
4680 @result{}
4681 f(`10')
4682 @result{}
4684 @result{}Answer: 10*9*8*7*6*5*4*3*2*1=3628800
4685 @end example
4687 Invocations of @code{m4wrap} at the same recursion level are
4688 concatenated and rescanned as usual:
4690 @example
4691 define(`aa', `AA
4693 @result{}
4694 m4wrap(`a')m4wrap(`a')
4695 @result{}
4697 @result{}AA
4698 @end example
4700 @noindent
4701 however, the transition between recursion levels behaves like an end of
4702 file condition between two input files.
4704 @comment status: 1
4705 @example
4706 m4wrap(`m4wrap(`)')len(abc')
4707 @result{}
4709 @error{}m4:stdin:1: len: end of file in argument list
4710 @end example
4712 @node File Inclusion
4713 @chapter File inclusion
4715 @cindex file inclusion
4716 @cindex inclusion, of files
4717 @code{m4} allows you to include named files at any point in the input.
4719 @menu
4720 * Include::                     Including named files
4721 * Search Path::                 Searching for include files
4722 @end menu
4724 @node Include
4725 @section Including named files
4727 There are two builtin macros in @code{m4} for including files:
4729 @deffn Builtin include (@var{file})
4730 @deffnx Builtin sinclude (@var{file})
4731 Both macros cause the file named @var{file} to be read by
4732 @code{m4}.  When the end of the file is reached, input is resumed from
4733 the previous input file.
4735 The expansion of @code{include} and @code{sinclude} is therefore the
4736 contents of @var{file}.
4738 If @var{file} does not exist (or cannot be read), the expansion is void,
4739 and @code{include} will fail with an error while @code{sinclude} is
4740 silent.  The empty string counts as a file that does not exist.
4742 The macros @code{include} and @code{sinclude} are recognized only with
4743 parameters.
4744 @end deffn
4746 @comment status: 1
4747 @example
4748 include(`n')
4749 @error{}m4:stdin:1: include: cannot open `n': No such file or directory
4750 @result{}
4751 include()
4752 @error{}m4:stdin:2: include: cannot open `': No such file or directory
4753 @result{}
4754 sinclude(`n')
4755 @result{}
4756 sinclude()
4757 @result{}
4758 @end example
4760 The rest of this section assumes that @code{m4} is invoked with the
4761 @option{-I} option (@pxref{Preprocessor features, , Invoking m4})
4762 pointing to the @file{m4-@value{VERSION}/@/examples}
4763 directory shipped as part of the @acronym{GNU} @code{m4} package.  The
4764 file @file{m4-@value{VERSION}/@/examples/@/incl.m4} in the distribution
4765 contains the lines:
4767 @comment ignore
4768 @example
4769 $ @kbd{cat examples/incl.m4}
4770 @result{}Include file start
4771 @result{}foo
4772 @result{}Include file end
4773 @end example
4775 Normally file inclusion is used to insert the contents of a file
4776 into the input stream.  The contents of the file will be read by
4777 @code{m4} and macro calls in the file will be expanded:
4779 @comment examples
4780 @example
4781 $ @kbd{m4 -I examples}
4782 define(`foo', `FOO')
4783 @result{}
4784 include(`incl.m4')
4785 @result{}Include file start
4786 @result{}FOO
4787 @result{}Include file end
4788 @result{}
4789 @end example
4791 The fact that @code{include} and @code{sinclude} expand to the contents
4792 of the file can be used to define macros that operate on entire files.
4793 Here is an example, which defines @samp{bar} to expand to the contents
4794 of @file{incl.m4}:
4796 @comment examples
4797 @example
4798 $ @kbd{m4 -I examples}
4799 define(`bar', include(`incl.m4'))
4800 @result{}
4801 This is `bar':  >>bar<<
4802 @result{}This is bar:  >>Include file start
4803 @result{}foo
4804 @result{}Include file end
4805 @result{}<<
4806 @end example
4808 This use of @code{include} is not trivial, though, as files can contain
4809 quotes, commas, and parentheses, which can interfere with the way the
4810 @code{m4} parser works.  @acronym{GNU} @code{m4} seamlessly concatenates
4811 the file contents with the next character, even if the included file
4812 ended in the middle of a comment, string, or macro call.  These
4813 conditions are only treated as end of file errors if specified as input
4814 files on the command line.
4816 In @acronym{GNU} @code{m4}, an alternative method of reading files is
4817 using @code{undivert} (@pxref{Undivert}) on a named file.
4819 @node Search Path
4820 @section Searching for include files
4822 @cindex search path for included files
4823 @cindex included files, search path for
4824 @cindex @acronym{GNU} extensions
4825 @acronym{GNU} @code{m4} allows included files to be found in other directories
4826 than the current working directory.
4828 @cindex @env{M4PATH}
4829 If the @option{--prepend-include} or @option{-B} command-line option was
4830 provided (@pxref{Preprocessor features, , Invoking m4}), those
4831 directories are searched first, in reverse order that those options were
4832 listed on the command line.  Then @code{m4} looks in the current working
4833 directory.  Next comes the directories specified with the
4834 @option{--include} or @option{-I} option, in the order found on the
4835 command line.  Finally, if the @env{M4PATH} environment variable is set,
4836 it is expected to contain a colon-separated list of directories, which
4837 will be searched in order.
4839 If the automatic search for include-files causes trouble, the @samp{p}
4840 debug flag (@pxref{Debug Levels}) can help isolate the problem.
4842 @node Diversions
4843 @chapter Diverting and undiverting output
4845 @cindex deferring output
4846 Diversions are a way of temporarily saving output.  The output of
4847 @code{m4} can at any time be diverted to a temporary file, and be
4848 reinserted into the output stream, @dfn{undiverted}, again at a later
4849 time.
4851 @cindex @env{TMPDIR}
4852 Numbered diversions are counted from 0 upwards, diversion number 0
4853 being the normal output stream.  The number of simultaneous diversions
4854 is limited mainly by the memory used to describe them, because @acronym{GNU}
4855 @code{m4} tries to keep diversions in memory.  However, there is a
4856 limit to the overall memory usable by all diversions taken altogether
4857 (512K, currently).  When this maximum is about to be exceeded,
4858 a temporary file is opened to receive the contents of the biggest
4859 diversion still in memory, freeing this memory for other diversions.
4860 When creating the temporary file, @code{m4} honors the value of the
4861 environment variable @env{TMPDIR}, and falls back to @file{/tmp}.
4862 So, it is theoretically possible that the number and aggregate size of
4863 diversions is limited only by available disk space.
4865 @ignore
4866 @comment We need to test spilled diversions, but don't need to expose
4867 @comment this highly repetitive test in the manual.
4869 @example
4870 divert(`-1')define(`f', `.')
4871 define(`f', defn(`f')defn(`f'))
4872 define(`f', defn(`f')defn(`f'))
4873 define(`f', defn(`f')defn(`f'))
4874 define(`f', defn(`f')defn(`f'))
4875 define(`f', defn(`f')defn(`f'))
4876 define(`f', defn(`f')defn(`f'))
4877 define(`f', defn(`f')defn(`f'))
4878 define(`f', defn(`f')defn(`f'))
4879 define(`f', defn(`f')defn(`f'))
4880 define(`f', defn(`f')defn(`f'))
4881 define(`f', defn(`f')defn(`f'))
4882 define(`f', defn(`f')defn(`f'))
4883 define(`f', defn(`f')defn(`f'))
4884 define(`f', defn(`f')defn(`f'))
4885 define(`f', defn(`f')defn(`f'))
4886 define(`f', defn(`f')defn(`f'))
4887 define(`f', defn(`f')defn(`f'))
4888 define(`f', defn(`f')defn(`f'))
4889 define(`f', defn(`f')defn(`f'))
4890 define(`f', defn(`f')defn(`f'))
4891 divert`'dnl
4892 len(f)
4893 @result{}1048576
4894 divert(`1')
4896 divert(`-1')undivert
4897 @end example
4899 @comment Another test of spilled diversions.
4901 @example
4902 divert(`-1')define(`f', `.')
4903 define(`f', defn(`f')defn(`f'))
4904 define(`f', defn(`f')defn(`f'))
4905 define(`f', defn(`f')defn(`f'))
4906 define(`f', defn(`f')defn(`f'))
4907 define(`f', defn(`f')defn(`f'))
4908 define(`f', defn(`f')defn(`f'))
4909 define(`f', defn(`f')defn(`f'))
4910 define(`f', defn(`f')defn(`f'))
4911 define(`f', defn(`f')defn(`f'))
4912 define(`f', defn(`f')defn(`f'))
4913 define(`f', defn(`f')defn(`f'))
4914 define(`f', defn(`f')defn(`f'))
4915 define(`f', defn(`f')defn(`f'))
4916 define(`f', defn(`f')defn(`f'))
4917 define(`f', defn(`f')defn(`f'))
4918 define(`f', defn(`f')defn(`f'))
4919 define(`f', defn(`f')defn(`f'))
4920 define(`f', defn(`f')defn(`f'))
4921 define(`f', defn(`f')defn(`f'))
4922 define(`f', defn(`f')defn(`f'))
4923 divert`'dnl
4924 len(f)
4925 @result{}1048576
4926 divert(`1')
4928 m4exit
4929 @end example
4930 @end ignore
4932 Diversions make it possible to generate output in a different order than
4933 the input was read.  It is possible to implement topological sorting
4934 dependencies.  For example, @acronym{GNU} Autoconf makes use of
4935 diversions under the hood to ensure that the expansion of a prerequisite
4936 macro appears in the output prior to the expansion of a dependent macro,
4937 regardless of which order the two macros were invoked in the user's
4938 input file.
4940 @menu
4941 * Divert::                      Diverting output
4942 * Undivert::                    Undiverting output
4943 * Divnum::                      Diversion numbers
4944 * Cleardivert::                 Discarding diverted text
4945 @end menu
4947 @node Divert
4948 @section Diverting output
4950 @cindex diverting output to files
4951 @cindex output, diverting to files
4952 @cindex files, diverting output to
4953 Output is diverted using @code{divert}:
4955 @deffn Builtin divert (@dvar{number, 0})
4956 The current diversion is changed to @var{number}.  If @var{number} is left
4957 out or empty, it is assumed to be zero.  If @var{number} cannot be
4958 parsed, the diversion is unchanged.
4960 The expansion of @code{divert} is void.
4961 @end deffn
4963 When all the @code{m4} input will have been processed, all existing
4964 diversions are automatically undiverted, in numerical order.
4966 @example
4967 divert(`1')
4968 This text is diverted.
4969 divert
4970 @result{}
4971 This text is not diverted.
4972 @result{}This text is not diverted.
4974 @result{}
4975 @result{}This text is diverted.
4976 @end example
4978 Several calls of @code{divert} with the same argument do not overwrite
4979 the previous diverted text, but append to it.  Diversions are printed
4980 after any wrapped text is expanded.
4982 @example
4983 define(`text', `TEXT')
4984 @result{}
4985 divert(`1')`diverted text.'
4986 divert
4987 @result{}
4988 m4wrap(`Wrapped text precedes ')
4989 @result{}
4991 @result{}Wrapped TEXT precedes diverted text.
4992 @end example
4994 @cindex discarding input
4995 @cindex input, discarding
4996 If output is diverted to a negative diversion, it is simply discarded.
4997 This can be used to suppress unwanted output.  A common example of
4998 unwanted output is the trailing newlines after macro definitions.  Here
4999 is a common programming idiom in @code{m4} for avoiding them.
5001 @example
5002 divert(`-1')
5003 define(`foo', `Macro `foo'.')
5004 define(`bar', `Macro `bar'.')
5005 divert
5006 @result{}
5007 @end example
5009 @cindex @acronym{GNU} extensions
5010 Traditional implementations only supported ten diversions.  But as a
5011 @acronym{GNU} extension, diversion numbers can be as large as positive
5012 integers will allow, rather than treating a multi-digit diversion number
5013 as a request to discard text.
5015 @example
5016 divert(eval(`1<<28'))world
5017 divert(`2')hello
5019 @result{}hello
5020 @result{}world
5021 @end example
5023 Note that @code{divert} is an English word, but also an active macro
5024 without arguments.  When processing plain text, the word might appear in
5025 normal text and be unintentionally swallowed as a macro invocation.  One
5026 way to avoid this is to use the @option{-P} option to rename all
5027 builtins (@pxref{Operation modes, , Invoking m4}).  Another is to write
5028 a wrapper that requires a parameter to be recognized.
5030 @example
5031 We decided to divert the stream for irrigation.
5032 @result{}We decided to  the stream for irrigation.
5033 define(`divert', `ifelse(`$#', `0', ``$0'', `builtin(`$0', $@@)')')
5034 @result{}
5035 divert(`-1')
5036 Ignored text.
5037 divert(`0')
5038 @result{}
5039 We decided to divert the stream for irrigation.
5040 @result{}We decided to divert the stream for irrigation.
5041 @end example
5043 @node Undivert
5044 @section Undiverting output
5046 Diverted text can be undiverted explicitly using the builtin
5047 @code{undivert}:
5049 @deffn Builtin undivert (@ovar{diversions@dots{}})
5050 Undiverts the numeric @var{diversions} given by the arguments, in the
5051 order given.  If no arguments are supplied, all diversions are
5052 undiverted, in numerical order.
5054 @cindex file inclusion
5055 @cindex inclusion, of files
5056 @cindex @acronym{GNU} extensions
5057 As a @acronym{GNU} extension, @var{diversions} may contain non-numeric
5058 strings, which are treated as the names of files to copy into the output
5059 without expansion.  A warning is issued if a file could not be opened.
5061 The expansion of @code{undivert} is void.
5062 @end deffn
5064 @example
5065 divert(`1')
5066 This text is diverted.
5067 divert
5068 @result{}
5069 This text is not diverted.
5070 @result{}This text is not diverted.
5071 undivert(`1')
5072 @result{}
5073 @result{}This text is diverted.
5074 @result{}
5075 @end example
5077 Notice the last two blank lines.  One of them comes from the newline
5078 following @code{undivert}, the other from the newline that followed the
5079 @code{divert}!  A diversion often starts with a blank line like this.
5081 When diverted text is undiverted, it is @emph{not} reread by @code{m4},
5082 but rather copied directly to the current output, and it is therefore
5083 not an error to undivert into a diversion.  Undiverting the empty string
5084 is the same as specifying diversion 0; in either case nothing happens
5085 since the output has already been flushed.
5087 @example
5088 divert(`1')diverted text
5089 divert
5090 @result{}
5091 undivert()
5092 @result{}
5093 undivert(`0')
5094 @result{}
5095 undivert
5096 @result{}diverted text
5097 @result{}
5098 @end example
5100 When a diversion has been undiverted, the diverted text is discarded,
5101 and it is not possible to bring back diverted text more than once.
5103 @example
5104 divert(`1')
5105 This text is diverted first.
5106 divert(`0')undivert(`1')dnl
5107 @result{}
5108 @result{}This text is diverted first.
5109 undivert(`1')
5110 @result{}
5111 divert(`1')
5112 This text is also diverted but not appended.
5113 divert(`0')undivert(`1')dnl
5114 @result{}
5115 @result{}This text is also diverted but not appended.
5116 @end example
5118 Attempts to undivert the current diversion are silently ignored.  Thus,
5119 when the current diversion is not 0, the current diversion does not get
5120 rearranged among the other diversions.
5122 @example
5123 divert(`1')one
5124 divert(`2')two
5125 divert(`3')three
5126 divert(`2')undivert`'dnl
5127 divert`'undivert`'dnl
5128 @result{}two
5129 @result{}one
5130 @result{}three
5131 @end example
5133 @cindex @acronym{GNU} extensions
5134 @cindex file inclusion
5135 @cindex inclusion, of files
5136 @acronym{GNU} @code{m4} allows named files to be undiverted.  Given a
5137 non-numeric argument, the contents of the file named will be copied,
5138 uninterpreted, to the current output.  This complements the builtin
5139 @code{include} (@pxref{Include}).  To illustrate the difference, assume
5140 the file @file{foo} contains:
5142 @comment ignore
5143 @example
5144 $ @kbd{cat foo}
5146 @end example
5148 @noindent
5149 then
5151 @example
5152 define(`bar', `BAR')
5153 @result{}
5154 undivert(`foo')
5155 @result{}bar
5156 @result{}
5157 include(`foo')
5158 @result{}BAR
5159 @result{}
5160 @end example
5162 If the file is not found (or cannot be read), an error message is
5163 issued, and the expansion is void.  It is possible to intermix files
5164 and diversion numbers.
5166 @example
5167 divert(`1')diversion one
5168 divert(`2')undivert(`foo')dnl
5169 divert(`3')diversion three
5170 divert`'dnl
5171 undivert(`1', `2', `foo', `3')dnl
5172 @result{}diversion one
5173 @result{}bar
5174 @result{}bar
5175 @result{}diversion three
5176 @end example
5178 @node Divnum
5179 @section Diversion numbers
5181 @cindex diversion numbers
5182 The current diversion is tracked by the builtin @code{divnum}:
5184 @deffn Builtin divnum
5185 Expands to the number of the current diversion.
5186 @end deffn
5188 @example
5189 Initial divnum
5190 @result{}Initial 0
5191 divert(`1')
5192 Diversion one: divnum
5193 divert(`2')
5194 Diversion two: divnum
5196 @result{}
5197 @result{}Diversion one: 1
5198 @result{}
5199 @result{}Diversion two: 2
5200 @end example
5202 @node Cleardivert
5203 @section Discarding diverted text
5205 @cindex discarding diverted text
5206 @cindex diverted text, discarding
5207 Often it is not known, when output is diverted, whether the diverted
5208 text is actually needed.  Since all non-empty diversion are brought back
5209 on the main output stream when the end of input is seen, a method of
5210 discarding a diversion is needed.  If all diversions should be
5211 discarded, the easiest is to end the input to @code{m4} with
5212 @samp{divert(`-1')} followed by an explicit @samp{undivert}:
5214 @example
5215 divert(`1')
5216 Diversion one: divnum
5217 divert(`2')
5218 Diversion two: divnum
5219 divert(`-1')
5220 undivert
5222 @end example
5224 @noindent
5225 No output is produced at all.
5227 Clearing selected diversions can be done with the following macro:
5229 @deffn Composite cleardivert (@ovar{diversions@dots{}})
5230 Discard the contents of each of the listed numeric @var{diversions}.
5231 @end deffn
5233 @example
5234 define(`cleardivert',
5235 `pushdef(`_n', divnum)divert(`-1')undivert($@@)divert(_n)popdef(`_n')')
5236 @result{}
5237 @end example
5239 It is called just like @code{undivert}, but the effect is to clear the
5240 diversions, given by the arguments.  (This macro has a nasty bug!  You
5241 should try to see if you can find it and correct it; or @pxref{Improved
5242 cleardivert, , Answers}).
5244 @node Text handling
5245 @chapter Macros for text handling
5247 There are a number of builtins in @code{m4} for manipulating text in
5248 various ways, extracting substrings, searching, substituting, and so on.
5250 @menu
5251 * Len::                         Calculating length of strings
5252 * Index macro::                 Searching for substrings
5253 * Regexp::                      Searching for regular expressions
5254 * Substr::                      Extracting substrings
5255 * Translit::                    Translating characters
5256 * Patsubst::                    Substituting text by regular expression
5257 * Format::                      Formatting strings (printf-like)
5258 @end menu
5260 @node Len
5261 @section Calculating length of strings
5263 @cindex length of strings
5264 @cindex strings, length of
5265 The length of a string can be calculated by @code{len}:
5267 @deffn Builtin len (@var{string})
5268 Expands to the length of @var{string}, as a decimal number.
5270 The macro @code{len} is recognized only with parameters.
5271 @end deffn
5273 @example
5274 len()
5275 @result{}0
5276 len(`abcdef')
5277 @result{}6
5278 @end example
5280 @node Index macro
5281 @section Searching for substrings
5283 @cindex substrings, locating
5284 Searching for substrings is done with @code{index}:
5286 @deffn Builtin index (@var{string}, @var{substring})
5287 Expands to the index of the first occurrence of @var{substring} in
5288 @var{string}.  The first character in @var{string} has index 0.  If
5289 @var{substring} does not occur in @var{string}, @code{index} expands to
5290 @samp{-1}.
5292 The macro @code{index} is recognized only with parameters.
5293 @end deffn
5295 @example
5296 index(`gnus, gnats, and armadillos', `nat')
5297 @result{}7
5298 index(`gnus, gnats, and armadillos', `dag')
5299 @result{}-1
5300 @end example
5302 Omitting @var{substring} evokes a warning, but still produces output;
5303 contrast this with an empty @var{substring}.
5305 @example
5306 index(`abc')
5307 @error{}m4:stdin:1: Warning: index: too few arguments: 1 < 2
5308 @result{}0
5309 index(`abc', `')
5310 @result{}0
5311 index(`abc', `b')
5312 @result{}1
5313 @end example
5315 @node Regexp
5316 @section Searching for regular expressions
5318 @cindex basic regular expressions
5319 @cindex regular expressions
5320 @cindex expressions, regular
5321 @cindex @acronym{GNU} extensions
5322 Searching for regular expressions is done with the builtin
5323 @code{regexp}:
5325 @deffn Builtin regexp (@var{string}, @var{regexp}, @ovar{replacement})
5326 Searches for @var{regexp} in @var{string}.  The syntax for regular
5327 expressions is the same as in @acronym{GNU} Emacs, which is similar to
5328 @acronym{BRE, Basic Regular Expressions} in @acronym{POSIX}.
5329 @ifnothtml
5330 @xref{Regexps, , Syntax of Regular Expressions, emacs, The GNU Emacs
5331 Manual}.
5332 @end ifnothtml
5333 @ifhtml
5335 @uref{http://www.gnu.org/@/software/@/emacs/@/manual/@/emacs.html#Regexps,
5336 Syntax of Regular Expressions} in the @acronym{GNU} Emacs Manual.
5337 @end ifhtml
5338 Support for @acronym{ERE, Extended Regular Expressions} is not
5339 available, but will be added in @acronym{GNU} M4 2.0.
5341 If @var{replacement} is omitted, @code{regexp} expands to the index of
5342 the first match of @var{regexp} in @var{string}.  If @var{regexp} does
5343 not match anywhere in @var{string}, it expands to -1.
5345 If @var{replacement} is supplied, and there was a match, @code{regexp}
5346 changes the expansion to this argument, with @samp{\@var{n}} substituted
5347 by the text matched by the @var{n}th parenthesized sub-expression of
5348 @var{regexp}, up to nine sub-expressions.  The escape @samp{\&} is
5349 replaced by the text of the entire regular expression matched.  For
5350 all other characters, @samp{\} treats the next character literally.  A
5351 warning is issued if there were fewer sub-expressions than the
5352 @samp{\@var{n}} requested, or if there is a trailing @samp{\}.  If there
5353 was no match, @code{regexp} expands to the empty string.
5355 The macro @code{regexp} is recognized only with parameters.
5356 @end deffn
5358 @example
5359 regexp(`GNUs not Unix', `\<[a-z]\w+')
5360 @result{}5
5361 regexp(`GNUs not Unix', `\<Q\w*')
5362 @result{}-1
5363 regexp(`GNUs not Unix', `\w\(\w+\)$', `*** \& *** \1 ***')
5364 @result{}*** Unix *** nix ***
5365 regexp(`GNUs not Unix', `\<Q\w*', `*** \& *** \1 ***')
5366 @result{}
5367 @end example
5369 Here are some more examples on the handling of backslash:
5371 @example
5372 regexp(`abc', `\(b\)', `\\\10\a')
5373 @result{}\b0a
5374 regexp(`abc', `b', `\1\')
5375 @error{}m4:stdin:2: Warning: regexp: sub-expression 1 not present
5376 @error{}m4:stdin:2: Warning: regexp: trailing \ ignored in replacement
5377 @result{}
5378 regexp(`abc', `\(\(d\)?\)\(c\)', `\1\2\3\4\5\6')
5379 @error{}m4:stdin:3: Warning: regexp: sub-expression 4 not present
5380 @error{}m4:stdin:3: Warning: regexp: sub-expression 5 not present
5381 @error{}m4:stdin:3: Warning: regexp: sub-expression 6 not present
5382 @result{}c
5383 @end example
5385 Omitting @var{regexp} evokes a warning, but still produces output;
5386 contrast this with an empty @var{regexp} argument.
5388 @example
5389 regexp(`abc')
5390 @error{}m4:stdin:1: Warning: regexp: too few arguments: 1 < 2
5391 @result{}0
5392 regexp(`abc', `')
5393 @result{}0
5394 regexp(`abc', `', `\\def')
5395 @result{}\def
5396 @end example
5398 @node Substr
5399 @section Extracting substrings
5401 @cindex extracting substrings
5402 @cindex substrings, extracting
5403 Substrings are extracted with @code{substr}:
5405 @deffn Builtin substr (@var{string}, @var{from}, @ovar{length})
5406 Expands to the substring of @var{string}, which starts at index
5407 @var{from}, and extends for @var{length} characters, or to the end of
5408 @var{string}, if @var{length} is omitted.  The starting index of a string
5409 is always 0.  The expansion is empty if there is an error parsing
5410 @var{from} or @var{length}, if @var{from} is beyond the end of
5411 @var{string}, or if @var{length} is negative.
5413 The macro @code{substr} is recognized only with parameters.
5414 @end deffn
5416 @example
5417 substr(`gnus, gnats, and armadillos', `6')
5418 @result{}gnats, and armadillos
5419 substr(`gnus, gnats, and armadillos', `6', `5')
5420 @result{}gnats
5421 @end example
5423 Omitting @var{from} evokes a warning, but still produces output.
5425 @example
5426 substr(`abc')
5427 @error{}m4:stdin:1: Warning: substr: too few arguments: 1 < 2
5428 @result{}abc
5429 substr(`abc',)
5430 @error{}m4:stdin:2: Warning: substr: empty string treated as 0
5431 @result{}abc
5432 @end example
5434 @node Translit
5435 @section Translating characters
5437 @cindex translating characters
5438 @cindex characters, translating
5439 Character translation is done with @code{translit}:
5441 @deffn Builtin translit (@var{string}, @var{chars}, @ovar{replacement})
5442 Expands to @var{string}, with each character that occurs in
5443 @var{chars} translated into the character from @var{replacement} with
5444 the same index.
5446 If @var{replacement} is shorter than @var{chars}, the excess characters
5447 of @var{chars} are deleted from the expansion; if @var{chars} is
5448 shorter, the excess characters in @var{replacement} are silently
5449 ignored.  If @var{replacement} is omitted, all characters in
5450 @var{string} that are present in @var{chars} are deleted from the
5451 expansion.  If a character appears more than once in @var{chars}, only
5452 the first instance is used in making the translation.  Only a single
5453 translation pass is made, even if characters in @var{replacement} also
5454 appear in @var{chars}.
5456 As a @acronym{GNU} extension, both @var{chars} and @var{replacement} can
5457 contain character-ranges, e.g., @samp{a-z} (meaning all lowercase
5458 letters) or @samp{0-9} (meaning all digits).  To include a dash @samp{-}
5459 in @var{chars} or @var{replacement}, place it first or last in the
5460 entire string, or as the last character of a range.  Back-to-back ranges
5461 can share a common endpoint.  It is not an error for the last character
5462 in the range to be `larger' than the first.  In that case, the range
5463 runs backwards, i.e., @samp{9-0} means the string @samp{9876543210}.
5464 The expansion of a range is dependent on the underlying encoding of
5465 characters, so using ranges is not always portable between machines.
5467 The macro @code{translit} is recognized only with parameters.
5468 @end deffn
5470 @example
5471 translit(`GNUs not Unix', `A-Z')
5472 @result{}s not nix
5473 translit(`GNUs not Unix', `a-z', `A-Z')
5474 @result{}GNUS NOT UNIX
5475 translit(`GNUs not Unix', `A-Z', `z-a')
5476 @result{}tmfs not fnix
5477 translit(`+,-12345', `+--1-5', `<;>a-c-a')
5478 @result{}<;>abcba
5479 translit(`abcdef', `aabdef', `bcged')
5480 @result{}bgced
5481 @end example
5483 In the @sc{ascii} encoding, the first example deletes all uppercase
5484 letters, the second converts lowercase to uppercase, and the third
5485 `mirrors' all uppercase letters, while converting them to lowercase.
5486 The two first cases are by far the most common, even though they are not
5487 portable to @sc{ebcdic} or other encodings.  The fourth example shows a
5488 range ending in @samp{-}, as well as back-to-back ranges.  The final
5489 example shows that @samp{a} is mapped to @samp{b}, not @samp{c}; the
5490 resulting @samp{b} is not further remapped to @samp{g}; the @samp{d} and
5491 @samp{e} are swapped, and the @samp{f} is discarded.
5493 @ignore
5494 @comment No need to fight 8-bit characters, as it is difficult to get
5495 @comment rendering right in both info and dvi.
5497 @example
5498 translit(`«abc~', `~-»')
5499 @result{}abc
5500 @end example
5501 @end ignore
5503 Omitting @var{chars} evokes a warning, but still produces output.
5505 @example
5506 translit(`abc')
5507 @error{}m4:stdin:1: Warning: translit: too few arguments: 1 < 2
5508 @result{}abc
5509 @end example
5511 @node Patsubst
5512 @section Substituting text by regular expression
5514 @cindex basic regular expressions
5515 @cindex regular expressions
5516 @cindex expressions, regular
5517 @cindex pattern substitution
5518 @cindex substitution by regular expression
5519 @cindex @acronym{GNU} extensions
5520 Global substitution in a string is done by @code{patsubst}:
5522 @deffn Builtin patsubst (@var{string}, @var{regexp}, @ovar{replacement})
5523 Searches @var{string} for matches of @var{regexp}, and substitutes
5524 @var{replacement} for each match.  The syntax for regular expressions
5525 is the same as in @acronym{GNU} Emacs (@pxref{Regexp}).
5527 The parts of @var{string} that are not covered by any match of
5528 @var{regexp} are copied to the expansion.  Whenever a match is found, the
5529 search proceeds from the end of the match, so a character from
5530 @var{string} will never be substituted twice.  If @var{regexp} matches a
5531 string of zero length, the start position for the search is incremented,
5532 to avoid infinite loops.
5534 When a replacement is to be made, @var{replacement} is inserted into
5535 the expansion, with @samp{\@var{n}} substituted by the text matched by
5536 the @var{n}th parenthesized sub-expression of @var{patsubst}, for up to
5537 nine sub-expressions.  The escape @samp{\&} is replaced by the text of
5538 the entire regular expression matched.  For all other characters,
5539 @samp{\} treats the next character literally.  A warning is issued if
5540 there were fewer sub-expressions than the @samp{\@var{n}} requested, or
5541 if there is a trailing @samp{\}.
5543 The @var{replacement} argument can be omitted, in which case the text
5544 matched by @var{regexp} is deleted.
5546 The macro @code{patsubst} is recognized only with parameters.
5547 @end deffn
5549 @example
5550 patsubst(`GNUs not Unix', `^', `OBS: ')
5551 @result{}OBS: GNUs not Unix
5552 patsubst(`GNUs not Unix', `\<', `OBS: ')
5553 @result{}OBS: GNUs OBS: not OBS: Unix
5554 patsubst(`GNUs not Unix', `\w*', `(\&)')
5555 @result{}(GNUs)() (not)() (Unix)()
5556 patsubst(`GNUs not Unix', `\w+', `(\&)')
5557 @result{}(GNUs) (not) (Unix)
5558 patsubst(`GNUs not Unix', `[A-Z][a-z]+')
5559 @result{}GN not@w{ }
5560 patsubst(`GNUs not Unix', `not', `NOT\')
5561 @error{}m4:stdin:6: Warning: patsubst: trailing \ ignored in replacement
5562 @result{}GNUs NOT Unix
5563 @end example
5565 Here is a slightly more realistic example, which capitalizes individual
5566 words or whole sentences, by substituting calls of the macros
5567 @code{upcase} and @code{downcase} into the strings.
5569 @deffn Composite upcase (@var{text})
5570 @deffnx Composite downcase (@var{text})
5571 @deffnx Composite capitalize (@var{text})
5572 Expand to @var{text}, but with capitalization changed: @code{upcase}
5573 changes all letters to upper case, @code{downcase} changes all letters
5574 to lower case, and @code{capitalize} changes the first character of each
5575 word to upper case and the remaining characters to lower case.
5576 @end deffn
5578 First, an example of their usage, using implementations distributed in
5579 @file{m4-@value{VERSION}/@/examples/@/capitalize.m4}.
5581 @comment examples
5582 @example
5583 $ @kbd{m4 -I examples}
5584 include(`capitalize.m4')
5585 @result{}
5586 upcase(`GNUs not Unix')
5587 @result{}GNUS NOT UNIX
5588 downcase(`GNUs not Unix')
5589 @result{}gnus not unix
5590 capitalize(`GNUs not Unix')
5591 @result{}Gnus Not Unix
5592 @end example
5594 Now for the implementation.  There is a helper macro @code{_capitalize}
5595 which puts only its first word in mixed case.  Then @code{capitalize}
5596 merely parses out the words, and replaces them with an invocation of
5597 @code{_capitalize}.  (As presented here, the @code{capitalize} macro has
5598 some subtle flaws.  You should try to see if you can find and correct
5599 them; or @pxref{Improved capitalize, , Answers}).
5601 @comment examples
5602 @example
5603 $ @kbd{m4 -I examples}
5604 undivert(`capitalize.m4')dnl
5605 @result{}divert(`-1')
5606 @result{}# upcase(text)
5607 @result{}# downcase(text)
5608 @result{}# capitalize(text)
5609 @result{}#   change case of text, simple version
5610 @result{}define(`upcase', `translit(`$*', `a-z', `A-Z')')
5611 @result{}define(`downcase', `translit(`$*', `A-Z', `a-z')')
5612 @result{}define(`_capitalize',
5613 @result{}       `regexp(`$1', `^\(\w\)\(\w*\)',
5614 @result{}               `upcase(`\1')`'downcase(`\2')')')
5615 @result{}define(`capitalize', `patsubst(`$1', `\w+', `_$0(`\&')')')
5616 @result{}divert`'dnl
5617 @end example
5619 While @code{regexp} replaces the whole input with the replacement as
5620 soon as there is a match, @code{patsubst} replaces each
5621 @emph{occurrence} of a match and preserves non-matching pieces:
5623 @example
5624 define(`patreg',
5625 `patsubst($@@)
5626 regexp($@@)')dnl
5627 patreg(`bar foo baz Foo', `foo\|Foo', `FOO')
5628 @result{}bar FOO baz FOO
5629 @result{}FOO
5630 patreg(`aba abb 121', `\(.\)\(.\)\1', `\2\1\2')
5631 @result{}bab abb 212
5632 @result{}bab
5633 @end example
5635 Omitting @var{regexp} evokes a warning, but still produces output;
5636 contrast this with an empty @var{regexp} argument.
5638 @example
5639 patsubst(`abc')
5640 @error{}m4:stdin:1: Warning: patsubst: too few arguments: 1 < 2
5641 @result{}abc
5642 patsubst(`abc', `')
5643 @result{}abc
5644 patsubst(`abc', `', `\\-')
5645 @result{}\-a\-b\-c\-
5646 @end example
5648 @node Format
5649 @section Formatting strings (printf-like)
5651 @cindex formatted output
5652 @cindex output, formatted
5653 @cindex @acronym{GNU} extensions
5654 Formatted output can be made with @code{format}:
5656 @deffn Builtin format (@var{format-string}, @dots{})
5657 Works much like the C function @code{printf}.  The first argument
5658 @var{format-string} can contain @samp{%} specifications which are
5659 satisfied by additional arguments, and the expansion of @code{format} is
5660 the formatted string.
5662 The macro @code{format} is recognized only with parameters.
5663 @end deffn
5665 Its use is best described by a few examples:
5667 @comment This test is a bit fragile, if someone tries to port to a
5668 @comment platform without infinity.
5669 @example
5670 define(`foo', `The brown fox jumped over the lazy dog')
5671 @result{}
5672 format(`The string "%s" uses %d characters', foo, len(foo))
5673 @result{}The string "The brown fox jumped over the lazy dog" uses 38 characters
5674 format(`%*.*d', `-1', `-1', `1')
5675 @result{}1
5676 format(`%.0f', `56789.9876')
5677 @result{}56790
5678 len(format(`%-*X', `5000', `1'))
5679 @result{}5000
5680 ifelse(format(`%010F', `infinity'), `       INF', `success',
5681        format(`%010F', `infinity'), `  INFINITY', `success',
5682        format(`%010F', `infinity'))
5683 @result{}success
5684 ifelse(format(`%.1A', `1.999'), `0X1.0P+1', `success',
5685        format(`%.1A', `1.999'), `0X2.0P+0', `success',
5686        format(`%.1A', `1.999'))
5687 @result{}success
5688 @end example
5690 Using the @code{forloop} macro defined earlier (@pxref{Forloop}), this
5691 example shows how @code{format} can be used to produce tabular output.
5693 @comment examples
5694 @example
5695 $ @kbd{m4 -I examples}
5696 include(`forloop.m4')
5697 @result{}
5698 forloop(`i', `1', `10', `format(`%6d squared is %10d
5699 ', i, eval(i**2))')
5700 @result{}     1 squared is          1
5701 @result{}     2 squared is          4
5702 @result{}     3 squared is          9
5703 @result{}     4 squared is         16
5704 @result{}     5 squared is         25
5705 @result{}     6 squared is         36
5706 @result{}     7 squared is         49
5707 @result{}     8 squared is         64
5708 @result{}     9 squared is         81
5709 @result{}    10 squared is        100
5710 @result{}
5711 @end example
5713 The builtin @code{format} is modeled after the ANSI C @samp{printf}
5714 function, and supports these @samp{%} specifiers: @samp{c}, @samp{s},
5715 @samp{d}, @samp{o}, @samp{x}, @samp{X}, @samp{u}, @samp{a}, @samp{A},
5716 @samp{e}, @samp{E}, @samp{f}, @samp{F}, @samp{g}, @samp{G}, and
5717 @samp{%}; it supports field widths and precisions, and the flags
5718 @samp{+}, @samp{-}, @samp{ }, @samp{0}, @samp{#}, and @samp{'}.  For
5719 integer specifiers, the width modifiers @samp{hh}, @samp{h}, and
5720 @samp{l} are recognized, and for floating point specifiers, the width
5721 modifier @samp{l} is recognized.  Items not yet supported include
5722 positional arguments, the @samp{n}, @samp{p}, @samp{S}, and @samp{C}
5723 specifiers, the @samp{z}, @samp{t}, @samp{j}, @samp{L} and @samp{ll}
5724 modifiers, and any platform extensions available in the native
5725 @code{printf}.  For more details on the functioning of @code{printf},
5726 see the C Library Manual, or the @acronym{POSIX} specification (for
5727 example, @samp{%a} is supported even on platforms that haven't yet
5728 implemented C99 hexadecimal floating point output natively).
5730 Warnings are issued for unrecognized specifiers, an improper number of
5731 arguments, or difficulty parsing an argument according to the format
5732 string (such as overflow or extra characters).  It is anticipated that a
5733 future release of @acronym{GNU} @code{m4} will support more specifiers.
5734 Likewise, escape sequences are not yet recognized.
5736 @example
5737 format(`%p', `0')
5738 @error{}m4:stdin:1: Warning: format: unrecognized specifier in `%p'
5739 @result{}
5740 format(`%*d', `')
5741 @error{}m4:stdin:2: Warning: format: empty string treated as 0
5742 @error{}m4:stdin:2: Warning: format: too few arguments: 2 < 3
5743 @result{}0
5744 format(`%.1f', `2a')
5745 @error{}m4:stdin:3: Warning: format: non-numeric argument `2a'
5746 @result{}2.0
5747 @end example
5749 @node Arithmetic
5750 @chapter Macros for doing arithmetic
5752 @cindex arithmetic
5753 @cindex integer arithmetic
5754 Integer arithmetic is included in @code{m4}, with a C-like syntax.  As
5755 convenient shorthands, there are builtins for simple increment and
5756 decrement operations.
5758 @menu
5759 * Incr::                        Decrement and increment operators
5760 * Eval::                        Evaluating integer expressions
5761 @end menu
5763 @node Incr
5764 @section Decrement and increment operators
5766 @cindex decrement operator
5767 @cindex increment operator
5768 Increment and decrement of integers are supported using the builtins
5769 @code{incr} and @code{decr}:
5771 @deffn Builtin incr (@var{number})
5772 @deffnx Builtin decr (@var{number})
5773 Expand to the numerical value of @var{number}, incremented
5774 or decremented, respectively, by one.  Except for the empty string, the
5775 expansion is empty if @var{number} could not be parsed.
5777 The macros @code{incr} and @code{decr} are recognized only with
5778 parameters.
5779 @end deffn
5781 @example
5782 incr(`4')
5783 @result{}5
5784 decr(`7')
5785 @result{}6
5786 incr()
5787 @error{}m4:stdin:3: Warning: incr: empty string treated as 0
5788 @result{}1
5789 decr()
5790 @error{}m4:stdin:4: Warning: decr: empty string treated as 0
5791 @result{}-1
5792 @end example
5794 @node Eval
5795 @section Evaluating integer expressions
5797 @cindex integer expression evaluation
5798 @cindex evaluation, of integer expressions
5799 @cindex expressions, evaluation of integer
5800 Integer expressions are evaluated with @code{eval}:
5802 @deffn Builtin eval (@var{expression}, @dvar{radix, 10}, @ovar{width})
5803 Expands to the value of @var{expression}.  The expansion is empty
5804 if a problem is encountered while parsing the arguments.  If specified,
5805 @var{radix} and @var{width} control the format of the output.
5807 Calculations are done with 32-bit signed numbers.  Overflow silently
5808 results in wraparound.  A warning is issued if division by zero is
5809 attempted, or if @var{expression} could not be parsed.
5811 Expressions can contain the following operators, listed in order of
5812 decreasing precedence.
5814 @table @samp
5815 @item ()
5816 Parentheses
5817 @item +  -  ~  !
5818 Unary plus and minus, and bitwise and logical negation
5819 @item **
5820 Exponentiation
5821 @item *  /  %
5822 Multiplication, division, and modulo
5823 @item +  -
5824 Addition and subtraction
5825 @item <<  >>
5826 Shift left or right
5827 @item >  >=  <  <=
5828 Relational operators
5829 @item ==  !=
5830 Equality operators
5831 @item &
5832 Bitwise and
5833 @item ^
5834 Bitwise exclusive-or
5835 @item |
5836 Bitwise or
5837 @item &&
5838 Logical and
5839 @item ||
5840 Logical or
5841 @end table
5843 The macro @code{eval} is recognized only with parameters.
5844 @end deffn
5846 All binary operators, except exponentiation, are left associative.  C
5847 operators that perform variable assignment, such as @samp{+=} or
5848 @samp{--}, are not implemented, since @code{eval} only operates on
5849 constants, not variables.  Attempting to use them results in an error.
5850 However, since traditional implementations treated @samp{=} as an
5851 undocumented alias for @samp{==} as opposed to an assignment operator,
5852 this usage is supported as a special case.  Be aware that a future
5853 version of @acronym{GNU} M4 may support assignment semantics as an
5854 extension when @acronym{POSIX} mode is not requested, and that using
5855 @samp{=} to check equality is not portable.
5857 @comment status: 1
5858 @example
5859 eval(`2 = 2')
5860 @error{}m4:stdin:1: Warning: eval: recommend ==, not =, for equality
5861 @result{}1
5862 eval(`++0')
5863 @error{}m4:stdin:2: eval: invalid operator: ++0
5864 @result{}
5865 eval(`0 |= 1')
5866 @error{}m4:stdin:3: eval: invalid operator: 0 |= 1
5867 @result{}
5868 @end example
5870 Note that some older @code{m4} implementations use @samp{^} as an
5871 alternate operator for the exponentiation, although @acronym{POSIX}
5872 requires the C behavior of bitwise exclusive-or.  The precedence of the
5873 negation operators, @samp{~} and @samp{!}, was traditionally lower than
5874 equality.  The unary operators could not be used reliably more than once
5875 on the same term without intervening parentheses.  The traditional
5876 precedence of the equality operators @samp{==} and @samp{!=} was
5877 identical instead of lower than the relational operators such as
5878 @samp{<}, even through @acronym{GNU} M4 1.4.8.  Starting with version
5879 1.4.9, @acronym{GNU} M4 correctly follows @acronym{POSIX} precedence
5880 rules.  M4 scripts designed to be portable between releases must be
5881 aware that parentheses may be required to enforce C precedence rules.
5882 Likewise, division by zero, even in the unused branch of a
5883 short-circuiting operator, is not always well-defined in other
5884 implementations.
5886 Following are some examples where the current version of M4 follows C
5887 precedence rules, but where older versions and some other
5888 implementations of @code{m4} require explicit parentheses to get the
5889 correct result:
5891 @example
5892 eval(`1 == 2 > 0')
5893 @result{}1
5894 eval(`(1 == 2) > 0')
5895 @result{}0
5896 eval(`! 0 * 2')
5897 @result{}2
5898 eval(`! (0 * 2)')
5899 @result{}1
5900 eval(`1 | 1 ^ 1')
5901 @result{}1
5902 eval(`(1 | 1) ^ 1')
5903 @result{}0
5904 eval(`+ + - ~ ! ~ 0')
5905 @result{}1
5906 eval(`2 || 1 / 0')
5907 @result{}1
5908 eval(`0 || 1 / 0')
5909 @error{}m4:stdin:9: Warning: eval: divide by zero: 0 || 1 / 0
5910 @result{}
5911 eval(`0 && 1 % 0')
5912 @result{}0
5913 eval(`2 && 1 % 0')
5914 @error{}m4:stdin:11: Warning: eval: modulo by zero: 2 && 1 % 0
5915 @result{}
5916 @end example
5918 @cindex @acronym{GNU} extensions
5919 As a @acronym{GNU} extension, the operator @samp{**} performs integral
5920 exponentiation.  The operator is right-associative, and if evaluated,
5921 the exponent must be non-negative, and at least one of the arguments
5922 must be non-zero, or a warning is issued.
5924 @example
5925 eval(`2 ** 3 ** 2')
5926 @result{}512
5927 eval(`(2 ** 3) ** 2')
5928 @result{}64
5929 eval(`0 ** 1')
5930 @result{}0
5931 eval(`2 ** 0')
5932 @result{}1
5933 eval(`0 ** 0')
5934 @result{}
5935 @error{}m4:stdin:5: Warning: eval: divide by zero: 0 ** 0
5936 eval(`4 ** -2')
5937 @error{}m4:stdin:6: Warning: eval: negative exponent: 4 ** -2
5938 @result{}
5939 @end example
5941 Within @var{expression}, (but not @var{radix} or @var{width}), numbers
5942 without a special prefix are decimal.  A simple @samp{0} prefix
5943 introduces an octal number.  @samp{0x} introduces a hexadecimal number.
5944 As @acronym{GNU} extensions, @samp{0b} introduces a binary number.
5945 @samp{0r} introduces a number expressed in any radix between 1 and 36:
5946 the prefix should be immediately followed by the decimal expression of
5947 the radix, a colon, then the digits making the number.  For radix 1,
5948 leading zeros are ignored, and all remaining digits must be @samp{1};
5949 for all other radices, the digits are @samp{0}, @samp{1}, @samp{2},
5950 @dots{}.  Beyond @samp{9}, the digits are @samp{a}, @samp{b} @dots{} up
5951 to @samp{z}.  Lower and upper case letters can be used interchangeably
5952 in numbers prefixes and as number digits.
5954 Parentheses may be used to group subexpressions whenever needed.  For the
5955 relational operators, a true relation returns @code{1}, and a false
5956 relation return @code{0}.
5958 Here are a few examples of use of @code{eval}.
5960 @example
5961 eval(`-3 * 5')
5962 @result{}-15
5963 eval(`-99 / 10')
5964 @result{}-9
5965 eval(`-99 % 10')
5966 @result{}-9
5967 eval(`99 % -10')
5968 @result{}9
5969 eval(index(`Hello world', `llo') >= 0)
5970 @result{}1
5971 eval(`0r1:0111 + 0b100 + 0r3:12')
5972 @result{}12
5973 define(`square', `eval(`($1) ** 2')')
5974 @result{}
5975 square(`9')
5976 @result{}81
5977 square(square(`5')` + 1')
5978 @result{}676
5979 define(`foo', `666')
5980 @result{}
5981 eval(`foo / 6')
5982 @error{}m4:stdin:11: Warning: eval: bad expression: foo / 6
5983 @result{}
5984 eval(foo / 6)
5985 @result{}111
5986 @end example
5988 As the last two lines show, @code{eval} does not handle macro
5989 names, even if they expand to a valid expression (or part of a valid
5990 expression).  Therefore all macros must be expanded before they are
5991 passed to @code{eval}.
5993 Some calculations are not portable to other implementations, since they
5994 have undefined semantics in C, but @acronym{GNU} @code{m4} has
5995 well-defined behavior on overflow.  When shifting, an out-of-range shift
5996 amount is implicitly brought into the range of 32-bit signed integers
5997 using an implicit bit-wise and with 0x1f).
5999 @example
6000 define(`max_int', eval(`0x7fffffff'))
6001 @result{}
6002 define(`min_int', incr(max_int))
6003 @result{}
6004 eval(min_int` < 0')
6005 @result{}1
6006 eval(max_int` > 0')
6007 @result{}1
6008 ifelse(eval(min_int` / -1'), min_int, `overflow occurred')
6009 @result{}overflow occurred
6010 min_int
6011 @result{}-2147483648
6012 eval(`0x80000000 % -1')
6013 @result{}0
6014 eval(`-4 >> 1')
6015 @result{}-2
6016 eval(`-4 >> 33')
6017 @result{}-2
6018 @end example
6020 If @var{radix} is specified, it specifies the radix to be used in the
6021 expansion.  The default radix is 10; this is also the case if
6022 @var{radix} is the empty string.  A warning results if the radix is
6023 outside the range of 1 through 36, inclusive.  The result of @code{eval}
6024 is always taken to be signed.  No radix prefix is output, and for
6025 radices greater than 10, the digits are lower case.  The @var{width}
6026 argument specifies the minimum output width, excluding any negative
6027 sign.  The result is zero-padded to extend the expansion to the
6028 requested width.  A warning results if the width is negative.  If
6029 @var{radix} or @var{width} is out of bounds, the expansion of
6030 @code{eval} is empty.
6032 @example
6033 eval(`666', `10')
6034 @result{}666
6035 eval(`666', `11')
6036 @result{}556
6037 eval(`666', `6')
6038 @result{}3030
6039 eval(`666', `6', `10')
6040 @result{}0000003030
6041 eval(`-666', `6', `10')
6042 @result{}-0000003030
6043 eval(`10', `', `0')
6044 @result{}10
6045 `0r1:'eval(`10', `1', `11')
6046 @result{}0r1:01111111111
6047 eval(`10', `16')
6048 @result{}a
6049 eval(`1', `37')
6050 @error{}m4:stdin:9: Warning: eval: radix 37 out of range
6051 @result{}
6052 eval(`1', , `-1')
6053 @error{}m4:stdin:10: Warning: eval: negative width
6054 @result{}
6055 eval()
6056 @error{}m4:stdin:11: Warning: eval: empty string treated as 0
6057 @result{}0
6058 @end example
6060 @node Shell commands
6061 @chapter Macros for running shell commands
6063 @cindex UNIX commands, running
6064 @cindex executing shell commands
6065 @cindex running shell commands
6066 @cindex shell commands, running
6067 @cindex commands, running shell
6068 There are a few builtin macros in @code{m4} that allow you to run shell
6069 commands from within @code{m4}.
6071 Note that the definition of a valid shell command is system dependent.
6072 On UNIX systems, this is the typical @command{/bin/sh}.  But on other
6073 systems, such as native Windows, the shell has a different syntax of
6074 commands that it understands.  Some examples in this chapter assume
6075 @command{/bin/sh}, and also demonstrate how to quit early with a known
6076 exit value if this is not the case.
6078 @menu
6079 * Platform macros::             Determining the platform
6080 * Syscmd::                      Executing simple commands
6081 * Esyscmd::                     Reading the output of commands
6082 * Sysval::                      Exit status
6083 * Mkstemp::                     Making temporary files
6084 @end menu
6086 @node Platform macros
6087 @section Determining the platform
6089 @cindex platform macros
6090 Sometimes it is desirable for an input file to know which platform
6091 @code{m4} is running on.  @acronym{GNU} @code{m4} provides several
6092 macros that are predefined to expand to the empty string; checking for
6093 their existence will confirm platform details.
6095 @deffn {Optional builtin} __gnu__
6096 @deffnx {Optional builtin} __os2__
6097 @deffnx {Optional builtin} os2
6098 @deffnx {Optional builtin} __unix__
6099 @deffnx {Optional builtin} unix
6100 @deffnx {Optional builtin} __windows__
6101 @deffnx {Optional builtin} windows
6102 Each of these macros is conditionally defined as needed to describe the
6103 environment of @code{m4}.  If defined, each macro expands to the empty
6104 string.  For now, these macros silently ignore all arguments, but in a
6105 future release of M4, they might warn if arguments are present.
6106 @end deffn
6108 When @acronym{GNU} extensions are in effect (that is, when you did not
6109 use the @option{-G} option, @pxref{Limits control, , Invoking m4}),
6110 @acronym{GNU} @code{m4} will define the macro @code{@w{__gnu__}} to
6111 expand to the empty string.
6113 @example
6114 $ @kbd{m4}
6115 __gnu__
6116 @result{}
6117 __gnu__(`ignored')
6118 @result{}
6119 Extensions are ifdef(`__gnu__', `active', `inactive')
6120 @result{}Extensions are active
6121 @end example
6123 @comment options: -G
6124 @example
6125 $ @kbd{m4 -G}
6126 __gnu__
6127 @result{}__gnu__
6128 __gnu__(`ignored')
6129 @result{}__gnu__(ignored)
6130 Extensions are ifdef(`__gnu__', `active', `inactive')
6131 @result{}Extensions are inactive
6132 @end example
6134 On UNIX systems, @acronym{GNU} @code{m4} will define @code{@w{__unix__}}
6135 by default, or @code{unix} when the @option{-G} option is specified.
6137 On native Windows systems, @acronym{GNU} @code{m4} will define
6138 @code{@w{__windows__}} by default, or @code{windows} when the
6139 @option{-G} option is specified.
6141 On OS/2 systems, @acronym{GNU} @code{m4} will define @code{@w{__os2__}}
6142 by default, or @code{os2} when the @option{-G} option is specified.
6144 If @acronym{GNU} @code{m4} does not provide a platform macro for your system,
6145 please report that as a bug.
6147 @example
6148 define(`provided', `0')
6149 @result{}
6150 ifdef(`__unix__', `define(`provided', incr(provided))')
6151 @result{}
6152 ifdef(`__windows__', `define(`provided', incr(provided))')
6153 @result{}
6154 ifdef(`__os2__', `define(`provided', incr(provided))')
6155 @result{}
6156 provided
6157 @result{}1
6158 @end example
6160 @node Syscmd
6161 @section Executing simple commands
6163 Any shell command can be executed, using @code{syscmd}:
6165 @deffn Builtin syscmd (@var{shell-command})
6166 Executes @var{shell-command} as a shell command.
6168 The expansion of @code{syscmd} is void, @emph{not} the output from
6169 @var{shell-command}!  Output or error messages from @var{shell-command}
6170 are not read by @code{m4}.  @xref{Esyscmd}, if you need to process the
6171 command output.
6173 Prior to executing the command, @code{m4} flushes its buffers.
6174 The default standard input, output and error of @var{shell-command} are
6175 the same as those of @code{m4}.
6177 The macro @code{syscmd} is recognized only with parameters.
6178 @end deffn
6180 @example
6181 define(`foo', `FOO')
6182 @result{}
6183 syscmd(`echo foo')
6184 @result{}foo
6185 @result{}
6186 @end example
6188 Note how the expansion of @code{syscmd} keeps the trailing newline of
6189 the command, as well as using the newline that appeared after the macro.
6191 The following is an example of @var{shell-command} using the same
6192 standard input as @code{m4}:
6194 @comment ignore
6195 @example
6196 $ @kbd{echo "m4wrap(\`syscmd(\`cat')')" | m4}
6197 @result{}
6198 @end example
6200 @ignore
6201 @comment If the user types the example below with stdin being an
6202 @comment interactive terminal, then cat will hang waiting for additional
6203 @comment input after m4 has exited.  But the testsuite is using a pipe
6204 @comment for stdin.  Hence, we have two versions - the one we feed the
6205 @comment testsuite below, and the one we display to the user above that
6206 @comment more accurately shows what the testsuite is really doing but
6207 @comment which the testsuite cannot parse.
6209 @example
6210 m4wrap(`syscmd(`cat')')
6211 @result{}
6213 @end example
6214 @end ignore
6216 It tells @code{m4} to read all of its input before executing the wrapped
6217 text, then hand a valid (albeit emptied) pipe as standard input for the
6218 @code{cat} subcommand.  Therefore, you should be careful when using
6219 standard input (either by specifying no files, or by passing @samp{-} as
6220 a file name on the command line, @pxref{Command line files, , Invoking
6221 m4}), and also invoking subcommands via @code{syscmd} or @code{esyscmd}
6222 that consume data from standard input.  When standard input is a
6223 seekable file, the subprocess will pick up with the next character not
6224 yet processed by @code{m4}; when it is a pipe or other non-seekable
6225 file, there is no guarantee how much data will already be buffered by
6226 @code{m4} and thus unavailable to the child.
6228 @node Esyscmd
6229 @section Reading the output of commands
6231 @cindex @acronym{GNU} extensions
6232 If you want @code{m4} to read the output of a shell command, use
6233 @code{esyscmd}:
6235 @deffn Builtin esyscmd (@var{shell-command})
6236 Expands to the standard output of the shell command
6237 @var{shell-command}.
6239 Prior to executing the command, @code{m4} flushes its buffers.
6240 The default standard input and standard error of @var{shell-command} are
6241 the same as those of @code{m4}.  The error output of @var{shell-command}
6242 is not a part of the expansion: it will appear along with the error
6243 output of @code{m4}.
6245 The macro @code{esyscmd} is recognized only with parameters.
6246 @end deffn
6248 @example
6249 define(`foo', `FOO')
6250 @result{}
6251 esyscmd(`echo foo')
6252 @result{}FOO
6253 @result{}
6254 @end example
6256 Note how the expansion of @code{esyscmd} keeps the trailing newline of
6257 the command, as well as using the newline that appeared after the macro.
6259 Just as with @code{syscmd}, care must be exercised when sharing standard
6260 input between @code{m4} and the child process of @code{esyscmd}.
6262 @node Sysval
6263 @section Exit status
6265 @cindex UNIX commands, exit status from
6266 @cindex exit status from shell commands
6267 @cindex shell commands, exit status from
6268 @cindex commands, exit status from shell
6269 @cindex status of shell commands
6270 To see whether a shell command succeeded, use @code{sysval}:
6272 @deffn Builtin sysval
6273 Expands to the exit status of the last shell command run with
6274 @code{syscmd} or @code{esyscmd}.  Expands to 0 if no command has been
6275 run yet.
6276 @end deffn
6278 @example
6279 sysval
6280 @result{}0
6281 syscmd(`false')
6282 @result{}
6283 ifelse(sysval, `0', `zero', `non-zero')
6284 @result{}non-zero
6285 syscmd(`exit 2')
6286 @result{}
6287 sysval
6288 @result{}2
6289 syscmd(`true')
6290 @result{}
6291 sysval
6292 @result{}0
6293 esyscmd(`false')
6294 @result{}
6295 ifelse(sysval, `0', `zero', `non-zero')
6296 @result{}non-zero
6297 esyscmd(`exit 2')
6298 @result{}
6299 sysval
6300 @result{}2
6301 esyscmd(`true')
6302 @result{}
6303 sysval
6304 @result{}0
6305 @end example
6307 @code{sysval} results in 127 if there was a problem executing the
6308 command, for example, if the system-imposed argument length is exceeded,
6309 or if there were not enough resources to fork.  It is not possible to
6310 distinguish between failed execution and successful execution that had
6311 an exit status of 127.
6313 On UNIX platforms, where it is possible to detect when command execution
6314 is terminated by a signal, rather than a normal exit, the result is the
6315 signal number shifted left by eight bits.
6317 @comment This test has difficulties being portable, even on platforms
6318 @comment where syscmd invokes /bin/sh.  Kill is not portable with signal
6319 @comment names.  According to autoconf, the only portable signal numbers
6320 @comment are 1 (HUP), 2 (INT), 9 (KILL), 13 (PIPE) and 15 (TERM).  But
6321 @comment all shells handle SIGINT, and ksh handles HUP (as in, the shell
6322 @comment exits normally rather than letting the signal terminate it).
6323 @comment Also, TERM is flaky, as it can also kill the running m4 on
6324 @comment systems where /bin/sh does not create its own process group.
6325 @comment And PIPE is unreliable, since people tend to run with it
6326 @comment ignored, with m4 inheriting that choice.  That leaves KILL as
6327 @comment the only signal we can reliably test.
6328 @example
6329 dnl This test assumes kill is a shell builtin, and that signals are
6330 dnl recognizable.
6331 ifdef(`__unix__', ,
6332       `errprint(` skipping: syscmd does not have unix semantics
6333 ')m4exit(`77')')dnl
6334 syscmd(`kill -9 $$')
6335 @result{}
6336 sysval
6337 @result{}2304
6338 syscmd()
6339 @result{}
6340 sysval
6341 @result{}0
6342 esyscmd(`kill -9 $$')
6343 @result{}
6344 sysval
6345 @result{}2304
6346 @end example
6348 @node Mkstemp
6349 @section Making temporary files
6351 @cindex temporary file names
6352 @cindex files, names of temporary
6353 Commands specified to @code{syscmd} or @code{esyscmd} might need a
6354 temporary file, for output or for some other purpose.  There is a
6355 builtin macro, @code{mkstemp}, for making a temporary file:
6357 @deffn Builtin mkstemp (@var{template})
6358 @deffnx Builtin maketemp (@var{template})
6359 Expands to the quoted name of a new, empty file, made from the string
6360 @var{template}, which should end with the string @samp{XXXXXX}.  The six
6361 @samp{X} characters are then replaced with random characters matching
6362 the regular expression @samp{[a-zA-Z0-9._-]}, in order to make the file
6363 name unique.  If fewer than six @samp{X} characters are found at the end
6364 of @code{template}, the result will be longer than the template.  The
6365 created file will have access permissions as if by @kbd{chmod =rw,go=},
6366 meaning that the current umask of the @code{m4} process is taken into
6367 account, and at most only the current user can read and write the file.
6369 The traditional behavior, standardized by @acronym{POSIX}, is that
6370 @code{maketemp} merely replaces the trailing @samp{X} with the process
6371 id, without creating a file or quoting the expansion, and without
6372 ensuring that the resulting
6373 string is a unique file name.  In part, this means that using the same
6374 @var{template} twice in the same input file will result in the same
6375 expansion.  This behavior is a security hole, as it is very easy for
6376 another process to guess the name that will be generated, and thus
6377 interfere with a subsequent use of @code{syscmd} trying to manipulate
6378 that file name.  Hence, @acronym{POSIX} has recommended that all new
6379 implementations of @code{m4} provide the secure @code{mkstemp} builtin,
6380 and that users of @code{m4} check for its existence.
6382 The expansion is void and an error issued if a temporary file could
6383 not be created.
6385 The macros @code{mkstemp} and @code{maketemp} are recognized only with
6386 parameters.
6387 @end deffn
6389 If you try this next example, you will most likely get different output
6390 for the two file names, since the replacement characters are randomly
6391 chosen:
6393 @comment ignore
6394 @example
6395 $ @kbd{m4}
6396 define(`tmp', `oops')
6397 @result{}
6398 maketemp(`/tmp/fooXXXXXX')
6399 @result{}/tmp/fooa07346
6400 ifdef(`mkstemp', `define(`maketemp', defn(`mkstemp'))',
6401       `define(`mkstemp', defn(`maketemp'))dnl
6402 errprint(`warning: potentially insecure maketemp implementation
6403 ')')
6404 @result{}
6405 mkstemp(`doc')
6406 @result{}docQv83Uw
6407 @end example
6409 @cindex @acronym{GNU} extensions
6410 Unless you use the @option{--traditional} command line option (or
6411 @option{-G}, @pxref{Limits control, , Invoking m4}), the @acronym{GNU}
6412 version of @code{maketemp} is secure.  This means that using the same
6413 template to multiple calls will generate multiple files.  However, we
6414 recommend that you use the new @code{mkstemp} macro, introduced in
6415 @acronym{GNU} M4 1.4.8, which is secure even in traditional mode.  Also,
6416 as of M4 1.4.11, the secure implementation quotes the resulting file
6417 name, so that you are guaranteed to know what file was created even if
6418 the random file name happens to match an existing macro.  Notice that
6419 this example is careful to use @code{defn} to avoid unintended expansion
6420 of @samp{foo}.
6422 @example
6423 $ @kbd{m4}
6424 define(`foo', `errprint(`oops')')
6425 @result{}
6426 syscmd(`rm -f foo-??????')sysval
6427 @result{}0
6428 define(`file1', maketemp(`foo-XXXXXX'))dnl
6429 ifelse(esyscmd(`echo \` foo-?????? \''), ` foo-?????? ',
6430        `no file', `created')
6431 @result{}created
6432 define(`file2', maketemp(`foo-XX'))dnl
6433 define(`file3', mkstemp(`foo-XXXXXX'))dnl
6434 ifelse(len(defn(`file1')), len(defn(`file2')),
6435        `same length', `different')
6436 @result{}same length
6437 ifelse(defn(`file1'), defn(`file2'), `same', `different file')
6438 @result{}different file
6439 ifelse(defn(`file2'), defn(`file3'), `same', `different file')
6440 @result{}different file
6441 ifelse(defn(`file1'), defn(`file3'), `same', `different file')
6442 @result{}different file
6443 syscmd(`rm 'defn(`file1') defn(`file2') defn(`file3'))
6444 @result{}
6445 sysval
6446 @result{}0
6447 @end example
6449 @ignore
6450 @c Not worth documenting, but make sure we don't leave trailing NUL in
6451 @c the expansion.
6453 @example
6454 syscmd(`rm -f foo??????')sysval
6455 @result{}0
6456 len(mkstemp(`fooXXXXX'))
6457 @result{}9
6458 syscmd(`rm foo??????')sysval
6459 @result{}0
6460 @end example
6462 @c Likewise, and ensure that traditional mode leaves the result unquoted
6463 @c without creating a file.
6465 @comment options: -G
6466 @example
6467 syscmd(`rm -f foo-*')sysval
6468 @result{}0
6469 len(maketemp(`foo-XXXXX'))
6470 @error{}m4:stdin:2: Warning: maketemp: recommend using mkstemp instead
6471 @result{}9
6472 define(`abc', `def')
6473 @result{}
6474 maketemp(`foo-abc')
6475 @result{}foo-def
6476 @error{}m4:stdin:4: Warning: maketemp: recommend using mkstemp instead
6477 syscmd(`test -f foo-*')sysval
6478 @result{}1
6479 @end example
6480 @end ignore
6482 @node Miscellaneous
6483 @chapter Miscellaneous builtin macros
6485 This chapter describes various builtins, that do not really belong in
6486 any of the previous chapters.
6488 @menu
6489 * Errprint::                    Printing error messages
6490 * Location::                    Printing current location
6491 * M4exit::                      Exiting from @code{m4}
6492 @end menu
6494 @node Errprint
6495 @section Printing error messages
6497 @cindex printing error messages
6498 @cindex error messages, printing
6499 @cindex messages, printing error
6500 @cindex standard error, output to
6501 You can print error messages using @code{errprint}:
6503 @deffn Builtin errprint (@var{message}, @dots{})
6504 Prints @var{message} and the rest of the arguments to standard error,
6505 separated by spaces.  Standard error is used, regardless of the
6506 @option{--debugfile} option (@pxref{Debugging options, , Invoking m4}).
6508 The expansion of @code{errprint} is void.
6509 The macro @code{errprint} is recognized only with parameters.
6510 @end deffn
6512 @example
6513 errprint(`Invalid arguments to forloop
6515 @error{}Invalid arguments to forloop
6516 @result{}
6517 errprint(`1')errprint(`2',`3
6519 @error{}12 3
6520 @result{}
6521 @end example
6523 A trailing newline is @emph{not} printed automatically, so it should be
6524 supplied as part of the argument, as in the example.  Unfortunately, the
6525 exact output of @code{errprint} is not very portable to other @code{m4}
6526 implementations: @acronym{POSIX} requires that all arguments be printed,
6527 but some implementations of @code{m4} only print the first.
6528 Furthermore, some @acronym{BSD} implementations always append a newline
6529 for each @code{errprint} call, regardless of whether the last argument
6530 already had one, and @acronym{POSIX} is silent on whether this is
6531 acceptable.
6533 @node Location
6534 @section Printing current location
6536 @cindex location, input
6537 @cindex input location
6538 To make it possible to specify the location of an error, three
6539 utility builtins exist:
6541 @deffn Builtin __file__
6542 @deffnx Builtin __line__
6543 @deffnx Builtin __program__
6544 Expand to the quoted name of the current input file, the
6545 current input line number in that file, and the quoted name of the
6546 current invocation of @code{m4}.
6547 @end deffn
6549 @example
6550 errprint(__program__:__file__:__line__: `input error
6552 @error{}m4:stdin:1: input error
6553 @result{}
6554 @end example
6556 Line numbers start at 1 for each file.  If the file was found due to the
6557 @option{-I} option or @env{M4PATH} environment variable, that is
6558 reflected in the file name.  The syncline option (@option{-s},
6559 @pxref{Preprocessor features, , Invoking m4}), and the
6560 @samp{f} and @samp{l} flags of @code{debugmode} (@pxref{Debug Levels}),
6561 also use this notion of current file and line.  Redefining the three
6562 location macros has no effect on syncline, debug, warning, or error
6563 message output.
6565 This example reuses the file @file{incl.m4} mentioned earlier
6566 (@pxref{Include}):
6568 @comment examples
6569 @example
6570 $ @kbd{m4 -I examples}
6571 define(`foo', ``$0' called at __file__:__line__')
6572 @result{}
6574 @result{}foo called at stdin:2
6575 include(`incl.m4')
6576 @result{}Include file start
6577 @result{}foo called at ../examples/incl.m4:2
6578 @result{}Include file end
6579 @result{}
6580 @end example
6582 The location of macros invoked during the rescanning of macro expansion
6583 text corresponds to the location in the file where the expansion was
6584 triggered, regardless of how many newline characters the expansion text
6585 contains.  As of @acronym{GNU} M4 1.4.8, the location of text wrapped
6586 with @code{m4wrap} (@pxref{M4wrap}) is the point at which the
6587 @code{m4wrap} was invoked.  Previous versions, however, behaved as
6588 though wrapped text came from line 0 of the file ``''.
6590 @example
6591 define(`echo', `$@@')
6592 @result{}
6593 define(`foo', `echo(__line__
6594 __line__)')
6595 @result{}
6596 echo(__line__
6597 __line__)
6598 @result{}4
6599 @result{}5
6600 m4wrap(`foo
6602 @result{}
6603 foo(errprint(__line__
6604 __line__
6606 @error{}8
6607 @error{}9
6608 @result{}8
6609 @result{}8
6610 __line__
6611 @result{}11
6612 m4wrap(`__line__
6614 @result{}
6616 @result{}12
6617 @result{}6
6618 @result{}6
6619 @end example
6621 The @code{@w{__program__}} macro behaves like @samp{$0} in shell
6622 terminology.  If you invoke @code{m4} through an absolute path or a link
6623 with a different spelling, rather than by relying on a @env{PATH} search
6624 for plain @samp{m4}, it will affect how @code{@w{__program__}} expands.
6625 The intent is that you can use it to produce error messages with the
6626 same formatting that @code{m4} produces internally.  It can also be used
6627 within @code{syscmd} (@pxref{Syscmd}) to pick the same version of
6628 @code{m4} that is currently running, rather than whatever version of
6629 @code{m4} happens to be first in @env{PATH}.  It was first introduced in
6630 @acronym{GNU} M4 1.4.6.
6632 @node M4exit
6633 @section Exiting from @code{m4}
6635 @cindex exiting from @code{m4}
6636 @cindex status, setting @code{m4} exit
6637 If you need to exit from @code{m4} before the entire input has been
6638 read, you can use @code{m4exit}:
6640 @deffn Builtin m4exit (@dvar{code, 0})
6641 Causes @code{m4} to exit, with exit status @var{code}.  If @var{code} is
6642 left out, the exit status is zero.  If @var{code} cannot be parsed, or
6643 is outside the range of 0 to 255, the exit status is one.  No further
6644 input is read, and all wrapped and diverted text is discarded.
6645 @end deffn
6647 @example
6648 m4wrap(`This text is lost due to `m4exit'.')
6649 @result{}
6650 divert(`1') So is this.
6651 divert
6652 @result{}
6653 m4exit And this is never read.
6654 @end example
6656 A common use of this is to abort processing:
6658 @deffn Composite fatal_error (@var{message})
6659 Abort processing with an error message and non-zero status.  Prefix
6660 @var{message} with details about where the error occurred, and print the
6661 resulting string to standard error.
6662 @end deffn
6664 @comment status: 1
6665 @example
6666 define(`fatal_error',
6667        `errprint(__program__:__file__:__line__`: fatal error: $*
6668 ')m4exit(`1')')
6669 @result{}
6670 fatal_error(`this is a BAD one, buster')
6671 @error{}m4:stdin:4: fatal error: this is a BAD one, buster
6672 @end example
6674 After this macro call, @code{m4} will exit with exit status 1.  This macro
6675 is only intended for error exits, since the normal exit procedures are
6676 not followed, i.e., diverted text is not undiverted, and saved text
6677 (@pxref{M4wrap}) is not reread.  (This macro could be made more robust
6678 to earlier versions of @code{m4}.  You should try to see if you can find
6679 weaknesses and correct them; or @pxref{Improved fatal_error, , Answers}).
6681 Note that it is still possible for the exit status to be different than
6682 what was requested by @code{m4exit}.  If @code{m4} detects some other
6683 error, such as a write error on standard output, the exit status will be
6684 non-zero even if @code{m4exit} requested zero.
6686 If standard input is seekable, then the file will be positioned at the
6687 next unread character.  If it is a pipe or other non-seekable file,
6688 then there are no guarantees how much data @code{m4} might have read
6689 into buffers, and thus discarded.
6691 @node Frozen files
6692 @chapter Fast loading of frozen state
6694 Some bigger @code{m4} applications may be built over a common base
6695 containing hundreds of definitions and other costly initializations.
6696 Usually, the common base is kept in one or more declarative files,
6697 which files are listed on each @code{m4} invocation prior to the
6698 user's input file, or else each input file uses @code{include}.
6700 Reading the common base of a big application, over and over again, may
6701 be time consuming.  @acronym{GNU} @code{m4} offers some machinery to
6702 speed up the start of an application using lengthy common bases.
6704 @menu
6705 * Using frozen files::          Using frozen files
6706 * Frozen file format::          Frozen file format
6707 @end menu
6709 @node Using frozen files
6710 @section Using frozen files
6712 @cindex fast loading of frozen files
6713 @cindex frozen files for fast loading
6714 @cindex initialization, frozen state
6715 @cindex dumping into frozen file
6716 @cindex reloading a frozen file
6717 @cindex @acronym{GNU} extensions
6718 Suppose a user has a library of @code{m4} initializations in
6719 @file{base.m4}, which is then used with multiple input files:
6721 @comment ignore
6722 @example
6723 $ @kbd{m4 base.m4 input1.m4}
6724 $ @kbd{m4 base.m4 input2.m4}
6725 $ @kbd{m4 base.m4 input3.m4}
6726 @end example
6728 Rather than spending time parsing the fixed contents of @file{base.m4}
6729 every time, the user might rather execute:
6731 @comment ignore
6732 @example
6733 $ @kbd{m4 -F base.m4f base.m4}
6734 @end example
6736 @noindent
6737 once, and further execute, as often as needed:
6739 @comment ignore
6740 @example
6741 $ @kbd{m4 -R base.m4f input1.m4}
6742 $ @kbd{m4 -R base.m4f input2.m4}
6743 $ @kbd{m4 -R base.m4f input3.m4}
6744 @end example
6746 @noindent
6747 with the varying input.  The first call, containing the @option{-F}
6748 option, only reads and executes file @file{base.m4}, defining
6749 various application macros and computing other initializations.
6750 Once the input file @file{base.m4} has been completely processed, @acronym{GNU}
6751 @code{m4} produces in @file{base.m4f} a @dfn{frozen} file, that is, a
6752 file which contains a kind of snapshot of the @code{m4} internal state.
6754 Later calls, containing the @option{-R} option, are able to reload
6755 the internal state of @code{m4}, from @file{base.m4f},
6756 @emph{prior} to reading any other input files.  This means
6757 instead of starting with a virgin copy of @code{m4}, input will be
6758 read after having effectively recovered the effect of a prior run.
6759 In our example, the effect is the same as if file @file{base.m4} has
6760 been read anew.  However, this effect is achieved a lot faster.
6762 Only one frozen file may be created or read in any one @code{m4}
6763 invocation.  It is not possible to recover two frozen files at once.
6764 However, frozen files may be updated incrementally, through using
6765 @option{-R} and @option{-F} options simultaneously.  For example, if
6766 some care is taken, the command:
6768 @comment ignore
6769 @example
6770 $ @kbd{m4 file1.m4 file2.m4 file3.m4 file4.m4}
6771 @end example
6773 @noindent
6774 could be broken down in the following sequence, accumulating the same
6775 output:
6777 @comment ignore
6778 @example
6779 $ @kbd{m4 -F file1.m4f file1.m4}
6780 $ @kbd{m4 -R file1.m4f -F file2.m4f file2.m4}
6781 $ @kbd{m4 -R file2.m4f -F file3.m4f file3.m4}
6782 $ @kbd{m4 -R file3.m4f file4.m4}
6783 @end example
6785 Some care is necessary because not every effort has been made for
6786 this to work in all cases.  In particular, the trace attribute of
6787 macros is not handled, nor the current setting of @code{changeword}.
6788 Currently, @code{m4wrap} and @code{sysval} also have problems.
6789 Also, interactions for some options of @code{m4}, being used in one call
6790 and not in the next, have not been fully analyzed yet.  On the other
6791 end, you may be confident that stacks of @code{pushdef} definitions
6792 are handled correctly, as well as undefined or renamed builtins, and
6793 changed strings for quotes or comments.  And future releases of
6794 @acronym{GNU} M4 will improve on the utility of frozen files.
6796 @ignore
6797 @c This example is not worth putting in the manual, but caused core
6798 @c dumps in all versions prior to 1.4.11.
6800 @comment options: -F /dev/null
6801 @example
6802 ifdef(`__unix__', ,
6803       `errprint(` skipping: /dev/null not known to exist
6804 ')m4exit(`77')')dnl
6805 traceon(`undefined')dnl
6806 @end example
6807 @end ignore
6809 When an @code{m4} run is to be frozen, the automatic undiversion
6810 which takes place at end of execution is inhibited.  Instead, all
6811 positively numbered diversions are saved into the frozen file.
6812 The active diversion number is also transmitted.
6814 A frozen file to be reloaded need not reside in the current directory.
6815 It is looked up the same way as an @code{include} file (@pxref{Search
6816 Path}).
6818 If the frozen file was generated with a newer version of @code{m4}, and
6819 contains directives that an older @code{m4} cannot parse, attempting to
6820 load the frozen file with option @option{-R} will cause @code{m4} to
6821 exit with status 63 to indicate version mismatch.
6823 @node Frozen file format
6824 @section Frozen file format
6826 @cindex frozen file format
6827 @cindex file format, frozen file
6828 Frozen files are sharable across architectures.  It is safe to write
6829 a frozen file on one machine and read it on another, given that the
6830 second machine uses the same or newer version of @acronym{GNU} @code{m4}.
6831 It is conventional, but not required, to give a frozen file the suffix
6832 of @code{.m4f}.
6834 These are simple (editable) text files, made up of directives,
6835 each starting with a capital letter and ending with a newline
6836 (@key{NL}).  Wherever a directive is expected, the character
6837 @samp{#} introduces a comment line; empty lines are also ignored if they
6838 are not part of an embedded string.
6839 In the following descriptions, each @var{len} refers to the length of
6840 the corresponding strings @var{str} in the next line of input.  Numbers
6841 are always expressed in decimal.  There are no escape characters.  The
6842 directives are:
6844 @table @code
6845 @item C @var{len1} , @var{len2} @key{NL} @var{str1} @var{str2} @key{NL}
6846 Uses @var{str1} and @var{str2} as the begin-comment and
6847 end-comment strings.  If omitted, then @samp{#} and @key{NL} are the
6848 comment delimiters.
6850 @item D @var{number}, @var{len} @key{NL} @var{str} @key{NL}
6851 Selects diversion @var{number}, making it current, then copy
6852 @var{str} in the current diversion.  @var{number} may be a negative
6853 number for a non-existing diversion.  To merely specify an active
6854 selection, use this command with an empty @var{str}.  With 0 as the
6855 diversion @var{number}, @var{str} will be issued on standard output
6856 at reload time.  @acronym{GNU} @code{m4} will not produce the @samp{D}
6857 directive with non-zero length for diversion 0, but this can be done
6858 with manual edits.  This directive may
6859 appear more than once for the same diversion, in which case the
6860 diversion is the concatenation of the various uses.  If omitted, then
6861 diversion 0 is current.
6863 @item F @var{len1} , @var{len2} @key{NL} @var{str1} @var{str2} @key{NL}
6864 Defines, through @code{pushdef}, a definition for @var{str1}
6865 expanding to the function whose builtin name is @var{str2}.  If the
6866 builtin does not exist (for example, if the frozen file was produced by
6867 a copy of @code{m4} compiled with changeword support, but the version
6868 of @code{m4} reloading was compiled without it), the reload is silent,
6869 but any subsequent use of the definition of @var{str1} will result in
6870 a warning.  This directive may appear more than once for the same name,
6871 and its order, along with @samp{T}, is important.  If omitted, you will
6872 have no access to any builtins.
6874 @item Q @var{len1} , @var{len2} @key{NL} @var{str1} @var{str2} @key{NL}
6875 Uses @var{str1} and @var{str2} as the begin-quote and end-quote
6876 strings.  If omitted, then @samp{`} and @samp{'} are the quote
6877 delimiters.
6879 @item T @var{len1} , @var{len2} @key{NL} @var{str1} @var{str2} @key{NL}
6880 Defines, though @code{pushdef}, a definition for @var{str1}
6881 expanding to the text given by @var{str2}.  This directive may appear
6882 more than once for the same name, and its order, along with @samp{F}, is
6883 important.
6885 @item V @var{number} @key{NL}
6886 Confirms the format of the file.  @code{m4} @value{VERSION} only creates
6887 and understands frozen files where @var{number} is 1.  This directive
6888 must be the first non-comment in the file, and may not appear more than
6889 once.
6890 @end table
6892 @node Compatibility
6893 @chapter Compatibility with other versions of @code{m4}
6895 @cindex compatibility
6896 This chapter describes the many of the differences between this
6897 implementation of @code{m4}, and of other implementations found under
6898 UNIX, such as System V Release 3, Solaris, and @acronym{BSD} flavors.
6899 In particular, it lists the known differences and extensions to
6900 @acronym{POSIX}.  However, the list is not necessarily comprehensive.
6902 At the time of this writing, @acronym{POSIX} 2001 (also known as IEEE
6903 Std 1003.1-2001) is the latest standard, although a new version of
6904 @acronym{POSIX} is under development and includes several proposals for
6905 modifying what @code{m4} is required to do.  The requirements for
6906 @code{m4} are shared between @acronym{SUSv3} and @acronym{POSIX}, and
6907 can be viewed at
6908 @uref{http://www.opengroup.org/onlinepubs/@/000095399/@/utilities/@/m4.html}.
6910 @menu
6911 * Extensions::                  Extensions in @acronym{GNU} M4
6912 * Incompatibilities::           Facilities in System V m4 not in GNU M4
6913 * Other Incompatibilities::     Other incompatibilities
6914 @end menu
6916 @node Extensions
6917 @section Extensions in @acronym{GNU} M4
6919 @cindex @acronym{GNU} extensions
6920 @cindex @acronym{POSIX}
6921 This version of @code{m4} contains a few facilities that do not exist
6922 in System V @code{m4}.  These extra facilities are all suppressed by
6923 using the @option{-G} command line option (@pxref{Limits control, ,
6924 Invoking m4}), unless overridden by other command line options.
6926 @itemize @bullet
6927 @item
6928 In the @code{$@var{n}} notation for macro arguments, @var{n} can contain
6929 several digits, while the System V @code{m4} only accepts one digit.
6930 This allows macros in @acronym{GNU} @code{m4} to take any number of
6931 arguments, and not only nine (@pxref{Arguments}).
6933 This means that @code{define(`foo', `$11')} is ambiguous between
6934 implementations.  To portably choose between grabbing the first
6935 parameter and appending 1 to the expansion, or grabbing the eleventh
6936 parameter, you can do the following:
6938 @example
6939 define(`a1', `A1')
6940 @result{}
6941 dnl First argument, concatenated with 1
6942 define(`_1', `$1')define(`first1', `_1($@@)1')
6943 @result{}
6944 dnl Eleventh argument, portable
6945 define(`_9', `$9')define(`eleventh', `_9(shift(shift($@@)))')
6946 @result{}
6947 dnl Eleventh argument, GNU style
6948 define(`Eleventh', `$11')
6949 @result{}
6950 first1(`a', `b', `c', `d', `e', `f', `g', `h', `i', `j', `k')
6951 @result{}A1
6952 eleventh(`a', `b', `c', `d', `e', `f', `g', `h', `i', `j', `k')
6953 @result{}k
6954 Eleventh(`a', `b', `c', `d', `e', `f', `g', `h', `i', `j', `k')
6955 @result{}k
6956 @end example
6958 @noindent
6959 Also see the @code{argn} macro (@pxref{Shift}).
6961 @item
6962 The @code{divert} (@pxref{Divert}) macro can manage more than 9
6963 diversions.  @acronym{GNU} @code{m4} treats all positive numbers as valid
6964 diversions, rather than discarding diversions greater than 9.
6966 @item
6967 Files included with @code{include} and @code{sinclude} are sought in a
6968 user specified search path, if they are not found in the working
6969 directory.  The search path is specified by the @option{-I} option and the
6970 @env{M4PATH} environment variable (@pxref{Search Path}).
6972 @item
6973 Arguments to @code{undivert} can be non-numeric, in which case the named
6974 file will be included uninterpreted in the output (@pxref{Undivert}).
6976 @item
6977 Formatted output is supported through the @code{format} builtin, which
6978 is modeled after the C library function @code{printf} (@pxref{Format}).
6980 @item
6981 Searches and text substitution through basic regular expressions are
6982 supported by the @code{regexp} (@pxref{Regexp}) and @code{patsubst}
6983 (@pxref{Patsubst}) builtins.  Some @acronym{BSD} implementations use
6984 extended regular expressions instead.
6986 @item
6987 The output of shell commands can be read into @code{m4} with
6988 @code{esyscmd} (@pxref{Esyscmd}).
6990 @item
6991 There is indirect access to any builtin macro with @code{builtin}
6992 (@pxref{Builtin}).
6994 @item
6995 Macros can be called indirectly through @code{indir} (@pxref{Indir}).
6997 @item
6998 The name of the program, the current input file, and the current input
6999 line number are accessible through the builtins @code{@w{__program__}},
7000 @code{@w{__file__}}, and @code{@w{__line__}} (@pxref{Location}).
7002 @item
7003 The format of the output from @code{dumpdef} and macro tracing can be
7004 controlled with @code{debugmode} (@pxref{Debug Levels}).
7006 @item
7007 The destination of trace and debug output can be controlled with
7008 @code{debugfile} (@pxref{Debug Output}).
7010 @item
7011 The @code{maketemp} (@pxref{Mkstemp}) macro behaves like @code{mkstemp},
7012 creating a new file with a unique name on every invocation, rather than
7013 following the insecure behavior of replacing the trailing @samp{X}
7014 characters with the @code{m4} process id.
7016 @item
7017 @acronym{POSIX} only requires support for the command line options
7018 @option{-s}, @option{-D}, and @option{-U}, so all other options accepted
7019 by @acronym{GNU} M4 are extensions.  @xref{Invoking m4}, for a
7020 description of these options.
7022 The debugging and tracing facilities in @acronym{GNU} @code{m4} are much
7023 more extensive than in most other versions of @code{m4}.
7024 @end itemize
7026 @node Incompatibilities
7027 @section Facilities in System V @code{m4} not in @acronym{GNU} @code{m4}
7029 The version of @code{m4} from System V contains a few facilities that
7030 have not been implemented in @acronym{GNU} @code{m4} yet.  Additionally,
7031 @acronym{POSIX} requires some behaviors that @acronym{GNU} @code{m4} has not
7032 implemented yet.  Relying on these behaviors is non-portable, as a
7033 future release of @acronym{GNU} @code{m4} may change.
7035 @itemize @bullet
7036 @item
7037 @acronym{POSIX} requires support for multiple arguments to @code{defn},
7038 without any clarification on how @code{defn} behaves when one of the
7039 multiple arguments names a builtin.  System V @code{m4} and some other
7040 implementations allow mixing builtins and text macros into a single
7041 macro.  @acronym{GNU} @code{m4} only supports joining multiple text
7042 arguments, although a future implementation may lift this restriction to
7043 behave more like System V@.  The only portable way to join text macros
7044 with builtins is via helper macros and implicit concatenation of macro
7045 results.
7047 @item
7048 @acronym{POSIX} requires an application to exit with non-zero status if
7049 it wrote an error message to stderr.  This has not yet been consistently
7050 implemented for the various builtins that are required to issue an error
7051 (such as @code{eval} (@pxref{Eval}) when an argument cannot be parsed).
7053 @item
7054 Some traditional implementations only allow reading standard input
7055 once, but @acronym{GNU} @code{m4} correctly handles multiple instances
7056 of @samp{-} on the command line.
7058 @item
7059 @acronym{POSIX} requires @code{m4wrap} (@pxref{M4wrap}) to act in FIFO
7060 (first-in, first-out) order, but @acronym{GNU} @code{m4} currently uses
7061 LIFO order.  Furthermore, @acronym{POSIX} states that only the first
7062 argument to @code{m4wrap} is saved for later evaluation, but
7063 @acronym{GNU} @code{m4} saves and processes all arguments, with output
7064 separated by spaces.
7066 @item
7067 @acronym{POSIX} states that builtins that require arguments, but are
7068 called without arguments, have undefined behavior.  Traditional
7069 implementations simply behave as though empty strings had been passed.
7070 For example, @code{a`'define`'b} would expand to @code{ab}.  But
7071 @acronym{GNU} @code{m4} ignores certain builtins if they have missing
7072 arguments, giving @code{adefineb} for the above example.
7074 @item
7075 Traditional implementations handle @code{define(`f',`1')} (@pxref{Define})
7076 by undefining the entire stack of previous definitions, and if doing
7077 @code{undefine(`f')} first.  @acronym{GNU} @code{m4} replaces just the top
7078 definition on the stack, as if doing @code{popdef(`f')} followed by
7079 @code{pushdef(`f',`1')}.  @acronym{POSIX} allows either behavior.
7081 @item
7082 @acronym{POSIX} 2001 requires @code{syscmd} (@pxref{Syscmd}) to evaluate
7083 command output for macro expansion, but this was a mistake that is
7084 anticipated to be corrected in the next version of @acronym{POSIX}.
7085 @acronym{GNU} @code{m4} follows traditional behavior in @code{syscmd}
7086 where output is not rescanned, and provides the extension @code{esyscmd}
7087 that does scan the output.
7089 @item
7090 At one point, @acronym{POSIX} required @code{changequote(@var{arg})}
7091 (@pxref{Changequote}) to use newline as the close quote, but this was a
7092 bug, and the next version of @acronym{POSIX} is anticipated to state
7093 that using empty strings or just one argument is unspecified.
7094 Meanwhile, the @acronym{GNU} @code{m4} behavior of treating an empty
7095 end-quote delimiter as @samp{'} is not portable, as Solaris treats it as
7096 repeating the start-quote delimiter, and BSD treats it as leaving the
7097 previous end-quote delimiter unchanged.  For predictable results, never
7098 call changequote with just one argument, or with empty strings for
7099 arguments.
7101 @item
7102 At one point, @acronym{POSIX} required @code{changecom(@var{arg},)}
7103 (@pxref{Changecom}) to make it impossible to end a comment, but this is
7104 a bug, and the next version of @acronym{POSIX} is anticipated to state
7105 that using empty strings is unspecified.  Meanwhile, the @acronym{GNU}
7106 @code{m4} behavior of treating an empty end-comment delimiter as newline
7107 is not portable, as BSD treats it as leaving the previous end-comment
7108 delimiter unchanged.  It is also impossible in BSD implementations to
7109 disable comments, even though that is required by @acronym{POSIX}.  For
7110 predictable results, never call changecom with empty strings for
7111 arguments.
7113 @item
7114 Most implementations of @code{m4} give macros a higher precedence than
7115 comments when parsing, meaning that if the start delimiter given to
7116 @code{changecom} (@pxref{Changecom}) starts with a macro name, comments
7117 are effectively disabled.  @acronym{POSIX} does not specify what the
7118 precedence is, so this version of @acronym{GNU} @code{m4} parser
7119 recognizes comments, then macros, then quoted strings.
7121 @item
7122 Traditional implementations allow argument collection, but not string
7123 and comment processing, to span file boundaries.  Thus, if @file{a.m4}
7124 contains @samp{len(}, and @file{b.m4} contains @samp{abc)},
7125 @kbd{m4 a.m4 b.m4} outputs @samp{3} with traditional @code{m4}, but
7126 gives an error message that the end of file was encountered inside a
7127 macro with @acronym{GNU} @code{m4}.  On the other hand, traditional
7128 implementations do end of file processing for files included with
7129 @code{include} or @code{sinclude} (@pxref{Include}), while @acronym{GNU}
7130 @code{m4} seamlessly integrates the content of those files.  Thus
7131 @code{include(`a.m4')include(`b.m4')} will output @samp{3} instead of
7132 giving an error.
7134 @item
7135 Traditional @code{m4} treats @code{traceon} (@pxref{Trace}) without
7136 arguments as a global variable, independent of named macro tracing.
7137 Also, once a macro is undefined, named tracing of that macro is lost.
7138 On the other hand, when @acronym{GNU} @code{m4} encounters
7139 @code{traceon} without
7140 arguments, it turns tracing on for all existing definitions at the time,
7141 but does not trace future definitions; @code{traceoff} without arguments
7142 turns tracing off for all definitions regardless of whether they were
7143 also traced by name; and tracing by name, such as with @option{-tfoo} at
7144 the command line or @code{traceon(`foo')} in the input, is an attribute
7145 that is preserved even if the macro is currently undefined.
7147 @item
7148 @acronym{POSIX} requires @code{eval} (@pxref{Eval}) to treat all
7149 operators with the same precedence as C@.  However, earlier versions of
7150 @acronym{GNU} @code{m4} followed the traditional behavior of other
7151 @code{m4} implementations, where bitwise and logical negation (@samp{~}
7152 and @samp{!}) have lower precedence than equality operators; and where
7153 equality operators (@samp{==} and @samp{!=}) had the same precedence as
7154 relational operators (such as @samp{<}).  Use explicit parentheses to
7155 ensure proper precedence.  As extensions to @acronym{POSIX},
7156 @acronym{GNU} @code{m4} gives well-defined semantics to operations that
7157 C leaves undefined, such as when overflow occurs, when shifting negative
7158 numbers, or when performing division by zero.  @acronym{POSIX} also
7159 requires @samp{=} to cause an error, but many traditional
7160 implementations allowed it as an alias for @samp{==}.
7162 @item
7163 @acronym{POSIX} 2001 requires @code{translit} (@pxref{Translit}) to
7164 treat each character of the second and third arguments literally.
7165 However, it is anticipated that the next version of @acronym{POSIX} will
7166 allow the @acronym{GNU} @code{m4} behavior of treating @samp{-} as a
7167 range operator.
7169 @item
7170 @acronym{POSIX} requires @code{m4} to honor the locale environment
7171 variables of @env{LANG}, @env{LC_ALL}, @env{LC_CTYPE},
7172 @env{LC_MESSAGES}, and @env{NLSPATH}, but this has not yet been
7173 implemented in @acronym{GNU} @code{m4}.
7175 @item
7176 @acronym{POSIX} states that only unquoted leading newlines and blanks
7177 (that is, space and tab) are ignored when collecting macro arguments.
7178 However, this appears to be a bug in @acronym{POSIX}, since most
7179 traditional implementations also ignore all whitespace (formfeed,
7180 carriage return, and vertical tab).  @acronym{GNU} @code{m4} follows
7181 tradition and ignores all leading unquoted whitespace.
7182 @end itemize
7184 @node Other Incompatibilities
7185 @section Other incompatibilities
7187 There are a few other incompatibilities between this implementation of
7188 @code{m4}, and the System V version.
7190 @itemize @bullet
7191 @item
7192 @acronym{GNU} @code{m4} implements sync lines differently from System V
7193 @code{m4}, when text is being diverted.  @acronym{GNU} @code{m4} outputs
7194 the sync lines when the text is being diverted, and System V @code{m4}
7195 when the diverted text is being brought back.
7197 The problem is which lines and file names should be attached to text
7198 that is being, or has been, diverted.  System V @code{m4} regards all
7199 the diverted text as being generated by the source line containing the
7200 @code{undivert} call, whereas @acronym{GNU} @code{m4} regards the
7201 diverted text as being generated at the time it is diverted.
7203 The sync line option is used mostly when using @code{m4} as
7204 a front end to a compiler.  If a diverted line causes a compiler error,
7205 the error messages should most probably refer to the place where the
7206 diversion was made, and not where it was inserted again.
7208 @comment options: -s
7209 @example
7210 divert(2)2
7211 divert(1)1
7212 divert`'0
7213 @result{}#line 3 "stdin"
7214 @result{}0
7216 @result{}#line 2 "stdin"
7217 @result{}1
7218 @result{}#line 1 "stdin"
7219 @result{}2
7220 @end example
7222 The current @code{m4} implementation has a limitation that the syncline
7223 output at the start of each diversion occurs no matter what, even if the
7224 previous diversion did not end with a newline.  This goes contrary to
7225 the claim that synclines appear on a line by themselves, so this
7226 limitation may be corrected in a future version of @code{m4}.  In the
7227 meantime, when using @option{-s}, it is wisest to make sure all
7228 diversions end with newline.
7230 @item
7231 @acronym{GNU} @code{m4} makes no attempt at prohibiting self-referential
7232 definitions like:
7234 @example
7235 define(`x', `x')
7236 @result{}
7237 define(`x', `x ')
7238 @result{}
7239 @end example
7241 @cindex rescanning
7242 There is nothing inherently wrong with defining @samp{x} to
7243 return @samp{x}.  The wrong thing is to expand @samp{x} unquoted,
7244 because that would cause an infinite rescan loop.
7245 In @code{m4}, one might use macros to hold strings, as we do for
7246 variables in other programming languages, further checking them with:
7248 @comment ignore
7249 @example
7250 ifelse(defn(`@var{holder}'), `@var{value}', @dots{})
7251 @end example
7253 @noindent
7254 In cases like this one, an interdiction for a macro to hold its own name
7255 would be a useless limitation.  Of course, this leaves more rope for the
7256 @acronym{GNU} @code{m4} user to hang himself!  Rescanning hangs may be
7257 avoided through careful programming, a little like for endless loops in
7258 traditional programming languages.
7259 @end itemize
7261 @node Answers
7262 @chapter Correct version of some examples
7264 Some of the examples in this manuals are buggy or not very robust, for
7265 demonstration purposes.  Improved versions of these composite macros are
7266 presented here.
7268 @menu
7269 * Improved exch::               Solution for @code{exch}
7270 * Improved forloop::            Solution for @code{forloop}
7271 * Improved foreach::            Solution for @code{foreach}
7272 * Improved m4wrap::             Solution for @code{m4wrap}
7273 * Improved cleardivert::        Solution for @code{cleardivert}
7274 * Improved capitalize::         Solution for @code{capitalize}
7275 * Improved fatal_error::        Solution for @code{fatal_error}
7276 @end menu
7278 @node Improved exch
7279 @section Solution for @code{exch}
7281 The @code{exch} macro (@pxref{Arguments}) as presented requires clients
7282 to double quote their arguments.  A nicer definition, which lets
7283 clients follow the rule of thumb of one level of quoting per level of
7284 parentheses, involves adding quotes in the definition of @code{exch}, as
7285 follows:
7287 @example
7288 define(`exch', ``$2', `$1'')
7289 @result{}
7290 define(exch(`expansion text', `macro'))
7291 @result{}
7292 macro
7293 @result{}expansion text
7294 @end example
7296 @node Improved forloop
7297 @section Solution for @code{forloop}
7299 The @code{forloop} macro (@pxref{Forloop}) as presented earlier can go
7300 into an infinite loop if given an iterator that is not parsed as a macro
7301 name.  It does not do any sanity checking on its numeric bounds, and
7302 only permits decimal numbers for bounds.  Here is an improved version,
7303 shipped as @file{m4-@value{VERSION}/@/examples/@/forloop2.m4}; this
7304 version also optimizes based on the fact that the starting bound does
7305 not need to be passed to the helper @code{@w{_forloop}}.
7307 @comment examples
7308 @example
7309 $ @kbd{m4 -I examples}
7310 undivert(`forloop2.m4')dnl
7311 @result{}divert(`-1')
7312 @result{}# forloop(var, from, to, stmt) - improved version:
7313 @result{}#   works even if VAR is not a strict macro name
7314 @result{}#   performs sanity check that FROM is larger than TO
7315 @result{}#   allows complex numerical expressions in TO and FROM
7316 @result{}define(`forloop', `ifelse(eval(`($3) >= ($2)'), `1',
7317 @result{}  `pushdef(`$1', eval(`$2'))_$0(`$1',
7318 @result{}    eval(`$3'), `$4')popdef(`$1')')')
7319 @result{}define(`_forloop',
7320 @result{}  `$3`'ifelse(indir(`$1'), `$2', `',
7321 @result{}    `define(`$1', incr(indir(`$1')))$0($@@)')')
7322 @result{}divert`'dnl
7323 include(`forloop2.m4')
7324 @result{}
7325 forloop(`i', `2', `1', `no iteration occurs')
7326 @result{}
7327 forloop(`', `1', `2', ` odd iterator name')
7328 @result{} odd iterator name odd iterator name
7329 forloop(`i', `5 + 5', `0xc', ` 0x`'eval(i, `16')')
7330 @result{} 0xa 0xb 0xc
7331 forloop(`i', `a', `b', `non-numeric bounds')
7332 @error{}m4:stdin:6: Warning: eval: bad expression (bad input): (b) >= (a)
7333 @result{}
7334 @end example
7336 One other change to notice is that the improved version used @samp{_$0}
7337 rather than @samp{_foreach} to invoke the helper routine.  In general,
7338 this is a good practice to follow, because then the set of macros can be
7339 uniformly transformed.  The following example shows a transformation
7340 that doubles the current quoting and appends a suffix @samp{2} to each
7341 transformed macro.  If @code{foreach} refers to the literal
7342 @samp{_foreach}, then @code{foreach2} invokes @code{_foreach} instead of
7343 the intended @code{_foreach2}, and the mixing of quoting paradigms leads
7344 to an infinite recursion loop in this example.
7346 @comment options: -L9
7347 @comment status: 1
7348 @comment examples
7349 @example
7350 $ @kbd{m4 -d -L 9 -I examples}
7351 define(`arg1', `$1')include(`forloop2.m4')include(`quote.m4')
7352 @result{}
7353 define(`double', `define(`$1'`2',
7354   arg1(patsubst(dquote(defn(`$1')), `[`']', `\&\&')))')
7355 @result{}
7356 double(`forloop')double(`_forloop')defn(`forloop2')
7357 @result{}ifelse(eval(``($3) >= ($2)''), ``1'',
7358 @result{}  ``pushdef(``$1'', eval(``$2''))_$0(``$1'',
7359 @result{}    eval(``$3''), ``$4'')popdef(``$1'')'')
7360 forloop(i, 1, 5, `ifelse(')forloop(i, 1, 5, `)')
7361 @result{}
7362 changequote(`[', `]')changequote([``], [''])
7363 @result{}
7364 forloop2(i, 1, 5, ``ifelse('')forloop2(i, 1, 5, ``)'')
7365 @result{}
7366 changequote`'include(`forloop.m4')
7367 @result{}
7368 double(`forloop')double(`_forloop')defn(`forloop2')
7369 @result{}pushdef(``$1'', ``$2'')_forloop($@@)popdef(``$1'')
7370 forloop(i, 1, 5, `ifelse(')forloop(i, 1, 5, `)')
7371 @result{}
7372 changequote(`[', `]')changequote([``], [''])
7373 @result{}
7374 forloop2(i, 1, 5, ``ifelse('')forloop2(i, 1, 5, ``)'')
7375 @error{}m4:stdin:12: recursion limit of 9 exceeded, use -L<N> to change it
7376 @end example
7378 Of course, it is possible to make even more improvements, such as
7379 adding an optional step argument, or allowing iteration through
7380 descending sequences.  @acronym{GNU} Autoconf provides some of these
7381 additional bells and whistles in its @code{m4_for} macro.
7383 @node Improved foreach
7384 @section Solution for @code{foreach}
7386 The @code{foreach} and @code{foreachq} macros (@pxref{Foreach}) as
7387 presented earlier each have flaws.  First, we will examine and fix the
7388 quadratic behavior of @code{foreachq}:
7390 @comment examples
7391 @example
7392 $ @kbd{m4 -I examples}
7393 include(`foreachq.m4')
7394 @result{}
7395 traceon(`shift')debugmode(`aq')
7396 @result{}
7397 foreachq(`x', ``1', `2', `3', `4'', `x
7398 ')dnl
7399 @result{}1
7400 @error{}m4trace: -3- shift(`1', `2', `3', `4')
7401 @error{}m4trace: -2- shift(`1', `2', `3', `4')
7402 @result{}2
7403 @error{}m4trace: -4- shift(`1', `2', `3', `4')
7404 @error{}m4trace: -3- shift(`2', `3', `4')
7405 @error{}m4trace: -3- shift(`1', `2', `3', `4')
7406 @error{}m4trace: -2- shift(`2', `3', `4')
7407 @result{}3
7408 @error{}m4trace: -5- shift(`1', `2', `3', `4')
7409 @error{}m4trace: -4- shift(`2', `3', `4')
7410 @error{}m4trace: -3- shift(`3', `4')
7411 @error{}m4trace: -4- shift(`1', `2', `3', `4')
7412 @error{}m4trace: -3- shift(`2', `3', `4')
7413 @error{}m4trace: -2- shift(`3', `4')
7414 @result{}4
7415 @error{}m4trace: -6- shift(`1', `2', `3', `4')
7416 @error{}m4trace: -5- shift(`2', `3', `4')
7417 @error{}m4trace: -4- shift(`3', `4')
7418 @error{}m4trace: -3- shift(`4')
7419 @end example
7421 @cindex quadratic behavior, avoiding
7422 @cindex avoiding quadratic behavior
7423 Each successive iteration was adding more quoted @code{shift}
7424 invocations, and the entire list contents were passing through every
7425 iteration.  In general, when recursing, it is a good idea to make the
7426 recursion use fewer arguments, rather than adding additional quoted
7427 uses of @code{shift}.  By doing so, @code{m4} uses less memory, invokes
7428 fewer macros, is less likely to run into machine limits, and most
7429 importantly, performs faster.  The fixed version of @code{foreachq} can
7430 be found in @file{m4-@value{VERSION}/@/examples/@/foreachq2.m4}:
7432 @comment examples
7433 @example
7434 $ @kbd{m4 -I examples}
7435 include(`foreachq2.m4')
7436 @result{}
7437 undivert(`foreachq2.m4')dnl
7438 @result{}include(`quote.m4')dnl
7439 @result{}divert(`-1')
7440 @result{}# foreachq(x, `item_1, item_2, ..., item_n', stmt)
7441 @result{}#   quoted list, improved version
7442 @result{}define(`foreachq', `pushdef(`$1')_$0($@@)popdef(`$1')')
7443 @result{}define(`_arg1q', ``$1'')
7444 @result{}define(`_rest', `ifelse(`$#', `1', `', `dquote(shift($@@))')')
7445 @result{}define(`_foreachq', `ifelse(`$2', `', `',
7446 @result{}  `define(`$1', _arg1q($2))$3`'$0(`$1', _rest($2), `$3')')')
7447 @result{}divert`'dnl
7448 traceon(`shift')debugmode(`aq')
7449 @result{}
7450 foreachq(`x', ``1', `2', `3', `4'', `x
7451 ')dnl
7452 @result{}1
7453 @error{}m4trace: -3- shift(`1', `2', `3', `4')
7454 @result{}2
7455 @error{}m4trace: -3- shift(`2', `3', `4')
7456 @result{}3
7457 @error{}m4trace: -3- shift(`3', `4')
7458 @result{}4
7459 @end example
7461 Note that the fixed version calls unquoted helper macros in
7462 @code{@w{_foreachq}} to trim elements immediately; those helper macros
7463 in turn must re-supply the layer of quotes lost in the macro invocation.
7464 Contrast the use of @code{@w{_arg1q}}, which quotes the first list
7465 element, with @code{@w{_arg1}} of the earlier implementation that
7466 returned the first list element directly.  Additionally, by calling the
7467 helper method immediately, the @samp{defn(`@var{iterator}')} no longer
7468 contains unexpanded macros.
7470 The astute m4 programmer might notice that the solution above still uses
7471 more macro invocations than strictly necessary.  Note that @samp{$2},
7472 which contains an arbitrarily long quoted list, is expanded and
7473 rescanned three times per iteration of @code{_foreachq}.  Furthermore,
7474 every iteration of the algorithm effectively unboxes then reboxes the
7475 list, which costs a couple of macro invocations.  It is possible to
7476 rewrite the algorithm by swapping the order of the arguments to
7477 @code{_foreachq} in order to operate on an unboxed list in the first
7478 place, and by using the fixed-length @samp{$#} instead of an arbitrary
7479 length list as the key to end recursion.  The result is eight macro
7480 invocations per loop, instead of nine.  This alternative approach is
7481 available as @file{m4-@value{VERSION}/@/examples/@/foreach3.m4}:
7483 @comment examples
7484 @example
7485 $ @kbd{m4 -I examples}
7486 include(`foreachq3.m4')
7487 @result{}
7488 undivert(`foreachq3.m4')dnl
7489 @result{}divert(`-1')
7490 @result{}# foreachq(x, `item_1, item_2, ..., item_n', stmt)
7491 @result{}#   quoted list, alternate improved version
7492 @result{}define(`foreachq',
7493 @result{}`pushdef(`$1')_$0(`$1', `$3'ifelse(`$2', `', `',
7494 @result{}  `, $2'))popdef(`$1')')
7495 @result{}define(`_foreachq', `ifelse(`$#', `2', `',
7496 @result{}  `define(`$1', `$3')$2`'$0(`$1', `$2'ifelse(`$#', `3', `',
7497 @result{}    `, shift(shift(shift($@@)))'))')')
7498 @result{}divert`'dnl
7499 traceon(`shift')debugmode(`aq')
7500 @result{}
7501 foreachq(`x', ``1', `2', `3', `4'', `x
7502 ')dnl
7503 @result{}1
7504 @error{}m4trace: -4- shift(`x', `x
7505 @error{}', `1', `2', `3', `4')
7506 @error{}m4trace: -3- shift(`x
7507 @error{}', `1', `2', `3', `4')
7508 @error{}m4trace: -2- shift(`1', `2', `3', `4')
7509 @result{}2
7510 @error{}m4trace: -4- shift(`x', `x
7511 @error{}', `2', `3', `4')
7512 @error{}m4trace: -3- shift(`x
7513 @error{}', `2', `3', `4')
7514 @error{}m4trace: -2- shift(`2', `3', `4')
7515 @result{}3
7516 @error{}m4trace: -4- shift(`x', `x
7517 @error{}', `3', `4')
7518 @error{}m4trace: -3- shift(`x
7519 @error{}', `3', `4')
7520 @error{}m4trace: -2- shift(`3', `4')
7521 @result{}4
7522 @end example
7524 Prior to M4 1.4.11, every instance of @samp{$@@} was rescanned as it was
7525 encountered.  Thus, the @file{foreachq3.m4} alternative used much less
7526 memory than @file{foreachq2.m4}, and executed as much as 10% faster,
7527 since each iteration encountered fewer @samp{$@@}.  However, the
7528 implementation of rescanning every byte in @samp{$@@} was quadratic in
7529 the number of bytes scanned (for example, making the broken version in
7530 @file{foreachq.m4} cubic, rather than quadratic, in behavior).  Once the
7531 underlying M4 implementation was improved in 1.4.11 to reuse results of
7532 previous scans, both styles of @code{foreachq} become linear in the
7533 number of bytes scanned, and the difference in timing is no longer
7534 noticeable; in fact, after the change, the @file{foreachq2.m4} version
7535 uses slightly less memory since it tracks fewer arguments per macro
7536 invocation.
7538 For yet another approach, the improved version of @code{foreach},
7539 available in @file{m4-@value{VERSION}/@/examples/@/foreach2.m4}, simply
7540 overquotes the arguments to @code{@w{_foreach}} to begin with, using
7541 @code{dquote_elt}.  Then @code{@w{_foreach}} can just use
7542 @code{@w{_arg1}} to remove the extra layer of quoting that was added up
7543 front:
7545 @comment examples
7546 @example
7547 $ @kbd{m4 -I examples}
7548 include(`foreach2.m4')
7549 @result{}
7550 undivert(`foreach2.m4')dnl
7551 @result{}include(`quote.m4')dnl
7552 @result{}divert(`-1')
7553 @result{}# foreach(x, (item_1, item_2, ..., item_n), stmt)
7554 @result{}#   parenthesized list, improved version
7555 @result{}define(`foreach', `pushdef(`$1')_$0(`$1',
7556 @result{}  (dquote(dquote_elt$2)), `$3')popdef(`$1')')
7557 @result{}define(`_arg1', `$1')
7558 @result{}define(`_foreach', `ifelse(`$2', `(`')', `',
7559 @result{}  `define(`$1', _arg1$2)$3`'$0(`$1', (dquote(shift$2)), `$3')')')
7560 @result{}divert`'dnl
7561 traceon(`shift')debugmode(`aq')
7562 @result{}
7563 foreach(`x', `(`1', `2', `3', `4')', `x
7564 ')dnl
7565 @error{}m4trace: -4- shift(`1', `2', `3', `4')
7566 @error{}m4trace: -4- shift(`2', `3', `4')
7567 @error{}m4trace: -4- shift(`3', `4')
7568 @result{}1
7569 @error{}m4trace: -3- shift(``1'', ``2'', ``3'', ``4'')
7570 @result{}2
7571 @error{}m4trace: -3- shift(``2'', ``3'', ``4'')
7572 @result{}3
7573 @error{}m4trace: -3- shift(``3'', ``4'')
7574 @result{}4
7575 @error{}m4trace: -3- shift(``4'')
7576 @end example
7578 In summary, recursion over list elements is trickier than it appeared at
7579 first glance, but provides a powerful idiom within @code{m4} processing.
7580 As a final demonstration, both list styles are now able to handle
7581 several scenarios that would wreak havoc on one or both of the original
7582 implementations.  This points out one other difference between the
7583 list styles.  @code{foreach} evaluates unquoted list elements only once,
7584 in preparation for calling @code{@w{_foreach}}, similary for
7585 @code{foreachq} as provided by @file{foreachq3.m4}.  But
7586 @code{foreachq}, as provided by @file{foreachq2.m4},
7587 evaluates unquoted list elements twice while visiting the first list
7588 element, once in @code{@w{_arg1q}} and once in @code{@w{_rest}}.  When
7589 deciding which list style to use, one must take into account whether
7590 repeating the side effects of unquoted list elements will have any
7591 detrimental effects.
7593 @comment examples
7594 @example
7595 $ @kbd{m4 -d -I examples}
7596 include(`foreach2.m4')
7597 @result{}
7598 include(`foreachq2.m4')
7599 @result{}
7600 dnl 0-element list:
7601 foreach(`x', `', `<x>') / foreachq(`x', `', `<x>')
7602 @result{} /@w{ }
7603 dnl 1-element list of empty element
7604 foreach(`x', `()', `<x>') / foreachq(`x', ``'', `<x>')
7605 @result{}<> / <>
7606 dnl 2-element list of empty elements
7607 foreach(`x', `(`',`')', `<x>') / foreachq(`x', ``',`'', `<x>')
7608 @result{}<><> / <><>
7609 dnl 1-element list of a comma
7610 foreach(`x', `(`,')', `<x>') / foreachq(`x', ``,'', `<x>')
7611 @result{}<,> / <,>
7612 dnl 2-element list of unbalanced parentheses
7613 foreach(`x', `(`(', `)')', `<x>') / foreachq(`x', ``(', `)'', `<x>')
7614 @result{}<(><)> / <(><)>
7615 define(`ab', `oops')dnl using defn(`iterator')
7616 foreach(`x', `(`a', `b')', `defn(`x')') /dnl
7617  foreachq(`x', ``a', `b'', `defn(`x')')
7618 @result{}ab / ab
7619 define(`active', `ACT, IVE')
7620 @result{}
7621 traceon(`active')
7622 @result{}
7623 dnl list of unquoted macros; expansion occurs before recursion
7624 foreach(`x', `(active, active)', `<x>
7625 ')dnl
7626 @error{}m4trace: -4- active -> `ACT, IVE'
7627 @error{}m4trace: -4- active -> `ACT, IVE'
7628 @result{}<ACT>
7629 @result{}<IVE>
7630 @result{}<ACT>
7631 @result{}<IVE>
7632 foreachq(`x', `active, active', `<x>
7633 ')dnl
7634 @error{}m4trace: -3- active -> `ACT, IVE'
7635 @error{}m4trace: -3- active -> `ACT, IVE'
7636 @result{}<ACT>
7637 @error{}m4trace: -3- active -> `ACT, IVE'
7638 @error{}m4trace: -3- active -> `ACT, IVE'
7639 @result{}<IVE>
7640 @result{}<ACT>
7641 @result{}<IVE>
7642 dnl list of quoted macros; expansion occurs during recursion
7643 foreach(`x', `(`active', `active')', `<x>
7644 ')dnl
7645 @error{}m4trace: -1- active -> `ACT, IVE'
7646 @result{}<ACT, IVE>
7647 @error{}m4trace: -1- active -> `ACT, IVE'
7648 @result{}<ACT, IVE>
7649 foreachq(`x', ``active', `active'', `<x>
7650 ')dnl
7651 @error{}m4trace: -1- active -> `ACT, IVE'
7652 @result{}<ACT, IVE>
7653 @error{}m4trace: -1- active -> `ACT, IVE'
7654 @result{}<ACT, IVE>
7655 dnl list of double-quoted macro names; no expansion
7656 foreach(`x', `(``active'', ``active'')', `<x>
7657 ')dnl
7658 @result{}<active>
7659 @result{}<active>
7660 foreachq(`x', ```active'', ``active''', `<x>
7661 ')dnl
7662 @result{}<active>
7663 @result{}<active>
7664 @end example
7666 @ignore
7667 @comment Not worth putting in the manual, but make sure that performance
7668 @comment on recursive algorithms is not quadratic.
7670 @comment boxed recursion
7672 @comment examples
7673 @comment options: -Dlimit=10 -Dverbose
7674 @example
7675 $ @kbd {m4 -I examples -Dlimit=10 -Dverbose}
7676 include(`loop.m4')dnl
7677 @result{} 1 2 3 4 5 6 7 8 9 10
7678 @end example
7680 @comment examples
7681 @comment options: -Dlimit=2500
7682 @example
7683 $ @kbd {m4 -I examples -Dlimit=2500}
7684 include(`loop.m4')dnl
7685 @end example
7687 @comment examples
7688 @comment options: -Dlimit=10000
7689 @example
7690 $ @kbd {m4 -I examples -Dlimit=10000}
7691 define(`debug', `define(`popdef',`divert`'i')')
7692 @result{}
7693 include(`loop.m4')dnl
7694 @result{}10000
7695 @end example
7697 @comment unboxed recursion
7699 @comment examples
7700 @comment options: -Dlimit=10 -Dverbose -Dalt
7701 @example
7702 $ @kbd {m4 -I examples -Dlimit=10 -Dverbose -Dalt}
7703 include(`loop.m4')dnl
7704 @result{} 1 2 3 4 5 6 7 8 9 10
7705 @end example
7707 @comment examples
7708 @comment options: -Dlimit=2500 -Dalt
7709 @example
7710 $ @kbd {m4 -I examples -Dlimit=2500 -Dalt}
7711 include(`loop.m4')dnl
7712 @end example
7714 @comment examples
7715 @comment options: -Dlimit=10000 -Dalt
7716 @example
7717 $ @kbd {m4 -I examples -Dlimit=10000 -Dalt}
7718 define(`debug', `define(`popdef',`divert`'i')')
7719 @result{}
7720 include(`loop.m4')dnl
7721 @result{}10000
7722 @end example
7724 @end ignore
7726 @node Improved m4wrap
7727 @section Solution for @code{m4wrap}
7729 The replacement @code{m4wrap} versions presented above, designed to
7730 guarantee FIFO or LIFO order regardless of the underlying M4
7731 implementation, share a bug when dealing with wrapped text that looks
7732 like parameter expansion.  Note how the invocation of
7733 @code{m4wrap@var{n}} interprets these parameters, while using the
7734 builtin preserves them for their intended use.
7736 @comment examples
7737 @example
7738 $ @kbd{m4 -I examples}
7739 include(`wraplifo.m4')
7740 @result{}
7741 m4wrap(`define(`foo', ``$0:'-$1-$*-$#-')foo(`a', `b')
7743 @result{}
7744 builtin(`m4wrap', ``'define(`bar', ``$0:'-$1-$*-$#-')bar(`a', `b')
7746 @result{}
7748 @result{}bar:-a-a,b-2-
7749 @result{}m4wrap0:---0-
7750 @end example
7752 Additionally, the computation of @code{_m4wrap_level} and creation of
7753 multiple @code{m4wrap@var{n}} placeholders in the original examples is
7754 more expensive in time and memory than strictly necessary.  Notice how
7755 the improved version grabs the wrapped text via @code{defn} to avoid
7756 parameter expansion, then undefines @code{_m4wrap_text}, before
7757 stripping a level of quotes with @code{_arg1} to expand the text.  That
7758 way, each level of wrapping reuses the single placeholder, which starts
7759 each nesting level in an undefined state.
7761 Finally, it is worth emulating the @acronym{GNU} M4 extension of saving
7762 all arguments to @code{m4wrap}, separated by a space, rather than saving
7763 just the first argument.  This is done with the @code{join} macro
7764 documented previously (@pxref{Shift}).  The improved LIFO example is
7765 shipped as @file{m4-@value{VERSION}/@/examples/@/wraplifo2.m4}, and can
7766 easily be converted to a FIFO solution by swapping the adjacent
7767 invocations of @code{joinall} and @code{defn}.
7769 @comment examples
7770 @example
7771 $ @kbd{m4 -I examples}
7772 include(`wraplifo2.m4')
7773 @result{}
7774 undivert(`wraplifo2.m4')dnl
7775 @result{}dnl Redefine m4wrap to have LIFO semantics, improved example.
7776 @result{}include(`join.m4')dnl
7777 @result{}define(`_m4wrap', defn(`m4wrap'))dnl
7778 @result{}define(`_arg1', `$1')dnl
7779 @result{}define(`m4wrap',
7780 @result{}`ifdef(`_$0_text',
7781 @result{}       `define(`_$0_text', joinall(` ', $@@)defn(`_$0_text'))',
7782 @result{}       `_$0(`_arg1(defn(`_$0_text')undefine(`_$0_text'))')dnl
7783 @result{}define(`_$0_text', joinall(` ', $@@))')')dnl
7784 m4wrap(`define(`foo', ``$0:'-$1-$*-$#-')foo(`a', `b')
7786 @result{}
7787 m4wrap(`lifo text
7788 m4wrap(`nested', `', `$@@
7789 ')')
7790 @result{}
7792 @result{}lifo text
7793 @result{}foo:-a-a,b-2-
7794 @result{}nested  $@@
7795 @end example
7797 @node Improved cleardivert
7798 @section Solution for @code{cleardivert}
7800 The @code{cleardivert} macro (@pxref{Cleardivert}) cannot, as it stands, be
7801 called without arguments to clear all pending diversions.  That is
7802 because using undivert with an empty string for an argument is different
7803 than using it with no arguments at all.  Compare the earlier definition
7804 with one that takes the number of arguments into account:
7806 @example
7807 define(`cleardivert',
7808   `pushdef(`_n', divnum)divert(`-1')undivert($@@)divert(_n)popdef(`_n')')
7809 @result{}
7810 divert(`1')one
7811 divert
7812 @result{}
7813 cleardivert
7814 @result{}
7815 undivert
7816 @result{}one
7817 @result{}
7818 define(`cleardivert',
7819   `pushdef(`_num', divnum)divert(`-1')ifelse(`$#', `0',
7820     `undivert`'', `undivert($@@)')divert(_num)popdef(`_num')')
7821 @result{}
7822 divert(`2')two
7823 divert
7824 @result{}
7825 cleardivert
7826 @result{}
7827 undivert
7828 @result{}
7829 @end example
7831 @node Improved capitalize
7832 @section Solution for @code{capitalize}
7834 The @code{capitalize} macro (@pxref{Patsubst}) as presented earlier does
7835 not allow clients to follow the quoting rule of thumb.  Consider the
7836 three macros @code{active}, @code{Active}, and @code{ACTIVE}, and the
7837 difference between calling @code{capitalize} with the expansion of a
7838 macro, expanding the result of a case change, and changing the case of a
7839 double-quoted string:
7841 @comment examples
7842 @example
7843 $ @kbd{m4 -I examples}
7844 include(`capitalize.m4')dnl
7845 define(`active', `act1, ive')dnl
7846 define(`Active', `Act2, Ive')dnl
7847 define(`ACTIVE', `ACT3, IVE')dnl
7848 upcase(active)
7849 @result{}ACT1,IVE
7850 upcase(`active')
7851 @result{}ACT3, IVE
7852 upcase(``active'')
7853 @result{}ACTIVE
7854 downcase(ACTIVE)
7855 @result{}act3,ive
7856 downcase(`ACTIVE')
7857 @result{}act1, ive
7858 downcase(``ACTIVE'')
7859 @result{}active
7860 capitalize(active)
7861 @result{}Act1
7862 capitalize(`active')
7863 @result{}Active
7864 capitalize(``active'')
7865 @result{}_capitalize(`active')
7866 define(`A', `OOPS')
7867 @result{}
7868 capitalize(active)
7869 @result{}OOPSct1
7870 capitalize(`active')
7871 @result{}OOPSctive
7872 @end example
7874 First, when @code{capitalize} is called with more than one argument, it
7875 was throwing away later arguments, whereas @code{upcase} and
7876 @code{downcase} used @samp{$*} to collect them all.  The fix is simple:
7877 use @samp{$*} consistently.
7879 Next, with single-quoting, @code{capitalize} outputs a single character,
7880 a set of quotes, then the rest of the characters, making it impossible
7881 to invoke @code{Active} after the fact, and allowing the alternate macro
7882 @code{A} to interfere.  Here, the solution is to use additional quoting
7883 in the helper macros, then pass the final over-quoted output string
7884 through @code{_arg1} to remove the extra quoting and finally invoke the
7885 concatenated portions as a single string.
7887 Finally, when passed a double-quoted string, the nested macro
7888 @code{_capitalize} is never invoked because it ended up nested inside
7889 quotes.  This one is the toughest to fix.  In short, we have no idea how
7890 many levels of quotes are in effect on the substring being altered by
7891 @code{patsubst}.  If the replacement string cannot be expressed entirely
7892 in terms of literal text and backslash substitutions, then we need a
7893 mechanism to guarantee that the helper macros are invoked outside of
7894 quotes.  In other words, this sounds like a job for @code{changequote}
7895 (@pxref{Changequote}).  By changing the active quoting characters, we
7896 can guarantee that replacement text injected by @code{patsubst} always
7897 occurs in the middle of a string that has exactly one level of
7898 over-quoting using alternate quotes; so the replacement text closes the
7899 quoted string, invokes the helper macros, then reopens the quoted
7900 string.  In turn, that means the replacement text has unbalanced quotes,
7901 necessitating another round of @code{changequote}.
7903 In the fixed version below, (also shipped as
7904 @file{m4-@value{VERSION}/@/examples/@/capitalize.m4}), @code{capitalize}
7905 uses the alternate quotes of @samp{<<[} and @samp{]>>} (the longer
7906 strings are chosen so as to be less likely to appear in the text being
7907 converted).  The helpers @code{_to_alt} and @code{_from_alt} merely
7908 reduce the number of characters required to perform a
7909 @code{changequote}, since the definition changes twice.  The outermost
7910 pair means that @code{patsubst} and @code{_capitalize_alt} are invoked
7911 with alternate quoting; the innermost pair is used so that the third
7912 argument to @code{patsubst} can contain an unbalanced
7913 @samp{]>>}/@samp{<<[} pair.  Note that @code{upcase} and @code{downcase}
7914 must be redefined as @code{_upcase_alt} and @code{_downcase_alt}, since
7915 they contain nested quotes but are invoked with the alternate quoting
7916 scheme in effect.
7918 @comment examples
7919 @example
7920 $ @kbd{m4 -I examples}
7921 include(`capitalize2.m4')dnl
7922 define(`active', `act1, ive')dnl
7923 define(`Active', `Act2, Ive')dnl
7924 define(`ACTIVE', `ACT3, IVE')dnl
7925 define(`A', `OOPS')dnl
7926 capitalize(active; `active'; ``active''; ```actIVE''')
7927 @result{}Act1,Ive; Act2, Ive; Active; `Active'
7928 undivert(`capitalize2.m4')dnl
7929 @result{}divert(`-1')
7930 @result{}# upcase(text)
7931 @result{}# downcase(text)
7932 @result{}# capitalize(text)
7933 @result{}#   change case of text, improved version
7934 @result{}define(`upcase', `translit(`$*', `a-z', `A-Z')')
7935 @result{}define(`downcase', `translit(`$*', `A-Z', `a-z')')
7936 @result{}define(`_arg1', `$1')
7937 @result{}define(`_to_alt', `changequote(`<<[', `]>>')')
7938 @result{}define(`_from_alt', `changequote(<<[`]>>, <<[']>>)')
7939 @result{}define(`_upcase_alt', `translit(<<[$*]>>, <<[a-z]>>, <<[A-Z]>>)')
7940 @result{}define(`_downcase_alt', `translit(<<[$*]>>, <<[A-Z]>>, <<[a-z]>>)')
7941 @result{}define(`_capitalize_alt',
7942 @result{}  `regexp(<<[$1]>>, <<[^\(\w\)\(\w*\)]>>,
7943 @result{}    <<[_upcase_alt(<<[<<[\1]>>]>>)_downcase_alt(<<[<<[\2]>>]>>)]>>)')
7944 @result{}define(`capitalize',
7945 @result{}  `_arg1(_to_alt()patsubst(<<[<<[$*]>>]>>, <<[\w+]>>,
7946 @result{}    _from_alt()`]>>_$0_alt(<<[\&]>>)<<['_to_alt())_from_alt())')
7947 @result{}divert`'dnl
7948 @end example
7950 @node Improved fatal_error
7951 @section Solution for @code{fatal_error}
7953 The @code{fatal_error} macro (@pxref{M4exit}) is not robust to versions
7954 of @acronym{GNU} M4 earlier than 1.4.8, where invoking
7955 @code{@w{__file__}} (@pxref{Location}) inside @code{m4wrap} would result
7956 in an empty string, and @code{@w{__line__}} resulted in @samp{0} even
7957 though all files start at line 1.  Furthermore, versions earlier than
7958 1.4.6 did not support the @code{@w{__program__}} macro.  If you want
7959 @code{fatal_error} to work across the entire 1.4.x release series, a
7960 better implementation would be:
7962 @comment status: 1
7963 @example
7964 define(`fatal_error',
7965   `errprint(ifdef(`__program__', `__program__', ``m4'')'dnl
7966 `:ifelse(__line__, `0', `',
7967     `__file__:__line__:')` fatal error: $*
7968 ')m4exit(`1')')
7969 @result{}
7970 m4wrap(`divnum(`demo of internal message')
7971 fatal_error(`inside wrapped text')')
7972 @result{}
7974 @error{}m4:stdin:6: Warning: divnum: extra arguments ignored: 1 > 0
7975 @result{}0
7976 @error{}m4:stdin:6: fatal error: inside wrapped text
7977 @end example
7979 @c ========================================================== Appendices
7981 @node Copying This Package
7982 @appendix How to make copies of the overall M4 package
7983 @cindex License, code
7985 This appendix covers the license for copying the source code of the
7986 overall M4 package.  This manual is under a different set of
7987 restrictions, covered later (@pxref{Copying This Manual}).
7989 @menu
7990 * GNU General Public License::  License for copying the M4 package
7991 @end menu
7993 @node GNU General Public License
7994 @appendixsec License for copying the M4 package
7995 @cindex GPL, GNU General Public License
7996 @cindex GNU General Public License
7997 @cindex General Public License (GPL), GNU
7998 @include gpl-3.0.texi
8000 @node Copying This Manual
8001 @appendix How to make copies of this manual
8002 @cindex License, manual
8004 This appendix covers the license for copying this manual.  Note that
8005 some of the longer examples in this manual are also distributed in the
8006 directory @file{m4-@value{VERSION}/@/examples/}, where a more
8007 permissive license is in effect when copying just the examples.
8009 @menu
8010 * GNU Free Documentation License::  License for copying this manual
8011 @end menu
8013 @node GNU Free Documentation License
8014 @appendixsec License for copying this manual
8015 @cindex FDL, GNU Free Documentation License
8016 @cindex GNU Free Documentation License
8017 @cindex Free Documentation License (FDL), GNU
8018 @include fdl.texi
8020 @node Indices
8021 @appendix Indices of concepts and macros
8023 @menu
8024 * Macro index::                 Index for all @code{m4} macros
8025 * Concept index::               Index for many concepts
8026 @end menu
8028 @node Macro index
8029 @appendixsec Index for all @code{m4} macros
8031 This index covers all @code{m4} builtins, as well as several useful
8032 composite macros.  References are exclusively to the places where a
8033 macro is introduced the first time.
8035 @printindex fn
8037 @node Concept index
8038 @appendixsec Index for many concepts
8040 @printindex cp
8042 @bye
8044 @c Local Variables:
8045 @c coding: iso-8859-1
8046 @c fill-column: 72
8047 @c ispell-local-dictionary: "american"
8048 @c indent-tabs-mode: nil
8049 @c whitespace-check-buffer-indent: nil
8050 @c End: