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