Fix 'm4 -F file -t undefined'.
[m4/ericb.git] / doc / m4.texinfo
blob3bece3aeccdafad122676027cd0438a839daf02b
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{de}, exactly as if @code{m4}
1350 has been given @w{@samp{substr(`abcde', `3', `2')}} as input:
1352 @example
1353 define(`x', `substr(ab')
1354 @result{}
1355 define(`y', `cde, `3', `2')')
1356 @result{}
1357 x`'y
1358 @result{}de
1359 @end example
1361 Unquoted strings on either side of a quoted string are subject to
1362 being recognized as macro names.  In the following example, quoting the
1363 empty string allows for the second @code{macro} to be recognized as such:
1365 @example
1366 define(`macro', `m')
1367 @result{}
1368 macro(`m')macro
1369 @result{}mmacro
1370 macro(`m')`'macro
1371 @result{}mm
1372 @end example
1374 Quoting may prevent recognizing as a macro name the concatenation of a
1375 macro expansion with the surrounding characters.  In this example:
1377 @example
1378 define(`macro', `di$1')
1379 @result{}
1380 macro(`v')`ert'
1381 @result{}divert
1382 macro(`v')ert
1383 @result{}
1384 @end example
1386 @noindent
1387 the input will produce the string @samp{divert}.  When the quotes were
1388 removed, the @code{divert} builtin was called instead.
1390 @node Macro Arguments
1391 @section Macro arguments
1393 @cindex macros, arguments to
1394 @cindex arguments to macros
1395 When a name is seen, and it has a macro definition, it will be expanded
1396 as a macro.
1398 If the name is followed by an opening parenthesis, the arguments will be
1399 collected before the macro is called.  If too few arguments are
1400 supplied, the missing arguments are taken to be the empty string.
1401 However, some builtins are documented to behave differently for a
1402 missing optional argument than for an explicit empty string.  If there
1403 are too many arguments, the excess arguments are ignored.  Unquoted
1404 leading whitespace is stripped off all arguments, but whitespace
1405 generated by a macro expansion or occurring after a macro that expanded
1406 to an empty string remains intact.  Whitespace includes space, tab,
1407 newline, carriage return, vertical tab, and formfeed.
1409 @example
1410 define(`macro', `$1')
1411 @result{}
1412 macro( unquoted leading space lost)
1413 @result{}unquoted leading space lost
1414 macro(` quoted leading space kept')
1415 @result{} quoted leading space kept
1416 macro(
1417  divert `unquoted space kept after expansion')
1418 @result{} unquoted space kept after expansion
1419 macro(macro(`
1420 ')`whitespace from expansion kept')
1421 @result{}
1422 @result{}whitespace from expansion kept
1423 macro(`unquoted trailing whitespace kept'
1425 @result{}unquoted trailing whitespace kept
1426 @result{}
1427 @end example
1429 @cindex warnings, suppressing
1430 @cindex suppressing warnings
1431 Normally @code{m4} will issue warnings if a builtin macro is called
1432 with an inappropriate number of arguments, but it can be suppressed with
1433 the @option{--quiet} command line option (or @option{--silent}, or
1434 @option{-Q}, @pxref{Operation modes, , Invoking m4}).  For user
1435 defined macros, there is no check of the number of arguments given.
1437 @example
1438 $ @kbd{m4}
1439 index(`abc')
1440 @error{}m4:stdin:1: Warning: too few arguments to builtin `index'
1441 @result{}0
1442 index(`abc',)
1443 @result{}0
1444 index(`abc', `b', `ignored')
1445 @error{}m4:stdin:3: Warning: excess arguments to builtin `index' ignored
1446 @result{}1
1447 @end example
1449 @comment options: -Q
1450 @example
1451 $ @kbd{m4 -Q}
1452 index(`abc')
1453 @result{}0
1454 index(`abc',)
1455 @result{}0
1456 index(`abc', `b', `ignored')
1457 @result{}1
1458 @end example
1460 Macros are expanded normally during argument collection, and whatever
1461 commas, quotes and parentheses that might show up in the resulting
1462 expanded text will serve to define the arguments as well.  Thus, if
1463 @var{foo} expands to @samp{, b, c}, the macro call
1465 @comment ignore
1466 @example
1467 bar(a foo, d)
1468 @end example
1470 @noindent
1471 is a macro call with four arguments, which are @samp{a }, @samp{b},
1472 @samp{c} and @samp{d}.  To understand why the first argument contains
1473 whitespace, remember that unquoted leading whitespace is never part
1474 of an argument, but trailing whitespace always is.
1476 It is possible for a macro's definition to change during argument
1477 collection, in which case the expansion uses the definition that was in
1478 effect at the time the opening @samp{(} was seen.
1480 @example
1481 define(`f', `1')
1482 @result{}
1483 f(define(`f', `2'))
1484 @result{}1
1486 @result{}2
1487 @end example
1489 It is an error if the end of file occurs while collecting arguments.
1491 @comment status: 1
1492 @example
1493 hello world
1494 @result{}hello world
1495 define(
1497 @error{}m4:stdin:2: ERROR: end of file in argument list
1498 @end example
1500 @node Quoting Arguments
1501 @section On Quoting Arguments to macros
1503 @cindex quoted macro arguments
1504 @cindex macros, quoted arguments to
1505 @cindex arguments, quoted macro
1506 Each argument has unquoted leading whitespace removed.  Within each
1507 argument, all unquoted parentheses must match.  For example, if
1508 @var{foo} is a macro,
1510 @comment ignore
1511 @example
1512 foo(() (`(') `(')
1513 @end example
1515 @noindent
1516 is a macro call, with one argument, whose value is @samp{() (() (}.
1517 Commas separate arguments, except when they occur inside quotes,
1518 comments, or unquoted parentheses.  @xref{Pseudo Arguments}, for
1519 examples.
1521 It is common practice to quote all arguments to macros, unless you are
1522 sure you want the arguments expanded.  Thus, in the above
1523 example with the parentheses, the `right' way to do it is like this:
1525 @comment ignore
1526 @example
1527 foo(`() (() (')
1528 @end example
1530 @cindex quoting rule of thumb
1531 @cindex rule of thumb, quoting
1532 It is, however, in certain cases necessary (because nested expansion
1533 must occur to create the arguments for the outer macro) or convenient
1534 (because it uses fewer characters) to leave out quotes for some
1535 arguments, and there is nothing wrong in doing it.  It just makes life a
1536 bit harder, if you are not careful to follow a consistent quoting style.
1537 For consistency, this manual follows the rule of thumb that each layer
1538 of parentheses introduces another layer of single quoting, except when
1539 showing the consequences of quoting rules.  This is done even when the
1540 quoted string cannot be a macro, such as with integers when you have not
1541 changed the syntax via @code{changeword} (@pxref{Changeword}).
1543 The quoting rule of thumb of one level of quoting per parentheses has a
1544 nice property: when a macro name appears inside parentheses, you can
1545 determine when it will be expanded.  If it is not quoted, it will be
1546 expanded prior to the outer macro, so that its expansion becomes the
1547 argument.  If it is single-quoted, it will be expanded after the outer
1548 macro.  And if it is double-quoted, it will be used as literal text
1549 instead of a macro name.
1551 @example
1552 define(`active', `ACT, IVE')
1553 @result{}
1554 define(`show', `$1 $1')
1555 @result{}
1556 show(active)
1557 @result{}ACT ACT
1558 show(`active')
1559 @result{}ACT, IVE ACT, IVE
1560 show(``active'')
1561 @result{}active active
1562 @end example
1564 @node Macro expansion
1565 @section Macro expansion
1567 @cindex macros, expansion of
1568 @cindex expansion of macros
1569 When the arguments, if any, to a macro call have been collected, the
1570 macro is expanded, and the expansion text is pushed back onto the input
1571 (unquoted), and reread.  The expansion text from one macro call might
1572 therefore result in more macros being called, if the calls are included,
1573 completely or partially, in the first macro calls' expansion.
1575 Taking a very simple example, if @var{foo} expands to @samp{bar}, and
1576 @var{bar} expands to @samp{Hello}, the input
1578 @comment options: -Dbar=Hello -Dfoo=bar
1579 @example
1580 $ @kbd{m4 -Dbar=Hello -Dfoo=bar}
1582 @result{}Hello
1583 @end example
1585 @noindent
1586 will expand first to @samp{bar}, and when this is reread and
1587 expanded, into @samp{Hello}.
1589 @node Definitions
1590 @chapter How to define new macros
1592 @cindex macros, how to define new
1593 @cindex defining new macros
1594 Macros can be defined, redefined and deleted in several different ways.
1595 Also, it is possible to redefine a macro without losing a previous
1596 value, and bring back the original value at a later time.
1598 @menu
1599 * Define::                      Defining a new macro
1600 * Arguments::                   Arguments to macros
1601 * Pseudo Arguments::            Special arguments to macros
1602 * Undefine::                    Deleting a macro
1603 * Defn::                        Renaming macros
1604 * Pushdef::                     Temporarily redefining macros
1606 * Indir::                       Indirect call of macros
1607 * Builtin::                     Indirect call of builtins
1608 @end menu
1610 @node Define
1611 @section Defining a macro
1613 The normal way to define or redefine macros is to use the builtin
1614 @code{define}:
1616 @deffn Builtin define (@var{name}, @ovar{expansion})
1617 Defines @var{name} to expand to @var{expansion}.  If
1618 @var{expansion} is not given, it is taken to be empty.
1620 The expansion of @code{define} is void.
1621 The macro @code{define} is recognized only with parameters.
1622 @end deffn
1624 The following example defines the macro @var{foo} to expand to the text
1625 @samp{Hello World.}.
1627 @example
1628 define(`foo', `Hello world.')
1629 @result{}
1631 @result{}Hello world.
1632 @end example
1634 The empty line in the output is there because the newline is not
1635 a part of the macro definition, and it is consequently copied to
1636 the output.  This can be avoided by use of the macro @code{dnl}.
1637 @xref{Dnl}, for details.
1639 The first argument to @code{define} should be quoted; otherwise, if the
1640 macro is already defined, you will be defining a different macro.  This
1641 example shows the problems with underquoting, since we did not want to
1642 redefine @code{one}:
1644 @example
1645 define(foo, one)
1646 @result{}
1647 define(foo, two)
1648 @result{}
1650 @result{}two
1651 @end example
1653 @cindex @acronym{GNU} extensions
1654 @acronym{GNU} @code{m4} normally replaces only the @emph{topmost}
1655 definition of a macro if it has several definitions from @code{pushdef}
1656 (@pxref{Pushdef}).  Some other implementations of @code{m4} replace all
1657 definitions of a macro with @code{define}.  @xref{Incompatibilities},
1658 for more details.
1660 As a @acronym{GNU} extension, the first argument to @code{define} does
1661 not have to be a simple word.
1662 It can be any text string, even the empty string.  A macro with a
1663 non-standard name cannot be invoked in the normal way, as the name is
1664 not recognized.  It can only be referenced by the builtins @code{indir}
1665 (@pxref{Indir}) and @code{defn} (@pxref{Defn}).
1667 @cindex arrays
1668 Arrays and associative arrays can be simulated by using non-standard
1669 macro names.
1671 @deffn Composite array (@var{index})
1672 @deffnx Composite array_set (@var{index}, @ovar{value})
1673 Provide access to entries within an array.  @code{array} reads the entry
1674 at location @var{index}, and @code{array_set} assigns @var{value} to
1675 location @var{index}.
1676 @end deffn
1678 @example
1679 define(`array', `defn(format(``array[%d]'', `$1'))')
1680 @result{}
1681 define(`array_set', `define(format(``array[%d]'', `$1'), `$2')')
1682 @result{}
1683 array_set(`4', `array element no. 4')
1684 @result{}
1685 array_set(`17', `array element no. 17')
1686 @result{}
1687 array(`4')
1688 @result{}array element no. 4
1689 array(eval(`10 + 7'))
1690 @result{}array element no. 17
1691 @end example
1693 Change the @samp{%d} to @samp{%s} and it is an associative array.
1695 @node Arguments
1696 @section Arguments to macros
1698 @cindex macros, arguments to
1699 @cindex arguments to macros
1700 Macros can have arguments.  The @var{n}th argument is denoted by
1701 @code{$n} in the expansion text, and is replaced by the @var{n}th actual
1702 argument, when the macro is expanded.  Replacement of arguments happens
1703 before rescanning, regardless of how many nesting levels of quoting
1704 appear in the expansion.  Here is an example of a macro with
1705 two arguments.
1707 @deffn Composite exch (@var{arg1}, @var{arg2})
1708 Expands to @var{arg2} followed by @var{arg1}, effectively exchanging
1709 their order.
1710 @end deffn
1712 @example
1713 define(`exch', `$2, $1')
1714 @result{}
1715 exch(`arg1', `arg2')
1716 @result{}arg2, arg1
1717 @end example
1719 This can be used, for example, if you like the arguments to
1720 @code{define} to be reversed.
1722 @example
1723 define(`exch', `$2, $1')
1724 @result{}
1725 define(exch(``expansion text'', ``macro''))
1726 @result{}
1727 macro
1728 @result{}expansion text
1729 @end example
1731 @xref{Quoting Arguments}, for an explanation of the double quotes.
1732 (You should try and improve this example so that clients of @code{exch}
1733 do not have to double quote; or @pxref{Improved exch, , Answers}).
1735 As a special case, the zeroth argument, @code{$0}, is always the name
1736 of the macro being expanded.
1738 @example
1739 define(`test', ``Macro name: $0'')
1740 @result{}
1741 test
1742 @result{}Macro name: test
1743 @end example
1745 If you want quoted text to appear as part of the expansion text,
1746 remember that quotes can be nested in quoted strings.  Thus, in
1748 @example
1749 define(`foo', `This is macro `foo'.')
1750 @result{}
1752 @result{}This is macro foo.
1753 @end example
1755 @noindent
1756 The @samp{foo} in the expansion text is @emph{not} expanded, since it is
1757 a quoted string, and not a name.
1759 @cindex @acronym{GNU} extensions
1760 @cindex nine arguments, more than
1761 @cindex more than nine arguments
1762 @cindex arguments, more than nine
1763 @cindex positional parameters, more than nine
1764 @acronym{GNU} @code{m4} allows the number following the @samp{$} to
1765 consist of one or more digits, allowing macros to have any number of
1766 arguments.  The extension of accepting multiple digits is incompatible
1767 with @acronym{POSIX}, and is different than traditional implementations
1768 of @code{m4}, which only recognize one digit.  Therefore, future
1769 versions of @acronym{GNU} M4 will phase out this feature.  To portably
1770 access beyond the ninth argument, you can use the @code{argn} macro
1771 documented later (@pxref{Shift}).
1773 @acronym{POSIX} also states that @samp{$} followed immediately by
1774 @samp{@{} in a macro definition is implementation-defined.  This version
1775 of M4 passes the literal characters @samp{$@{} through unchanged, but M4
1776 2.0 will implement an optional feature similar to @command{sh}, where
1777 @samp{$@{11@}} expands to the eleventh argument, to replace the current
1778 recognition of @samp{$11}.  Meanwhile, if you want to guarantee that you
1779 will get a literal @samp{$@{} in output when expanding a macro, even
1780 when you upgrade to M4 2.0, you can use nested quoting to your
1781 advantage:
1783 @example
1784 define(`foo', `single quoted $`'@{1@} output')
1785 @result{}
1786 define(`bar', ``double quoted $'`@{2@} output'')
1787 @result{}
1788 foo(`a', `b')
1789 @result{}single quoted $@{1@} output
1790 bar(`a', `b')
1791 @result{}double quoted $@{2@} output
1792 @end example
1794 To help you detect places in your M4 input files that might change in
1795 behavior due to the changed behavior of M4 2.0, you can use the
1796 @option{--warn-macro-sequence} command-line option (@pxref{Operation
1797 modes, , Invoking m4}) with the default regular expression.  This will
1798 add a warning any time a macro definition includes @samp{$} followed by
1799 multiple digits, or by @samp{@{}.  The warning is not enabled by
1800 default, because it triggers a number of warnings in Autoconf 2.61 (and
1801 Autoconf uses @option{-E} to treat warnings as errors), and because it
1802 will still be possible to restore older behavior in M4 2.0.
1804 @comment ignore
1805 @example
1806 $ @kbd{m4 --warn-macro-sequence}
1807 define(`foo', `$001 $@{1@} $1')
1808 @error{}m4:stdin:1: Warning: definition of `foo' contains sequence `$001'
1809 @error{}m4:stdin:1: Warning: definition of `foo' contains sequence `$@{1@}'
1810 @result{}
1811 foo(`bar')
1812 @result{}bar $@{1@} bar
1813 @end example
1815 @node Pseudo Arguments
1816 @section Special arguments to macros
1818 @cindex special arguments to macros
1819 @cindex macros, special arguments to
1820 @cindex arguments to macros, special
1821 There is a special notation for the number of actual arguments supplied,
1822 and for all the actual arguments.
1824 The number of actual arguments in a macro call is denoted by @code{$#}
1825 in the expansion text.
1827 @deffn Composite nargs (@dots{})
1828 Expands to a count of the number of arguments supplied.
1829 @end deffn
1831 @example
1832 define(`nargs', `$#')
1833 @result{}
1834 nargs
1835 @result{}0
1836 nargs()
1837 @result{}1
1838 nargs(`arg1', `arg2', `arg3')
1839 @result{}3
1840 nargs(`commas can be quoted, like this')
1841 @result{}1
1842 nargs(arg1#inside comments, commas do not separate arguments
1843 still arg1)
1844 @result{}1
1845 nargs((unquoted parentheses, like this, group arguments))
1846 @result{}1
1847 @end example
1849 Remember that @samp{#} defaults to the comment character; if you forget
1850 quotes to inhibit the comment behavior, your macro definition may not
1851 end where you expected.
1853 @example
1854 dnl Attempt to define a macro to just `$#'
1855 define(underquoted, $#)
1856 oops)
1857 @result{}
1858 underquoted
1859 @result{}0)
1860 @result{}oops
1861 @end example
1863 The notation @code{$*} can be used in the expansion text to denote all
1864 the actual arguments, unquoted, with commas in between.  For example
1866 @example
1867 define(`echo', `$*')
1868 @result{}
1869 echo(arg1,    arg2, arg3 , arg4)
1870 @result{}arg1,arg2,arg3 ,arg4
1871 @end example
1873 Often each argument should be quoted, and the notation @code{$@@} handles
1874 that.  It is just like @code{$*}, except that it quotes each argument.
1875 A simple example of that is:
1877 @example
1878 define(`echo', `$@@')
1879 @result{}
1880 echo(arg1,    arg2, arg3 , arg4)
1881 @result{}arg1,arg2,arg3 ,arg4
1882 @end example
1884 Where did the quotes go?  Of course, they were eaten, when the expanded
1885 text were reread by @code{m4}.  To show the difference, try
1887 @example
1888 define(`echo1', `$*')
1889 @result{}
1890 define(`echo2', `$@@')
1891 @result{}
1892 define(`foo', `This is macro `foo'.')
1893 @result{}
1894 echo1(foo)
1895 @result{}This is macro This is macro foo..
1896 echo1(`foo')
1897 @result{}This is macro foo.
1898 echo2(foo)
1899 @result{}This is macro foo.
1900 echo2(`foo')
1901 @result{}foo
1902 @end example
1904 @noindent
1905 @xref{Trace}, if you do not understand this.  As another example of the
1906 difference, remember that comments encountered in arguments are passed
1907 untouched to the macro, and that quoting disables comments.
1909 @example
1910 define(`echo1', `$*')
1911 @result{}
1912 define(`echo2', `$@@')
1913 @result{}
1914 define(`foo', `bar')
1915 @result{}
1916 echo1(#foo'foo
1917 foo)
1918 @result{}#foo'foo
1919 @result{}bar
1920 echo2(#foo'foo
1921 foo)
1922 @result{}#foobar
1923 @result{}bar'
1924 @end example
1926 A @samp{$} sign in the expansion text, that is not followed by anything
1927 @code{m4} understands, is simply copied to the macro expansion, as any
1928 other text is.
1930 @example
1931 define(`foo', `$$$ hello $$$')
1932 @result{}
1934 @result{}$$$ hello $$$
1935 @end example
1937 @cindex rescanning
1938 @cindex literal output
1939 @cindex output, literal
1940 If you want a macro to expand to something like @samp{$12}, the
1941 judicious use of nested quoting can put a safe character between the
1942 @code{$} and the next character, relying on the rescanning to remove the
1943 nested quote.  This will prevent @code{m4} from interpreting the
1944 @code{$} sign as a reference to an argument.
1946 @example
1947 define(`foo', `no nested quote: $1')
1948 @result{}
1949 foo(`arg')
1950 @result{}no nested quote: arg
1951 define(`foo', `nested quote around $: `$'1')
1952 @result{}
1953 foo(`arg')
1954 @result{}nested quote around $: $1
1955 define(`foo', `nested empty quote after $: $`'1')
1956 @result{}
1957 foo(`arg')
1958 @result{}nested empty quote after $: $1
1959 define(`foo', `nested quote around next character: $`1'')
1960 @result{}
1961 foo(`arg')
1962 @result{}nested quote around next character: $1
1963 define(`foo', `nested quote around both: `$1'')
1964 @result{}
1965 foo(`arg')
1966 @result{}nested quote around both: arg
1967 @end example
1969 @node Undefine
1970 @section Deleting a macro
1972 @cindex macros, how to delete
1973 @cindex deleting macros
1974 @cindex undefining macros
1975 A macro definition can be removed with @code{undefine}:
1977 @deffn Builtin undefine (@var{name}@dots{})
1978 For each argument, remove the macro @var{name}.  The macro names must
1979 necessarily be quoted, since they will be expanded otherwise.
1981 The expansion of @code{undefine} is void.
1982 The macro @code{undefine} is recognized only with parameters.
1983 @end deffn
1985 @example
1986 foo bar blah
1987 @result{}foo bar blah
1988 define(`foo', `some')define(`bar', `other')define(`blah', `text')
1989 @result{}
1990 foo bar blah
1991 @result{}some other text
1992 undefine(`foo')
1993 @result{}
1994 foo bar blah
1995 @result{}foo other text
1996 undefine(`bar', `blah')
1997 @result{}
1998 foo bar blah
1999 @result{}foo bar blah
2000 @end example
2002 Undefining a macro inside that macro's expansion is safe; the macro
2003 still expands to the definition that was in effect at the @samp{(}.
2005 @example
2006 define(`f', ``$0':$1')
2007 @result{}
2008 f(f(f(undefine(`f')`hello world')))
2009 @result{}f:f:f:hello world
2010 f(`bye')
2011 @result{}f(bye)
2012 @end example
2014 It is not an error for @var{name} to have no macro definition.  In that
2015 case, @code{undefine} does nothing.
2017 @node Defn
2018 @section Renaming macros
2020 @cindex macros, how to rename
2021 @cindex renaming macros
2022 @cindex macros, displaying definitions
2023 @cindex definitions, displaying macro
2024 It is possible to rename an already defined macro.  To do this, you need
2025 the builtin @code{defn}:
2027 @deffn Builtin defn (@var{name}@dots{})
2028 Expands to the @emph{quoted definition} of each @var{name}.  If an
2029 argument is not a defined macro, the expansion for that argument is
2030 empty.
2032 If @var{name} is a user-defined macro, the quoted definition is simply
2033 the quoted expansion text.  If, instead, there is only one @var{name}
2034 and it is a builtin, the
2035 expansion is a special token, which points to the builtin's internal
2036 definition.  This token is only meaningful as the second argument to
2037 @code{define} (and @code{pushdef}), and is silently converted to an
2038 empty string in most other contexts.  Combining a builtin with anything
2039 else is not supported; a warning is issued and the builtin is omitted
2040 from the final expansion.
2042 The macro @code{defn} is recognized only with parameters.
2043 @end deffn
2045 Its normal use is best understood through an example, which shows how to
2046 rename @code{undefine} to @code{zap}:
2048 @example
2049 define(`zap', defn(`undefine'))
2050 @result{}
2051 zap(`undefine')
2052 @result{}
2053 undefine(`zap')
2054 @result{}undefine(zap)
2055 @end example
2057 In this way, @code{defn} can be used to copy macro definitions, and also
2058 definitions of builtin macros.  Even if the original macro is removed,
2059 the other name can still be used to access the definition.
2061 The fact that macro definitions can be transferred also explains why you
2062 should use @code{$0}, rather than retyping a macro's name in its
2063 definition:
2065 @example
2066 define(`foo', `This is `$0'')
2067 @result{}
2068 define(`bar', defn(`foo'))
2069 @result{}
2071 @result{}This is bar
2072 @end example
2074 Macros used as string variables should be referred through @code{defn},
2075 to avoid unwanted expansion of the text:
2077 @example
2078 define(`string', `The macro dnl is very useful
2080 @result{}
2081 string
2082 @result{}The macro@w{ }
2083 defn(`string')
2084 @result{}The macro dnl is very useful
2085 @result{}
2086 @end example
2088 @cindex rescanning
2089 However, it is important to remember that @code{m4} rescanning is purely
2090 textual.  If an unbalanced end-quote string occurs in a macro
2091 definition, the rescan will see that embedded quote as the termination
2092 of the quoted string, and the remainder of the macro's definition will
2093 be rescanned unquoted.  Thus it is a good idea to avoid unbalanced
2094 end-quotes in macro definitions or arguments to macros.
2096 @example
2097 define(`foo', a'a)
2098 @result{}
2099 define(`a', `A')
2100 @result{}
2101 define(`echo', `$@@')
2102 @result{}
2104 @result{}A'A
2105 defn(`foo')
2106 @result{}aA'
2107 echo(foo)
2108 @result{}AA'
2109 @end example
2111 On the other hand, it is possible to exploit the fact that @code{defn}
2112 can concatenate multiple macros prior to the rescanning phase, in order
2113 to join the definitions of macros that, in isolation, have unbalanced
2114 quotes.  This is particularly useful when one has used several macros to
2115 accumulate text that M4 should rescan as a whole.  In the example below,
2116 note how the use of @code{defn} on @code{l} in isolation opens a string,
2117 which is not closed until the next line; but used on @code{l} and
2118 @code{r} together results in nested quoting.
2120 @example
2121 define(`l', `<[>')define(`r', `<]>')
2122 @result{}
2123 changequote(`[', `]')
2124 @result{}
2125 defn([l])defn([r])
2127 @result{}<[>]defn([r])
2128 @result{})
2129 defn([l], [r])
2130 @result{}<[>][<]>
2131 @end example
2133 @cindex builtins, special tokens
2134 @cindex tokens, builtin macro
2135 Using @code{defn} to generate special tokens for builtin macros outside
2136 of expected contexts can sometimes trigger warnings.  But most of the
2137 time, such tokens are silently converted to the empty string.
2139 @example
2140 defn(`defn')
2141 @result{}
2142 define(defn(`divnum'), `cannot redefine a builtin token')
2143 @error{}m4:stdin:2: Warning: define: invalid macro name ignored
2144 @result{}
2145 divnum
2146 @result{}0
2147 @end example
2149 Also note that @code{defn} with multiple arguments can only join text
2150 macros, not builtins, although a future version of @acronym{GNU} M4 may
2151 lift this restriction.
2153 @example
2154 define(`a', `A')
2155 @result{}
2156 defn(`a', `defn', `a')
2157 @error{}m4:stdin:2: Warning: cannot concatenate builtin `defn'
2158 @result{}AA
2159 @end example
2161 @node Pushdef
2162 @section Temporarily redefining macros
2164 @cindex macros, temporary redefinition of
2165 @cindex temporary redefinition of macros
2166 @cindex redefinition of macros, temporary
2167 @cindex definition stack
2168 @cindex stack, macro definition
2169 It is possible to redefine a macro temporarily, reverting to the
2170 previous definition at a later time.  This is done with the builtins
2171 @code{pushdef} and @code{popdef}:
2173 @deffn Builtin pushdef (@var{name}, @ovar{expansion})
2174 @deffnx Builtin popdef (@var{name}@dots{})
2175 Analogous to @code{define} and @code{undefine}.
2177 These macros work in a stack-like fashion.  A macro is temporarily
2178 redefined with @code{pushdef}, which replaces an existing definition of
2179 @var{name}, while saving the previous definition, before the new one is
2180 installed.  If there is no previous definition, @code{pushdef} behaves
2181 exactly like @code{define}.
2183 If a macro has several definitions (of which only one is accessible),
2184 the topmost definition can be removed with @code{popdef}.  If there is
2185 no previous definition, @code{popdef} behaves like @code{undefine}.
2187 The expansion of both @code{pushdef} and @code{popdef} is void.
2188 The macros @code{pushdef} and @code{popdef} are recognized only with
2189 parameters.
2190 @end deffn
2192 @example
2193 define(`foo', `Expansion one.')
2194 @result{}
2196 @result{}Expansion one.
2197 pushdef(`foo', `Expansion two.')
2198 @result{}
2200 @result{}Expansion two.
2201 pushdef(`foo', `Expansion three.')
2202 @result{}
2203 pushdef(`foo', `Expansion four.')
2204 @result{}
2205 popdef(`foo')
2206 @result{}
2208 @result{}Expansion three.
2209 popdef(`foo', `foo')
2210 @result{}
2212 @result{}Expansion one.
2213 popdef(`foo')
2214 @result{}
2216 @result{}foo
2217 @end example
2219 If a macro with several definitions is redefined with @code{define}, the
2220 topmost definition is @emph{replaced} with the new definition.  If it is
2221 removed with @code{undefine}, @emph{all} the definitions are removed,
2222 and not only the topmost one.  However, @acronym{POSIX} allows other
2223 implementations that treat @code{define} as replacing an entire stack
2224 of definitions with a single new definition, so to be portable to other
2225 implementations, it may be worth explicitly using @code{popdef} and
2226 @code{pushdef} rather than relying on the @acronym{GNU} behavior of
2227 @code{define}.
2229 @example
2230 define(`foo', `Expansion one.')
2231 @result{}
2233 @result{}Expansion one.
2234 pushdef(`foo', `Expansion two.')
2235 @result{}
2237 @result{}Expansion two.
2238 define(`foo', `Second expansion two.')
2239 @result{}
2241 @result{}Second expansion two.
2242 undefine(`foo')
2243 @result{}
2245 @result{}foo
2246 @end example
2248 @cindex local variables
2249 @cindex variables, local
2250 Local variables within macros are made with @code{pushdef} and
2251 @code{popdef}.  At the start of the macro a new definition is pushed,
2252 within the macro it is manipulated and at the end it is popped,
2253 revealing the former definition.
2255 It is possible to temporarily redefine a builtin with @code{pushdef}
2256 and @code{defn}.
2258 @node Indir
2259 @section Indirect call of macros
2261 @cindex indirect call of macros
2262 @cindex call of macros, indirect
2263 @cindex macros, indirect call of
2264 @cindex @acronym{GNU} extensions
2265 Any macro can be called indirectly with @code{indir}:
2267 @deffn Builtin indir (@var{name}, @ovar{args@dots{}})
2268 Results in a call to the macro @var{name}, which is passed the
2269 rest of the arguments @var{args}.  If @var{name} is not defined, an
2270 error message is printed, and the expansion is void.
2272 The macro @code{indir} is recognized only with parameters.
2273 @end deffn
2275 This can be used to call macros with computed or ``invalid''
2276 names (@code{define} allows such names to be defined):
2278 @example
2279 define(`$$internal$macro', `Internal macro (name `$0')')
2280 @result{}
2281 $$internal$macro
2282 @result{}$$internal$macro
2283 indir(`$$internal$macro')
2284 @result{}Internal macro (name $$internal$macro)
2285 @end example
2287 The point is, here, that larger macro packages can have private macros
2288 defined, that will not be called by accident.  They can @emph{only} be
2289 called through the builtin @code{indir}.
2291 One other point to observe is that argument collection occurs before
2292 @code{indir} invokes @var{name}, so if argument collection changes the
2293 value of @var{name}, that will be reflected in the final expansion.
2294 This is different than the behavior when invoking macros directly,
2295 where the definition that was in effect before argument collection is
2296 used.
2298 @example
2299 $ @kbd{m4 -d}
2300 define(`f', `1')
2301 @result{}
2302 f(define(`f', `2'))
2303 @result{}1
2304 indir(`f', define(`f', `3'))
2305 @result{}3
2306 indir(`f', undefine(`f'))
2307 @error{}m4:stdin:4: undefined macro `f'
2308 @result{}
2309 @end example
2311 When handed the result of @code{defn} (@pxref{Defn}) as one of its
2312 arguments, @code{indir} defers to the invoked @var{name} for whether a
2313 token representing a builtin is recognized or flattened to the empty
2314 string.
2316 @example
2317 $ @kbd{m4 -d}
2318 indir(defn(`defn'), `divnum')
2319 @error{}m4:stdin:1: Warning: indir: invalid macro name ignored
2320 @result{}
2321 indir(`define', defn(`defn'), `divnum')
2322 @error{}m4:stdin:2: Warning: define: invalid macro name ignored
2323 @result{}
2324 indir(`define', `foo', defn(`divnum'))
2325 @result{}
2327 @result{}0
2328 indir(`divert', defn(`foo'))
2329 @error{}m4:stdin:5: empty string treated as 0 in builtin `divert'
2330 @result{}
2331 @end example
2333 @node Builtin
2334 @section Indirect call of builtins
2336 @cindex indirect call of builtins
2337 @cindex call of builtins, indirect
2338 @cindex builtins, indirect call of
2339 @cindex @acronym{GNU} extensions
2340 Builtin macros can be called indirectly with @code{builtin}:
2342 @deffn Builtin builtin (@var{name}, @ovar{args@dots{}})
2343 Results in a call to the builtin @var{name}, which is passed the
2344 rest of the arguments @var{args}.  If @var{name} does not name a
2345 builtin, an error message is printed, and the expansion is void.
2347 The macro @code{builtin} is recognized only with parameters.
2348 @end deffn
2350 This can be used even if @var{name} has been given another definition
2351 that has covered the original, or been undefined so that no macro
2352 maps to the builtin.
2354 @example
2355 pushdef(`define', `hidden')
2356 @result{}
2357 undefine(`undefine')
2358 @result{}
2359 define(`foo', `bar')
2360 @result{}hidden
2362 @result{}foo
2363 builtin(`define', `foo', defn(`divnum'))
2364 @result{}
2366 @result{}0
2367 builtin(`define', `foo', `BAR')
2368 @result{}
2370 @result{}BAR
2371 undefine(`foo')
2372 @result{}undefine(foo)
2374 @result{}BAR
2375 builtin(`undefine', `foo')
2376 @result{}
2378 @result{}foo
2379 @end example
2381 The @var{name} argument only matches the original name of the builtin,
2382 even when the @option{--prefix-builtins} option (or @option{-P},
2383 @pxref{Operation modes, , Invoking m4}) is in effect.  This is different
2384 from @code{indir}, which only tracks current macro names.
2386 @comment options: -P
2387 @example
2388 $ @kbd{m4 -P}
2389 m4_builtin(`divnum')
2390 @result{}0
2391 m4_builtin(`m4_divnum')
2392 @error{}m4:stdin:2: undefined builtin `m4_divnum'
2393 @result{}
2394 m4_indir(`divnum')
2395 @error{}m4:stdin:3: undefined macro `divnum'
2396 @result{}
2397 m4_indir(`m4_divnum')
2398 @result{}0
2399 @end example
2401 Note that @code{indir} and @code{builtin} can be used to invoke builtins
2402 without arguments, even when they normally require parameters to be
2403 recognized; but it will provoke a warning, and result in a void expansion.
2405 @example
2406 builtin
2407 @result{}builtin
2408 builtin()
2409 @error{}m4:stdin:2: undefined builtin `'
2410 @result{}
2411 builtin(`builtin')
2412 @error{}m4:stdin:3: Warning: too few arguments to builtin `builtin'
2413 @result{}
2414 builtin(`builtin',)
2415 @error{}m4:stdin:4: undefined builtin `'
2416 @result{}
2417 @end example
2419 @node Conditionals
2420 @chapter Conditionals, loops, and recursion
2422 Macros, expanding to plain text, perhaps with arguments, are not quite
2423 enough.  We would like to have macros expand to different things, based
2424 on decisions taken at run-time.  For that, we need some kind of conditionals.
2425 Also, we would like to have some kind of loop construct, so we could do
2426 something a number of times, or while some condition is true.
2428 @menu
2429 * Ifdef::                       Testing if a macro is defined
2430 * Ifelse::                      If-else construct, or multibranch
2431 * Shift::                       Recursion in @code{m4}
2432 * Forloop::                     Iteration by counting
2433 * Foreach::                     Iteration by list contents
2434 @end menu
2436 @node Ifdef
2437 @section Testing if a macro is defined
2439 @cindex conditionals
2440 There are two different builtin conditionals in @code{m4}.  The first is
2441 @code{ifdef}:
2443 @deffn Builtin ifdef (@var{name}, @var{string-1}, @ovar{string-2})
2444 If @var{name} is defined as a macro, @code{ifdef} expands to
2445 @var{string-1}, otherwise to @var{string-2}.  If @var{string-2} is
2446 omitted, it is taken to be the empty string (according to the normal
2447 rules).
2449 The macro @code{ifdef} is recognized only with parameters.
2450 @end deffn
2452 @example
2453 ifdef(`foo', ``foo' is defined', ``foo' is not defined')
2454 @result{}foo is not defined
2455 define(`foo', `')
2456 @result{}
2457 ifdef(`foo', ``foo' is defined', ``foo' is not defined')
2458 @result{}foo is defined
2459 ifdef(`no_such_macro', `yes', `no', `extra argument')
2460 @error{}m4:stdin:4: Warning: excess arguments to builtin `ifdef' ignored
2461 @result{}no
2462 @end example
2464 @node Ifelse
2465 @section If-else construct, or multibranch
2467 @cindex comparing strings
2468 @cindex discarding input
2469 @cindex input, discarding
2470 The other conditional, @code{ifelse}, is much more powerful.  It can be
2471 used as a way to introduce a long comment, as an if-else construct, or
2472 as a multibranch, depending on the number of arguments supplied:
2474 @deffn Builtin ifelse (@var{comment})
2475 @deffnx Builtin ifelse (@var{string-1}, @var{string-2}, @var{equal}, @
2476   @ovar{not-equal})
2477 @deffnx Builtin ifelse (@var{string-1}, @var{string-2}, @var{equal-1}, @
2478   @var{string-3}, @var{string-4}, @var{equal-2}, @dots{})
2479 Used with only one argument, the @code{ifelse} simply discards it and
2480 produces no output.
2482 If called with three or four arguments, @code{ifelse} expands into
2483 @var{equal}, if @var{string-1} and @var{string-2} are equal (character
2484 for character), otherwise it expands to @var{not-equal}.  A final fifth
2485 argument is ignored, after triggering a warning.
2487 If called with six or more arguments, and @var{string-1} and
2488 @var{string-2} are equal, @code{ifelse} expands into @var{equal-1},
2489 otherwise the first three arguments are discarded and the processing
2490 starts again.
2492 The macro @code{ifelse} is recognized only with parameters.
2493 @end deffn
2495 Using only one argument is a common @code{m4} idiom for introducing a
2496 block comment, as an alternative to repeatedly using @code{dnl}.  This
2497 special usage is recognized by @acronym{GNU} @code{m4}, so that in this
2498 case, the warning about missing arguments is never triggered.
2500 @example
2501 ifelse(`some comments')
2502 @result{}
2503 ifelse(`foo', `bar')
2504 @error{}m4:stdin:2: Warning: too few arguments to builtin `ifelse'
2505 @result{}
2506 @end example
2508 Using three or four arguments provides decision points.
2510 @example
2511 ifelse(`foo', `bar', `true')
2512 @result{}
2513 ifelse(`foo', `foo', `true')
2514 @result{}true
2515 define(`foo', `bar')
2516 @result{}
2517 ifelse(foo, `bar', `true', `false')
2518 @result{}true
2519 ifelse(foo, `foo', `true', `false')
2520 @result{}false
2521 @end example
2523 @cindex macro, blind
2524 @cindex blind macro
2525 Notice how the first argument was used unquoted; it is common to compare
2526 the expansion of a macro with a string.  With this macro, you can now
2527 reproduce the behavior of blind builtins, where the macro is recognized
2528 only with arguments.
2530 @example
2531 define(`foo', `ifelse(`$#', `0', ``$0'', `arguments:$#')')
2532 @result{}
2534 @result{}foo
2535 foo()
2536 @result{}arguments:1
2537 foo(`a', `b', `c')
2538 @result{}arguments:3
2539 @end example
2541 @cindex multibranches
2542 @cindex switch statement
2543 @cindex case statement
2544 However, @code{ifelse} can take more than four arguments.  If given more
2545 than four arguments, @code{ifelse} works like a @code{case} or @code{switch}
2546 statement in traditional programming languages.  If @var{string-1} and
2547 @var{string-2} are equal, @code{ifelse} expands into @var{equal-1}, otherwise
2548 the procedure is repeated with the first three arguments discarded.  This
2549 calls for an example:
2551 @example
2552 ifelse(`foo', `bar', `third', `gnu', `gnats')
2553 @error{}m4:stdin:1: Warning: excess arguments to builtin `ifelse' ignored
2554 @result{}gnu
2555 ifelse(`foo', `bar', `third', `gnu', `gnats', `sixth')
2556 @result{}
2557 ifelse(`foo', `bar', `third', `gnu', `gnats', `sixth', `seventh')
2558 @result{}seventh
2559 ifelse(`foo', `bar', `3', `gnu', `gnats', `6', `7', `8')
2560 @error{}m4:stdin:4: Warning: excess arguments to builtin `ifelse' ignored
2561 @result{}7
2562 @end example
2564 Naturally, the normal case will be slightly more advanced than these
2565 examples.  A common use of @code{ifelse} is in macros implementing loops
2566 of various kinds.
2568 @node Shift
2569 @section Recursion in @code{m4}
2571 @cindex recursive macros
2572 @cindex macros, recursive
2573 There is no direct support for loops in @code{m4}, but macros can be
2574 recursive.  There is no limit on the number of recursion levels, other
2575 than those enforced by your hardware and operating system.
2577 @cindex loops
2578 Loops can be programmed using recursion and the conditionals described
2579 previously.
2581 There is a builtin macro, @code{shift}, which can, among other things,
2582 be used for iterating through the actual arguments to a macro:
2584 @deffn Builtin shift (@var{arg1}, @dots{})
2585 Takes any number of arguments, and expands to all its arguments except
2586 @var{arg1}, separated by commas, with each argument quoted.
2588 The macro @code{shift} is recognized only with parameters.
2589 @end deffn
2591 @example
2592 shift
2593 @result{}shift
2594 shift(`bar')
2595 @result{}
2596 shift(`foo', `bar', `baz')
2597 @result{}bar,baz
2598 @end example
2600 An example of the use of @code{shift} is this macro:
2602 @deffn Composite reverse (@dots{})
2603 Takes any number of arguments, and reverses their order.
2604 @end deffn
2606 It is implemented as:
2608 @example
2609 define(`reverse', `ifelse(`$#', `0', , `$#', `1', ``$1'',
2610                           `reverse(shift($@@)), `$1'')')
2611 @result{}
2612 reverse
2613 @result{}
2614 reverse(`foo')
2615 @result{}foo
2616 reverse(`foo', `bar', `gnats', `and gnus')
2617 @result{}and gnus, gnats, bar, foo
2618 @end example
2620 While not a very interesting macro, it does show how simple loops can be
2621 made with @code{shift}, @code{ifelse} and recursion.  It also shows
2622 that @code{shift} is usually used with @samp{$@@}.  Sometimes, a
2623 recursive algorithm requires adding quotes to each element:
2625 @deffn Composite quote (@dots{})
2626 @deffnx Composite dquote (@dots{})
2627 @deffnx Composite dquote_elt (@dots{})
2628 Takes any number of arguments, and adds quoting.  With @code{quote},
2629 only one level of quoting is added, effectively removing whitespace
2630 after commas and turning multiple arguments into a single string.  With
2631 @code{dquote}, two levels of quoting are added, one around each element,
2632 and one around the list.  And with @code{dquote_elt}, two levels of
2633 quoting are added around each element.
2634 @end deffn
2636 An actual implementation of these three macros is distributed as
2637 @file{m4-@value{VERSION}/@/examples/@/quote.m4} in this package.  First,
2638 let's examine their usage:
2640 @example
2641 $ @kbd{m4 -I examples}
2642 include(`quote.m4')
2643 @result{}
2644 -quote-dquote-dquote_elt-
2645 @result{}----
2646 -quote()-dquote()-dquote_elt()-
2647 @result{}--`'-`'-
2648 -quote(`1')-dquote(`1')-dquote_elt(`1')-
2649 @result{}-1-`1'-`1'-
2650 -quote(`1', `2')-dquote(`1', `2')-dquote_elt(`1', `2')-
2651 @result{}-1,2-`1',`2'-`1',`2'-
2652 define(`n', `$#')dnl
2653 -n(quote(`1', `2'))-n(dquote(`1', `2'))-n(dquote_elt(`1', `2'))-
2654 @result{}-1-1-2-
2655 dquote(dquote_elt(`1', `2'))
2656 @result{}``1'',``2''
2657 dquote_elt(dquote(`1', `2'))
2658 @result{}``1',`2''
2659 @end example
2661 The last two lines show that when given two arguments, @code{dquote}
2662 results in one string, while @code{dquote_elt} results in two.  Now,
2663 examine the implementation.  Note that @code{quote} and
2664 @code{dquote_elt} make decisions based on their number of arguments, so
2665 that when called without arguments, they result in nothing instead of a
2666 quoted empty string; this is so that it is possible to distinguish
2667 between no arguments and an empty first argument.  @code{dquote}, on the
2668 other hand, results in a string no matter what, since it is still
2669 possible to tell whether it was invoked without arguments based on the
2670 resulting string.
2672 @example
2673 $ @kbd{m4 -I examples}
2674 undivert(`quote.m4')dnl
2675 @result{}divert(`-1')
2676 @result{}# quote(args) - convert args to single-quoted string
2677 @result{}define(`quote', `ifelse(`$#', `0', `', ``$*'')')
2678 @result{}# dquote(args) - convert args to quoted list of quoted strings
2679 @result{}define(`dquote', ``$@@'')
2680 @result{}# dquote_elt(args) - convert args to list of double-quoted strings
2681 @result{}define(`dquote_elt', `ifelse(`$#', `0', `', `$#', `1', ```$1''',
2682 @result{}                             ```$1'',$0(shift($@@))')')
2683 @result{}divert`'dnl
2684 @end example
2686 @cindex nine arguments, more than
2687 @cindex more than nine arguments
2688 @cindex arguments, more than nine
2689 One more useful macro based on @code{shift} allows portably selecting
2690 an arbitrary argument (usually greater than the ninth argument), without
2691 relying on the @acronym{GNU} extension of multi-digit arguments
2692 (@pxref{Arguments}).
2694 @deffn Composite argn (@var{n}, @dots{})
2695 Expands to argument @var{n} out of the remaining arguments.  @var{n}
2696 must be a positive number.  Usually invoked as
2697 @samp{argn(`@var{n}',$@@)}.
2698 @end deffn
2700 It is implemented as:
2702 @example
2703 define(`argn', `ifelse(`$1', 1, ``$2'',
2704   `argn(decr(`$1'), shift(shift($@@)))')')
2705 @result{}
2706 argn(`1', `a')
2707 @result{}a
2708 define(`foo', `argn(`11', $@@)')
2709 @result{}
2710 foo(`a', `b', `c', `d', `e', `f', `g', `h', `i', `j', `k', `l')
2711 @result{}k
2712 @end example
2714 @node Forloop
2715 @section Iteration by counting
2717 @cindex for loops
2718 @cindex loops, counting
2719 @cindex counting loops
2720 Here is an example of a loop macro that implements a simple for loop.
2722 @deffn Composite forloop (@var{iterator}, @var{start}, @var{end}, @var{text})
2723 Takes the name in @var{iterator}, which must be a valid macro name, and
2724 successively assign it each integer value from @var{start} to @var{end},
2725 inclusive.  For each assignment to @var{iterator}, append @var{text} to
2726 the expansion of the @code{forloop}.  @var{text} may refer to
2727 @var{iterator}.  Any definition of @var{iterator} prior to this
2728 invocation is restored.
2729 @end deffn
2731 It can, for example, be used for simple counting:
2733 @example
2734 $ @kbd{m4 -I examples}
2735 include(`forloop.m4')
2736 @result{}
2737 forloop(`i', `1', `8', `i ')
2738 @result{}1 2 3 4 5 6 7 8@w{ }
2739 @end example
2741 For-loops can be nested, like:
2743 @example
2744 $ @kbd{m4 -I examples}
2745 include(`forloop.m4')
2746 @result{}
2747 forloop(`i', `1', `4', `forloop(`j', `1', `8', ` (i, j)')
2749 @result{} (1, 1) (1, 2) (1, 3) (1, 4) (1, 5) (1, 6) (1, 7) (1, 8)
2750 @result{} (2, 1) (2, 2) (2, 3) (2, 4) (2, 5) (2, 6) (2, 7) (2, 8)
2751 @result{} (3, 1) (3, 2) (3, 3) (3, 4) (3, 5) (3, 6) (3, 7) (3, 8)
2752 @result{} (4, 1) (4, 2) (4, 3) (4, 4) (4, 5) (4, 6) (4, 7) (4, 8)
2753 @result{}
2754 @end example
2756 The implementation of the @code{forloop} macro is fairly
2757 straightforward.  The @code{forloop} macro itself is simply a wrapper,
2758 which saves the previous definition of the first argument, calls the
2759 internal macro @code{@w{_forloop}}, and re-establishes the saved
2760 definition of the first argument.
2762 The macro @code{@w{_forloop}} expands the fourth argument once, and
2763 tests to see if the iterator has reached the final value.  If it has
2764 not finished, it increments the iterator (using the predefined macro
2765 @code{incr}, @pxref{Incr}), and recurses.
2767 Here is an actual implementation of @code{forloop}, distributed as
2768 @file{m4-@value{VERSION}/@/examples/@/forloop.m4} in this package:
2770 @example
2771 $ @kbd{m4 -I examples}
2772 undivert(`forloop.m4')dnl
2773 @result{}divert(`-1')
2774 @result{}# forloop(var, from, to, stmt) - simple version
2775 @result{}define(`forloop', `pushdef(`$1', `$2')_forloop($@@)popdef(`$1')')
2776 @result{}define(`_forloop',
2777 @result{}       `$4`'ifelse($1, `$3', `', `define(`$1', incr($1))$0($@@)')')
2778 @result{}divert`'dnl
2779 @end example
2781 Notice the careful use of quotes.  Certain macro arguments are left
2782 unquoted, each for its own reason.  Try to find out @emph{why} these
2783 arguments are left unquoted, and see what happens if they are quoted.
2784 (As presented, these two macros are useful but not very robust for
2785 general use.  They lack even basic error handling for cases like
2786 @var{start} less than @var{end}, @var{end} not numeric, or
2787 @var{iterator} not being a macro name.  See if you can improve these
2788 macros; or @pxref{Improved forloop, , Answers}).
2790 @node Foreach
2791 @section Iteration by list contents
2793 @cindex for each loops
2794 @cindex loops, list iteration
2795 @cindex iterating over lists
2796 Here is an example of a loop macro that implements list iteration.
2798 @deffn Composite foreach (@var{iterator}, @var{paren-list}, @var{text})
2799 @deffnx Composite foreachq (@var{iterator}, @var{quote-list}, @var{text})
2800 Takes the name in @var{iterator}, which must be a valid macro name, and
2801 successively assign it each value from @var{paren-list} or
2802 @var{quote-list}.  In @code{foreach}, @var{paren-list} is a
2803 comma-separated list of elements contained in parentheses.  In
2804 @code{foreachq}, @var{quote-list} is a comma-separated list of elements
2805 contained in a quoted string.  For each assignment to @var{iterator},
2806 append @var{text} to the overall expansion.  @var{text} may refer to
2807 @var{iterator}.  Any definition of @var{iterator} prior to this
2808 invocation is restored.
2809 @end deffn
2811 As an example, this displays each word in a list inside of a sentence,
2812 using an implementation of @code{foreach} distributed as
2813 @file{m4-@value{VERSION}/@/examples/@/foreach.m4}, and @code{foreachq}
2814 in @file{m4-@value{VERSION}/@/examples/@/foreachq.m4}.
2816 @example
2817 $ @kbd{m4 -I examples}
2818 include(`foreach.m4')
2819 @result{}
2820 foreach(`x', (foo, bar, foobar), `Word was: x
2821 ')dnl
2822 @result{}Word was: foo
2823 @result{}Word was: bar
2824 @result{}Word was: foobar
2825 include(`foreachq.m4')
2826 @result{}
2827 foreachq(`x', `foo, bar, foobar', `Word was: x
2828 ')dnl
2829 @result{}Word was: foo
2830 @result{}Word was: bar
2831 @result{}Word was: foobar
2832 @end example
2834 It is possible to be more complex; each element of the @var{paren-list}
2835 or @var{quote-list} can itself be a list, to pass as further arguments
2836 to a helper macro.  This example generates a shell case statement:
2838 @example
2839 $ @kbd{m4 -I examples}
2840 include(`foreach.m4')
2841 @result{}
2842 define(`_case', `  $1)
2843     $2=" $1";;
2844 ')dnl
2845 define(`_cat', `$1$2')dnl
2846 case $`'1 in
2847 @result{}case $1 in
2848 foreach(`x', `(`(`a', `vara')', `(`b', `varb')', `(`c', `varc')')',
2849         `_cat(`_case', x)')dnl
2850 @result{}  a)
2851 @result{}    vara=" a";;
2852 @result{}  b)
2853 @result{}    varb=" b";;
2854 @result{}  c)
2855 @result{}    varc=" c";;
2856 esac
2857 @result{}esac
2858 @end example
2860 The implementation of the @code{foreach} macro is a bit more involved;
2861 it is a wrapper around two helper macros.  First, @code{@w{_arg1}} is
2862 needed to grab the first element of a list.  Second,
2863 @code{@w{_foreach}} implements the recursion, successively walking
2864 through the original list.  Here is a simple implementation of
2865 @code{foreach}:
2867 @example
2868 $ @kbd{m4 -I examples}
2869 undivert(`foreach.m4')dnl
2870 @result{}divert(`-1')
2871 @result{}# foreach(x, (item_1, item_2, ..., item_n), stmt)
2872 @result{}#   parenthesized list, simple version
2873 @result{}define(`foreach', `pushdef(`$1')_foreach($@@)popdef(`$1')')
2874 @result{}define(`_arg1', `$1')
2875 @result{}define(`_foreach', `ifelse(`$2', `()', `',
2876 @result{}  `define(`$1', _arg1$2)$3`'$0(`$1', (shift$2), `$3')')')
2877 @result{}divert`'dnl
2878 @end example
2880 Unfortunately, that implementation is not robust to macro names as list
2881 elements.  Each iteration of @code{@w{_foreach}} is stripping another
2882 layer of quotes, leading to erratic results if list elements are not
2883 already fully expanded.  The first cut at implementing @code{foreachq}
2884 takes this into account.  Also, when using quoted elements in a
2885 @var{paren-list}, the overall list must be quoted.  A @var{quote-list}
2886 has the nice property of requiring fewer characters to create a list
2887 containing the same quoted elements.  To see the difference between the
2888 two macros, we attempt to pass double-quoted macro names in a list,
2889 expecting the macro name on output after one layer of quotes is removed
2890 during list iteration and the final layer removed during the final
2891 rescan:
2893 @example
2894 $ @kbd{m4 -I examples}
2895 define(`a', `1')define(`b', `2')define(`c', `3')
2896 @result{}
2897 include(`foreach.m4')
2898 @result{}
2899 include(`foreachq.m4')
2900 @result{}
2901 foreach(`x', `(``a'', ``(b'', ``c)'')', `x
2903 @result{}1
2904 @result{}(2)1
2905 @result{}
2906 @result{}, x
2907 @result{})
2908 foreachq(`x', ```a'', ``(b'', ``c)''', `x
2909 ')dnl
2910 @result{}a
2911 @result{}(b
2912 @result{}c)
2913 @end example
2915 Obviously, @code{foreachq} did a better job; here is its implementation:
2917 @example
2918 $ @kbd{m4 -I examples}
2919 undivert(`foreachq.m4')dnl
2920 @result{}include(`quote.m4')dnl
2921 @result{}divert(`-1')
2922 @result{}# foreachq(x, `item_1, item_2, ..., item_n', stmt)
2923 @result{}#   quoted list, simple version
2924 @result{}define(`foreachq', `pushdef(`$1')_foreachq($@@)popdef(`$1')')
2925 @result{}define(`_arg1', `$1')
2926 @result{}define(`_foreachq', `ifelse(quote($2), `', `',
2927 @result{}  `define(`$1', `_arg1($2)')$3`'$0(`$1', `shift($2)', `$3')')')
2928 @result{}divert`'dnl
2929 @end example
2931 Notice that @code{@w{_foreachq}} had to use the helper macro
2932 @code{quote} defined earlier (@pxref{Shift}), to ensure that the
2933 embedded @code{ifelse} call does not go haywire if a list element
2934 contains a comma.  Unfortunately, this implementation of @code{foreachq}
2935 has its own severe flaw.  Whereas the @code{foreach} implementation was
2936 linear, this macro is quadratic in the number of list elements, and is
2937 much more likely to trip up the limit set by the command line option
2938 @option{--nesting-limit} (or @option{-L}, @pxref{Limits control, ,
2939 Invoking m4}).  (It is possible to have robust iteration with linear
2940 behavior for either list style.  See if you can learn from the best
2941 elements of both of these implementations to create robust macros; or
2942 @pxref{Improved foreach, , Answers}).
2944 @node Debugging
2945 @chapter How to debug macros and input
2947 @cindex debugging macros
2948 @cindex macros, debugging
2949 When writing macros for @code{m4}, they often do not work as intended on
2950 the first try (as is the case with most programming languages).
2951 Fortunately, there is support for macro debugging in @code{m4}.
2953 @menu
2954 * Dumpdef::                     Displaying macro definitions
2955 * Trace::                       Tracing macro calls
2956 * Debug Levels::                Controlling debugging output
2957 * Debug Output::                Saving debugging output
2958 @end menu
2960 @node Dumpdef
2961 @section Displaying macro definitions
2963 @cindex displaying macro definitions
2964 @cindex macros, displaying definitions
2965 @cindex definitions, displaying macro
2966 @cindex standard error, output to
2967 If you want to see what a name expands into, you can use the builtin
2968 @code{dumpdef}:
2970 @deffn Builtin dumpdef (@ovar{names@dots{}})
2971 Accepts any number of arguments.  If called without any arguments,
2972 it displays the definitions of all known names, otherwise it displays
2973 the definitions of the @var{names} given.  The output is printed to the
2974 current debug file (usually standard error), and is sorted by name.  If
2975 an unknown name is encountered, a warning is printed.
2977 The expansion of @code{dumpdef} is void.
2978 @end deffn
2980 @example
2981 $ @kbd{m4 -d}
2982 define(`foo', `Hello world.')
2983 @result{}
2984 dumpdef(`foo')
2985 @error{}foo:@tabchar{}`Hello world.'
2986 @result{}
2987 dumpdef(`define')
2988 @error{}define:@tabchar{}<define>
2989 @result{}
2990 @end example
2992 The last example shows how builtin macros definitions are displayed.
2993 The definition that is dumped corresponds to what would occur if the
2994 macro were to be called at that point, even if other definitions are
2995 still live due to redefining a macro during argument collection.
2997 @example
2998 $ @kbd{m4 -d}
2999 pushdef(`f', ``$0'1')pushdef(`f', ``$0'2')
3000 @result{}
3001 f(popdef(`f')dumpdef(`f'))
3002 @error{}f:@tabchar{}``$0'1'
3003 @result{}f2
3004 f(popdef(`f')dumpdef(`f'))
3005 @error{}m4:stdin:3: undefined macro `f'
3006 @result{}f1
3007 @end example
3009 @xref{Debug Levels}, for information on controlling the details of the
3010 display.
3012 @node Trace
3013 @section Tracing macro calls
3015 @cindex tracing macro expansion
3016 @cindex macro expansion, tracing
3017 @cindex expansion, tracing macro
3018 @cindex standard error, output to
3019 It is possible to trace macro calls and expansions through the builtins
3020 @code{traceon} and @code{traceoff}:
3022 @deffn Builtin traceon (@ovar{names@dots{}})
3023 @deffnx Builtin traceoff (@ovar{names@dots{}})
3024 When called without any arguments, @code{traceon} and @code{traceoff}
3025 will turn tracing on and off, respectively, for all currently defined
3026 macros.
3028 When called with arguments, only the macros listed in @var{names} are
3029 affected, whether or not they are currently defined.
3031 The expansion of @code{traceon} and @code{traceoff} is void.
3032 @end deffn
3034 Whenever a traced macro is called and the arguments have been collected,
3035 the call is displayed.  If the expansion of the macro call is not void,
3036 the expansion can be displayed after the call.  The output is printed
3037 to the current debug file (defaulting to standard error, @pxref{Debug
3038 Output}).
3040 @example
3041 $ @kbd{m4 -d}
3042 define(`foo', `Hello World.')
3043 @result{}
3044 define(`echo', `$@@')
3045 @result{}
3046 traceon(`foo', `echo')
3047 @result{}
3049 @error{}m4trace: -1- foo -> `Hello World.'
3050 @result{}Hello World.
3051 echo(`gnus', `and gnats')
3052 @error{}m4trace: -1- echo(`gnus', `and gnats') -> ``gnus',`and gnats''
3053 @result{}gnus,and gnats
3054 @end example
3056 The number between dashes is the depth of the expansion.  It is one most
3057 of the time, signifying an expansion at the outermost level, but it
3058 increases when macro arguments contain unquoted macro calls.  The
3059 maximum number that will appear between dashes is controlled by the
3060 option @option{--nesting-limit} (or @option{-L}, @pxref{Limits control,
3061 , Invoking m4}).  Additionally, the option @option{--trace} (or
3062 @option{-t}) can be used to invoke @code{traceon(@var{name})} before
3063 parsing input.
3065 @comment options: -dp -L3 -tifelse
3066 @comment status: 1
3067 @example
3068 $ @kbd{m4 -L 3 -t ifelse}
3069 ifelse(`one level')
3070 @error{}m4trace: -1- ifelse
3071 @result{}
3072 ifelse(ifelse(ifelse(`three levels')))
3073 @error{}m4trace: -3- ifelse
3074 @error{}m4trace: -2- ifelse
3075 @error{}m4trace: -1- ifelse
3076 @result{}
3077 ifelse(ifelse(ifelse(ifelse(`four levels'))))
3078 @error{}m4:stdin:3: recursion limit of 3 exceeded, use -L<N> to change it
3079 @end example
3081 Tracing by name is an attribute that is preserved whether the macro is
3082 defined or not.  This allows the selection of macros to trace before
3083 those macros are defined.
3085 @example
3086 $ @kbd{m4 -d}
3087 traceoff(`foo')
3088 @result{}
3089 traceon(`foo')
3090 @result{}
3092 @result{}foo
3093 define(`foo', `bar')
3094 @result{}
3096 @error{}m4trace: -1- foo -> `bar'
3097 @result{}bar
3098 undefine(`foo')
3099 @result{}
3100 ifdef(`foo', `yes', `no')
3101 @result{}no
3102 indir(`foo')
3103 @error{}m4:stdin:8: undefined macro `foo'
3104 @result{}
3105 define(`foo', `blah')
3106 @result{}
3108 @error{}m4trace: -1- foo -> `blah'
3109 @result{}blah
3110 traceoff
3111 @result{}
3113 @result{}blah
3114 @end example
3116 Tracing even works on builtins.  However, @code{defn} (@pxref{Defn})
3117 does not transfer tracing status.
3119 @example
3120 $ @kbd{m4 -d}
3121 traceon(`eval', `m4_divnum')
3122 @result{}
3123 define(`m4_eval', defn(`eval'))
3124 @result{}
3125 define(`m4_divnum', defn(`divnum'))
3126 @result{}
3127 eval(divnum)
3128 @error{}m4trace: -1- eval(`0') -> `0'
3129 @result{}0
3130 m4_eval(m4_divnum)
3131 @error{}m4trace: -2- m4_divnum -> `0'
3132 @result{}0
3133 @end example
3135 @xref{Debug Levels}, for information on controlling the details of the
3136 display.
3138 @node Debug Levels
3139 @section Controlling debugging output
3141 @cindex controlling debugging output
3142 @cindex debugging output, controlling
3143 The @option{-d} option to @code{m4} (or @option{--debug},
3144 @pxref{Debugging options, , Invoking m4}) controls the amount of details
3145 presented in three
3146 categories of output.  Trace output is requested by @code{traceon}
3147 (@pxref{Trace}), and each line is prefixed by @samp{m4trace:} in
3148 relation to a macro invocation.  Debug output tracks useful events not
3149 associated with a macro invocation, and each line is prefixed by
3150 @samp{m4debug:}.  Finally, @code{dumpdef} (@pxref{Dumpdef}) output is
3151 affected, with no prefix added to the output lines.
3153 The @var{flags} following the option can be one or more of the
3154 following:
3156 @table @code
3157 @item a
3158 In trace output, show the actual arguments that were collected before
3159 invoking the macro.  This applies to all macro calls if the @samp{t}
3160 flag is used, otherwise only the macros covered by calls of
3161 @code{traceon}.
3163 @item c
3164 In trace output, show several trace lines for each macro call.  A line
3165 is shown when the macro is seen, but before the arguments are collected;
3166 a second line when the arguments have been collected and a third line
3167 after the call has completed.
3169 @item e
3170 In trace output, show the expansion of each macro call, if it is not
3171 void.  This applies to all macro calls if the @samp{t} flag is used,
3172 otherwise only the macros covered by calls of @code{traceon}.
3174 @item f
3175 In debug and trace output, include the name of the current input file in
3176 the output line.
3178 @item i
3179 In debug output, print a message each time the current input file is
3180 changed.
3182 @item l
3183 In debug and trace output, include the current input line number in the
3184 output line.
3186 @item p
3187 In debug output, print a message when a named file is found through the
3188 path search mechanism (@pxref{Search Path}), giving the actual file name
3189 used.
3191 @item q
3192 In trace and dumpdef output, quote actual arguments and macro expansions
3193 in the display with the current quotes.  This is useful in connection
3194 with the @samp{a} and @samp{e} flags above.
3196 @item t
3197 In trace output, trace all macro calls made in this invocation of
3198 @code{m4}, regardless of the settings of @code{traceon}.
3200 @item x
3201 In trace output, add a unique `macro call id' to each line of the trace
3202 output.  This is useful in connection with the @samp{c} flag above.
3204 @item V
3205 A shorthand for all of the above flags.
3206 @end table
3208 If no flags are specified with the @option{-d} option, the default is
3209 @samp{aeq}.  The examples throughout this manual assume the default
3210 flags.
3212 @cindex @acronym{GNU} extensions
3213 There is a builtin macro @code{debugmode}, which allows on-the-fly control of
3214 the debugging output format:
3216 @deffn Builtin debugmode (@ovar{flags})
3217 The argument @var{flags} should be a subset of the letters listed above.
3218 As special cases, if the argument starts with a @samp{+}, the flags are
3219 added to the current debug flags, and if it starts with a @samp{-}, they
3220 are removed.  If no argument is present, all debugging flags are cleared
3221 (as if no @option{-d} was given), and with an empty argument the flags
3222 are reset to the default of @samp{aeq}.
3224 The expansion of @code{debugmode} is void.
3225 @end deffn
3227 @comment options: -dp
3228 @example
3229 $ @kbd{m4}
3230 define(`foo', `FOO')
3231 @result{}
3232 traceon(`foo')
3233 @result{}
3234 debugmode()
3235 @result{}
3237 @error{}m4trace: -1- foo -> `FOO'
3238 @result{}FOO
3239 debugmode
3240 @result{}
3242 @error{}m4trace: -1- foo
3243 @result{}FOO
3244 debugmode(`+l')
3245 @result{}
3247 @error{}m4trace:8: -1- foo
3248 @result{}FOO
3249 @end example
3251 @node Debug Output
3252 @section Saving debugging output
3254 @cindex saving debugging output
3255 @cindex debugging output, saving
3256 @cindex output, saving debugging
3257 @cindex @acronym{GNU} extensions
3258 Debug and tracing output can be redirected to files using either the
3259 @option{--debugfile} option to @code{m4} (@pxref{Debugging options, ,
3260 Invoking m4}), or with the builtin macro @code{debugfile}:
3262 @deffn Builtin debugfile (@ovar{file})
3263 Sends all further debug and trace output to @var{file}, opened in append
3264 mode.  If @var{file} is the empty string, debug and trace output are
3265 discarded.  If @code{debugfile} is called without any arguments, debug
3266 and trace output are sent to standard error.  This does not affect
3267 warnings, error messages, or @code{errprint} output, which are
3268 always sent to standard error.  If @var{file} cannot be opened, the
3269 current debug file is unchanged, and an error is issued.
3271 The expansion of @code{debugfile} is void.
3272 @end deffn
3274 @example
3275 $ @kbd{m4}
3276 traceon(`divnum')
3277 @result{}
3278 divnum(`extra')
3279 @error{}m4:stdin:2: Warning: excess arguments to builtin `divnum' ignored
3280 @error{}m4trace: -1- divnum(`extra') -> `0'
3281 @result{}0
3282 debugfile()
3283 @result{}
3284 divnum(`extra')
3285 @error{}m4:stdin:4: Warning: excess arguments to builtin `divnum' ignored
3286 @result{}0
3287 debugfile
3288 @result{}
3289 divnum
3290 @error{}m4trace: -1- divnum -> `0'
3291 @result{}0
3292 @end example
3294 @node Input Control
3295 @chapter Input control
3297 This chapter describes various builtin macros for controlling the input
3298 to @code{m4}.
3300 @menu
3301 * Dnl::                         Deleting whitespace in input
3302 * Changequote::                 Changing the quote characters
3303 * Changecom::                   Changing the comment delimiters
3304 * Changeword::                  Changing the lexical structure of words
3305 * M4wrap::                      Saving text until end of input
3306 @end menu
3308 @node Dnl
3309 @section Deleting whitespace in input
3311 @cindex deleting whitespace in input
3312 @cindex discarding input
3313 @cindex input, discarding
3314 The builtin @code{dnl} stands for ``Discard to Next Line'':
3316 @deffn Builtin dnl
3317 All characters, up to and including the next newline, are discarded
3318 without performing any macro expansion.  A warning is issued if the end
3319 of the file is encountered without a newline.
3321 The expansion of @code{dnl} is void.
3322 @end deffn
3324 It is often used in connection with @code{define}, to remove the
3325 newline that follows the call to @code{define}.  Thus
3327 @example
3328 define(`foo', `Macro `foo'.')dnl A very simple macro, indeed.
3330 @result{}Macro foo.
3331 @end example
3333 The input up to and including the next newline is discarded, as opposed
3334 to the way comments are treated (@pxref{Comments}).
3336 Usually, @code{dnl} is immediately followed by an end of line or some
3337 other whitespace.  @acronym{GNU} @code{m4} will produce a warning diagnostic if
3338 @code{dnl} is followed by an open parenthesis.  In this case, @code{dnl}
3339 will collect and process all arguments, looking for a matching close
3340 parenthesis.  All predictable side effects resulting from this
3341 collection will take place.  @code{dnl} will return no output.  The
3342 input following the matching close parenthesis up to and including the
3343 next newline, on whatever line containing it, will still be discarded.
3345 @example
3346 dnl(`args are ignored, but side effects occur',
3347 define(`foo', `like this')) while this text is ignored: undefine(`foo')
3348 @error{}m4:stdin:1: Warning: excess arguments to builtin `dnl' ignored
3349 See how `foo' was defined, foo?
3350 @result{}See how foo was defined, like this?
3351 @end example
3353 If the end of file is encountered without a newline character, a
3354 warning is issued and dnl stops consuming input.
3356 @example
3357 m4wrap(`m4wrap(`2 hi
3358 ')0 hi dnl 1 hi')
3359 @result{}
3360 define(`hi', `HI')
3361 @result{}
3363 @error{}m4:stdin:1: Warning: end of file treated as newline
3364 @result{}0 HI 2 HI
3365 @end example
3367 @node Changequote
3368 @section Changing the quote characters
3370 @cindex changing quote delimiters
3371 @cindex quote delimiters, changing
3372 @cindex delimiters, changing
3373 The default quote delimiters can be changed with the builtin
3374 @code{changequote}:
3376 @deffn Builtin changequote (@dvar{start, `}, @dvar{end, '})
3377 This sets @var{start} as the new begin-quote delimiter and @var{end} as
3378 the new end-quote delimiter.  If both arguments are missing, the default
3379 quotes (@code{`} and @code{'}) are used.  If @var{start} is void, then
3380 quoting is disabled.  Otherwise, if @var{end} is missing or void, the
3381 default end-quote delimiter (@code{'}) is used.  The quote delimiters
3382 can be of any length.
3384 The expansion of @code{changequote} is void.
3385 @end deffn
3387 @example
3388 changequote(`[', `]')
3389 @result{}
3390 define([foo], [Macro [foo].])
3391 @result{}
3393 @result{}Macro foo.
3394 @end example
3396 The quotation strings can safely contain eight-bit characters.
3397 @ignore
3398 @comment Yuck.  I know of no clean way to render an 8-bit character in
3399 @comment both info and dvi.  This example uses the `open-guillemot' and
3400 @comment `close-guillemot' characters of the Latin-1 character set.
3402 @example
3403 define(`a', `b')
3404 @result{}
3405 «a»
3406 @result{}«b»
3407 changequote(`«', `»')
3408 @result{}
3409 «a»
3410 @result{}a
3411 @end example
3412 @end ignore
3413 If no single character is appropriate, @var{start} and @var{end} can be
3414 of any length.  Other implementations cap the delimiter length to five
3415 characters, but @acronym{GNU} has no inherent limit.
3417 @example
3418 changequote(`[[[', `]]]')
3419 @result{}
3420 define([[[foo]]], [[[Macro [[[[[foo]]]]].]]])
3421 @result{}
3423 @result{}Macro [[foo]].
3424 @end example
3426 Calling @code{changequote} with @var{start} as the empty string will
3427 effectively disable the quoting mechanism, leaving no way to quote text.
3428 However, using an empty string is not portable, as some other
3429 implementations of @code{m4} revert to the default quoting, while others
3430 preserve the prior non-empty delimiter.  If @var{start} is not empty,
3431 then an empty @var{end} will use the default end-quote delimiter of
3432 @samp{'}, as otherwise, it would be impossible to end a quoted string.
3433 Again, this is not portable, as some other @code{m4} implementations
3434 reuse @var{start} as the end-quote delimiter, while others preserve the
3435 previous non-empty value.  Omitting both arguments restores the default
3436 begin-quote and end-quote delimiters; fortunately this behavior is
3437 portable to all implementations of @code{m4}.
3439 @example
3440 define(`foo', `Macro `FOO'.')
3441 @result{}
3442 changequote(`', `')
3443 @result{}
3445 @result{}Macro `FOO'.
3446 `foo'
3447 @result{}`Macro `FOO'.'
3448 changequote(`,)
3449 @result{}
3451 @result{}Macro FOO.
3452 @end example
3454 There is no way in @code{m4} to quote a string containing an unmatched
3455 begin-quote, except using @code{changequote} to change the current
3456 quotes.
3458 If the quotes should be changed from, say, @samp{[} to @samp{[[},
3459 temporary quote characters have to be defined.  To achieve this, two
3460 calls of @code{changequote} must be made, one for the temporary quotes
3461 and one for the new quotes.
3463 Macros are recognized in preference to the begin-quote string, so if a
3464 prefix of @var{start} can be recognized as part of a potential macro
3465 name, the quoting mechanism is effectively disabled.  Unless you use
3466 @code{changeword} (@pxref{Changeword}), this means that @var{start}
3467 should not begin with a letter, digit, or @samp{_} (underscore).
3468 However, even though quoted strings are not recognized, the quote
3469 characters can still be discerned in macro expansion and in trace
3470 output.
3472 @example
3473 define(`echo', `$@@')
3474 @result{}
3475 define(`hi', `HI')
3476 @result{}
3477 changequote(`q', `Q')
3478 @result{}
3479 q hi Q hi
3480 @result{}q HI Q HI
3481 echo(hi)
3482 @result{}qHIQ
3483 changequote
3484 @result{}
3485 changequote(`-', `EOF')
3486 @result{}
3487 - hi EOF hi
3488 @result{} hi  HI
3489 changequote
3490 @result{}
3491 changequote(`1', `2')
3492 @result{}
3493 hi1hi2
3494 @result{}hi1hi2
3495 hi 1hi2
3496 @result{}HI hi
3497 @end example
3499 Quotes are recognized in preference to argument collection.  In
3500 particular, if @var{start} is a single @samp{(}, then argument
3501 collection is effectively disabled.  For portability with other
3502 implementations, it is a good idea to avoid @samp{(}, @samp{,}, and
3503 @samp{)} as the first character in @var{start}.
3505 @example
3506 define(`echo', `$#:$@@:')
3507 @result{}
3508 define(`hi', `HI')
3509 @result{}
3510 changequote(`(',`)')
3511 @result{}
3512 echo(hi)
3513 @result{}0::hi
3514 changequote
3515 @result{}
3516 changequote(`((', `))')
3517 @result{}
3518 echo(hi)
3519 @result{}1:HI:
3520 echo((hi))
3521 @result{}0::hi
3522 changequote
3523 @result{}
3524 changequote(`,', `)')
3525 @result{}
3526 echo(hi,hi)bye)
3527 @result{}1:HIhibye:
3528 @end example
3530 If @var{end} is a prefix of @var{start}, the end-quote will be
3531 recognized in preference to a nested begin-quote.  In particular,
3532 changing the quotes to have the same string for @var{start} and
3533 @var{end} disables nesting of quotes.  When quote nesting is disabled,
3534 it is impossible to double-quote strings across macro expansions, so
3535 using the same string is not done very often.
3537 @example
3538 define(`hi', `HI')
3539 @result{}
3540 changequote(`""', `"')
3541 @result{}
3542 ""hi"""hi"
3543 @result{}hihi
3544 ""hi" ""hi"
3545 @result{}hi hi
3546 ""hi"" "hi"
3547 @result{}hi" "HI"
3548 changequote
3549 @result{}
3550 `hi`hi'hi'
3551 @result{}hi`hi'hi
3552 changequote(`"', `"')
3553 @result{}
3554 "hi"hi"hi"
3555 @result{}hiHIhi
3556 @end example
3558 It is an error if the end of file occurs within a quoted string.
3560 @comment status: 1
3561 @example
3562 `hello world'
3563 @result{}hello world
3564 `dangling quote
3566 @error{}m4:stdin:2: ERROR: end of file in string
3567 @end example
3569 @node Changecom
3570 @section Changing the comment delimiters
3572 @cindex changing comment delimiters
3573 @cindex comment delimiters, changing
3574 @cindex delimiters, changing
3575 The default comment delimiters can be changed with the builtin
3576 macro @code{changecom}:
3578 @deffn Builtin changecom (@ovar{start}, @dvar{end, @key{NL}})
3579 This sets @var{start} as the new begin-comment delimiter and @var{end}
3580 as the new end-comment delimiter.  If both arguments are missing, or
3581 @var{start} is void, then comments are disabled.  Otherwise, if
3582 @var{end} is missing or void, the default end-comment delimiter of
3583 newline is used.  The comment delimiters can be of any length.
3585 The expansion of @code{changecom} is void.
3586 @end deffn
3588 @example
3589 define(`comment', `COMMENT')
3590 @result{}
3591 # A normal comment
3592 @result{}# A normal comment
3593 changecom(`/*', `*/')
3594 @result{}
3595 # Not a comment anymore
3596 @result{}# Not a COMMENT anymore
3597 But: /* this is a comment now */ while this is not a comment
3598 @result{}But: /* this is a comment now */ while this is not a COMMENT
3599 @end example
3601 @cindex comments, copied to output
3602 Note how comments are copied to the output, much as if they were quoted
3603 strings.  If you want the text inside a comment expanded, quote the
3604 begin-comment delimiter.
3606 Calling @code{changecom} without any arguments, or with @var{start} as
3607 the empty string, will effectively disable the commenting mechanism.  To
3608 restore the original comment start of @samp{#}, you must explicitly ask
3609 for it.  If @var{start} is not empty, then an empty @var{end} will use
3610 the default end-comment delimiter of newline, as otherwise, it would be
3611 impossible to end a comment.  However, this is not portable, as some
3612 other @code{m4} implementations preserve the previous non-empty
3613 delimiters instead.
3615 @example
3616 define(`comment', `COMMENT')
3617 @result{}
3618 changecom
3619 @result{}
3620 # Not a comment anymore
3621 @result{}# Not a COMMENT anymore
3622 changecom(`#', `')
3623 @result{}
3624 # comment again
3625 @result{}# comment again
3626 @end example
3628 The comment strings can safely contain eight-bit characters.
3629 @ignore
3630 @comment Yuck.  I know of no clean way to render an 8-bit character in
3631 @comment both info and dvi.  This example uses the `open-guillemot' and
3632 @comment `close-guillemot' characters of the Latin-1 character set.
3634 @example
3635 define(`a', `b')
3636 @result{}
3637 «a»
3638 @result{}«b»
3639 changecom(`«', `»')
3640 @result{}
3641 «a»
3642 @result{}«a»
3643 @end example
3644 @end ignore
3645 If no single character is appropriate, @var{start} and @var{end} can be
3646 of any length.  Other implementations cap the delimiter length to five
3647 characters, but @acronym{GNU} has no inherent limit.
3649 Comments are recognized in preference to macros.  However, this is not
3650 compatible with other implementations, where macros and even quoting
3651 takes precedence over comments, so it may change in a future release.
3652 For portability, this means that @var{start} should not begin with a
3653 letter, digit, or @samp{_} (underscore), and that neither the
3654 start-quote nor the start-comment string should be a prefix of the
3655 other.
3657 @example
3658 define(`hi', `HI')
3659 @result{}
3660 define(`hi1hi2', `hello')
3661 @result{}
3662 changecom(`q', `Q')
3663 @result{}
3664 q hi Q hi
3665 @result{}q hi Q HI
3666 changecom(`1', `2')
3667 @result{}
3668 hi1hi2
3669 @result{}hello
3670 hi 1hi2
3671 @result{}HI 1hi2
3672 @end example
3674 Comments are recognized in preference to argument collection.  In
3675 particular, if @var{start} is a single @samp{(}, then argument
3676 collection is effectively disabled.  For portability with other
3677 implementations, it is a good idea to avoid @samp{(}, @samp{,}, and
3678 @samp{)} as the first character in @var{start}.
3680 @example
3681 define(`echo', `$#:$@@:')
3682 @result{}
3683 define(`hi', `HI')
3684 @result{}
3685 changecom(`(',`)')
3686 @result{}
3687 echo(hi)
3688 @result{}0::(hi)
3689 changecom
3690 @result{}
3691 changecom(`((', `))')
3692 @result{}
3693 echo(hi)
3694 @result{}1:HI:
3695 echo((hi))
3696 @result{}0::((hi))
3697 changecom(`,', `)')
3698 @result{}
3699 echo(hi,hi)bye)
3700 @result{}1:HI,hi)bye:
3701 @end example
3703 It is an error if the end of file occurs within a comment.
3705 @comment status: 1
3706 @example
3707 changecom(`/*', `*/')
3708 @result{}
3709 /*dangling comment
3711 @error{}m4:stdin:2: ERROR: end of file in comment
3712 @end example
3714 @node Changeword
3715 @section Changing the lexical structure of words
3717 @cindex lexical structure of words
3718 @cindex words, lexical structure of
3719 @cindex syntax, changing
3720 @cindex changing syntax
3721 @cindex regular expressions
3722 @quotation
3723 The macro @code{changeword} and all associated functionality is
3724 experimental.  It is only available if the @option{--enable-changeword}
3725 option was given to @code{configure}, at @acronym{GNU} @code{m4} installation
3726 time.  The functionality will go away in the future, to be replaced by
3727 other new features that are more efficient at providing the same
3728 capabilities.  @emph{Do not rely on it}.  Please direct your comments
3729 about it the same way you would do for bugs.
3730 @end quotation
3732 A file being processed by @code{m4} is split into quoted strings, words
3733 (potential macro names) and simple tokens (any other single character).
3734 Initially a word is defined by the following regular expression:
3736 @comment ignore
3737 @example
3738 [_a-zA-Z][_a-zA-Z0-9]*
3739 @end example
3741 Using @code{changeword}, you can change this regular expression:
3743 @deffn {Optional builtin} changeword (@var{regex})
3744 Changes the regular expression for recognizing macro names to be
3745 @var{regex}.  If @var{regex} is empty, use
3746 @samp{[_a-zA-Z][_a-zA-Z0-9]*}.  @var{regex} must obey the constraint
3747 that every prefix of the desired final pattern is also accepted by the
3748 regular expression.  If @var{regex} contains grouping parentheses, the
3749 macro invoked is the portion that matched the first group, rather than
3750 the entire matching string.
3752 The expansion of @code{changeword} is void.
3753 The macro @code{changeword} is recognized only with parameters.
3754 @end deffn
3756 Relaxing the lexical rules of @code{m4} might be useful (for example) if
3757 you wanted to apply translations to a file of numbers:
3759 @example
3760 ifdef(`changeword', `', `errprint(` skipping: no changeword support
3761 ')m4exit(`77')')dnl
3762 changeword(`[_a-zA-Z0-9]+')
3763 @result{}
3764 define(`1', `0')1
3765 @result{}0
3766 @end example
3768 Tightening the lexical rules is less useful, because it will generally
3769 make some of the builtins unavailable.  You could use it to prevent
3770 accidental call of builtins, for example:
3772 @example
3773 ifdef(`changeword', `', `errprint(` skipping: no changeword support
3774 ')m4exit(`77')')dnl
3775 define(`_indir', defn(`indir'))
3776 @result{}
3777 changeword(`_[_a-zA-Z0-9]*')
3778 @result{}
3779 esyscmd(`foo')
3780 @result{}esyscmd(foo)
3781 _indir(`esyscmd', `echo hi')
3782 @result{}hi
3783 @result{}
3784 @end example
3786 Because @code{m4} constructs its words a character at a time, there
3787 is a restriction on the regular expressions that may be passed to
3788 @code{changeword}.  This is that if your regular expression accepts
3789 @samp{foo}, it must also accept @samp{f} and @samp{fo}.
3791 @example
3792 ifdef(`changeword', `', `errprint(` skipping: no changeword support
3793 ')m4exit(`77')')dnl
3794 define(`foo
3795 ', `bar
3797 @result{}
3798 dnl This example wants to recognize changeword, dnl, and `foo\n'.
3799 dnl First, we check that our regexp will match.
3800 regexp(`changeword', `[cd][a-z]*\|foo[
3802 @result{}0
3803 regexp(`foo
3804 ', `[cd][a-z]*\|foo[
3806 @result{}0
3807 regexp(`f', `[cd][a-z]*\|foo[
3809 @result{}-1
3811 @result{}foo
3812 changeword(`[cd][a-z]*\|foo[
3814 @result{}
3815 dnl Even though `foo\n' matches, we forgot to allow `f'.
3817 @result{}foo
3818 changeword(`[cd][a-z]*\|fo*[
3819 ]?')
3820 @result{}
3821 dnl Now we can call `foo\n'.
3823 @result{}bar
3824 @end example
3826 @ignore
3827 @comment One more test of including newline in a macro name; but this
3828 @comment does not need to be displayed in the manual.  This ensures
3829 @comment that line numbering is correct when dnl cuts across include
3830 @comment file boundaries, and when __file__ or __line__ is the last
3831 @comment token in an include file.
3833 @example
3834 ifdef(`changeword', `', `errprint(` skipping: no changeword support
3835 ')m4exit(`77')')dnl
3836 define(`bar
3837 ', defn(`dnl'))dnl
3838 define(`baz', `dnl
3839 include(`foo') ignored
3840 dnl')dnl
3841 changeword(`\([_a-zA-Z][_a-zA-Z0-9]*\|bar
3842 \)')
3843 @result{}
3844 __file__:__line__
3845 @result{}stdin:10
3846 include(`foo') ignored
3847 __file__:__line__
3848 @result{}stdin:12
3849 baz ignored
3850 __file__:__line__
3851 @result{}stdin:14
3852 define(`bar
3853 ', defn(`__file__'))
3854 @result{}
3855 include(`foo')
3856 @result{}../examples/foo
3857 define(`bar
3858 ', defn(`__line__'))
3859 @result{}
3860 include(`foo')
3861 @result{}1
3862 __file__:__line__
3863 @result{}stdin:21
3864 @end example
3865 @end ignore
3867 @code{changeword} has another function.  If the regular expression
3868 supplied contains any grouped subexpressions, then text outside
3869 the first of these is discarded before symbol lookup.  So:
3871 @example
3872 ifdef(`changeword', `', `errprint(` skipping: no changeword support
3873 ')m4exit(`77')')dnl
3874 ifdef(`__unix__', ,
3875       `errprint(` skipping: syscmd does not have unix semantics
3876 ')m4exit(`77')')dnl
3877 changecom(`/*', `*/')dnl
3878 define(`foo', `bar')dnl
3879 changeword(`#\([_a-zA-Z0-9]*\)')
3880 @result{}
3881 #esyscmd(`echo foo \#foo')
3882 @result{}foo bar
3883 @result{}
3884 @end example
3886 @code{m4} now requires a @samp{#} mark at the beginning of every
3887 macro invocation, so one can use @code{m4} to preprocess plain
3888 text without losing various words like @samp{divert}.
3890 In @code{m4}, macro substitution is based on text, while in @TeX{}, it
3891 is based on tokens.  @code{changeword} can throw this difference into
3892 relief.  For example, here is the same idea represented in @TeX{} and
3893 @code{m4}.  First, the @TeX{} version:
3895 @comment ignore
3896 @example
3897 \def\a@{\message@{Hello@}@}
3898 \catcode`\@@=0
3899 \catcode`\\=12
3901 @@bye
3902 @result{}Hello
3903 @end example
3905 @noindent
3906 Then, the @code{m4} version:
3908 @example
3909 ifdef(`changeword', `', `errprint(` skipping: no changeword support
3910 ')m4exit(`77')')dnl
3911 define(`a', `errprint(`Hello')')dnl
3912 changeword(`@@\([_a-zA-Z0-9]*\)')
3913 @result{}
3915 @result{}errprint(Hello)
3916 @end example
3918 In the @TeX{} example, the first line defines a macro @code{a} to
3919 print the message @samp{Hello}.  The second line defines @key{@@} to
3920 be usable instead of @key{\} as an escape character.  The third line
3921 defines @key{\} to be a normal printing character, not an escape.
3922 The fourth line invokes the macro @code{a}.  So, when @TeX{} is run
3923 on this file, it displays the message @samp{Hello}.
3925 When the @code{m4} example is passed through @code{m4}, it outputs
3926 @samp{errprint(Hello)}.  The reason for this is that @TeX{} does
3927 lexical analysis of macro definition when the macro is @emph{defined}.
3928 @code{m4} just stores the text, postponing the lexical analysis until
3929 the macro is @emph{used}.
3931 You should note that using @code{changeword} will slow @code{m4} down
3932 by a factor of about seven, once it is changed to something other
3933 than the default regular expression.  You can invoke @code{changeword}
3934 with the empty string to restore the default word definition, and regain
3935 the parsing speed.
3937 @node M4wrap
3938 @section Saving text until end of input
3940 @cindex saving input
3941 @cindex input, saving
3942 @cindex deferring expansion
3943 @cindex expansion, deferring
3944 It is possible to `save' some text until the end of the normal input has
3945 been seen.  Text can be saved, to be read again by @code{m4} when the
3946 normal input has been exhausted.  This feature is normally used to
3947 initiate cleanup actions before normal exit, e.g., deleting temporary
3948 files.
3950 To save input text, use the builtin @code{m4wrap}:
3952 @deffn Builtin m4wrap (@var{string}, @dots{})
3953 Stores @var{string} in a safe place, to be reread when end of input is
3954 reached.  As a @acronym{GNU} extension, additional arguments are
3955 concatenated with a space to the @var{string}.
3957 The expansion of @code{m4wrap} is void.
3958 The macro @code{m4wrap} is recognized only with parameters.
3959 @end deffn
3961 @example
3962 define(`cleanup', `This is the `cleanup' action.
3964 @result{}
3965 m4wrap(`cleanup')
3966 @result{}
3967 This is the first and last normal input line.
3968 @result{}This is the first and last normal input line.
3970 @result{}This is the cleanup action.
3971 @end example
3973 The saved input is only reread when the end of normal input is seen, and
3974 not if @code{m4exit} is used to exit @code{m4}.
3976 @comment FIXME: this contradicts POSIX, which requires that "If the
3977 @comment m4wrap macro is used multiple times, the arguments specified
3978 @comment shall be processed in the order in which the m4wrap macros were
3979 @comment processed."
3980 It is safe to call @code{m4wrap} from saved text, but then the order in
3981 which the saved text is reread is undefined.  If @code{m4wrap} is not used
3982 recursively, the saved pieces of text are reread in the opposite order
3983 in which they were saved (LIFO---last in, first out).  However, this
3984 behavior is likely to change in a future release, to match
3985 @acronym{POSIX}, so you should not depend on this order.
3987 Here is an example of implementing a factorial function using
3988 @code{m4wrap}:
3990 @example
3991 define(`f', `ifelse(`$1', `0', `Answer: 0!=1
3992 ', eval(`$1>1'), `0', `Answer: $2$1=eval(`$2$1')
3993 ', `m4wrap(`f(decr(`$1'), `$2$1*')')')')
3994 @result{}
3995 f(`10')
3996 @result{}
3998 @result{}Answer: 10*9*8*7*6*5*4*3*2*1=3628800
3999 @end example
4001 Invocations of @code{m4wrap} at the same recursion level are
4002 concatenated and rescanned as usual:
4004 @example
4005 define(`aa', `AA
4007 @result{}
4008 m4wrap(`a')m4wrap(`a')
4009 @result{}
4011 @result{}AA
4012 @end example
4014 @noindent
4015 however, the transition between recursion levels behaves like an end of
4016 file condition between two input files.
4018 @comment status: 1
4019 @example
4020 m4wrap(`m4wrap(`)')len(abc')
4021 @result{}
4023 @error{}m4:stdin:1: ERROR: end of file in argument list
4024 @end example
4026 @node File Inclusion
4027 @chapter File inclusion
4029 @cindex file inclusion
4030 @cindex inclusion, of files
4031 @code{m4} allows you to include named files at any point in the input.
4033 @menu
4034 * Include::                     Including named files
4035 * Search Path::                 Searching for include files
4036 @end menu
4038 @node Include
4039 @section Including named files
4041 There are two builtin macros in @code{m4} for including files:
4043 @deffn Builtin include (@var{file})
4044 @deffnx Builtin sinclude (@var{file})
4045 Both macros cause the file named @var{file} to be read by
4046 @code{m4}.  When the end of the file is reached, input is resumed from
4047 the previous input file.
4049 The expansion of @code{include} and @code{sinclude} is therefore the
4050 contents of @var{file}.
4052 If @var{file} does not exist (or cannot be read), the expansion is void,
4053 and @code{include} will fail with an error while @code{sinclude} is
4054 silent.  The empty string counts as a file that does not exist.
4056 The macros @code{include} and @code{sinclude} are recognized only with
4057 parameters.
4058 @end deffn
4060 @comment status: 1
4061 @example
4062 include(`none')
4063 @error{}m4:stdin:1: cannot open `none': No such file or directory
4064 @result{}
4065 include()
4066 @error{}m4:stdin:2: cannot open `': No such file or directory
4067 @result{}
4068 sinclude(`none')
4069 @result{}
4070 sinclude()
4071 @result{}
4072 @end example
4074 The rest of this section assumes that @code{m4} is invoked with the
4075 @option{-I} option (@pxref{Preprocessor features, , Invoking m4})
4076 pointing to the @file{m4-@value{VERSION}/@/examples}
4077 directory shipped as part of the @acronym{GNU} @code{m4} package.  The
4078 file @file{m4-@value{VERSION}/@/examples/@/incl.m4} in the distribution
4079 contains the lines:
4081 @comment ignore
4082 @example
4083 $ @kbd{cat examples/incl.m4}
4084 @result{}Include file start
4085 @result{}foo
4086 @result{}Include file end
4087 @end example
4089 Normally file inclusion is used to insert the contents of a file
4090 into the input stream.  The contents of the file will be read by
4091 @code{m4} and macro calls in the file will be expanded:
4093 @example
4094 $ @kbd{m4 -I examples}
4095 define(`foo', `FOO')
4096 @result{}
4097 include(`incl.m4')
4098 @result{}Include file start
4099 @result{}FOO
4100 @result{}Include file end
4101 @result{}
4102 @end example
4104 The fact that @code{include} and @code{sinclude} expand to the contents
4105 of the file can be used to define macros that operate on entire files.
4106 Here is an example, which defines @samp{bar} to expand to the contents
4107 of @file{incl.m4}:
4109 @example
4110 $ @kbd{m4 -I examples}
4111 define(`bar', include(`incl.m4'))
4112 @result{}
4113 This is `bar':  >>bar<<
4114 @result{}This is bar:  >>Include file start
4115 @result{}foo
4116 @result{}Include file end
4117 @result{}<<
4118 @end example
4120 This use of @code{include} is not trivial, though, as files can contain
4121 quotes, commas, and parentheses, which can interfere with the way the
4122 @code{m4} parser works.  @acronym{GNU} @code{m4} seamlessly concatenates
4123 the file contents with the next character, even if the included file
4124 ended in the middle of a comment, string, or macro call.  These
4125 conditions are only treated as end of file errors if specified as input
4126 files on the command line.
4128 In @acronym{GNU} @code{m4}, an alternative method of reading files is
4129 using @code{undivert} (@pxref{Undivert}) on a named file.
4131 @node Search Path
4132 @section Searching for include files
4134 @cindex search path for included files
4135 @cindex included files, search path for
4136 @cindex @acronym{GNU} extensions
4137 @acronym{GNU} @code{m4} allows included files to be found in other directories
4138 than the current working directory.
4140 @cindex @env{M4PATH}
4141 If the @option{--prepend-include} or @option{-B} command-line option was
4142 provided (@pxref{Preprocessor features, , Invoking m4}), those
4143 directories are searched first, in reverse order that those options were
4144 listed on the command line.  Then @code{m4} looks in the current working
4145 directory.  Next comes the directories specified with the
4146 @option{--include} or @option{-I} option, in the order found on the
4147 command line.  Finally, if the @env{M4PATH} environment variable is set,
4148 it is expected to contain a colon-separated list of directories, which
4149 will be searched in order.
4151 If the automatic search for include-files causes trouble, the @samp{p}
4152 debug flag (@pxref{Debug Levels}) can help isolate the problem.
4154 @node Diversions
4155 @chapter Diverting and undiverting output
4157 @cindex deferring output
4158 Diversions are a way of temporarily saving output.  The output of
4159 @code{m4} can at any time be diverted to a temporary file, and be
4160 reinserted into the output stream, @dfn{undiverted}, again at a later
4161 time.
4163 @cindex @env{TMPDIR}
4164 Numbered diversions are counted from 0 upwards, diversion number 0
4165 being the normal output stream.  The number of simultaneous diversions
4166 is limited mainly by the memory used to describe them, because @acronym{GNU}
4167 @code{m4} tries to keep diversions in memory.  However, there is a
4168 limit to the overall memory usable by all diversions taken altogether
4169 (512K, currently).  When this maximum is about to be exceeded,
4170 a temporary file is opened to receive the contents of the biggest
4171 diversion still in memory, freeing this memory for other diversions.
4172 When creating the temporary file, @code{m4} honors the value of the
4173 environment variable @env{TMPDIR}, and falls back to @file{/tmp}.
4174 So, it is theoretically possible that the number and aggregate size of
4175 diversions is limited only by available disk space.
4177 @ignore
4178 @comment We need to test spilled diversions, but don't need to expose
4179 @comment this highly repetitive test in the manual.
4181 @example
4182 divert(`-1')define(`f', `.')
4183 define(`f', defn(`f')defn(`f'))
4184 define(`f', defn(`f')defn(`f'))
4185 define(`f', defn(`f')defn(`f'))
4186 define(`f', defn(`f')defn(`f'))
4187 define(`f', defn(`f')defn(`f'))
4188 define(`f', defn(`f')defn(`f'))
4189 define(`f', defn(`f')defn(`f'))
4190 define(`f', defn(`f')defn(`f'))
4191 define(`f', defn(`f')defn(`f'))
4192 define(`f', defn(`f')defn(`f'))
4193 define(`f', defn(`f')defn(`f'))
4194 define(`f', defn(`f')defn(`f'))
4195 define(`f', defn(`f')defn(`f'))
4196 define(`f', defn(`f')defn(`f'))
4197 define(`f', defn(`f')defn(`f'))
4198 define(`f', defn(`f')defn(`f'))
4199 define(`f', defn(`f')defn(`f'))
4200 define(`f', defn(`f')defn(`f'))
4201 define(`f', defn(`f')defn(`f'))
4202 define(`f', defn(`f')defn(`f'))
4203 divert`'dnl
4204 len(f)
4205 @result{}1048576
4206 divert(`1')
4208 divert(`-1')undivert
4209 @end example
4211 @comment Another test of spilled diversions.
4213 @example
4214 divert(`-1')define(`f', `.')
4215 define(`f', defn(`f')defn(`f'))
4216 define(`f', defn(`f')defn(`f'))
4217 define(`f', defn(`f')defn(`f'))
4218 define(`f', defn(`f')defn(`f'))
4219 define(`f', defn(`f')defn(`f'))
4220 define(`f', defn(`f')defn(`f'))
4221 define(`f', defn(`f')defn(`f'))
4222 define(`f', defn(`f')defn(`f'))
4223 define(`f', defn(`f')defn(`f'))
4224 define(`f', defn(`f')defn(`f'))
4225 define(`f', defn(`f')defn(`f'))
4226 define(`f', defn(`f')defn(`f'))
4227 define(`f', defn(`f')defn(`f'))
4228 define(`f', defn(`f')defn(`f'))
4229 define(`f', defn(`f')defn(`f'))
4230 define(`f', defn(`f')defn(`f'))
4231 define(`f', defn(`f')defn(`f'))
4232 define(`f', defn(`f')defn(`f'))
4233 define(`f', defn(`f')defn(`f'))
4234 define(`f', defn(`f')defn(`f'))
4235 divert`'dnl
4236 len(f)
4237 @result{}1048576
4238 divert(`1')
4240 m4exit
4241 @end example
4242 @end ignore
4244 Diversions make it possible to generate output in a different order than
4245 the input was read.  It is possible to implement topological sorting
4246 dependencies.  For example, @acronym{GNU} Autoconf makes use of
4247 diversions under the hood to ensure that the expansion of a prerequisite
4248 macro appears in the output prior to the expansion of a dependent macro,
4249 regardless of which order the two macros were invoked in the user's
4250 input file.
4252 @menu
4253 * Divert::                      Diverting output
4254 * Undivert::                    Undiverting output
4255 * Divnum::                      Diversion numbers
4256 * Cleardivert::                 Discarding diverted text
4257 @end menu
4259 @node Divert
4260 @section Diverting output
4262 @cindex diverting output to files
4263 @cindex output, diverting to files
4264 @cindex files, diverting output to
4265 Output is diverted using @code{divert}:
4267 @deffn Builtin divert (@dvar{number, 0})
4268 The current diversion is changed to @var{number}.  If @var{number} is left
4269 out or empty, it is assumed to be zero.  If @var{number} cannot be
4270 parsed, the diversion is unchanged.
4272 The expansion of @code{divert} is void.
4273 @end deffn
4275 When all the @code{m4} input will have been processed, all existing
4276 diversions are automatically undiverted, in numerical order.
4278 @example
4279 divert(`1')
4280 This text is diverted.
4281 divert
4282 @result{}
4283 This text is not diverted.
4284 @result{}This text is not diverted.
4286 @result{}
4287 @result{}This text is diverted.
4288 @end example
4290 Several calls of @code{divert} with the same argument do not overwrite
4291 the previous diverted text, but append to it.  Diversions are printed
4292 after any wrapped text is expanded.
4294 @example
4295 define(`text', `TEXT')
4296 @result{}
4297 divert(`1')`diverted text.'
4298 divert
4299 @result{}
4300 m4wrap(`Wrapped text precedes ')
4301 @result{}
4303 @result{}Wrapped TEXT precedes diverted text.
4304 @end example
4306 @cindex discarding input
4307 @cindex input, discarding
4308 If output is diverted to a negative diversion, it is simply discarded.
4309 This can be used to suppress unwanted output.  A common example of
4310 unwanted output is the trailing newlines after macro definitions.  Here
4311 is a common programming idiom in @code{m4} for avoiding them.
4313 @example
4314 divert(`-1')
4315 define(`foo', `Macro `foo'.')
4316 define(`bar', `Macro `bar'.')
4317 divert
4318 @result{}
4319 @end example
4321 @cindex @acronym{GNU} extensions
4322 Traditional implementations only supported ten diversions.  But as a
4323 @acronym{GNU} extension, diversion numbers can be as large as positive
4324 integers will allow, rather than treating a multi-digit diversion number
4325 as a request to discard text.
4327 @example
4328 divert(eval(`1<<28'))world
4329 divert(`2')hello
4331 @result{}hello
4332 @result{}world
4333 @end example
4335 Note that @code{divert} is an English word, but also an active macro
4336 without arguments.  When processing plain text, the word might appear in
4337 normal text and be unintentionally swallowed as a macro invocation.  One
4338 way to avoid this is to use the @option{-P} option to rename all
4339 builtins (@pxref{Operation modes, , Invoking m4}).  Another is to write
4340 a wrapper that requires a parameter to be recognized.
4342 @example
4343 We decided to divert the stream for irrigation.
4344 @result{}We decided to  the stream for irrigation.
4345 define(`divert', `ifelse(`$#', `0', ``$0'', `builtin(`$0', $@@)')')
4346 @result{}
4347 divert(`-1')
4348 Ignored text.
4349 divert(`0')
4350 @result{}
4351 We decided to divert the stream for irrigation.
4352 @result{}We decided to divert the stream for irrigation.
4353 @end example
4355 @node Undivert
4356 @section Undiverting output
4358 Diverted text can be undiverted explicitly using the builtin
4359 @code{undivert}:
4361 @deffn Builtin undivert (@ovar{diversions@dots{}})
4362 Undiverts the numeric @var{diversions} given by the arguments, in the
4363 order given.  If no arguments are supplied, all diversions are
4364 undiverted, in numerical order.
4366 @cindex file inclusion
4367 @cindex inclusion, of files
4368 @cindex @acronym{GNU} extensions
4369 As a @acronym{GNU} extension, @var{diversions} may contain non-numeric
4370 strings, which are treated as the names of files to copy into the output
4371 without expansion.  A warning is issued if a file could not be opened.
4373 The expansion of @code{undivert} is void.
4374 @end deffn
4376 @example
4377 divert(`1')
4378 This text is diverted.
4379 divert
4380 @result{}
4381 This text is not diverted.
4382 @result{}This text is not diverted.
4383 undivert(`1')
4384 @result{}
4385 @result{}This text is diverted.
4386 @result{}
4387 @end example
4389 Notice the last two blank lines.  One of them comes from the newline
4390 following @code{undivert}, the other from the newline that followed the
4391 @code{divert}!  A diversion often starts with a blank line like this.
4393 When diverted text is undiverted, it is @emph{not} reread by @code{m4},
4394 but rather copied directly to the current output, and it is therefore
4395 not an error to undivert into a diversion.  Undiverting the empty string
4396 is the same as specifying diversion 0; in either case nothing happens
4397 since the output has already been flushed.
4399 @example
4400 divert(`1')diverted text
4401 divert
4402 @result{}
4403 undivert()
4404 @result{}
4405 undivert(`0')
4406 @result{}
4407 undivert
4408 @result{}diverted text
4409 @result{}
4410 @end example
4412 When a diversion has been undiverted, the diverted text is discarded,
4413 and it is not possible to bring back diverted text more than once.
4415 @example
4416 divert(`1')
4417 This text is diverted first.
4418 divert(`0')undivert(`1')dnl
4419 @result{}
4420 @result{}This text is diverted first.
4421 undivert(`1')
4422 @result{}
4423 divert(`1')
4424 This text is also diverted but not appended.
4425 divert(`0')undivert(`1')dnl
4426 @result{}
4427 @result{}This text is also diverted but not appended.
4428 @end example
4430 Attempts to undivert the current diversion are silently ignored.  Thus,
4431 when the current diversion is not 0, the current diversion does not get
4432 rearranged among the other diversions.
4434 @example
4435 divert(`1')one
4436 divert(`2')two
4437 divert(`3')three
4438 divert(`2')undivert`'dnl
4439 divert`'undivert`'dnl
4440 @result{}two
4441 @result{}one
4442 @result{}three
4443 @end example
4445 @cindex @acronym{GNU} extensions
4446 @cindex file inclusion
4447 @cindex inclusion, of files
4448 @acronym{GNU} @code{m4} allows named files to be undiverted.  Given a
4449 non-numeric argument, the contents of the file named will be copied,
4450 uninterpreted, to the current output.  This complements the builtin
4451 @code{include} (@pxref{Include}).  To illustrate the difference, assume
4452 the file @file{foo} contains:
4454 @comment ignore
4455 @example
4456 $ @kbd{cat foo}
4458 @end example
4460 @noindent
4461 then
4463 @example
4464 define(`bar', `BAR')
4465 @result{}
4466 undivert(`foo')
4467 @result{}bar
4468 @result{}
4469 include(`foo')
4470 @result{}BAR
4471 @result{}
4472 @end example
4474 If the file is not found (or cannot be read), an error message is
4475 issued, and the expansion is void.  It is possible to intermix files
4476 and diversion numbers.
4478 @example
4479 divert(`1')diversion one
4480 divert(`2')undivert(`foo')dnl
4481 divert(`3')diversion three
4482 divert`'dnl
4483 undivert(`1', `2', `foo', `3')dnl
4484 @result{}diversion one
4485 @result{}bar
4486 @result{}bar
4487 @result{}diversion three
4488 @end example
4490 @node Divnum
4491 @section Diversion numbers
4493 @cindex diversion numbers
4494 The current diversion is tracked by the builtin @code{divnum}:
4496 @deffn Builtin divnum
4497 Expands to the number of the current diversion.
4498 @end deffn
4500 @example
4501 Initial divnum
4502 @result{}Initial 0
4503 divert(`1')
4504 Diversion one: divnum
4505 divert(`2')
4506 Diversion two: divnum
4508 @result{}
4509 @result{}Diversion one: 1
4510 @result{}
4511 @result{}Diversion two: 2
4512 @end example
4514 @node Cleardivert
4515 @section Discarding diverted text
4517 @cindex discarding diverted text
4518 @cindex diverted text, discarding
4519 Often it is not known, when output is diverted, whether the diverted
4520 text is actually needed.  Since all non-empty diversion are brought back
4521 on the main output stream when the end of input is seen, a method of
4522 discarding a diversion is needed.  If all diversions should be
4523 discarded, the easiest is to end the input to @code{m4} with
4524 @samp{divert(`-1')} followed by an explicit @samp{undivert}:
4526 @example
4527 divert(`1')
4528 Diversion one: divnum
4529 divert(`2')
4530 Diversion two: divnum
4531 divert(`-1')
4532 undivert
4534 @end example
4536 @noindent
4537 No output is produced at all.
4539 Clearing selected diversions can be done with the following macro:
4541 @deffn Composite cleardivert (@ovar{diversions@dots{}})
4542 Discard the contents of each of the listed numeric @var{diversions}.
4543 @end deffn
4545 @example
4546 define(`cleardivert',
4547 `pushdef(`_n', divnum)divert(`-1')undivert($@@)divert(_n)popdef(`_n')')
4548 @result{}
4549 @end example
4551 It is called just like @code{undivert}, but the effect is to clear the
4552 diversions, given by the arguments.  (This macro has a nasty bug!  You
4553 should try to see if you can find it and correct it; or @pxref{Improved
4554 cleardivert, , Answers}).
4556 @node Text handling
4557 @chapter Macros for text handling
4559 There are a number of builtins in @code{m4} for manipulating text in
4560 various ways, extracting substrings, searching, substituting, and so on.
4562 @menu
4563 * Len::                         Calculating length of strings
4564 * Index macro::                 Searching for substrings
4565 * Regexp::                      Searching for regular expressions
4566 * Substr::                      Extracting substrings
4567 * Translit::                    Translating characters
4568 * Patsubst::                    Substituting text by regular expression
4569 * Format::                      Formatting strings (printf-like)
4570 @end menu
4572 @node Len
4573 @section Calculating length of strings
4575 @cindex length of strings
4576 @cindex strings, length of
4577 The length of a string can be calculated by @code{len}:
4579 @deffn Builtin len (@var{string})
4580 Expands to the length of @var{string}, as a decimal number.
4582 The macro @code{len} is recognized only with parameters.
4583 @end deffn
4585 @example
4586 len()
4587 @result{}0
4588 len(`abcdef')
4589 @result{}6
4590 @end example
4592 @node Index macro
4593 @section Searching for substrings
4595 @cindex substrings, locating
4596 Searching for substrings is done with @code{index}:
4598 @deffn Builtin index (@var{string}, @var{substring})
4599 Expands to the index of the first occurrence of @var{substring} in
4600 @var{string}.  The first character in @var{string} has index 0.  If
4601 @var{substring} does not occur in @var{string}, @code{index} expands to
4602 @samp{-1}.
4604 The macro @code{index} is recognized only with parameters.
4605 @end deffn
4607 @example
4608 index(`gnus, gnats, and armadillos', `nat')
4609 @result{}7
4610 index(`gnus, gnats, and armadillos', `dag')
4611 @result{}-1
4612 @end example
4614 Omitting @var{substring} evokes a warning, but still produces output;
4615 contrast this with an empty @var{substring}.
4617 @example
4618 index(`abc')
4619 @error{}m4:stdin:1: Warning: too few arguments to builtin `index'
4620 @result{}0
4621 index(`abc', `')
4622 @result{}0
4623 index(`abc', `b')
4624 @result{}1
4625 @end example
4627 @node Regexp
4628 @section Searching for regular expressions
4630 @cindex basic regular expressions
4631 @cindex regular expressions
4632 @cindex expressions, regular
4633 @cindex @acronym{GNU} extensions
4634 Searching for regular expressions is done with the builtin
4635 @code{regexp}:
4637 @deffn Builtin regexp (@var{string}, @var{regexp}, @ovar{replacement})
4638 Searches for @var{regexp} in @var{string}.  The syntax for regular
4639 expressions is the same as in @acronym{GNU} Emacs, which is similar to
4640 @acronym{BRE, Basic Regular Expressions} in @acronym{POSIX}.
4641 @ifnothtml
4642 @xref{Regexps, , Syntax of Regular Expressions, emacs, The GNU Emacs
4643 Manual}.
4644 @end ifnothtml
4645 @ifhtml
4647 @uref{http://www.gnu.org/@/software/@/emacs/@/manual/@/emacs.html#Regexps,
4648 Syntax of Regular Expressions} in the @acronym{GNU} Emacs Manual.
4649 @end ifhtml
4650 Support for @acronym{ERE, Extended Regular Expressions} is not
4651 available, but will be added in @acronym{GNU} M4 2.0.
4653 If @var{replacement} is omitted, @code{regexp} expands to the index of
4654 the first match of @var{regexp} in @var{string}.  If @var{regexp} does
4655 not match anywhere in @var{string}, it expands to -1.
4657 If @var{replacement} is supplied, and there was a match, @code{regexp}
4658 changes the expansion to this argument, with @samp{\@var{n}} substituted
4659 by the text matched by the @var{n}th parenthesized sub-expression of
4660 @var{regexp}, up to nine sub-expressions.  The escape @samp{\&} is
4661 replaced by the text of the entire regular expression matched.  For
4662 all other characters, @samp{\} treats the next character literally.  A
4663 warning is issued if there were fewer sub-expressions than the
4664 @samp{\@var{n}} requested, or if there is a trailing @samp{\}.  If there
4665 was no match, @code{regexp} expands to the empty string.
4667 The macro @code{regexp} is recognized only with parameters.
4668 @end deffn
4670 @example
4671 regexp(`GNUs not Unix', `\<[a-z]\w+')
4672 @result{}5
4673 regexp(`GNUs not Unix', `\<Q\w*')
4674 @result{}-1
4675 regexp(`GNUs not Unix', `\w\(\w+\)$', `*** \& *** \1 ***')
4676 @result{}*** Unix *** nix ***
4677 regexp(`GNUs not Unix', `\<Q\w*', `*** \& *** \1 ***')
4678 @result{}
4679 @end example
4681 Here are some more examples on the handling of backslash:
4683 @example
4684 regexp(`abc', `\(b\)', `\\\10\a')
4685 @result{}\b0a
4686 regexp(`abc', `b', `\1\')
4687 @error{}m4:stdin:2: Warning: sub-expression 1 not present
4688 @error{}m4:stdin:2: Warning: trailing \ ignored in replacement
4689 @result{}
4690 regexp(`abc', `\(\(d\)?\)\(c\)', `\1\2\3\4\5\6')
4691 @error{}m4:stdin:3: Warning: sub-expression 4 not present
4692 @error{}m4:stdin:3: Warning: sub-expression 5 not present
4693 @error{}m4:stdin:3: Warning: sub-expression 6 not present
4694 @result{}c
4695 @end example
4697 Omitting @var{regexp} evokes a warning, but still produces output;
4698 contrast this with an empty @var{regexp} argument.
4700 @example
4701 regexp(`abc')
4702 @error{}m4:stdin:1: Warning: too few arguments to builtin `regexp'
4703 @result{}0
4704 regexp(`abc', `')
4705 @result{}0
4706 regexp(`abc', `', `\\def')
4707 @result{}\def
4708 @end example
4710 @node Substr
4711 @section Extracting substrings
4713 @cindex extracting substrings
4714 @cindex substrings, extracting
4715 Substrings are extracted with @code{substr}:
4717 @deffn Builtin substr (@var{string}, @var{from}, @ovar{length})
4718 Expands to the substring of @var{string}, which starts at index
4719 @var{from}, and extends for @var{length} characters, or to the end of
4720 @var{string}, if @var{length} is omitted.  The starting index of a string
4721 is always 0.  The expansion is empty if there is an error parsing
4722 @var{from} or @var{length}, if @var{from} is beyond the end of
4723 @var{string}, or if @var{length} is negative.
4725 The macro @code{substr} is recognized only with parameters.
4726 @end deffn
4728 @example
4729 substr(`gnus, gnats, and armadillos', `6')
4730 @result{}gnats, and armadillos
4731 substr(`gnus, gnats, and armadillos', `6', `5')
4732 @result{}gnats
4733 @end example
4735 Omitting @var{from} evokes a warning, but still produces output.
4737 @example
4738 substr(`abc')
4739 @error{}m4:stdin:1: Warning: too few arguments to builtin `substr'
4740 @result{}abc
4741 substr(`abc',)
4742 @error{}m4:stdin:2: empty string treated as 0 in builtin `substr'
4743 @result{}abc
4744 @end example
4746 @node Translit
4747 @section Translating characters
4749 @cindex translating characters
4750 @cindex characters, translating
4751 Character translation is done with @code{translit}:
4753 @deffn Builtin translit (@var{string}, @var{chars}, @ovar{replacement})
4754 Expands to @var{string}, with each character that occurs in
4755 @var{chars} translated into the character from @var{replacement} with
4756 the same index.
4758 If @var{replacement} is shorter than @var{chars}, the excess characters
4759 of @var{chars} are deleted from the expansion; if @var{chars} is
4760 shorter, the excess characters in @var{replacement} are silently
4761 ignored.  If @var{replacement} is omitted, all characters in
4762 @var{string} that are present in @var{chars} are deleted from the
4763 expansion.  If a character appears more than once in @var{chars}, only
4764 the first instance is used in making the translation.  Only a single
4765 translation pass is made, even if characters in @var{replacement} also
4766 appear in @var{chars}.
4768 As a @acronym{GNU} extension, both @var{chars} and @var{replacement} can
4769 contain character-ranges, e.g., @samp{a-z} (meaning all lowercase
4770 letters) or @samp{0-9} (meaning all digits).  To include a dash @samp{-}
4771 in @var{chars} or @var{replacement}, place it first or last in the
4772 entire string, or as the last character of a range.  Back-to-back ranges
4773 can share a common endpoint.  It is not an error for the last character
4774 in the range to be `larger' than the first.  In that case, the range
4775 runs backwards, i.e., @samp{9-0} means the string @samp{9876543210}.
4776 The expansion of a range is dependent on the underlying encoding of
4777 characters, so using ranges is not always portable between machines.
4779 The macro @code{translit} is recognized only with parameters.
4780 @end deffn
4782 @example
4783 translit(`GNUs not Unix', `A-Z')
4784 @result{}s not nix
4785 translit(`GNUs not Unix', `a-z', `A-Z')
4786 @result{}GNUS NOT UNIX
4787 translit(`GNUs not Unix', `A-Z', `z-a')
4788 @result{}tmfs not fnix
4789 translit(`+,-12345', `+--1-5', `<;>a-c-a')
4790 @result{}<;>abcba
4791 translit(`abcdef', `aabdef', `bcged')
4792 @result{}bgced
4793 @end example
4795 In the @sc{ascii} encoding, the first example deletes all uppercase
4796 letters, the second converts lowercase to uppercase, and the third
4797 `mirrors' all uppercase letters, while converting them to lowercase.
4798 The two first cases are by far the most common, even though they are not
4799 portable to @sc{ebcdic} or other encodings.  The fourth example shows a
4800 range ending in @samp{-}, as well as back-to-back ranges.  The final
4801 example shows that @samp{a} is mapped to @samp{b}, not @samp{c}; the
4802 resulting @samp{b} is not further remapped to @samp{g}; the @samp{d} and
4803 @samp{e} are swapped, and the @samp{f} is discarded.
4805 @ignore
4806 @comment No need to fight 8-bit characters, as it is difficult to get
4807 @comment rendering right in both info and dvi.
4809 @example
4810 translit(`«abc~', `~-»')
4811 @result{}abc
4812 @end example
4813 @end ignore
4815 Omitting @var{chars} evokes a warning, but still produces output.
4817 @example
4818 translit(`abc')
4819 @error{}m4:stdin:1: Warning: too few arguments to builtin `translit'
4820 @result{}abc
4821 @end example
4823 @node Patsubst
4824 @section Substituting text by regular expression
4826 @cindex basic regular expressions
4827 @cindex regular expressions
4828 @cindex expressions, regular
4829 @cindex pattern substitution
4830 @cindex substitution by regular expression
4831 @cindex @acronym{GNU} extensions
4832 Global substitution in a string is done by @code{patsubst}:
4834 @deffn Builtin patsubst (@var{string}, @var{regexp}, @ovar{replacement})
4835 Searches @var{string} for matches of @var{regexp}, and substitutes
4836 @var{replacement} for each match.  The syntax for regular expressions
4837 is the same as in @acronym{GNU} Emacs (@pxref{Regexp}).
4839 The parts of @var{string} that are not covered by any match of
4840 @var{regexp} are copied to the expansion.  Whenever a match is found, the
4841 search proceeds from the end of the match, so a character from
4842 @var{string} will never be substituted twice.  If @var{regexp} matches a
4843 string of zero length, the start position for the search is incremented,
4844 to avoid infinite loops.
4846 When a replacement is to be made, @var{replacement} is inserted into
4847 the expansion, with @samp{\@var{n}} substituted by the text matched by
4848 the @var{n}th parenthesized sub-expression of @var{patsubst}, for up to
4849 nine sub-expressions.  The escape @samp{\&} is replaced by the text of
4850 the entire regular expression matched.  For all other characters,
4851 @samp{\} treats the next character literally.  A warning is issued if
4852 there were fewer sub-expressions than the @samp{\@var{n}} requested, or
4853 if there is a trailing @samp{\}.
4855 The @var{replacement} argument can be omitted, in which case the text
4856 matched by @var{regexp} is deleted.
4858 The macro @code{patsubst} is recognized only with parameters.
4859 @end deffn
4861 @example
4862 patsubst(`GNUs not Unix', `^', `OBS: ')
4863 @result{}OBS: GNUs not Unix
4864 patsubst(`GNUs not Unix', `\<', `OBS: ')
4865 @result{}OBS: GNUs OBS: not OBS: Unix
4866 patsubst(`GNUs not Unix', `\w*', `(\&)')
4867 @result{}(GNUs)() (not)() (Unix)()
4868 patsubst(`GNUs not Unix', `\w+', `(\&)')
4869 @result{}(GNUs) (not) (Unix)
4870 patsubst(`GNUs not Unix', `[A-Z][a-z]+')
4871 @result{}GN not@w{ }
4872 patsubst(`GNUs not Unix', `not', `NOT\')
4873 @error{}m4:stdin:6: Warning: trailing \ ignored in replacement
4874 @result{}GNUs NOT Unix
4875 @end example
4877 Here is a slightly more realistic example, which capitalizes individual
4878 words or whole sentences, by substituting calls of the macros
4879 @code{upcase} and @code{downcase} into the strings.
4881 @deffn Composite upcase (@var{text})
4882 @deffnx Composite downcase (@var{text})
4883 @deffnx Composite capitalize (@var{text})
4884 Expand to @var{text}, but with capitalization changed: @code{upcase}
4885 changes all letters to upper case, @code{downcase} changes all letters
4886 to lower case, and @code{capitalize} changes the first character of each
4887 word to upper case and the remaining characters to lower case.
4888 @end deffn
4890 First, an example of their usage, using implementations distributed in
4891 @file{m4-@value{VERSION}/@/examples/@/capitalize.m4}.
4893 @example
4894 $ @kbd{m4 -I examples}
4895 include(`capitalize.m4')
4896 @result{}
4897 upcase(`GNUs not Unix')
4898 @result{}GNUS NOT UNIX
4899 downcase(`GNUs not Unix')
4900 @result{}gnus not unix
4901 capitalize(`GNUs not Unix')
4902 @result{}Gnus Not Unix
4903 @end example
4905 Now for the implementation.  There is a helper macro @code{_capitalize}
4906 which puts only its first word in mixed case.  Then @code{capitalize}
4907 merely parses out the words, and replaces them with an invocation of
4908 @code{_capitalize}.  (As presented here, the @code{capitalize} macro has
4909 some subtle flaws.  You should try to see if you can find and correct
4910 them; or @pxref{Improved capitalize, , Answers}).
4912 @example
4913 $ @kbd{m4 -I examples}
4914 undivert(`capitalize.m4')dnl
4915 @result{}divert(`-1')
4916 @result{}# upcase(text)
4917 @result{}# downcase(text)
4918 @result{}# capitalize(text)
4919 @result{}#   change case of text, simple version
4920 @result{}define(`upcase', `translit(`$*', `a-z', `A-Z')')
4921 @result{}define(`downcase', `translit(`$*', `A-Z', `a-z')')
4922 @result{}define(`_capitalize',
4923 @result{}       `regexp(`$1', `^\(\w\)\(\w*\)',
4924 @result{}               `upcase(`\1')`'downcase(`\2')')')
4925 @result{}define(`capitalize', `patsubst(`$1', `\w+', `_$0(`\&')')')
4926 @result{}divert`'dnl
4927 @end example
4929 While @code{regexp} replaces the whole input with the replacement as
4930 soon as there is a match, @code{patsubst} replaces each
4931 @emph{occurrence} of a match and preserves non-matching pieces:
4933 @example
4934 define(`patreg',
4935 `patsubst($@@)
4936 regexp($@@)')dnl
4937 patreg(`bar foo baz Foo', `foo\|Foo', `FOO')
4938 @result{}bar FOO baz FOO
4939 @result{}FOO
4940 patreg(`aba abb 121', `\(.\)\(.\)\1', `\2\1\2')
4941 @result{}bab abb 212
4942 @result{}bab
4943 @end example
4945 Omitting @var{regexp} evokes a warning, but still produces output;
4946 contrast this with an empty @var{regexp} argument.
4948 @example
4949 patsubst(`abc')
4950 @error{}m4:stdin:1: Warning: too few arguments to builtin `patsubst'
4951 @result{}abc
4952 patsubst(`abc', `')
4953 @result{}abc
4954 patsubst(`abc', `', `\\-')
4955 @result{}\-a\-b\-c\-
4956 @end example
4958 @node Format
4959 @section Formatting strings (printf-like)
4961 @cindex formatted output
4962 @cindex output, formatted
4963 @cindex @acronym{GNU} extensions
4964 Formatted output can be made with @code{format}:
4966 @deffn Builtin format (@var{format-string}, @dots{})
4967 Works much like the C function @code{printf}.  The first argument
4968 @var{format-string} can contain @samp{%} specifications which are
4969 satisfied by additional arguments, and the expansion of @code{format} is
4970 the formatted string.
4972 The macro @code{format} is recognized only with parameters.
4973 @end deffn
4975 Its use is best described by a few examples:
4977 @comment This test is a bit fragile, if someone tries to port to a
4978 @comment platform without infinity.
4979 @example
4980 define(`foo', `The brown fox jumped over the lazy dog')
4981 @result{}
4982 format(`The string "%s" uses %d characters', foo, len(foo))
4983 @result{}The string "The brown fox jumped over the lazy dog" uses 38 characters
4984 format(`%*.*d', `-1', `-1', `1')
4985 @result{}1
4986 format(`%.0f', `56789.9876')
4987 @result{}56790
4988 len(format(`%-*X', `5000', `1'))
4989 @result{}5000
4990 ifelse(format(`%010F', `infinity'), `       INF', `success',
4991        format(`%010F', `infinity'), `  INFINITY', `success',
4992        format(`%010F', `infinity'))
4993 @result{}success
4994 ifelse(format(`%.1A', `1.999'), `0X1.0P+1', `success',
4995        format(`%.1A', `1.999'), `0X2.0P+0', `success',
4996        format(`%.1A', `1.999'))
4997 @result{}success
4998 @end example
5000 Using the @code{forloop} macro defined earlier (@pxref{Forloop}), this
5001 example shows how @code{format} can be used to produce tabular output.
5003 @example
5004 $ @kbd{m4 -I examples}
5005 include(`forloop.m4')
5006 @result{}
5007 forloop(`i', `1', `10', `format(`%6d squared is %10d
5008 ', i, eval(i**2))')
5009 @result{}     1 squared is          1
5010 @result{}     2 squared is          4
5011 @result{}     3 squared is          9
5012 @result{}     4 squared is         16
5013 @result{}     5 squared is         25
5014 @result{}     6 squared is         36
5015 @result{}     7 squared is         49
5016 @result{}     8 squared is         64
5017 @result{}     9 squared is         81
5018 @result{}    10 squared is        100
5019 @result{}
5020 @end example
5022 The builtin @code{format} is modeled after the ANSI C @samp{printf}
5023 function, and supports these @samp{%} specifiers: @samp{c}, @samp{s},
5024 @samp{d}, @samp{o}, @samp{x}, @samp{X}, @samp{u}, @samp{a}, @samp{A},
5025 @samp{e}, @samp{E}, @samp{f}, @samp{F}, @samp{g}, @samp{G}, and
5026 @samp{%}; it supports field widths and precisions, and the flags
5027 @samp{+}, @samp{-}, @samp{ }, @samp{0}, @samp{#}, and @samp{'}.  For
5028 integer specifiers, the width modifiers @samp{hh}, @samp{h}, and
5029 @samp{l} are recognized, and for floating point specifiers, the width
5030 modifier @samp{l} is recognized.  Items not yet supported include
5031 positional arguments, the @samp{n}, @samp{p}, @samp{S}, and @samp{C}
5032 specifiers, the @samp{z}, @samp{t}, @samp{j}, @samp{L} and @samp{ll}
5033 modifiers, and any platform extensions available in the native
5034 @code{printf}.  For more details on the functioning of @code{printf},
5035 see the C Library Manual, or the @acronym{POSIX} specification (for
5036 example, @samp{%a} is supported even on platforms that haven't yet
5037 implemented C99 hexadecimal floating point output natively).
5039 Unrecognized specifiers result in a warning.  It is anticipated that a
5040 future release of @acronym{GNU} @code{m4} will support more specifiers,
5041 and give better warnings when various problems such as overflow are
5042 encountered.  Likewise, escape sequences are not yet recognized.
5044 @example
5045 format(`%p', `0')
5046 @error{}m4:stdin:1: Warning: unrecognized specifier in `%p'
5047 @result{}
5048 @end example
5050 @node Arithmetic
5051 @chapter Macros for doing arithmetic
5053 @cindex arithmetic
5054 @cindex integer arithmetic
5055 Integer arithmetic is included in @code{m4}, with a C-like syntax.  As
5056 convenient shorthands, there are builtins for simple increment and
5057 decrement operations.
5059 @menu
5060 * Incr::                        Decrement and increment operators
5061 * Eval::                        Evaluating integer expressions
5062 @end menu
5064 @node Incr
5065 @section Decrement and increment operators
5067 @cindex decrement operator
5068 @cindex increment operator
5069 Increment and decrement of integers are supported using the builtins
5070 @code{incr} and @code{decr}:
5072 @deffn Builtin incr (@var{number})
5073 @deffnx Builtin decr (@var{number})
5074 Expand to the numerical value of @var{number}, incremented
5075 or decremented, respectively, by one.  Except for the empty string, the
5076 expansion is empty if @var{number} could not be parsed.
5078 The macros @code{incr} and @code{decr} are recognized only with
5079 parameters.
5080 @end deffn
5082 @example
5083 incr(`4')
5084 @result{}5
5085 decr(`7')
5086 @result{}6
5087 incr()
5088 @error{}m4:stdin:3: empty string treated as 0 in builtin `incr'
5089 @result{}1
5090 decr()
5091 @error{}m4:stdin:4: empty string treated as 0 in builtin `decr'
5092 @result{}-1
5093 @end example
5095 @node Eval
5096 @section Evaluating integer expressions
5098 @cindex integer expression evaluation
5099 @cindex evaluation, of integer expressions
5100 @cindex expressions, evaluation of integer
5101 Integer expressions are evaluated with @code{eval}:
5103 @deffn Builtin eval (@var{expression}, @dvar{radix, 10}, @ovar{width})
5104 Expands to the value of @var{expression}.  The expansion is empty
5105 if a problem is encountered while parsing the arguments.  If specified,
5106 @var{radix} and @var{width} control the format of the output.
5108 Calculations are done with 32-bit signed numbers.  Overflow silently
5109 results in wraparound.  A warning is issued if division by zero is
5110 attempted, or if @var{expression} could not be parsed.
5112 Expressions can contain the following operators, listed in order of
5113 decreasing precedence.
5115 @table @samp
5116 @item ()
5117 Parentheses
5118 @item +  -  ~  !
5119 Unary plus and minus, and bitwise and logical negation
5120 @item **
5121 Exponentiation
5122 @item *  /  %
5123 Multiplication, division, and modulo
5124 @item +  -
5125 Addition and subtraction
5126 @item <<  >>
5127 Shift left or right
5128 @item >  >=  <  <=
5129 Relational operators
5130 @item ==  !=
5131 Equality operators
5132 @item &
5133 Bitwise and
5134 @item ^
5135 Bitwise exclusive-or
5136 @item |
5137 Bitwise or
5138 @item &&
5139 Logical and
5140 @item ||
5141 Logical or
5142 @end table
5144 The macro @code{eval} is recognized only with parameters.
5145 @end deffn
5147 All binary operators, except exponentiation, are left associative.  C
5148 operators that perform variable assignment, such as @samp{+=} or
5149 @samp{--}, are not implemented, since @code{eval} only operates on
5150 constants, not variables.  Attempting to use them results in an error.
5151 However, since traditional implementations treated @samp{=} as an
5152 undocumented alias for @samp{==} as opposed to an assignment operator,
5153 this usage is supported as a special case.  Be aware that a future
5154 version of @acronym{GNU} M4 may support assignment semantics as an
5155 extension when @acronym{POSIX} mode is not requested, and that using
5156 @samp{=} to check equality is not portable.
5158 @comment status: 1
5159 @example
5160 eval(`2 = 2')
5161 @error{}m4:stdin:1: Warning: recommend ==, not =, for equality operator
5162 @result{}1
5163 eval(`++0')
5164 @error{}m4:stdin:2: invalid operator in eval: ++0
5165 @result{}
5166 eval(`0 |= 1')
5167 @error{}m4:stdin:3: invalid operator in eval: 0 |= 1
5168 @result{}
5169 @end example
5171 Note that some older @code{m4} implementations use @samp{^} as an
5172 alternate operator for the exponentiation, although @acronym{POSIX}
5173 requires the C behavior of bitwise exclusive-or.  The precedence of the
5174 negation operators, @samp{~} and @samp{!}, was traditionally lower than
5175 equality.  The unary operators could not be used reliably more than once
5176 on the same term without intervening parentheses.  The traditional
5177 precedence of the equality operators @samp{==} and @samp{!=} was
5178 identical instead of lower than the relational operators such as
5179 @samp{<}, even through @acronym{GNU} M4 1.4.8.  Starting with version
5180 1.4.9, @acronym{GNU} M4 correctly follows @acronym{POSIX} precedence
5181 rules.  M4 scripts designed to be portable between releases must be
5182 aware that parentheses may be required to enforce C precedence rules.
5183 Likewise, division by zero, even in the unused branch of a
5184 short-circuiting operator, is not always well-defined in other
5185 implementations.
5187 Following are some examples where the current version of M4 follows C
5188 precedence rules, but where older versions and some other
5189 implementations of @code{m4} require explicit parentheses to get the
5190 correct result:
5192 @example
5193 eval(`1 == 2 > 0')
5194 @result{}1
5195 eval(`(1 == 2) > 0')
5196 @result{}0
5197 eval(`! 0 * 2')
5198 @result{}2
5199 eval(`! (0 * 2)')
5200 @result{}1
5201 eval(`1 | 1 ^ 1')
5202 @result{}1
5203 eval(`(1 | 1) ^ 1')
5204 @result{}0
5205 eval(`+ + - ~ ! ~ 0')
5206 @result{}1
5207 eval(`2 || 1 / 0')
5208 @result{}1
5209 eval(`0 || 1 / 0')
5210 @error{}m4:stdin:9: divide by zero in eval: 0 || 1 / 0
5211 @result{}
5212 eval(`0 && 1 % 0')
5213 @result{}0
5214 eval(`2 && 1 % 0')
5215 @error{}m4:stdin:11: modulo by zero in eval: 2 && 1 % 0
5216 @result{}
5217 @end example
5219 @cindex @acronym{GNU} extensions
5220 As a @acronym{GNU} extension, the operator @samp{**} performs integral
5221 exponentiation.  The operator is right-associative, and if evaluated,
5222 the exponent must be non-negative, and at least one of the arguments
5223 must be non-zero, or a warning is issued.
5225 @example
5226 eval(`2 ** 3 ** 2')
5227 @result{}512
5228 eval(`(2 ** 3) ** 2')
5229 @result{}64
5230 eval(`0 ** 1')
5231 @result{}0
5232 eval(`2 ** 0')
5233 @result{}1
5234 eval(`0 ** 0')
5235 @result{}
5236 @error{}m4:stdin:5: divide by zero in eval: 0 ** 0
5237 eval(`4 ** -2')
5238 @error{}m4:stdin:6: negative exponent in eval: 4 ** -2
5239 @result{}
5240 @end example
5242 Within @var{expression}, (but not @var{radix} or @var{width}), numbers
5243 without a special prefix are decimal.  A simple @samp{0} prefix
5244 introduces an octal number.  @samp{0x} introduces a hexadecimal number.
5245 As @acronym{GNU} extensions, @samp{0b} introduces a binary number.
5246 @samp{0r} introduces a number expressed in any radix between 1 and 36:
5247 the prefix should be immediately followed by the decimal expression of
5248 the radix, a colon, then the digits making the number.  For radix 1,
5249 leading zeros are ignored, and all remaining digits must be @samp{1};
5250 for all other radices, the digits are @samp{0}, @samp{1}, @samp{2},
5251 @dots{}.  Beyond @samp{9}, the digits are @samp{a}, @samp{b} @dots{} up
5252 to @samp{z}.  Lower and upper case letters can be used interchangeably
5253 in numbers prefixes and as number digits.
5255 Parentheses may be used to group subexpressions whenever needed.  For the
5256 relational operators, a true relation returns @code{1}, and a false
5257 relation return @code{0}.
5259 Here are a few examples of use of @code{eval}.
5261 @example
5262 eval(`-3 * 5')
5263 @result{}-15
5264 eval(`-99 / 10')
5265 @result{}-9
5266 eval(`-99 % 10')
5267 @result{}-9
5268 eval(`99 % -10')
5269 @result{}9
5270 eval(index(`Hello world', `llo') >= 0)
5271 @result{}1
5272 eval(`0r1:0111 + 0b100 + 0r3:12')
5273 @result{}12
5274 define(`square', `eval(`($1) ** 2')')
5275 @result{}
5276 square(`9')
5277 @result{}81
5278 square(square(`5')` + 1')
5279 @result{}676
5280 define(`foo', `666')
5281 @result{}
5282 eval(`foo / 6')
5283 @error{}m4:stdin:11: bad expression in eval: foo / 6
5284 @result{}
5285 eval(foo / 6)
5286 @result{}111
5287 @end example
5289 As the last two lines show, @code{eval} does not handle macro
5290 names, even if they expand to a valid expression (or part of a valid
5291 expression).  Therefore all macros must be expanded before they are
5292 passed to @code{eval}.
5294 Some calculations are not portable to other implementations, since they
5295 have undefined semantics in C, but @acronym{GNU} @code{m4} has
5296 well-defined behavior on overflow.  When shifting, an out-of-range shift
5297 amount is implicitly brought into the range of 32-bit signed integers
5298 using an implicit bit-wise and with 0x1f).
5300 @example
5301 define(`max_int', eval(`0x7fffffff'))
5302 @result{}
5303 define(`min_int', incr(max_int))
5304 @result{}
5305 eval(min_int` < 0')
5306 @result{}1
5307 eval(max_int` > 0')
5308 @result{}1
5309 ifelse(eval(min_int` / -1'), min_int, `overflow occurred')
5310 @result{}overflow occurred
5311 min_int
5312 @result{}-2147483648
5313 eval(`0x80000000 % -1')
5314 @result{}0
5315 eval(`-4 >> 1')
5316 @result{}-2
5317 eval(`-4 >> 33')
5318 @result{}-2
5319 @end example
5321 If @var{radix} is specified, it specifies the radix to be used in the
5322 expansion.  The default radix is 10; this is also the case if
5323 @var{radix} is the empty string.  A warning results if the radix is
5324 outside the range of 1 through 36, inclusive.  The result of @code{eval}
5325 is always taken to be signed.  No radix prefix is output, and for
5326 radices greater than 10, the digits are lower case.  The @var{width}
5327 argument specifies the minimum output width, excluding any negative
5328 sign.  The result is zero-padded to extend the expansion to the
5329 requested width.  A warning results if the width is negative.  If
5330 @var{radix} or @var{width} is out of bounds, the expansion of
5331 @code{eval} is empty.
5333 @example
5334 eval(`666', `10')
5335 @result{}666
5336 eval(`666', `11')
5337 @result{}556
5338 eval(`666', `6')
5339 @result{}3030
5340 eval(`666', `6', `10')
5341 @result{}0000003030
5342 eval(`-666', `6', `10')
5343 @result{}-0000003030
5344 eval(`10', `', `0')
5345 @result{}10
5346 `0r1:'eval(`10', `1', `11')
5347 @result{}0r1:01111111111
5348 eval(`10', `16')
5349 @result{}a
5350 eval(`1', `37')
5351 @error{}m4:stdin:9: radix 37 in builtin `eval' out of range
5352 @result{}
5353 eval(`1', , `-1')
5354 @error{}m4:stdin:10: negative width to builtin `eval'
5355 @result{}
5356 eval()
5357 @error{}m4:stdin:11: empty string treated as 0 in builtin `eval'
5358 @result{}0
5359 @end example
5361 @node Shell commands
5362 @chapter Macros for running shell commands
5364 @cindex UNIX commands, running
5365 @cindex executing shell commands
5366 @cindex running shell commands
5367 @cindex shell commands, running
5368 @cindex commands, running shell
5369 There are a few builtin macros in @code{m4} that allow you to run shell
5370 commands from within @code{m4}.
5372 Note that the definition of a valid shell command is system dependent.
5373 On UNIX systems, this is the typical @command{/bin/sh}.  But on other
5374 systems, such as native Windows, the shell has a different syntax of
5375 commands that it understands.  Some examples in this chapter assume
5376 @command{/bin/sh}, and also demonstrate how to quit early with a known
5377 exit value if this is not the case.
5379 @menu
5380 * Platform macros::             Determining the platform
5381 * Syscmd::                      Executing simple commands
5382 * Esyscmd::                     Reading the output of commands
5383 * Sysval::                      Exit status
5384 * Mkstemp::                     Making temporary files
5385 @end menu
5387 @node Platform macros
5388 @section Determining the platform
5390 @cindex platform macros
5391 Sometimes it is desirable for an input file to know which platform
5392 @code{m4} is running on.  @acronym{GNU} @code{m4} provides several
5393 macros that are predefined to expand to the empty string; checking for
5394 their existence will confirm platform details.
5396 @deffn {Optional builtin} __gnu__
5397 @deffnx {Optional builtin} __os2__
5398 @deffnx {Optional builtin} os2
5399 @deffnx {Optional builtin} __unix__
5400 @deffnx {Optional builtin} unix
5401 @deffnx {Optional builtin} __windows__
5402 @deffnx {Optional builtin} windows
5403 Each of these macros is conditionally defined as needed to describe the
5404 environment of @code{m4}.  If defined, each macro expands to the empty
5405 string.
5406 @end deffn
5408 When @acronym{GNU} extensions are in effect (that is, when you did not
5409 use the @option{-G} option, @pxref{Limits control, , Invoking m4}),
5410 @acronym{GNU} @code{m4} will define the macro @code{@w{__gnu__}} to
5411 expand to the empty string.
5413 @example
5414 __gnu__
5415 @result{}
5416 ifdef(`__gnu__', `Extensions are active')
5417 @result{}Extensions are active
5418 @end example
5420 On UNIX systems, @acronym{GNU} @code{m4} will define @code{@w{__unix__}}
5421 by default, or @code{unix} when the @option{-G} option is specified.
5423 On native Windows systems, @acronym{GNU} @code{m4} will define
5424 @code{@w{__windows__}} by default, or @code{windows} when the
5425 @option{-G} option is specified.
5427 On OS/2 systems, @acronym{GNU} @code{m4} will define @code{@w{__os2__}}
5428 by default, or @code{os2} when the @option{-G} option is specified.
5430 If @acronym{GNU} @code{m4} does not provide a platform macro for your system,
5431 please report that as a bug.
5433 @example
5434 define(`provided', `0')
5435 @result{}
5436 ifdef(`__unix__', `define(`provided', incr(provided))')
5437 @result{}
5438 ifdef(`__windows__', `define(`provided', incr(provided))')
5439 @result{}
5440 ifdef(`__os2__', `define(`provided', incr(provided))')
5441 @result{}
5442 provided
5443 @result{}1
5444 @end example
5446 @node Syscmd
5447 @section Executing simple commands
5449 Any shell command can be executed, using @code{syscmd}:
5451 @deffn Builtin syscmd (@var{shell-command})
5452 Executes @var{shell-command} as a shell command.
5454 The expansion of @code{syscmd} is void, @emph{not} the output from
5455 @var{shell-command}!  Output or error messages from @var{shell-command}
5456 are not read by @code{m4}.  @xref{Esyscmd}, if you need to process the
5457 command output.
5459 Prior to executing the command, @code{m4} flushes its buffers.
5460 The default standard input, output and error of @var{shell-command} are
5461 the same as those of @code{m4}.
5463 The macro @code{syscmd} is recognized only with parameters.
5464 @end deffn
5466 @example
5467 define(`foo', `FOO')
5468 @result{}
5469 syscmd(`echo foo')
5470 @result{}foo
5471 @result{}
5472 @end example
5474 Note how the expansion of @code{syscmd} keeps the trailing newline of
5475 the command, as well as using the newline that appeared after the macro.
5477 The following is an example of @var{shell-command} using the same
5478 standard input as @code{m4}:
5480 @comment ignore
5481 @example
5482 $ @kbd{echo "m4wrap(\`syscmd(\`cat')')" | m4}
5483 @result{}
5484 @end example
5486 @ignore
5487 @comment If the user types the example below with stdin being an
5488 @comment interactive terminal, then cat will hang waiting for additional
5489 @comment input after m4 has exited.  But the testsuite is using a pipe
5490 @comment for stdin.  Hence, we have two versions - the one we feed the
5491 @comment testsuite below, and the one we display to the user above that
5492 @comment more accurately shows what the testsuite is really doing but
5493 @comment which the testsuite cannot parse.
5495 @example
5496 m4wrap(`syscmd(`cat')')
5497 @result{}
5499 @end example
5500 @end ignore
5502 It tells @code{m4} to read all of its input before executing the wrapped
5503 text, then hand a valid (albeit emptied) pipe as standard input for the
5504 @code{cat} subcommand.  Therefore, you should be careful when using
5505 standard input (either by specifying no files, or by passing @samp{-} as
5506 a file name on the command line, @pxref{Command line files, , Invoking
5507 m4}), and also invoking subcommands via @code{syscmd} or @code{esyscmd}
5508 that consume data from standard input.  When standard input is a
5509 seekable file, the subprocess will pick up with the next character not
5510 yet processed by @code{m4}; when it is a pipe or other non-seekable
5511 file, there is no guarantee how much data will already be buffered by
5512 @code{m4} and thus unavailable to the child.
5514 @node Esyscmd
5515 @section Reading the output of commands
5517 @cindex @acronym{GNU} extensions
5518 If you want @code{m4} to read the output of a shell command, use
5519 @code{esyscmd}:
5521 @deffn Builtin esyscmd (@var{shell-command})
5522 Expands to the standard output of the shell command
5523 @var{shell-command}.
5525 Prior to executing the command, @code{m4} flushes its buffers.
5526 The default standard input and standard error of @var{shell-command} are
5527 the same as those of @code{m4}.  The error output of @var{shell-command}
5528 is not a part of the expansion: it will appear along with the error
5529 output of @code{m4}.
5531 The macro @code{esyscmd} is recognized only with parameters.
5532 @end deffn
5534 @example
5535 define(`foo', `FOO')
5536 @result{}
5537 esyscmd(`echo foo')
5538 @result{}FOO
5539 @result{}
5540 @end example
5542 Note how the expansion of @code{esyscmd} keeps the trailing newline of
5543 the command, as well as using the newline that appeared after the macro.
5545 Just as with @code{syscmd}, care must be exercised when sharing standard
5546 input between @code{m4} and the child process of @code{esyscmd}.
5548 @node Sysval
5549 @section Exit status
5551 @cindex UNIX commands, exit status from
5552 @cindex exit status from shell commands
5553 @cindex shell commands, exit status from
5554 @cindex commands, exit status from shell
5555 @cindex status of shell commands
5556 To see whether a shell command succeeded, use @code{sysval}:
5558 @deffn Builtin sysval
5559 Expands to the exit status of the last shell command run with
5560 @code{syscmd} or @code{esyscmd}.  Expands to 0 if no command has been
5561 run yet.
5562 @end deffn
5564 @example
5565 sysval
5566 @result{}0
5567 syscmd(`false')
5568 @result{}
5569 ifelse(sysval, `0', `zero', `non-zero')
5570 @result{}non-zero
5571 syscmd(`exit 2')
5572 @result{}
5573 sysval
5574 @result{}2
5575 syscmd(`true')
5576 @result{}
5577 sysval
5578 @result{}0
5579 esyscmd(`false')
5580 @result{}
5581 ifelse(sysval, `0', `zero', `non-zero')
5582 @result{}non-zero
5583 esyscmd(`exit 2')
5584 @result{}
5585 sysval
5586 @result{}2
5587 esyscmd(`true')
5588 @result{}
5589 sysval
5590 @result{}0
5591 @end example
5593 @code{sysval} results in 127 if there was a problem executing the
5594 command, for example, if the system-imposed argument length is exceeded,
5595 or if there were not enough resources to fork.  It is not possible to
5596 distinguish between failed execution and successful execution that had
5597 an exit status of 127.
5599 On UNIX platforms, where it is possible to detect when command execution
5600 is terminated by a signal, rather than a normal exit, the result is the
5601 signal number shifted left by eight bits.
5603 @comment This test has difficulties being portable, even on platforms
5604 @comment where syscmd invokes /bin/sh.  Kill is not portable with signal
5605 @comment names.  According to autoconf, the only portable signal numbers
5606 @comment are 1 (HUP), 2 (INT), 9 (KILL), 13 (PIPE) and 15 (TERM).  But
5607 @comment all shells handle SIGINT, and ksh handles HUP (as in, the shell
5608 @comment exits normally rather than letting the signal terminate it).
5609 @comment Also, TERM is flaky, as it can also kill the running m4 on
5610 @comment systems where /bin/sh does not create its own process group.
5611 @comment And PIPE is unreliable, since people tend to run with it
5612 @comment ignored, with m4 inheriting that choice.  That leaves KILL as
5613 @comment the only signal we can reliably test.
5614 @example
5615 dnl This test assumes kill is a shell builtin, and that signals are
5616 dnl recognizable.
5617 ifdef(`__unix__', ,
5618       `errprint(` skipping: syscmd does not have unix semantics
5619 ')m4exit(`77')')dnl
5620 syscmd(`kill -9 $$')
5621 @result{}
5622 sysval
5623 @result{}2304
5624 syscmd()
5625 @result{}
5626 sysval
5627 @result{}0
5628 esyscmd(`kill -9 $$')
5629 @result{}
5630 sysval
5631 @result{}2304
5632 @end example
5634 @node Mkstemp
5635 @section Making temporary files
5637 @cindex temporary file names
5638 @cindex files, names of temporary
5639 Commands specified to @code{syscmd} or @code{esyscmd} might need a
5640 temporary file, for output or for some other purpose.  There is a
5641 builtin macro, @code{mkstemp}, for making a temporary file:
5643 @deffn Builtin mkstemp (@var{template})
5644 @deffnx Builtin maketemp (@var{template})
5645 Expands to a name of a new, empty file, made from the string
5646 @var{template}, which should end with the string @samp{XXXXXX}.  The six
5647 @samp{X} characters are then replaced with random characters matching
5648 the regular expression @samp{[a-zA-Z0-9._-]}, in order to make the file
5649 name unique.  If fewer than six @samp{X} characters are found at the end
5650 of @code{template}, the result will be longer than the template.  The
5651 created file will have access permissions as if by @kbd{chmod =rw,go=},
5652 meaning that the current umask of the @code{m4} process is taken into
5653 account, and at most only the current user can read and write the file.
5655 The traditional behavior, standardized by @acronym{POSIX}, is that
5656 @code{maketemp} merely replaces the trailing @samp{X} with the process
5657 id, without creating a file, and without ensuring that the resulting
5658 string is a unique file name.  In part, this means that using the same
5659 @var{template} twice in the same input file will result in the same
5660 expansion.  This behavior is a security hole, as it is very easy for
5661 another process to guess the name that will be generated, and thus
5662 interfere with a subsequent use of @code{syscmd} trying to manipulate
5663 that file name.  Hence, @acronym{POSIX} has recommended that all new
5664 implementations of @code{m4} provide the secure @code{mkstemp} builtin,
5665 and that users of @code{m4} check for its existence.
5667 The expansion is void and an error issued if a temporary file could
5668 not be created.
5670 The macros @code{mkstemp} and @code{maketemp} are recognized only with
5671 parameters.
5672 @end deffn
5674 If you try this next example, you will most likely get different output
5675 for the two file names, since the replacement characters are randomly
5676 chosen:
5678 @comment ignore
5679 @example
5680 $ @kbd{m4}
5681 maketemp(`/tmp/fooXXXXXX')
5682 @result{}/tmp/fooa07346
5683 ifdef(`mkstemp', `define(`maketemp', defn(`mkstemp'))',
5684       `define(`mkstemp', defn(`maketemp'))dnl
5685 errprint(`warning: potentially insecure maketemp implementation
5686 ')')
5687 @result{}
5688 mkstemp(`doc')
5689 @result{}docQv83Uw
5690 @end example
5692 @cindex @acronym{GNU} extensions
5693 Unless you use the @option{--traditional} command line option (or
5694 @option{-G}, @pxref{Limits control, , Invoking m4}), the @acronym{GNU}
5695 version of @code{maketemp} is secure.  This means that using the same
5696 template to multiple calls will generate multiple files.  However, we
5697 recommend that you use the new @code{mkstemp} macro, introduced in
5698 @acronym{GNU} M4 1.4.8, which is secure even in traditional mode.
5700 @example
5701 $ @kbd{m4}
5702 syscmd(`echo foo??????')dnl
5703 @result{}foo??????
5704 define(`file1', maketemp(`fooXXXXXX'))dnl
5705 ifelse(esyscmd(`echo foo??????'), `foo??????', `no file', `created')
5706 @result{}created
5707 define(`file2', maketemp(`fooXX'))dnl
5708 define(`file3', mkstemp(`fooXXXXXX'))dnl
5709 ifelse(len(file1), len(file2), `same length', `different')
5710 @result{}same length
5711 ifelse(file1, file2, `same', `different file')
5712 @result{}different file
5713 ifelse(file2, file3, `same', `different file')
5714 @result{}different file
5715 ifelse(file1, file3, `same', `different file')
5716 @result{}different file
5717 syscmd(`rm 'file1 file2 file3)
5718 @result{}
5719 sysval
5720 @result{}0
5721 @end example
5723 @node Miscellaneous
5724 @chapter Miscellaneous builtin macros
5726 This chapter describes various builtins, that do not really belong in
5727 any of the previous chapters.
5729 @menu
5730 * Errprint::                    Printing error messages
5731 * Location::                    Printing current location
5732 * M4exit::                      Exiting from @code{m4}
5733 @end menu
5735 @node Errprint
5736 @section Printing error messages
5738 @cindex printing error messages
5739 @cindex error messages, printing
5740 @cindex messages, printing error
5741 @cindex standard error, output to
5742 You can print error messages using @code{errprint}:
5744 @deffn Builtin errprint (@var{message}, @dots{})
5745 Prints @var{message} and the rest of the arguments to standard error,
5746 separated by spaces.  Standard error is used, regardless of the
5747 @option{--debugfile} option (@pxref{Debugging options, , Invoking m4}).
5749 The expansion of @code{errprint} is void.
5750 The macro @code{errprint} is recognized only with parameters.
5751 @end deffn
5753 @example
5754 errprint(`Invalid arguments to forloop
5756 @error{}Invalid arguments to forloop
5757 @result{}
5758 errprint(`1')errprint(`2',`3
5760 @error{}12 3
5761 @result{}
5762 @end example
5764 A trailing newline is @emph{not} printed automatically, so it should be
5765 supplied as part of the argument, as in the example.  Unfortunately, the
5766 exact output of @code{errprint} is not very portable to other @code{m4}
5767 implementations: @acronym{POSIX} requires that all arguments be printed,
5768 but some implementations of @code{m4} only print the first.
5769 Furthermore, some @acronym{BSD} implementations always append a newline
5770 for each @code{errprint} call, regardless of whether the last argument
5771 already had one, and @acronym{POSIX} is silent on whether this is
5772 acceptable.
5774 @node Location
5775 @section Printing current location
5777 @cindex location, input
5778 @cindex input location
5779 To make it possible to specify the location of an error, three
5780 utility builtins exist:
5782 @deffn Builtin __file__
5783 @deffnx Builtin __line__
5784 @deffnx Builtin __program__
5785 Expand to the quoted name of the current input file, the
5786 current input line number in that file, and the quoted name of the
5787 current invocation of @code{m4}.
5788 @end deffn
5790 @example
5791 errprint(__program__:__file__:__line__: `input error
5793 @error{}m4:stdin:1: input error
5794 @result{}
5795 @end example
5797 Line numbers start at 1 for each file.  If the file was found due to the
5798 @option{-I} option or @env{M4PATH} environment variable, that is
5799 reflected in the file name.  The syncline option (@option{-s},
5800 @pxref{Preprocessor features, , Invoking m4}), and the
5801 @samp{f} and @samp{l} flags of @code{debugmode} (@pxref{Debug Levels}),
5802 also use this notion of current file and line.  Redefining the three
5803 location macros has no effect on syncline, debug, warning, or error
5804 message output.
5806 This example reuses the file @file{incl.m4} mentioned earlier
5807 (@pxref{Include}):
5809 @example
5810 $ @kbd{m4 -I examples}
5811 define(`foo', ``$0' called at __file__:__line__')
5812 @result{}
5814 @result{}foo called at stdin:2
5815 include(`incl.m4')
5816 @result{}Include file start
5817 @result{}foo called at ../examples/incl.m4:2
5818 @result{}Include file end
5819 @result{}
5820 @end example
5822 The location of macros invoked during the rescanning of macro expansion
5823 text corresponds to the location in the file where the expansion was
5824 triggered, regardless of how many newline characters the expansion text
5825 contains.  As of @acronym{GNU} M4 1.4.8, the location of text wrapped
5826 with @code{m4wrap} (@pxref{M4wrap}) is the point at which the
5827 @code{m4wrap} was invoked.  Previous versions, however, behaved as
5828 though wrapped text came from line 0 of the file ``''.
5830 @example
5831 define(`echo', `$@@')
5832 @result{}
5833 define(`foo', `echo(__line__
5834 __line__)')
5835 @result{}
5836 echo(__line__
5837 __line__)
5838 @result{}4
5839 @result{}5
5840 m4wrap(`foo
5842 @result{}
5843 foo(errprint(__line__
5844 __line__
5846 @error{}8
5847 @error{}9
5848 @result{}8
5849 @result{}8
5850 __line__
5851 @result{}11
5853 @result{}6
5854 @result{}6
5855 @end example
5857 The @code{@w{__program__}} macro behaves like @samp{$0} in shell
5858 terminology.  If you invoke @code{m4} through an absolute path or a link
5859 with a different spelling, rather than by relying on a @env{PATH} search
5860 for plain @samp{m4}, it will affect how @code{@w{__program__}} expands.
5861 The intent is that you can use it to produce error messages with the
5862 same formatting that @code{m4} produces internally.  It can also be used
5863 within @code{syscmd} (@pxref{Syscmd}) to pick the same version of
5864 @code{m4} that is currently running, rather than whatever version of
5865 @code{m4} happens to be first in @env{PATH}.  It was first introduced in
5866 @acronym{GNU} M4 1.4.6.
5868 @node M4exit
5869 @section Exiting from @code{m4}
5871 @cindex exiting from @code{m4}
5872 @cindex status, setting @code{m4} exit
5873 If you need to exit from @code{m4} before the entire input has been
5874 read, you can use @code{m4exit}:
5876 @deffn Builtin m4exit (@dvar{code, 0})
5877 Causes @code{m4} to exit, with exit status @var{code}.  If @var{code} is
5878 left out, the exit status is zero.  If @var{code} cannot be parsed, or
5879 is outside the range of 0 to 255, the exit status is one.  No further
5880 input is read, and all wrapped and diverted text is discarded.
5881 @end deffn
5883 @example
5884 m4wrap(`This text is lost due to `m4exit'.')
5885 @result{}
5886 divert(`1') So is this.
5887 divert
5888 @result{}
5889 m4exit And this is never read.
5890 @end example
5892 A common use of this is to abort processing:
5894 @deffn Composite fatal_error (@var{message})
5895 Abort processing with an error message and non-zero status.  Prefix
5896 @var{message} with details about where the error occurred, and print the
5897 resulting string to standard error.
5898 @end deffn
5900 @comment status: 1
5901 @example
5902 define(`fatal_error',
5903        `errprint(__program__:__file__:__line__`: fatal error: $*
5904 ')m4exit(`1')')
5905 @result{}
5906 fatal_error(`this is a BAD one, buster')
5907 @error{}m4:stdin:4: fatal error: this is a BAD one, buster
5908 @end example
5910 After this macro call, @code{m4} will exit with exit status 1.  This macro
5911 is only intended for error exits, since the normal exit procedures are
5912 not followed, e.g., diverted text is not undiverted, and saved text
5913 (@pxref{M4wrap}) is not reread.  (This macro could be made more robust
5914 to earlier versions of @code{m4}.  You should try to see if you can find
5915 weaknesses and correct them; or @pxref{Improved fatal_error, , Answers}).
5917 Note that it is still possible for the exit status to be different than
5918 what was requested by @code{m4exit}.  If @code{m4} detects some other
5919 error, such as a write error on standard output, the exit status will be
5920 non-zero even if @code{m4exit} requested zero.
5922 If standard input is seekable, then the file will be positioned at the
5923 next unread character.  If it is a pipe or other non-seekable file,
5924 then there are no guarantees how much data @code{m4} might have read
5925 into buffers, and thus discarded.
5927 @node Frozen files
5928 @chapter Fast loading of frozen state
5930 Some bigger @code{m4} applications may be built over a common base
5931 containing hundreds of definitions and other costly initializations.
5932 Usually, the common base is kept in one or more declarative files,
5933 which files are listed on each @code{m4} invocation prior to the
5934 user's input file, or else each input file uses @code{include}.
5936 Reading the common base of a big application, over and over again, may
5937 be time consuming.  @acronym{GNU} @code{m4} offers some machinery to
5938 speed up the start of an application using lengthy common bases.
5940 @menu
5941 * Using frozen files::          Using frozen files
5942 * Frozen file format::          Frozen file format
5943 @end menu
5945 @node Using frozen files
5946 @section Using frozen files
5948 @cindex fast loading of frozen files
5949 @cindex frozen files for fast loading
5950 @cindex initialization, frozen state
5951 @cindex dumping into frozen file
5952 @cindex reloading a frozen file
5953 @cindex @acronym{GNU} extensions
5954 Suppose a user has a library of @code{m4} initializations in
5955 @file{base.m4}, which is then used with multiple input files:
5957 @comment ignore
5958 @example
5959 $ @kbd{m4 base.m4 input1.m4}
5960 $ @kbd{m4 base.m4 input2.m4}
5961 $ @kbd{m4 base.m4 input3.m4}
5962 @end example
5964 Rather than spending time parsing the fixed contents of @file{base.m4}
5965 every time, the user might rather execute:
5967 @comment ignore
5968 @example
5969 $ @kbd{m4 -F base.m4f base.m4}
5970 @end example
5972 @noindent
5973 once, and further execute, as often as needed:
5975 @comment ignore
5976 @example
5977 $ @kbd{m4 -R base.m4f input1.m4}
5978 $ @kbd{m4 -R base.m4f input2.m4}
5979 $ @kbd{m4 -R base.m4f input3.m4}
5980 @end example
5982 @noindent
5983 with the varying input.  The first call, containing the @option{-F}
5984 option, only reads and executes file @file{base.m4}, defining
5985 various application macros and computing other initializations.
5986 Once the input file @file{base.m4} has been completely processed, @acronym{GNU}
5987 @code{m4} produces in @file{base.m4f} a @dfn{frozen} file, that is, a
5988 file which contains a kind of snapshot of the @code{m4} internal state.
5990 Later calls, containing the @option{-R} option, are able to reload
5991 the internal state of @code{m4}, from @file{base.m4f},
5992 @emph{prior} to reading any other input files.  This means
5993 instead of starting with a virgin copy of @code{m4}, input will be
5994 read after having effectively recovered the effect of a prior run.
5995 In our example, the effect is the same as if file @file{base.m4} has
5996 been read anew.  However, this effect is achieved a lot faster.
5998 Only one frozen file may be created or read in any one @code{m4}
5999 invocation.  It is not possible to recover two frozen files at once.
6000 However, frozen files may be updated incrementally, through using
6001 @option{-R} and @option{-F} options simultaneously.  For example, if
6002 some care is taken, the command:
6004 @comment ignore
6005 @example
6006 $ @kbd{m4 file1.m4 file2.m4 file3.m4 file4.m4}
6007 @end example
6009 @noindent
6010 could be broken down in the following sequence, accumulating the same
6011 output:
6013 @comment ignore
6014 @example
6015 $ @kbd{m4 -F file1.m4f file1.m4}
6016 $ @kbd{m4 -R file1.m4f -F file2.m4f file2.m4}
6017 $ @kbd{m4 -R file2.m4f -F file3.m4f file3.m4}
6018 $ @kbd{m4 -R file3.m4f file4.m4}
6019 @end example
6021 Some care is necessary because not every effort has been made for
6022 this to work in all cases.  In particular, the trace attribute of
6023 macros is not handled, nor the current setting of @code{changeword}.
6024 Currently, @code{m4wrap} and @code{sysval} also have problems.
6025 Also, interactions for some options of @code{m4}, being used in one call
6026 and not in the next, have not been fully analyzed yet.  On the other
6027 end, you may be confident that stacks of @code{pushdef} definitions
6028 are handled correctly, as well as undefined or renamed builtins, and
6029 changed strings for quotes or comments.  And future releases of
6030 @acronym{GNU} M4 will improve on the utility of frozen files.
6032 @ignore
6033 @c This example is not worth putting in the manual, but caused core
6034 @c dumps in all versions prior to 1.4.11.
6036 @comment options: -F /dev/null
6037 @example
6038 traceon(`undefined')dnl
6039 @end example
6040 @end ignore
6042 When an @code{m4} run is to be frozen, the automatic undiversion
6043 which takes place at end of execution is inhibited.  Instead, all
6044 positively numbered diversions are saved into the frozen file.
6045 The active diversion number is also transmitted.
6047 A frozen file to be reloaded need not reside in the current directory.
6048 It is looked up the same way as an @code{include} file (@pxref{Search
6049 Path}).
6051 If the frozen file was generated with a newer version of @code{m4}, and
6052 contains directives that an older @code{m4} cannot parse, attempting to
6053 load the frozen file with option @option{-R} will cause @code{m4} to
6054 exit with status 63 to indicate version mismatch.
6056 @node Frozen file format
6057 @section Frozen file format
6059 @cindex frozen file format
6060 @cindex file format, frozen file
6061 Frozen files are sharable across architectures.  It is safe to write
6062 a frozen file on one machine and read it on another, given that the
6063 second machine uses the same or newer version of @acronym{GNU} @code{m4}.
6064 It is conventional, but not required, to give a frozen file the suffix
6065 of @code{.m4f}.
6067 These are simple (editable) text files, made up of directives,
6068 each starting with a capital letter and ending with a newline
6069 (@key{NL}).  Wherever a directive is expected, the character
6070 @samp{#} introduces a comment line; empty lines are also ignored if they
6071 are not part of an embedded string.
6072 In the following descriptions, each @var{len} refers to the length of
6073 the corresponding strings @var{str} in the next line of input.  Numbers
6074 are always expressed in decimal.  There are no escape characters.  The
6075 directives are:
6077 @table @code
6078 @item C @var{len1} , @var{len2} @key{NL} @var{str1} @var{str2} @key{NL}
6079 Uses @var{str1} and @var{str2} as the begin-comment and
6080 end-comment strings.  If omitted, then @samp{#} and @key{NL} are the
6081 comment delimiters.
6083 @item D @var{number}, @var{len} @key{NL} @var{str} @key{NL}
6084 Selects diversion @var{number}, making it current, then copy
6085 @var{str} in the current diversion.  @var{number} may be a negative
6086 number for a non-existing diversion.  To merely specify an active
6087 selection, use this command with an empty @var{str}.  With 0 as the
6088 diversion @var{number}, @var{str} will be issued on standard output
6089 at reload time.  @acronym{GNU} @code{m4} will not produce the @samp{D}
6090 directive with non-zero length for diversion 0, but this can be done
6091 with manual edits.  This directive may
6092 appear more than once for the same diversion, in which case the
6093 diversion is the concatenation of the various uses.  If omitted, then
6094 diversion 0 is current.
6096 @item F @var{len1} , @var{len2} @key{NL} @var{str1} @var{str2} @key{NL}
6097 Defines, through @code{pushdef}, a definition for @var{str1}
6098 expanding to the function whose builtin name is @var{str2}.  If the
6099 builtin does not exist (for example, if the frozen file was produced by
6100 a copy of @code{m4} compiled with changeword support, but the version
6101 of @code{m4} reloading was compiled without it), the reload is silent,
6102 but any subsequent use of the definition of @var{str1} will result in
6103 a warning.  This directive may appear more than once for the same name,
6104 and its order, along with @samp{T}, is important.  If omitted, you will
6105 have no access to any builtins.
6107 @item Q @var{len1} , @var{len2} @key{NL} @var{str1} @var{str2} @key{NL}
6108 Uses @var{str1} and @var{str2} as the begin-quote and end-quote
6109 strings.  If omitted, then @samp{`} and @samp{'} are the quote
6110 delimiters.
6112 @item T @var{len1} , @var{len2} @key{NL} @var{str1} @var{str2} @key{NL}
6113 Defines, though @code{pushdef}, a definition for @var{str1}
6114 expanding to the text given by @var{str2}.  This directive may appear
6115 more than once for the same name, and its order, along with @samp{F}, is
6116 important.
6118 @item V @var{number} @key{NL}
6119 Confirms the format of the file.  @code{m4} @value{VERSION} only creates
6120 and understands frozen files where @var{number} is 1.  This directive
6121 must be the first non-comment in the file, and may not appear more than
6122 once.
6123 @end table
6125 @node Compatibility
6126 @chapter Compatibility with other versions of @code{m4}
6128 @cindex compatibility
6129 This chapter describes the many of the differences between this
6130 implementation of @code{m4}, and of other implementations found under
6131 UNIX, such as System V Release 3, Solaris, and @acronym{BSD} flavors.
6132 In particular, it lists the known differences and extensions to
6133 @acronym{POSIX}.  However, the list is not necessarily comprehensive.
6135 At the time of this writing, @acronym{POSIX} 2001 (also known as IEEE
6136 Std 1003.1-2001) is the latest standard, although a new version of
6137 @acronym{POSIX} is under development and includes several proposals for
6138 modifying what @code{m4} is required to do.  The requirements for
6139 @code{m4} are shared between @acronym{SUSv3} and @acronym{POSIX}, and
6140 can be viewed at
6141 @uref{http://www.opengroup.org/onlinepubs/@/000095399/@/utilities/@/m4.html}.
6143 @menu
6144 * Extensions::                  Extensions in @acronym{GNU} M4
6145 * Incompatibilities::           Facilities in System V m4 not in GNU M4
6146 * Other Incompatibilities::     Other incompatibilities
6147 @end menu
6149 @node Extensions
6150 @section Extensions in @acronym{GNU} M4
6152 @cindex @acronym{GNU} extensions
6153 @cindex @acronym{POSIX}
6154 This version of @code{m4} contains a few facilities that do not exist
6155 in System V @code{m4}.  These extra facilities are all suppressed by
6156 using the @option{-G} command line option (@pxref{Limits control, ,
6157 Invoking m4}), unless overridden by other command line options.
6159 @itemize @bullet
6160 @item
6161 In the @code{$@var{n}} notation for macro arguments, @var{n} can contain
6162 several digits, while the System V @code{m4} only accepts one digit.
6163 This allows macros in @acronym{GNU} @code{m4} to take any number of
6164 arguments, and not only nine (@pxref{Arguments}).
6166 This means that @code{define(`foo', `$11')} is ambiguous between
6167 implementations.  To portably choose between grabbing the first
6168 parameter and appending 1 to the expansion, or grabbing the eleventh
6169 parameter, you can do the following:
6171 @example
6172 define(`a1', `A1')
6173 @result{}
6174 dnl First argument, concatenated with 1
6175 define(`_1', `$1')define(`first1', `_1($@@)1')
6176 @result{}
6177 dnl Eleventh argument, portable
6178 define(`_9', `$9')define(`eleventh', `_9(shift(shift($@@)))')
6179 @result{}
6180 dnl Eleventh argument, GNU style
6181 define(`Eleventh', `$11')
6182 @result{}
6183 first1(`a', `b', `c', `d', `e', `f', `g', `h', `i', `j', `k')
6184 @result{}A1
6185 eleventh(`a', `b', `c', `d', `e', `f', `g', `h', `i', `j', `k')
6186 @result{}k
6187 Eleventh(`a', `b', `c', `d', `e', `f', `g', `h', `i', `j', `k')
6188 @result{}k
6189 @end example
6191 @noindent
6192 Also see the @code{argn} macro (@pxref{Shift}).
6194 @item
6195 The @code{divert} (@pxref{Divert}) macro can manage more than 9
6196 diversions.  @acronym{GNU} @code{m4} treats all positive numbers as valid
6197 diversions, rather than discarding diversions greater than 9.
6199 @item
6200 Files included with @code{include} and @code{sinclude} are sought in a
6201 user specified search path, if they are not found in the working
6202 directory.  The search path is specified by the @option{-I} option and the
6203 @env{M4PATH} environment variable (@pxref{Search Path}).
6205 @item
6206 Arguments to @code{undivert} can be non-numeric, in which case the named
6207 file will be included uninterpreted in the output (@pxref{Undivert}).
6209 @item
6210 Formatted output is supported through the @code{format} builtin, which
6211 is modeled after the C library function @code{printf} (@pxref{Format}).
6213 @item
6214 Searches and text substitution through basic regular expressions are
6215 supported by the @code{regexp} (@pxref{Regexp}) and @code{patsubst}
6216 (@pxref{Patsubst}) builtins.  Some @acronym{BSD} implementations use
6217 extended regular expressions instead.
6219 @item
6220 The output of shell commands can be read into @code{m4} with
6221 @code{esyscmd} (@pxref{Esyscmd}).
6223 @item
6224 There is indirect access to any builtin macro with @code{builtin}
6225 (@pxref{Builtin}).
6227 @item
6228 Macros can be called indirectly through @code{indir} (@pxref{Indir}).
6230 @item
6231 The name of the program, the current input file, and the current input
6232 line number are accessible through the builtins @code{@w{__program__}},
6233 @code{@w{__file__}}, and @code{@w{__line__}} (@pxref{Location}).
6235 @item
6236 The format of the output from @code{dumpdef} and macro tracing can be
6237 controlled with @code{debugmode} (@pxref{Debug Levels}).
6239 @item
6240 The destination of trace and debug output can be controlled with
6241 @code{debugfile} (@pxref{Debug Output}).
6243 @item
6244 The @code{maketemp} (@pxref{Mkstemp}) macro behaves like @code{mkstemp},
6245 creating a new file with a unique name on every invocation, rather than
6246 following the insecure behavior of replacing the trailing @samp{X}
6247 characters with the @code{m4} process id.
6249 @item
6250 @acronym{POSIX} only requires support for the command line options
6251 @option{-s}, @option{-D}, and @option{-U}, so all other options accepted
6252 by @acronym{GNU} M4 are extensions.  @xref{Invoking m4}, for a
6253 description of these options.
6255 The debugging and tracing facilities in @acronym{GNU} @code{m4} are much
6256 more extensive than in most other versions of @code{m4}.
6257 @end itemize
6259 @node Incompatibilities
6260 @section Facilities in System V @code{m4} not in @acronym{GNU} @code{m4}
6262 The version of @code{m4} from System V contains a few facilities that
6263 have not been implemented in @acronym{GNU} @code{m4} yet.  Additionally,
6264 @acronym{POSIX} requires some behaviors that @acronym{GNU} @code{m4} has not
6265 implemented yet.  Relying on these behaviors is non-portable, as a
6266 future release of @acronym{GNU} @code{m4} may change.
6268 @itemize @bullet
6269 @item
6270 @acronym{POSIX} requires support for multiple arguments to @code{defn},
6271 without any clarification on how @code{defn} behaves when one of the
6272 multiple arguments names a builtin.  System V @code{m4} and some other
6273 implementations allow mixing builtins and text macros into a single
6274 macro.  @acronym{GNU} @code{m4} only supports joining multiple text
6275 arguments, although a future implementation may lift this restriction to
6276 behave more like System V.  The only portable way to join text macros
6277 with builtins is via helper macros and implicit concatenation of macro
6278 results.
6280 @item
6281 @acronym{POSIX} requires an application to exit with non-zero status if
6282 it wrote an error message to stderr.  This has not yet been consistently
6283 implemented for the various builtins that are required to issue an error
6284 (such as @code{eval} (@pxref{Eval}) when an argument cannot be parsed).
6286 @item
6287 Some traditional implementations only allow reading standard input
6288 once, but @acronym{GNU} @code{m4} correctly handles multiple instances
6289 of @samp{-} on the command line.
6291 @item
6292 @acronym{POSIX} requires @code{m4wrap} (@pxref{M4wrap}) to act in FIFO
6293 (first-in, first-out) order, but @acronym{GNU} @code{m4} currently uses
6294 LIFO order.  Furthermore, @acronym{POSIX} states that only the first
6295 argument to @code{m4wrap} is saved for later evaluation, bug
6296 @acronym{GNU} @code{m4} saves and processes all arguments, with output
6297 separated by spaces.
6299 However, it is possible to emulate @acronym{POSIX} behavior by
6300 including the file @file{m4-@value{VERSION}/@/examples/@/wrapfifo.m4}
6301 from the distribution:
6303 @example
6304 undivert(`wrapfifo.m4')dnl
6305 @result{}dnl Redefine m4wrap to have FIFO semantics.
6306 @result{}define(`_m4wrap_level', `0')dnl
6307 @result{}define(`m4wrap',
6308 @result{}`ifdef(`m4wrap'_m4wrap_level,
6309 @result{}       `define(`m4wrap'_m4wrap_level,
6310 @result{}               defn(`m4wrap'_m4wrap_level)`$1')',
6311 @result{}       `builtin(`m4wrap', `define(`_m4wrap_level',
6312 @result{}                                  incr(_m4wrap_level))dnl
6313 @result{}m4wrap'_m4wrap_level)dnl
6314 @result{}define(`m4wrap'_m4wrap_level, `$1')')')dnl
6315 include(`wrapfifo.m4')
6316 @result{}
6317 m4wrap(`a`'m4wrap(`c
6318 ', `d')')m4wrap(`b')
6319 @result{}
6321 @result{}abc
6322 @end example
6324 @item
6325 @acronym{POSIX} states that builtins that require arguments, but are
6326 called without arguments, have undefined behavior.  Traditional
6327 implementations simply behave as though empty strings had been passed.
6328 For example, @code{a`'define`'b} would expand to @code{ab}.  But
6329 @acronym{GNU} @code{m4} ignores certain builtins if they have missing
6330 arguments, giving @code{adefineb} for the above example.
6332 @item
6333 Traditional implementations handle @code{define(`f',`1')} (@pxref{Define})
6334 by undefining the entire stack of previous definitions, and if doing
6335 @code{undefine(`f')} first.  @acronym{GNU} @code{m4} replaces just the top
6336 definition on the stack, as if doing @code{popdef(`f')} followed by
6337 @code{pushdef(`f',`1')}.  @acronym{POSIX} allows either behavior.
6339 @item
6340 @acronym{POSIX} 2001 requires @code{syscmd} (@pxref{Syscmd}) to evaluate
6341 command output for macro expansion, but this was a mistake that is
6342 anticipated to be corrected in the next version of @acronym{POSIX}.
6343 @acronym{GNU} @code{m4} follows traditional behavior in @code{syscmd}
6344 where output is not rescanned, and provides the extension @code{esyscmd}
6345 that does scan the output.
6347 @item
6348 At one point, @acronym{POSIX} required @code{changequote(@var{arg})}
6349 (@pxref{Changequote}) to use newline as the close quote, but this was a
6350 bug, and the next version of @acronym{POSIX} is anticipated to state
6351 that using empty strings or just one argument is unspecified.
6352 Meanwhile, the @acronym{GNU} @code{m4} behavior of treating an empty
6353 end-quote delimiter as @samp{'} is not portable, as Solaris treats it as
6354 repeating the start-quote delimiter, and BSD treats it as leaving the
6355 previous end-quote delimiter unchanged.  For predictable results, never
6356 call changequote with just one argument, or with empty strings for
6357 arguments.
6359 @item
6360 At one point, @acronym{POSIX} required @code{changecom(@var{arg},)}
6361 (@pxref{Changecom}) to make it impossible to end a comment, but this is
6362 a bug, and the next version of @acronym{POSIX} is anticipated to state
6363 that using empty strings is unspecified.  Meanwhile, the @acronym{GNU}
6364 @code{m4} behavior of treating an empty end-comment delimiter as newline
6365 is not portable, as BSD treats it as leaving the previous end-comment
6366 delimiter unchanged.  It is also impossible in BSD implementations to
6367 disable comments, even though that is required by @acronym{POSIX}.  For
6368 predictable results, never call changecom with empty strings for
6369 arguments.
6371 @item
6372 Most implementations of @code{m4} give macros a higher precedence than
6373 comments when parsing, meaning that if the start delimiter given to
6374 @code{changecom} (@pxref{Changecom}) starts with a macro name, comments
6375 are effectively disabled.  @acronym{POSIX} does not specify what the
6376 precedence is, so this version of @acronym{GNU} @code{m4} parser
6377 recognizes comments, then macros, then quoted strings.
6379 @item
6380 Traditional implementations allow argument collection, but not string
6381 and comment processing, to span file boundaries.  Thus, if @file{a.m4}
6382 contains @samp{len(}, and @file{b.m4} contains @samp{abc)},
6383 @kbd{m4 a.m4 b.m4} outputs @samp{3} with traditional @code{m4}, but
6384 gives an error message that the end of file was encountered inside a
6385 macro with @acronym{GNU} @code{m4}.  On the other hand, traditional
6386 implementations do end of file processing for files included with
6387 @code{include} or @code{sinclude} (@pxref{Include}), while @acronym{GNU}
6388 @code{m4} seamlessly integrates the content of those files.  Thus
6389 @code{include(`a.m4')include(`b.m4')} will output @samp{3} instead of
6390 giving an error.
6392 @item
6393 Traditional @code{m4} treats @code{traceon} (@pxref{Trace}) without
6394 arguments as a global variable, independent of named macro tracing.
6395 Also, once a macro is undefined, named tracing of that macro is lost.
6396 On the other hand, when @acronym{GNU} @code{m4} encounters
6397 @code{traceon} without
6398 arguments, it turns tracing on for all existing definitions at the time,
6399 but does not trace future definitions; @code{traceoff} without arguments
6400 turns tracing off for all definitions regardless of whether they were
6401 also traced by name; and tracing by name, such as with @option{-tfoo} at
6402 the command line or @code{traceon(`foo')} in the input, is an attribute
6403 that is preserved even if the macro is currently undefined.
6405 @item
6406 @acronym{POSIX} requires @code{eval} (@pxref{Eval}) to treat all
6407 operators with the same precedence as C.  However, earlier versions of
6408 @acronym{GNU} @code{m4} followed the traditional behavior of other
6409 @code{m4} implementations, where bitwise and logical negation (@samp{~}
6410 and @samp{!}) have lower precedence than equality operators; and where
6411 equality operators (@samp{==} and @samp{!=}) had the same precedence as
6412 relational operators (such as @samp{<}).  Use explicit parentheses to
6413 ensure proper precedence.  As extensions to @acronym{POSIX},
6414 @acronym{GNU} @code{m4} gives well-defined semantics to operations that
6415 C leaves undefined, such as when overflow occurs, when shifting negative
6416 numbers, or when performing division by zero.  @acronym{POSIX} also
6417 requires @samp{=} to cause an error, but many traditional
6418 implementations allowed it as an alias for @samp{==}.
6420 @item
6421 @acronym{POSIX} 2001 requires @code{translit} (@pxref{Translit}) to
6422 treat each character of the second and third arguments literally.
6423 However, it is anticipated that the next version of @acronym{POSIX} will
6424 allow the @acronym{GNU} @code{m4} behavior of treating @samp{-} as a
6425 range operator.
6427 @item
6428 @acronym{POSIX} requires @code{m4} to honor the locale environment
6429 variables of @env{LANG}, @env{LC_ALL}, @env{LC_CTYPE},
6430 @env{LC_MESSAGES}, and @env{NLSPATH}, but this has not yet been
6431 implemented in @acronym{GNU} @code{m4}.
6433 @item
6434 @acronym{POSIX} states that only unquoted leading newlines and blanks
6435 (that is, space and tab) are ignored when collecting macro arguments.
6436 However, this appears to be a bug in @acronym{POSIX}, since most
6437 traditional implementations also ignore all whitespace (formfeed,
6438 carriage return, and vertical tab).  @acronym{GNU} @code{m4} follows
6439 tradition and ignores all leading unquoted whitespace.
6440 @end itemize
6442 @node Other Incompatibilities
6443 @section Other incompatibilities
6445 There are a few other incompatibilities between this implementation of
6446 @code{m4}, and the System V version.
6448 @itemize @bullet
6449 @item
6450 @acronym{GNU} @code{m4} implements sync lines differently from System V
6451 @code{m4}, when text is being diverted.  @acronym{GNU} @code{m4} outputs
6452 the sync lines when the text is being diverted, and System V @code{m4}
6453 when the diverted text is being brought back.
6455 The problem is which lines and file names should be attached to text
6456 that is being, or has been, diverted.  System V @code{m4} regards all
6457 the diverted text as being generated by the source line containing the
6458 @code{undivert} call, whereas @acronym{GNU} @code{m4} regards the
6459 diverted text as being generated at the time it is diverted.
6461 The sync line option is used mostly when using @code{m4} as
6462 a front end to a compiler.  If a diverted line causes a compiler error,
6463 the error messages should most probably refer to the place where the
6464 diversion was made, and not where it was inserted again.
6466 @comment options: -s
6467 @example
6468 divert(2)2
6469 divert(1)1
6470 divert`'0
6471 @result{}#line 3 "stdin"
6472 @result{}0
6474 @result{}#line 2 "stdin"
6475 @result{}1
6476 @result{}#line 1 "stdin"
6477 @result{}2
6478 @end example
6480 The current @code{m4} implementation has a limitation that the syncline
6481 output at the start of each diversion occurs no matter what, even if the
6482 previous diversion did not end with a newline.  This goes contrary to
6483 the claim that synclines appear on a line by themselves, so this
6484 limitation may be corrected in a future version of @code{m4}.  In the
6485 meantime, when using @option{-s}, it is wisest to make sure all
6486 diversions end with newline.
6488 @item
6489 @acronym{GNU} @code{m4} makes no attempt at prohibiting self-referential
6490 definitions like:
6492 @example
6493 define(`x', `x')
6494 @result{}
6495 define(`x', `x ')
6496 @result{}
6497 @end example
6499 @cindex rescanning
6500 There is nothing inherently wrong with defining @samp{x} to
6501 return @samp{x}.  The wrong thing is to expand @samp{x} unquoted,
6502 because that would cause an infinite rescan loop.
6503 In @code{m4}, one might use macros to hold strings, as we do for
6504 variables in other programming languages, further checking them with:
6506 @comment ignore
6507 @example
6508 ifelse(defn(`@var{holder}'), `@var{value}', @dots{})
6509 @end example
6511 @noindent
6512 In cases like this one, an interdiction for a macro to hold its own name
6513 would be a useless limitation.  Of course, this leaves more rope for the
6514 @acronym{GNU} @code{m4} user to hang himself!  Rescanning hangs may be
6515 avoided through careful programming, a little like for endless loops in
6516 traditional programming languages.
6517 @end itemize
6519 @node Answers
6520 @chapter Correct version of some examples
6522 Some of the examples in this manuals are buggy or not very robust, for
6523 demonstration purposes.  Improved versions of these composite macros are
6524 presented here.
6526 @menu
6527 * Improved exch::               Solution for @code{exch}
6528 * Improved forloop::            Solution for @code{forloop}
6529 * Improved foreach::            Solution for @code{foreach}
6530 * Improved cleardivert::        Solution for @code{cleardivert}
6531 * Improved capitalize::         Solution for @code{capitalize}
6532 * Improved fatal_error::        Solution for @code{fatal_error}
6533 @end menu
6535 @node Improved exch
6536 @section Solution for @code{exch}
6538 The @code{exch} macro (@pxref{Arguments}) as presented requires clients
6539 to double quote their arguments.  A nicer definition, which lets
6540 clients follow the rule of thumb of one level of quoting per level of
6541 parentheses, involves adding quotes in the definition of @code{exch}, as
6542 follows:
6544 @example
6545 define(`exch', ``$2', `$1'')
6546 @result{}
6547 define(exch(`expansion text', `macro'))
6548 @result{}
6549 macro
6550 @result{}expansion text
6551 @end example
6553 @node Improved forloop
6554 @section Solution for @code{forloop}
6556 The @code{forloop} macro (@pxref{Forloop}) as presented earlier can go
6557 into an infinite loop if given an iterator that is not parsed as a macro
6558 name.  It does not do any sanity checking on its numeric bounds, and
6559 only permits decimal numbers for bounds.  Here is an improved version,
6560 shipped as @file{m4-@value{VERSION}/@/examples/@/forloop2.m4}; this
6561 version also optimizes based on the fact that the starting bound does
6562 not need to be passed to the helper @code{@w{_forloop}}.
6564 @example
6565 $ @kbd{m4 -I examples}
6566 undivert(`forloop2.m4')dnl
6567 @result{}divert(`-1')
6568 @result{}# forloop(var, from, to, stmt) - improved version:
6569 @result{}#   works even if VAR is not a strict macro name
6570 @result{}#   performs sanity check that FROM is larger than TO
6571 @result{}#   allows complex numerical expressions in TO and FROM
6572 @result{}define(`forloop', `ifelse(eval(`($3) >= ($2)'), `1',
6573 @result{}  `pushdef(`$1', eval(`$2'))_forloop(`$1',
6574 @result{}    eval(`$3'), `$4')popdef(`$1')')')
6575 @result{}define(`_forloop',
6576 @result{}  `$3`'ifelse(indir(`$1'), `$2', `',
6577 @result{}    `define(`$1', incr(indir(`$1')))$0($@@)')')
6578 @result{}divert`'dnl
6579 include(`forloop2.m4')
6580 @result{}
6581 forloop(`i', `2', `1', `no iteration occurs')
6582 @result{}
6583 forloop(`', `1', `2', ` odd iterator name')
6584 @result{} odd iterator name odd iterator name
6585 forloop(`i', `5 + 5', `0xc', ` 0x`'eval(i, `16')')
6586 @result{} 0xa 0xb 0xc
6587 forloop(`i', `a', `b', `non-numeric bounds')
6588 @error{}m4:stdin:6: bad expression in eval (bad input): (b) >= (a)
6589 @result{}
6590 @end example
6592 Of course, it is possible to make even more improvements, such as
6593 adding an optional step argument, or allowing iteration through
6594 descending sequences.  @acronym{GNU} Autoconf provides some of these
6595 additional bells and whistles in its @code{m4_for} macro.
6597 @node Improved foreach
6598 @section Solution for @code{foreach}
6600 The @code{foreach} and @code{foreachq} macros (@pxref{Foreach}) as
6601 presented earlier each have flaws.  First, we will examine and fix the
6602 quadratic behavior of @code{foreachq}:
6604 @example
6605 $ @kbd{m4 -I examples}
6606 include(`foreachq.m4')
6607 @result{}
6608 traceon(`shift')debugmode(`aq')
6609 @result{}
6610 foreachq(`x', ``1', `2', `3', `4'', `x
6611 ')dnl
6612 @result{}1
6613 @error{}m4trace: -3- shift(`1', `2', `3', `4')
6614 @error{}m4trace: -2- shift(`1', `2', `3', `4')
6615 @result{}2
6616 @error{}m4trace: -4- shift(`1', `2', `3', `4')
6617 @error{}m4trace: -3- shift(`2', `3', `4')
6618 @error{}m4trace: -3- shift(`1', `2', `3', `4')
6619 @error{}m4trace: -2- shift(`2', `3', `4')
6620 @result{}3
6621 @error{}m4trace: -5- shift(`1', `2', `3', `4')
6622 @error{}m4trace: -4- shift(`2', `3', `4')
6623 @error{}m4trace: -3- shift(`3', `4')
6624 @error{}m4trace: -4- shift(`1', `2', `3', `4')
6625 @error{}m4trace: -3- shift(`2', `3', `4')
6626 @error{}m4trace: -2- shift(`3', `4')
6627 @result{}4
6628 @error{}m4trace: -6- shift(`1', `2', `3', `4')
6629 @error{}m4trace: -5- shift(`2', `3', `4')
6630 @error{}m4trace: -4- shift(`3', `4')
6631 @error{}m4trace: -3- shift(`4')
6632 @end example
6634 @cindex quadratic behavior, avoiding
6635 @cindex avoiding quadratic behavior
6636 Each successive iteration was adding more quoted @code{shift}
6637 invocations, and the entire list contents were passing through every
6638 iteration.  In general, when recursing, it is a good idea to make the
6639 recursion use fewer arguments, rather than adding additional quoted
6640 uses of @code{shift}.  By doing so, @code{m4} uses less memory, invokes
6641 fewer macros, is less likely to run into machine limits, and most
6642 importantly, performs faster.  The fixed version of @code{foreachq} can
6643 be found in @file{m4-@value{VERSION}/@/examples/@/foreachq2.m4}:
6645 @example
6646 $ @kbd{m4 -I examples}
6647 include(`foreachq2.m4')
6648 @result{}
6649 undivert(`foreachq2.m4')dnl
6650 @result{}include(`quote.m4')dnl
6651 @result{}divert(`-1')
6652 @result{}# foreachq(x, `item_1, item_2, ..., item_n', stmt)
6653 @result{}#   quoted list, improved version
6654 @result{}define(`foreachq', `pushdef(`$1')_foreachq($@@)popdef(`$1')')
6655 @result{}define(`_arg1q', ``$1'')
6656 @result{}define(`_rest', `ifelse(`$#', `1', `', `dquote(shift($@@))')')
6657 @result{}define(`_foreachq', `ifelse(`$2', `', `',
6658 @result{}  `define(`$1', _arg1q($2))$3`'$0(`$1', _rest($2), `$3')')')
6659 @result{}divert`'dnl
6660 traceon(`shift')debugmode(`aq')
6661 @result{}
6662 foreachq(`x', ``1', `2', `3', `4'', `x
6663 ')dnl
6664 @result{}1
6665 @error{}m4trace: -3- shift(`1', `2', `3', `4')
6666 @result{}2
6667 @error{}m4trace: -3- shift(`2', `3', `4')
6668 @result{}3
6669 @error{}m4trace: -3- shift(`3', `4')
6670 @result{}4
6671 @end example
6673 Note that the fixed version calls unquoted helper macros in
6674 @code{@w{_foreachq}} to trim elements immediately; those helper macros
6675 in turn must re-supply the layer of quotes lost in the macro invocation.
6676 Contrast the use of @code{@w{_arg1q}}, which quotes the first list
6677 element, with @code{@w{_arg1}} of the earlier implementation that
6678 returned the first list element directly.
6680 For a different approach, the improved version of @code{foreach},
6681 available in @file{m4-@value{VERSION}/@/examples/@/foreach2.m4}, simply
6682 overquotes the arguments to @code{@w{_foreach}} to begin with, using
6683 @code{dquote_elt}.  Then @code{@w{_foreach}} can just use
6684 @code{@w{_arg1}} to remove the extra layer of quoting that was added up
6685 front:
6687 @example
6688 $ @kbd{m4 -I examples}
6689 include(`foreach2.m4')
6690 @result{}
6691 undivert(`foreach2.m4')dnl
6692 @result{}include(`quote.m4')dnl
6693 @result{}divert(`-1')
6694 @result{}# foreach(x, (item_1, item_2, ..., item_n), stmt)
6695 @result{}#   parenthesized list, improved version
6696 @result{}define(`foreach', `pushdef(`$1')_foreach(`$1',
6697 @result{}  (dquote(dquote_elt$2)), `$3')popdef(`$1')')
6698 @result{}define(`_arg1', `$1')
6699 @result{}define(`_foreach', `ifelse(`$2', `(`')', `',
6700 @result{}  `define(`$1', _arg1$2)$3`'$0(`$1', (dquote(shift$2)), `$3')')')
6701 @result{}divert`'dnl
6702 traceon(`shift')debugmode(`aq')
6703 @result{}
6704 foreach(`x', `(`1', `2', `3', `4')', `x
6705 ')dnl
6706 @error{}m4trace: -4- shift(`1', `2', `3', `4')
6707 @error{}m4trace: -4- shift(`2', `3', `4')
6708 @error{}m4trace: -4- shift(`3', `4')
6709 @result{}1
6710 @error{}m4trace: -3- shift(``1'', ``2'', ``3'', ``4'')
6711 @result{}2
6712 @error{}m4trace: -3- shift(``2'', ``3'', ``4'')
6713 @result{}3
6714 @error{}m4trace: -3- shift(``3'', ``4'')
6715 @result{}4
6716 @error{}m4trace: -3- shift(``4'')
6717 @end example
6719 In summary, recursion over list elements is trickier than it appeared at
6720 first glance, but provides a powerful idiom within @code{m4} processing.
6721 As a final demonstration, both list styles are now able to handle
6722 several scenarios that would wreak havoc on the original
6723 implementations.  This points out one other difference between the two
6724 list styles.  @code{foreach} evaluates unquoted list elements only once,
6725 in preparation for calling @code{@w{_foreach}}.  But @code{foreachq}
6726 evaluates unquoted list elements twice while visiting the first list
6727 element, once in @code{@w{_arg1q}} and once in @code{@w{_rest}}.  When
6728 deciding which list style to use, one must take into account whether
6729 repeating the side effects of unquoted list elements will have any
6730 detrimental effects.
6732 @example
6733 $ @kbd{m4 -I examples}
6734 include(`foreach2.m4')
6735 @result{}
6736 include(`foreachq2.m4')
6737 @result{}
6738 dnl 0-element list:
6739 foreach(`x', `', `<x>') / foreachq(`x', `', `<x>')
6740 @result{} /@w{ }
6741 dnl 1-element list of empty element
6742 foreach(`x', `()', `<x>') / foreachq(`x', ``'', `<x>')
6743 @result{}<> / <>
6744 dnl 2-element list of empty elements
6745 foreach(`x', `(`',`')', `<x>') / foreachq(`x', ``',`'', `<x>')
6746 @result{}<><> / <><>
6747 dnl 1-element list of a comma
6748 foreach(`x', `(`,')', `<x>') / foreachq(`x', ``,'', `<x>')
6749 @result{}<,> / <,>
6750 dnl 2-element list of unbalanced parentheses
6751 foreach(`x', `(`(', `)')', `<x>') / foreachq(`x', ``(', `)'', `<x>')
6752 @result{}<(><)> / <(><)>
6753 define(`active', `ACT, IVE')
6754 @result{}
6755 traceon(`active')
6756 @result{}
6757 dnl list of unquoted macros; expansion occurs before recursion
6758 foreach(`x', `(active, active)', `<x>
6759 ')dnl
6760 @error{}m4trace: -4- active -> `ACT, IVE'
6761 @error{}m4trace: -4- active -> `ACT, IVE'
6762 @result{}<ACT>
6763 @result{}<IVE>
6764 @result{}<ACT>
6765 @result{}<IVE>
6766 foreachq(`x', `active, active', `<x>
6767 ')dnl
6768 @error{}m4trace: -3- active -> `ACT, IVE'
6769 @error{}m4trace: -3- active -> `ACT, IVE'
6770 @result{}<ACT>
6771 @error{}m4trace: -3- active -> `ACT, IVE'
6772 @error{}m4trace: -3- active -> `ACT, IVE'
6773 @result{}<IVE>
6774 @result{}<ACT>
6775 @result{}<IVE>
6776 dnl list of quoted macros; expansion occurs during recursion
6777 foreach(`x', `(`active', `active')', `<x>
6778 ')dnl
6779 @error{}m4trace: -1- active -> `ACT, IVE'
6780 @result{}<ACT, IVE>
6781 @error{}m4trace: -1- active -> `ACT, IVE'
6782 @result{}<ACT, IVE>
6783 foreachq(`x', ``active', `active'', `<x>
6784 ')dnl
6785 @error{}m4trace: -1- active -> `ACT, IVE'
6786 @result{}<ACT, IVE>
6787 @error{}m4trace: -1- active -> `ACT, IVE'
6788 @result{}<ACT, IVE>
6789 dnl list of double-quoted macro names; no expansion
6790 foreach(`x', `(``active'', ``active'')', `<x>
6791 ')dnl
6792 @result{}<active>
6793 @result{}<active>
6794 foreachq(`x', ```active'', ``active''', `<x>
6795 ')dnl
6796 @result{}<active>
6797 @result{}<active>
6798 @end example
6800 @node Improved cleardivert
6801 @section Solution for @code{cleardivert}
6803 The @code{cleardivert} macro (@pxref{Cleardivert}) cannot, as it stands, be
6804 called without arguments to clear all pending diversions.  That is
6805 because using undivert with an empty string for an argument is different
6806 than using it with no arguments at all.  Compare the earlier definition
6807 with one that takes the number of arguments into account:
6809 @example
6810 define(`cleardivert',
6811   `pushdef(`_n', divnum)divert(`-1')undivert($@@)divert(_n)popdef(`_n')')
6812 @result{}
6813 divert(`1')one
6814 divert
6815 @result{}
6816 cleardivert
6817 @result{}
6818 undivert
6819 @result{}one
6820 @result{}
6821 define(`cleardivert',
6822   `pushdef(`_num', divnum)divert(`-1')ifelse(`$#', `0',
6823     `undivert`'', `undivert($@@)')divert(_num)popdef(`_num')')
6824 @result{}
6825 divert(`2')two
6826 divert
6827 @result{}
6828 cleardivert
6829 @result{}
6830 undivert
6831 @result{}
6832 @end example
6834 @node Improved capitalize
6835 @section Solution for @code{capitalize}
6837 The @code{capitalize} macro (@pxref{Patsubst}) as presented earlier does
6838 not allow clients to follow the quoting rule of thumb.  Consider the
6839 three macros @code{active}, @code{Active}, and @code{ACTIVE}, and the
6840 difference between calling @code{capitalize} with the expansion of a
6841 macro, expanding the result of a case change, and changing the case of a
6842 double-quoted string:
6844 @example
6845 $ @kbd{m4 -I examples}
6846 include(`capitalize.m4')dnl
6847 define(`active', `act1, ive')dnl
6848 define(`Active', `Act2, Ive')dnl
6849 define(`ACTIVE', `ACT3, IVE')dnl
6850 upcase(active)
6851 @result{}ACT1,IVE
6852 upcase(`active')
6853 @result{}ACT3, IVE
6854 upcase(``active'')
6855 @result{}ACTIVE
6856 downcase(ACTIVE)
6857 @result{}act3,ive
6858 downcase(`ACTIVE')
6859 @result{}act1, ive
6860 downcase(``ACTIVE'')
6861 @result{}active
6862 capitalize(active)
6863 @result{}Act1
6864 capitalize(`active')
6865 @result{}Active
6866 capitalize(``active'')
6867 @result{}_capitalize(`active')
6868 define(`A', `OOPS')
6869 @result{}
6870 capitalize(active)
6871 @result{}OOPSct1
6872 capitalize(`active')
6873 @result{}OOPSctive
6874 @end example
6876 First, when @code{capitalize} is called with more than one argument, it
6877 was throwing away later arguments, whereas @code{upcase} and
6878 @code{downcase} used @samp{$*} to collect them all.  The fix is simple:
6879 use @samp{$*} consistently.
6881 Next, with single-quoting, @code{capitalize} outputs a single character,
6882 a set of quotes, then the rest of the characters, making it impossible
6883 to invoke @code{Active} after the fact, and allowing the alternate macro
6884 @code{A} to interfere.  Here, the solution is to use additional quoting
6885 in the helper macros, then pass the final over-quoted output string
6886 through @code{_arg1} to remove the extra quoting and finally invoke the
6887 concatenated portions as a single string.
6889 Finally, when passed a double-quoted string, the nested macro
6890 @code{_capitalize} is never invoked because it ended up nested inside
6891 quotes.  This one is the toughest to fix.  In short, we have no idea how
6892 many levels of quotes are in effect on the substring being altered by
6893 @code{patsubst}.  If the replacement string cannot be expressed entirely
6894 in terms of literal text and backslash substitutions, then we need a
6895 mechanism to guarantee that the helper macros are invoked outside of
6896 quotes.  In other words, this sounds like a job for @code{changequote}
6897 (@pxref{Changequote}).  By changing the active quoting characters, we
6898 can guarantee that replacement text injected by @code{patsubst} always
6899 occurs in the middle of a string that has exactly one level of
6900 over-quoting using alternate quotes; so the replacement text closes the
6901 quoted string, invokes the helper macros, then reopens the quoted
6902 string.  In turn, that means the replacement text has unbalanced quotes,
6903 necessitating another round of @code{changequote}.
6905 In the fixed version below, (also shipped as
6906 @file{m4-@value{VERSION}/@/examples/@/capitalize.m4}), @code{capitalize}
6907 uses the alternate quotes of @samp{<<[} and @samp{]>>} (the longer
6908 strings are chosen so as to be less likely to appear in the text being
6909 converted).  The helpers @code{_to_alt} and @code{_from_alt} merely
6910 reduce the number of characters required to perform a
6911 @code{changequote}, since the definition changes twice.  The outermost
6912 pair means that @code{patsubst} and @code{_capitalize_alt} are invoked
6913 with alternate quoting; the innermost pair is used so that the third
6914 argument to @code{patsubst} can contain an unbalanced
6915 @samp{]>>}/@samp{<<[} pair.  Note that @code{upcase} and @code{downcase}
6916 must be redefined as @code{_upcase_alt} and @code{_downcase_alt}, since
6917 they contain nested quotes but are invoked with the alternate quoting
6918 scheme in effect.
6920 @example
6921 $ @kbd{m4 -I examples}
6922 include(`capitalize2.m4')dnl
6923 define(`active', `act1, ive')dnl
6924 define(`Active', `Act2, Ive')dnl
6925 define(`ACTIVE', `ACT3, IVE')dnl
6926 define(`A', `OOPS')dnl
6927 capitalize(active)
6928 @result{}Act1,Ive
6929 capitalize(`active')
6930 @result{}Act2, Ive
6931 capitalize(``active'')
6932 @result{}Active
6933 capitalize(```actIVE''')
6934 @result{}`Active'
6935 undivert(`capitalize2.m4')dnl
6936 @result{}divert(`-1')
6937 @result{}# upcase(text)
6938 @result{}# downcase(text)
6939 @result{}# capitalize(text)
6940 @result{}#   change case of text, improved version
6941 @result{}define(`upcase', `translit(`$*', `a-z', `A-Z')')
6942 @result{}define(`downcase', `translit(`$*', `A-Z', `a-z')')
6943 @result{}define(`_arg1', `$1')
6944 @result{}define(`_to_alt', `changequote(`<<[', `]>>')')
6945 @result{}define(`_from_alt', `changequote(<<[`]>>, <<[']>>)')
6946 @result{}define(`_upcase_alt', `translit(<<[$*]>>, <<[a-z]>>, <<[A-Z]>>)')
6947 @result{}define(`_downcase_alt', `translit(<<[$*]>>, <<[A-Z]>>, <<[a-z]>>)')
6948 @result{}define(`_capitalize_alt',
6949 @result{}  `regexp(<<[$1]>>, <<[^\(\w\)\(\w*\)]>>,
6950 @result{}    <<[_upcase_alt(<<[<<[\1]>>]>>)_downcase_alt(<<[<<[\2]>>]>>)]>>)')
6951 @result{}define(`capitalize',
6952 @result{}  `_arg1(_to_alt()patsubst(<<[<<[$*]>>]>>, <<[\w+]>>,
6953 @result{}    _from_alt()`]>>_$0_alt(<<[\&]>>)<<['_to_alt())_from_alt())')
6954 @result{}divert`'dnl
6955 @end example
6957 @node Improved fatal_error
6958 @section Solution for @code{fatal_error}
6960 The @code{fatal_error} macro (@pxref{M4exit}) is not robust to versions
6961 of @acronym{GNU} M4 earlier than 1.4.8, where invoking
6962 @code{@w{__file__}} (@pxref{Location}) inside @code{m4wrap} would result
6963 in an empty string, and @code{@w{__line__}} resulted in @samp{0} even
6964 though all files start at line 1.  Furthermore, versions earlier than
6965 1.4.6 did not support the @code{@w{__program__}} macro.  If you want
6966 @code{fatal_error} to work across the entire 1.4.x release series, a
6967 better implementation would be:
6969 @comment status: 1
6970 @example
6971 define(`fatal_error',
6972   `errprint(ifdef(`__program__', `__program__', ``m4'')'dnl
6973 `:ifelse(__line__, `0', `',
6974     `__file__:__line__:')` fatal error: $*
6975 ')m4exit(`1')')
6976 @result{}
6977 m4wrap(`divnum(`demo of internal message')
6978 fatal_error(`inside wrapped text')')
6979 @result{}
6981 @error{}m4:stdin:6: Warning: excess arguments to builtin `divnum' ignored
6982 @result{}0
6983 @error{}m4:stdin:6: fatal error: inside wrapped text
6984 @end example
6986 @c ========================================================== Appendices
6988 @node Copying This Package
6989 @appendix How to make copies of the overall M4 package
6990 @cindex License, code
6992 This appendix covers the license for copying the source code of the
6993 overall M4 package.  This manual is under a different set of
6994 restrictions, covered later (@pxref{Copying This Manual}).
6996 @menu
6997 * GNU General Public License::  License for copying the M4 package
6998 @end menu
7000 @node GNU General Public License
7001 @appendixsec License for copying the M4 package
7002 @cindex GPL, GNU General Public License
7003 @cindex GNU General Public License
7004 @cindex General Public License (GPL), GNU
7005 @include gpl-3.0.texi
7007 @node Copying This Manual
7008 @appendix How to make copies of this manual
7009 @cindex License, manual
7011 This appendix covers the license for copying this manual.  Note that
7012 some of the longer examples in this manual are also distributed in the
7013 directory @file{m4-@value{VERSION}/@/examples/}, where a more
7014 permissive license is in effect when copying just the examples.
7016 @menu
7017 * GNU Free Documentation License::  License for copying this manual
7018 @end menu
7020 @node GNU Free Documentation License
7021 @appendixsec License for copying this manual
7022 @cindex FDL, GNU Free Documentation License
7023 @cindex GNU Free Documentation License
7024 @cindex Free Documentation License (FDL), GNU
7025 @include fdl.texi
7027 @node Indices
7028 @appendix Indices of concepts and macros
7030 @menu
7031 * Macro index::                 Index for all @code{m4} macros
7032 * Concept index::               Index for many concepts
7033 @end menu
7035 @node Macro index
7036 @appendixsec Index for all @code{m4} macros
7038 This index covers all @code{m4} builtins, as well as several useful
7039 composite macros.  References are exclusively to the places where a
7040 macro is introduced the first time.
7042 @printindex fn
7044 @node Concept index
7045 @appendixsec Index for many concepts
7047 @printindex cp
7049 @bye
7051 @c Local Variables:
7052 @c coding: iso-8859-1
7053 @c fill-column: 72
7054 @c ispell-local-dictionary: "american"
7055 @c indent-tabs-mode: nil
7056 @c whitespace-check-buffer-indent: nil
7057 @c End: