modules: clean up no-longer supported preloading references.
[m4/ericb.git] / doc / m4.texi
blobba1b1576a1d8121191ceab86cb4726ba43d7096f
1 \input texinfo @c -*- texinfo -*-
2 @comment ========================================================
3 @comment %**start of header
4 @setfilename m4.info
5 @include version.texi
6 @settitle GNU M4 @value{VERSION} macro processor
7 @setchapternewpage odd
8 @ifnothtml
9 @setcontentsaftertitlepage
10 @end ifnothtml
11 @finalout
13 @set beta
15 @c @tabchar{}
16 @c ----------
17 @c The testsuite expects literal tab output in some examples, but
18 @c literal tabs in texinfo leads to formatting issues.
19 @macro tabchar
20 @       @c
21 @end macro
23 @c @ovar{ARG}
24 @c -------------------
25 @c The ARG is an optional argument.  To be used for macro arguments in
26 @c their documentation (@defmac).
27 @macro ovar{varname}
28 @r{[}@var{\varname\}@r{]}@c
29 @end macro
31 @c @dvar{ARG, DEFAULT}
32 @c -------------------
33 @c The ARG is an optional argument, defaulting to DEFAULT.  To be used
34 @c for macro arguments in their documentation (@defmac).
35 @macro dvar{varname, default}
36 @r{[}@var{\varname\} = @samp{\default\}@r{]}@c
37 @end macro
39 @comment %**end of header
40 @comment ========================================================
42 @copying
44 This manual (@value{UPDATED}) is for GNU M4 (version
45 @value{VERSION}), a package containing an implementation of the m4 macro
46 language.
48 Copyright @copyright{} 1989-1994, 2004-2011, 2013-2014 Free Software
49 Foundation, Inc.
51 @quotation
52 Permission is granted to copy, distribute and/or modify this document
53 under the terms of the GNU Free Documentation License,
54 Version 1.3 or any later version published by the Free Software
55 Foundation; with no Invariant Sections, no Front-Cover Texts, and no
56 Back-Cover Texts.  A copy of the license is included in the section
57 entitled ``GNU Free Documentation License.''
58 @end quotation
59 @end copying
61 @dircategory Text creation and manipulation
62 @direntry
63 * M4: (m4).                     A powerful macro processor.
64 @end direntry
66 @titlepage
67 @title GNU M4, version @value{VERSION}
68 @subtitle A powerful macro processor
69 @subtitle Edition @value{EDITION}, @value{UPDATED}
70 @author by Ren@'e Seindal, Fran@,{c}ois Pinard,
71 @author Gary V. Vaughan, and Eric Blake
72 @author (@email{bug-m4@@gnu.org})
74 @page
75 @vskip 0pt plus 1filll
76 @insertcopying
77 @end titlepage
79 @contents
81 @ifnottex
82 @node Top
83 @top GNU M4
84 @insertcopying
85 @end ifnottex
87 GNU @code{m4} is an implementation of the traditional UNIX macro
88 processor.  It is mostly SVR4 compatible, although it has some
89 extensions (for example, handling more than 9 positional parameters
90 to macros).  @code{m4} also has builtin functions for including
91 files, running shell commands, doing arithmetic, etc.  Autoconf needs
92 GNU @code{m4} for generating @file{configure} scripts, but not for
93 running them.
95 GNU @code{m4} was originally written by Ren@'e Seindal, with
96 subsequent changes by Fran@,{c}ois Pinard and other volunteers
97 on the Internet.  All names and email addresses can be found in the
98 files @file{m4-@value{VERSION}/@/AUTHORS} and
99 @file{m4-@value{VERSION}/@/THANKS} from the GNU M4
100 distribution.
102 @ifclear beta
103 This is release @value{VERSION}.  It is now considered stable:  future
104 releases on this branch are only meant to fix bugs, increase speed, or
105 improve documentation.
106 @end ifclear
108 @ifset beta
109 This is BETA release @value{VERSION}.  This is a development release,
110 and as such, is prone to bugs, crashes, unforeseen features, incomplete
111 documentation@dots{}, therefore, use at your own peril.  In case of
112 problems, please do not hesitate to report them (see the
113 @file{m4-@value{VERSION}/@/README} file in the distribution).
114 @xref{Experiments}.
115 @end ifset
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 * Modules::                     Extending M4 with dynamic runtime modules
134 * Text handling::               Macros for text handling
135 * Arithmetic::                  Macros for doing arithmetic
136 * Shell commands::              Macros for running shell commands
137 * Miscellaneous::               Miscellaneous builtin macros
138 * Frozen files::                Fast loading of frozen state
140 * Compatibility::               Compatibility with other versions of @code{m4}
141 * Answers::                     Correct version of some examples
143 * Copying This Package::        How to make copies of the overall M4 package
144 * Copying This Manual::         How to make copies of this manual
145 * Indices::                     Indices of concepts and macros
147 @detailmenu
148  --- The Detailed Node Listing ---
150 Introduction and preliminaries
152 * Intro::                       Introduction to @code{m4}
153 * History::                     Historical references
154 * Bugs::                        Problems and bugs
155 * Manual::                      Using this manual
157 Invoking @code{m4}
159 * Operation modes::             Command line options for operation modes
160 * Preprocessor features::       Command line options for preprocessor features
161 * Limits control::              Command line options for limits control
162 * Frozen state::                Command line options for frozen state
163 * Debugging options::           Command line options for debugging
164 * Command line files::          Specifying input files on the command line
166 Lexical and syntactic conventions
168 * Names::                       Macro names
169 * Quoted strings::              Quoting input to @code{m4}
170 * Comments::                    Comments in @code{m4} input
171 * Other tokens::                Other kinds of input tokens
172 * Input processing::            How @code{m4} copies input to output
173 * Regular expression syntax::   How @code{m4} interprets regular expressions
175 How to invoke macros
177 * Invocation::                  Macro invocation
178 * Inhibiting Invocation::       Preventing macro invocation
179 * Macro Arguments::             Macro arguments
180 * Quoting Arguments::           On Quoting Arguments to macros
181 * Macro expansion::             Expanding macros
183 How to define new macros
185 * Define::                      Defining a new macro
186 * Arguments::                   Arguments to macros
187 * Pseudo Arguments::            Special arguments to macros
188 * Undefine::                    Deleting a macro
189 * Defn::                        Renaming macros
190 * Pushdef::                     Temporarily redefining macros
191 * Renamesyms::                  Renaming macros with regular expressions
193 * Indir::                       Indirect call of macros
194 * Builtin::                     Indirect call of builtins
195 * M4symbols::                   Getting the defined macro names
197 Conditionals, loops, and recursion
199 * Ifdef::                       Testing if a macro is defined
200 * Ifelse::                      If-else construct, or multibranch
201 * Shift::                       Recursion in @code{m4}
202 * Forloop::                     Iteration by counting
203 * Foreach::                     Iteration by list contents
204 * Stacks::                      Working with definition stacks
205 * Composition::                 Building macros with macros
207 How to debug macros and input
209 * Dumpdef::                     Displaying macro definitions
210 * Trace::                       Tracing macro calls
211 * Debugmode::                   Controlling debugging options
212 * Debuglen::                    Limiting debug output
213 * Debugfile::                   Saving debugging output
215 Input control
217 * Dnl::                         Deleting whitespace in input
218 * Changequote::                 Changing the quote characters
219 * Changecom::                   Changing the comment delimiters
220 * Changeresyntax::              Changing the regular expression syntax
221 * Changesyntax::                Changing the lexical structure of the input
222 * M4wrap::                      Saving text until end of input
224 File inclusion
226 * Include::                     Including named files
227 * Search Path::                 Searching for include files
229 Diverting and undiverting output
231 * Divert::                      Diverting output
232 * Undivert::                    Undiverting output
233 * Divnum::                      Diversion numbers
234 * Cleardivert::                 Discarding diverted text
236 Extending M4 with dynamic runtime modules
238 * M4modules::                   Listing loaded modules
239 * Standard Modules::            Standard bundled modules
241 Macros for text handling
243 * Len::                         Calculating length of strings
244 * Index macro::                 Searching for substrings
245 * Regexp::                      Searching for regular expressions
246 * Substr::                      Extracting substrings
247 * Translit::                    Translating characters
248 * Patsubst::                    Substituting text by regular expression
249 * Format::                      Formatting strings (printf-like)
251 Macros for doing arithmetic
253 * Incr::                        Decrement and increment operators
254 * Eval::                        Evaluating integer expressions
255 * Mpeval::                      Multiple precision arithmetic
257 Macros for running shell commands
259 * Platform macros::             Determining the platform
260 * Syscmd::                      Executing simple commands
261 * Esyscmd::                     Reading the output of commands
262 * Sysval::                      Exit status
263 * Mkstemp::                     Making temporary files
264 * Mkdtemp::                     Making temporary directories
266 Miscellaneous builtin macros
268 * Errprint::                    Printing error messages
269 * Location::                    Printing current location
270 * M4exit::                      Exiting from @code{m4}
271 * Syncoutput::                  Turning on and off sync lines
273 Fast loading of frozen state
275 * Using frozen files::          Using frozen files
276 * Frozen file format 1::        Frozen file format 1
277 * Frozen file format 2::        Frozen file format 2
279 Compatibility with other versions of @code{m4}
281 * Extensions::                  Extensions in GNU M4
282 * Incompatibilities::           Other incompatibilities
283 * Experiments::                 Experimental features in GNU M4
285 Correct version of some examples
287 * Improved exch::               Solution for @code{exch}
288 * Improved forloop::            Solution for @code{forloop}
289 * Improved foreach::            Solution for @code{foreach}
290 * Improved copy::               Solution for @code{copy}
291 * Improved m4wrap::             Solution for @code{m4wrap}
292 * Improved cleardivert::        Solution for @code{cleardivert}
293 * Improved capitalize::         Solution for @code{capitalize}
294 * Improved fatal_error::        Solution for @code{fatal_error}
296 How to make copies of the overall M4 package
298 * GNU General Public License::  License for copying the M4 package
300 How to make copies of this manual
302 * GNU Free Documentation License::  License for copying this manual
304 Indices of concepts and macros
306 * Macro index::                 Index for all @code{m4} macros
307 * Concept index::               Index for many concepts
309 @end detailmenu
310 @end menu
312 @node Preliminaries
313 @chapter Introduction and preliminaries
315 This first chapter explains what GNU @code{m4} is, where @code{m4}
316 comes from, how to read and use this documentation, how to call the
317 @code{m4} program, and how to report bugs about it.  It concludes by
318 giving tips for reading the remainder of the manual.
320 The following chapters then detail all the features of the @code{m4}
321 language, as shipped in the GNU M4 package.
323 @menu
324 * Intro::                       Introduction to @code{m4}
325 * History::                     Historical references
326 * Bugs::                        Problems and bugs
327 * Manual::                      Using this manual
328 @end menu
330 @node Intro
331 @section Introduction to @code{m4}
333 @cindex overview of @code{m4}
334 @code{m4} is a macro processor, in the sense that it copies its
335 input to the output, expanding macros as it goes.  Macros are either
336 builtin or user-defined, and can take any number of arguments.
337 Besides just doing macro expansion, @code{m4} has builtin functions
338 for including named files, running shell commands, doing integer
339 arithmetic, manipulating text in various ways, performing recursion,
340 etc.@dots{}  @code{m4} can be used either as a front-end to a compiler,
341 or as a macro processor in its own right.
343 The @code{m4} macro processor is widely available on all UNIXes, and has
344 been standardized by POSIX.
345 Usually, only a small percentage of users are aware of its existence.
346 However, those who find it often become committed users.  The
347 popularity of GNU Autoconf, which requires GNU
348 @code{m4} for @emph{generating} @file{configure} scripts, is an incentive
349 for many to install it, while these people will not themselves
350 program in @code{m4}.  GNU @code{m4} is mostly compatible with the
351 System V, Release 4 version, except for some minor differences.
352 @xref{Compatibility}, for more details.
354 Some people find @code{m4} to be fairly addictive.  They first use
355 @code{m4} for simple problems, then take bigger and bigger challenges,
356 learning how to write complex sets of @code{m4} macros along the way.
357 Once really addicted, users pursue writing of sophisticated @code{m4}
358 applications even to solve simple problems, devoting more time
359 debugging their @code{m4} scripts than doing real work.  Beware that
360 @code{m4} may be dangerous for the health of compulsive programmers.
362 @node History
363 @section Historical references
365 @cindex history of @code{m4}
366 @cindex GNU M4, history of
367 Macro languages were invented early in the history of computing.  In the
368 1950s Alan Perlis suggested that the macro language be independent of the
369 language being processed.  Techniques such as conditional and recursive
370 macros, and using macros to define other macros, were described by Doug
371 McIlroy of Bell Labs in ``Macro Instruction Extensions of Compiler
372 Languages'', @emph{Communications of the ACM} 3, 4 (1960), 214--20,
373 @url{http://dx.doi.org/10.1145/367177.367223}.
375 An important precursor of @code{m4} was GPM; see C. Strachey,
376 @c The title uses lower case and has no space between "macro" and "generator".
377 ``A general purpose macrogenerator'', @emph{Computer Journal} 8, 3
378 (1965), 225--41, @url{http://dx.doi.org/10.1093/comjnl/8.3.225}.  GPM is
379 also succinctly described in David Gries's book @emph{Compiler
380 Construction for Digital Computers}, Wiley (1971).  Strachey was a
381 brilliant programmer: GPM fit into 250 machine instructions!
383 Inspired by GPM while visiting Strachey's Lab in 1968, McIlroy wrote a
384 model preprocessor in that fit into a page of Snobol 3 code, and McIlroy
385 and Robert Morris developed a series of further models at Bell Labs.
386 Andrew D. Hall followed up with M6, a general purpose macro processor
387 used to port the Fortran source code of the Altran computer algebra
388 system; see Hall's ``The M6 Macro Processor'', Computing Science
389 Technical Report #2, Bell Labs (1972),
390 @url{http://cm.bell-labs.com/cm/cs/cstr/2.pdf}.  M6's source code
391 consisted of about 600 Fortran statements.  Its name was the first of
392 the @code{m4} line.
394 The Brian Kernighan and P.J. Plauger book @emph{Software Tools},
395 Addison-Wesley (1976), describes and implements a Unix
396 macro-processor language, which inspired Dennis Ritchie to write
397 @code{m3}, a macro processor for the AP-3 minicomputer.
399 Kernighan and Ritchie then joined forces to develop the original
400 @code{m4}, described in ``The M4 Macro Processor'', Bell Laboratories
401 (1977), @url{http://wolfram.schneider.org/bsd/7thEdManVol2/m4/m4.pdf}.
402 It had only 21 builtin macros.
404 While @code{GPM} was more @emph{pure}, @code{m4} is meant to deal with
405 the true intricacies of real life: macros can be recognized without
406 being pre-announced, skipping whitespace or end-of-lines is easier,
407 more constructs are builtin instead of derived, etc.
409 Originally, the Kernighan and Plauger macro-processor, and then
410 @code{m3}, formed the engine for the Rational FORTRAN preprocessor,
411 that is, the @code{Ratfor} equivalent of @code{cpp}.  Later, @code{m4}
412 was used as a front-end for @code{Ratfor}, @code{C} and @code{Cobol}.
414 Ren@'e Seindal released his implementation of @code{m4}, GNU
415 @code{m4},
416 in 1990, with the aim of removing the artificial limitations in many
417 of the traditional @code{m4} implementations, such as maximum line
418 length, macro size, or number of macros.
420 The late Professor A. Dain Samples described and implemented a further
421 evolution in the form of @code{M5}: ``User's Guide to the M5 Macro
422 Language: 2nd edition'', Electronic Announcement on comp.compilers
423 newsgroup (1992).
425 Fran@,{c}ois Pinard took over maintenance of GNU @code{m4} in
426 1992, until 1994 when he released GNU @code{m4} 1.4, which was
427 the stable release for 10 years.  It was at this time that GNU
428 Autoconf decided to require GNU @code{m4} as its underlying
429 engine, since all other implementations of @code{m4} had too many
430 limitations.
432 More recently, in 2004, Paul Eggert released 1.4.1 and 1.4.2 which
433 addressed some long standing bugs in the venerable 1.4 release.  Then in
434 2005, Gary V. Vaughan collected together the many patches to
435 GNU @code{m4} 1.4 that were floating around the net and
436 released 1.4.3 and 1.4.4.  And in 2006, Eric Blake joined the team and
437 prepared patches for the release of 1.4.5, 1.4.6, 1.4.7, and 1.4.8.
438 More bug fixes were incorporated in 2007, with releases 1.4.9 and
439 1.4.10.  Eric continued with some portability fixes for 1.4.11 and
440 1.4.12 in 2008, 1.4.13 in 2009, 1.4.14 and 1.4.15 in 2010,  and 1.4.16
441 in 2011.  Following a long hiatus, Gary released 1.4.17 after upgrading
442 to the latest autotools (and gnulib) along with all the small fixes they
443 had accumulated.
445 Additionally, in 2008, Eric rewrote the scanning engine to reduce
446 recursive evaluation from quadratic to linear complexity.  This was
447 released as M4 1.6 in 2009.  The 1.x branch series remains open for bug
448 fixes.
450 Meanwhile, development was underway for new features for @code{m4},
451 such as dynamic module loading and additional builtins, practically
452 rewriting the entire code base.  This development has spurred
453 improvements to other GNU software, such as GNU
454 Libtool.  GNU M4 2.0 is the result of this effort.
456 @node Bugs
457 @section Problems and bugs
459 @cindex reporting bugs
460 @cindex bug reports
461 @cindex suggestions, reporting
462 If you have problems with GNU M4 or think you've found a bug,
463 please report it.  Before reporting a bug, make sure you've actually
464 found a real bug.  Carefully reread the documentation and see if it
465 really says you can do what you're trying to do.  If it's not clear
466 whether you should be able to do something or not, report that too; it's
467 a bug in the documentation!
469 Before reporting a bug or trying to fix it yourself, try to isolate it
470 to the smallest possible input file that reproduces the problem.  Then
471 send us the input file and the exact results @code{m4} gave you.  Also
472 say what you expected to occur; this will help us decide whether the
473 problem was really in the documentation.
475 Once you've got a precise problem, send e-mail to
476 @email{bug-m4@@gnu.org}.  Please include the version number of @code{m4}
477 you are using.  You can get this information with the command
478 @kbd{m4 --version}.  You can also run @kbd{make check} to generate the
479 file @file{tests/@/testsuite.log}, useful for including in your report.
481 Non-bug suggestions are always welcome as well.  If you have questions
482 about things that are unclear in the documentation or are just obscure
483 features, please report them too.
485 @node Manual
486 @section Using this manual
488 @cindex examples, understanding
489 This manual contains a number of examples of @code{m4} input and output,
490 and a simple notation is used to distinguish input, output and error
491 messages from @code{m4}.  Examples are set out from the normal text, and
492 shown in a fixed width font, like this
494 @comment ignore
495 @example
496 This is an example of an example!
497 @end example
499 To distinguish input from output, all output from @code{m4} is prefixed
500 by the string @samp{@result{}}, and all error messages by the string
501 @samp{@error{}}.  When showing how command line options affect matters,
502 the command line is shown with a prompt @samp{$ @kbd{like this}},
503 otherwise, you can assume that a simple @kbd{m4} invocation will work.
504 Thus:
506 @comment ignore
507 @example
508 $ @kbd{command line to invoke m4}
509 Example of input line
510 @result{}Output line from m4
511 @error{}and an error message
512 @end example
514 The sequence @samp{^D} in an example indicates the end of the input
515 file.  The sequence @samp{@key{NL}} refers to the newline character.
516 The majority of these examples are self-contained, and you can run them
517 with similar results.  In fact, the testsuite that is bundled in the
518 GNU M4 package consists in part of the examples
519 in this document!  Some of the examples assume that your current
520 directory is located where you unpacked the installation, so if you plan
521 on following along, you may find it helpful to do this now:
523 @comment ignore
524 @example
525 $ @kbd{cd m4-@value{VERSION}}
526 @end example
528 As each of the predefined macros in @code{m4} is described, a prototype
529 call of the macro will be shown, giving descriptive names to the
530 arguments, e.g.,
532 @deffn {Composite (none)} example (@var{string}, @dvar{count, 1}, @
533   @ovar{argument}@dots{})
534 This is a sample prototype.  There is not really a macro named
535 @code{example}, but this documents that if there were, it would be a
536 Composite macro, rather than a Builtin, and would be provided by the
537 module @code{none}.
539 It requires at least one argument, @var{string}.  Remember that in
540 @code{m4}, there must not be a space between the macro name and the
541 opening parenthesis, unless it was intended to call the macro without
542 any arguments.  The brackets around @var{count} and @var{argument} show
543 that these arguments are optional.  If @var{count} is omitted, the macro
544 behaves as if count were @samp{1}, whereas if @var{argument} is omitted,
545 the macro behaves as if it were the empty string.  A blank argument is
546 not the same as an omitted argument.  For example, @samp{example(`a')},
547 @samp{example(`a',`1')}, and @samp{example(`a',`1',)} would behave
548 identically with @var{count} set to @samp{1}; while @samp{example(`a',)}
549 and @samp{example(`a',`')} would explicitly pass the empty string for
550 @var{count}.  The ellipses (@samp{@dots{}}) show that the macro
551 processes additional arguments after @var{argument}, rather than
552 ignoring them.
553 @end deffn
555 Each builtin definition will list, in parentheses, the module that must
556 be loaded to use that macro.  The standard modules include
557 @samp{m4} (which is always available), @samp{gnu} (for GNU specific
558 m4 extensions), and @samp{traditional} (for compatibility with System V
559 m4).  @xref{Modules}.
561 @cindex numbers
562 All macro arguments in @code{m4} are strings, but some are given
563 special interpretation, e.g., as numbers, file names, regular
564 expressions, etc.  The documentation for each macro will state how the
565 parameters are interpreted, and what happens if the argument cannot be
566 parsed according to the desired interpretation.  Unless specified
567 otherwise, a parameter specified to be a number is parsed as a decimal,
568 even if the argument has leading zeros; and parsing the empty string as
569 a number results in 0 rather than an error, although a warning will be
570 issued.
572 This document consistently writes and uses @dfn{builtin}, without a
573 hyphen, as if it were an English word.  This is how the @code{builtin}
574 primitive is spelled within @code{m4}.
576 @node Invoking m4
577 @chapter Invoking @code{m4}
579 @cindex command line
580 @cindex invoking @code{m4}
581 The format of the @code{m4} command is:
583 @comment ignore
584 @example
585 @code{m4} @r{[}@var{option}@dots{}@r{]} @r{[}@var{file}@dots{}@r{]}
586 @end example
588 @cindex command line, options
589 @cindex options, command line
590 @cindex @env{POSIXLY_CORRECT}
591 All options begin with @samp{-}, or if long option names are used, with
592 @samp{--}.  A long option name need not be written completely, any
593 unambiguous prefix is sufficient.  POSIX requires @code{m4} to
594 recognize arguments intermixed with files, even when
595 @env{POSIXLY_CORRECT} is set in the environment.  Most options take
596 effect at startup regardless of their position, but some are documented
597 below as taking effect after any files that occurred earlier in the
598 command line.  The argument @option{--} is a marker to denote the end of
599 options.
601 With short options, options that do not take arguments may be combined
602 into a single command line argument with subsequent options, options
603 with mandatory arguments may be provided either as a single command line
604 argument or as two arguments, and options with optional arguments must
605 be provided as a single argument.  In other words,
606 @kbd{m4 -QPDfoo -d a -d+f} is equivalent to
607 @kbd{m4 -Q -P -D foo -d ./a -d+f}, although the latter form is
608 considered canonical.
610 With long options, options with mandatory arguments may be provided with
611 an equal sign (@samp{=}) in a single argument, or as two arguments, and
612 options with optional arguments must be provided as a single argument.
613 In other words, @kbd{m4 --def foo --debug a} is equivalent to
614 @kbd{m4 --define=foo --debug= -- ./a}, although the latter form is
615 considered canonical (not to mention more robust, in case a future
616 version of @code{m4} introduces an option named @option{--default}).
618 @code{m4} understands the following options, grouped by functionality.
620 @menu
621 * Operation modes::             Command line options for operation modes
622 * Preprocessor features::       Command line options for preprocessor features
623 * Limits control::              Command line options for limits control
624 * Frozen state::                Command line options for frozen state
625 * Debugging options::           Command line options for debugging
626 * Command line files::          Specifying input files on the command line
627 @end menu
629 @node Operation modes
630 @section Command line options for operation modes
632 Several options control the overall operation of @code{m4}:
634 @table @code
635 @item --help
636 Print a help summary on standard output, then immediately exit
637 @code{m4} without reading any input files or performing any other
638 actions.
640 @item --version
641 Print the version number of the program on standard output, then
642 immediately exit @code{m4} without reading any input files or
643 performing any other actions.
645 @item -b
646 @itemx --batch
647 Makes this invocation of @code{m4} non-interactive.  This means that
648 output will be buffered, and an interrupt or pipe write error will halt
649 execution.  If neither
650 @option{-b} nor @option{-i} are specified, this is activated by default
651 when any input files are specified, or when either standard input or
652 standard error is not a terminal.  Note that this means that @kbd{m4}
653 alone might be interactive, but @kbd{m4 -} is not, even though both
654 commands process only standard input.  If both @option{-b} and
655 @option{-i} are specified, only the last one takes effect.
657 @item -c
658 @itemx --discard-comments
659 Discard all comments instead of copying them to the output.
661 @item -E
662 @itemx --fatal-warnings
663 @cindex errors, fatal
664 @cindex fatal errors
665 Controls the effect of warnings.  If unspecified, then execution
666 continues and exit status is unaffected when a warning is printed.  If
667 specified exactly once, warnings become fatal; when one is issued,
668 execution continues, but the exit status will be non-zero.  If specified
669 multiple times, then execution halts with non-zero status the first time
670 a warning is issued.  The introduction of behavior levels is new to M4
671 1.4.9; for behavior consistent with earlier versions, you should specify
672 @option{-E} twice.
675 For backwards compatibility reasons, using @option{-E} behaves as if an
676 implicit @option{--debug=-d} option is also present.  This is so that
677 scripts written for older M4 versions will not fail if they used
678 constructs that were previously silently allowed, but would now trigger
679 a warning.
681 @example
682 $ @kbd{m4}
683 defn(`oops')
684 @error{}m4:stdin:1: warning: defn: undefined macro 'oops'
685 @result{}
687 @end example
689 @comment ignore
690 @example
691 $ @kbd{echo $?}
692 @result{}0
693 @end example
695 @comment options: -E
696 @example
697 $ @kbd{m4 -E}
698 defn(`oops')
699 @result{}
701 @end example
703 @comment ignore
704 @example
705 $ @kbd{echo $?}
706 @result{}0
707 @end example
709 @comment options: -E -d
710 @comment status: 1
711 @example
712 $ @kbd{m4 -E -d}
713 defn(`oops')
714 @error{}m4:stdin:1: warning: defn: undefined macro 'oops'
715 @result{}
717 @end example
719 @comment ignore
720 @example
721 $ @kbd{echo $?}
722 @result{}1
723 @end example
725 @item -i
726 @itemx --interactive
727 @itemx -e
728 Makes this invocation of @code{m4} interactive.  This means that all
729 output will be unbuffered, interrupts will be ignored, and behavior on
730 pipe write errors is inherited from the parent process.  If neither
731 @option{-b} nor @option{-i} are specified, this is activated by default
732 when no input files are specified, and when both standard input and
733 standard error are terminals (similar to the way that /bin/sh determines
734 when to be interactive).  If both @option{-b} and @option{-i} are
735 specified, only the last one takes effect.  The spelling @option{-e}
736 exists for compatibility with other @code{m4} implementations, and
737 issues a warning because it may be withdrawn in a future version of
738 GNU M4.
740 @item -P
741 @itemx --prefix-builtins
742 Internally modify @emph{all} builtin macro names so they all start with
743 the prefix @samp{m4_}.  For example, using this option, one should write
744 @samp{m4_define} instead of @samp{define}, and @samp{@w{m4___file__}}
745 instead of @samp{@w{__file__}}.  This option has no effect if @option{-R}
746 is also specified.
748 @item -Q
749 @itemx --quiet
750 @itemx --silent
751 Suppress warnings, such as missing or superfluous arguments in macro
752 calls, or treating the empty string as zero.  Error messages are still
753 printed.  The distinction between error and warning is fuzzy, and if
754 you encounter a situation where the message output did not match your
755 expectations, please report that as a bug.  This option is implied if
756 @env{POSIXLY_CORRECT} is set in the environment.
758 @item -r@r{[}@var{resyntax-spec}@r{]}
759 @itemx --regexp-syntax@r{[}=@var{resyntax-spec}@r{]}
760 Set the regular expression syntax according to @var{resyntax-spec}.
761 When this option is not given, or @var{resyntax-spec} is omitted,
762 GNU M4 uses the flavor @code{GNU_M4}, which provides
763 emacs-compatible regular expressions.  @xref{Changeresyntax}, for more
764 details on the format and meaning of @var{resyntax-spec}.  This option
765 may be given more than once, and order with respect to file names is
766 significant.
768 @item --safer
769 Cripple the following builtins, since each can perform potentially
770 unsafe actions: @code{maketemp}, @code{mkstemp} (@pxref{Mkstemp}),
771 @code{mkdtemp} (@pxref{Mkdtemp}), @code{debugfile} (@pxref{Debugfile}),
772 @code{syscmd} (@pxref{Syscmd}), and @code{esyscmd} (@pxref{Esyscmd}).
773 An attempt to use any of these macros will result in an error.  This
774 option is intended to make it safer to preprocess an input file of
775 unknown origin.
777 @item -W
778 @itemx --warnings
779 Enable warnings.  Warnings are on by default unless
780 @env{POSIXLY_CORRECT} was set in the environment; this option exists to
781 allow overriding @option{--silent}.
782 @comment FIXME should we accept -Wall, -Wnone, -Wcategory,
783 @comment -Wno-category...?
784 @end table
786 @node Preprocessor features
787 @section Command line options for preprocessor features
789 @cindex macro definitions, on the command line
790 @cindex command line, macro definitions on the
791 @cindex preprocessor features
792 Several options allow @code{m4} to behave more like a preprocessor.
793 Macro definitions and deletions can be made on the command line, the
794 search path can be altered, and the output file can track where the
795 input came from.  These features occur with the following options:
797 @table @code
798 @item -B @var{directory}
799 @itemx --prepend-include=@var{directory}
800 Make @code{m4} search @var{directory} for included files, prior to
801 searching the current working directory.  @xref{Search Path}, for more
802 details.  This option may be given more than once.  Some other
803 implementations of @code{m4} use @option{-B @var{number}} to change their
804 hard-coded limits, but that is unnecessary in GNU where the
805 only limit is your hardware capability.  So although it is unlikely that
806 you will want to include a relative directory whose name is purely
807 numeric, GNU @code{m4} will warn you about this potential
808 compatibility issue; you can avoid the warning by using the long
809 spelling, or by using @samp{./@var{number}} if you really meant it.
811 @item -D @var{name}@r{[}=@var{value}@r{]}
812 @itemx --define=@var{name}@r{[}=@var{value}@r{]}
813 This enters @var{name} into the symbol table.  If @samp{=@var{value}} is
814 missing, the value is taken to be the empty string.  The @var{value} can
815 be any string, and the macro can be defined to take arguments, just as
816 if it was defined from within the input.  This option may be given more
817 than once; order with respect to file names is significant, and
818 redefining the same @var{name} loses the previous value.
820 @item --import-environment
821 Imports every variable in the environment as a macro.  This is done
822 before @option{-D} and @option{-U}, so they can override the
823 environment.
825 @item -I @var{directory}
826 @itemx --include=@var{directory}
827 Make @code{m4} search @var{directory} for included files that are not
828 found in the current working directory.  @xref{Search Path}, for more
829 details.  This option may be given more than once.
831 @item --popdef=@var{name}
832 This deletes the top-most meaning @var{name} might have.  Obviously,
833 only predefined macros can be deleted in this way.  This option may be
834 given more than once; popping a @var{name} that does not have a
835 definition is silently ignored.  Order is significant with respect to
836 file names.
838 @item -p @var{name}@r{[}=@var{value}@r{]}
839 @itemx --pushdef=@var{name}@r{[}=@var{value}@r{]}
840 This enters @var{name} into the symbol table.  If @samp{=@var{value}} is
841 missing, the value is taken to be the empty string.  The @var{value} can
842 be any string, and the macro can be defined to take arguments, just as
843 if it was defined from within the input.  This option may be given more
844 than once; order with respect to file names is significant, and
845 redefining the same @var{name} adds another definition to its stack.
847 @item -s
848 @itemx --synclines
849 Short for @option{--syncoutput=1}, turning on synchronization lines
850 (sometimes called @dfn{synclines}).
852 @item --syncoutput@r{[}=@var{state}@r{]}
853 @cindex synchronization lines
854 @cindex location, input
855 @cindex input location
856 Control the generation of synchronization lines from the command line.
857 Synchronization lines are for use by the C preprocessor or other
858 similar tools.  Order is significant with respect to file names.  This
859 option is useful, for example, when @code{m4} is used as a
860 front end to a compiler.  Source file name and line number information
861 is conveyed by directives of the form @samp{#line @var{linenum}
862 "@var{file}"}, which are inserted as needed into the middle of the
863 output.  Such directives mean that the following line originated or was
864 expanded from the contents of input file @var{file} at line
865 @var{linenum}.  The @samp{"@var{file}"} part is often omitted when
866 the file name did not change from the previous directive.
868 Synchronization directives are always given on complete lines by
869 themselves.  When a synchronization discrepancy occurs in the middle of
870 an output line, the associated synchronization directive is delayed
871 until the next newline that does not occur in the middle of a quoted
872 string or comment.  @xref{Syncoutput}, for runtime control.  @var{state}
873 is interpreted the same as the argument to @code{syncoutput}; if
874 @var{state} is omitted, or @option{--syncoutput} is not used,
875 synchronization lines are disabled.
877 @item -U @var{name}
878 @itemx --undefine=@var{name}
879 This deletes any predefined meaning @var{name} might have.  Obviously,
880 only predefined macros can be deleted in this way.  This option may be
881 given more than once; undefining a @var{name} that does not have a
882 definition is silently ignored.  Order is significant with respect to
883 file names.
884 @end table
886 @node Limits control
887 @section Command line options for limits control
889 There are some limits within @code{m4} that can be tuned.  For
890 compatibility, @code{m4} also accepts some options that control limits
891 in other implementations, but which are automatically unbounded (limited
892 only by your hardware and operating system constraints) in GNU
893 @code{m4}.
895 @table @code
896 @item -g
897 @itemx --gnu
898 Enable all the extensions in this implementation.  This is on by
899 default unless @env{POSIXLY_CORRECT} is set in the environment; it
900 exists to allow overriding @option{--traditional}.
902 @item -G
903 @itemx --posix
904 @itemx --traditional
905 Suppress all the extensions made in this implementation, compared to the
906 System V version.  @xref{Compatibility}, for a list of these.  This
907 loads the @samp{traditional} module in place of the @samp{gnu} module.
908 It is implied if @env{POSIXLY_CORRECT} is set in the environment.
910 @item -L @var{num}
911 @itemx --nesting-limit=@var{num}
912 @cindex nesting limit
913 @cindex limit, nesting
914 Artificially limit the nesting of macro calls to @var{num} levels,
915 stopping program execution if this limit is ever exceeded.  When not
916 specified, nesting is limited to 1024 levels.  A value of zero means
917 unlimited; but then heavily nested code could potentially cause a stack
918 overflow.  @var{num} can have an optional scaling suffix.
919 @comment FIXME - need a node on what scaling suffixes are supported (see
920 @comment [info coreutils 'block size'] for ideas), and need to consider
921 @comment whether builtins should also understand scaling suffixes:
922 @comment eval, mpeval, perhaps format
924 The precise effect of this option might be more correctly associated
925 with textual nesting than dynamic recursion.  It has been useful
926 when some complex @code{m4} input was generated by mechanical means.
927 Most users would never need this option.  If shown to be obtrusive,
928 this option (which is still experimental) might well disappear.
930 @cindex rescanning
931 This option does @emph{not} have the ability to break endless
932 rescanning loops, since these do not necessarily consume much memory
933 or stack space.  Through clever usage of rescanning loops, one can
934 request complex, time-consuming computations from @code{m4} with useful
935 results.  Putting limitations in this area would break @code{m4} power.
936 There are many pathological cases: @w{@samp{define(`a', `a')a}} is
937 only the simplest example (but @pxref{Compatibility}).  Expecting GNU
938 @code{m4} to detect these would be a little like expecting a compiler
939 system to detect and diagnose endless loops: it is a quite @emph{hard}
940 problem in general, if not undecidable!
942 @item -H @var{num}
943 @itemx --hashsize=@var{num}
944 @itemx --word-regexp=@var{regexp}
945 These options are present only for compatibility with previous versions
946 of GNU @code{m4}.  They do nothing except issue a warning, because the
947 symbol table size is not fixed anymore, and because the new
948 @code{changesyntax} feature is more efficient than the withdrawn
949 experimental @code{changeword}.  These options will eventually disappear
950 in future releases.
952 @item -S @var{num}
953 @itemx -T @var{num}
954 These options are present for compatibility with System V @code{m4}, but
955 do nothing in this implementation.  They may disappear in future
956 releases, and issue a warning to that effect.
957 @end table
959 @node Frozen state
960 @section Command line options for frozen state
962 GNU @code{m4} comes with a feature of freezing internal state
963 (@pxref{Frozen files}).  This can be used to speed up @code{m4}
964 execution when reusing a common initialization script.
966 @table @code
967 @item -F @var{file}
968 @itemx --freeze-state=@var{file}
969 Once execution is finished, write out the frozen state on the specified
970 @var{file}.  It is conventional, but not required, for @var{file} to end
971 in @samp{.m4f}.
973 @item -R @var{file}
974 @itemx --reload-state=@var{file}
975 Before execution starts, recover the internal state from the specified
976 frozen @var{file}.  The options @option{-D}, @option{-U}, @option{-t},
977 @option{-m}, @option{-r}, and @option{--import-environment} take effect
978 after state is reloaded, but before the input files are read.
979 @end table
981 @node Debugging options
982 @section Command line options for debugging
984 Finally, there are several options for aiding in debugging @code{m4}
985 scripts.
987 @table @code
988 @item -d@r{[}@r{[}-@r{|}+@r{]}@var{flags}@r{]}
989 @itemx --debug@r{[}=@r{[}-@r{|}+@r{]}@var{flags}@r{]}
990 @itemx --debugmode@r{[}=@r{[}-@r{|}+@r{]}@var{flags}@r{]}
991 Set the debug-level according to the flags @var{flags}.  The debug-level
992 controls the format and amount of information presented by the debugging
993 functions.  @xref{Debugmode}, for more details on the format and
994 meaning of @var{flags}.  If omitted, @var{flags} defaults to
995 @samp{+adeq}.  If the option occurs multiple times, @var{flags} starting
996 with @samp{-} or @samp{+} are cumulative, while @var{flags} starting
997 with a letter override all earlier settings.  The debug-level starts
998 with @samp{d} enabled and all other flags disabled.  To disable all
999 previously set flags, specify an explicit @var{flags} of @samp{-V}.  For
1000 backward compatibility reasons, the option @option{--fatal-warnings}
1001 implies @samp{--debug=-d} as part of its effects.  The spelling
1002 @option{--debug} is recognized as an unambiguous option for
1003 compatibility with earlier versions of GNU M4, but for
1004 consistency with the builtin name, you can also use the spelling
1005 @option{--debugmode}.  Order is significant with respect to file names.
1007 The cumulative effect of the various options in this example is
1008 equivalent to a single invocation of @code{debugmode(`adlqx')}:
1010 @comment options: -d-V -d+lx --debug --debugmode=-e
1011 @example
1012 $ @kbd{m4 -d+lx --debug --debugmode=-e}
1013 traceon(`len')
1014 @result{}
1015 len(`123')
1016 @error{}m4trace:2: -1- id 2: len(`123')
1017 @result{}3
1018 @end example
1020 @item --debugfile@r{[}=@var{file}@r{]}
1021 @itemx -o @var{file}
1022 @itemx --error-output=@var{file}
1023 Redirect debug messages and trace output to the
1024 named @var{file}.  Warnings, error messages, and @code{errprint} output
1025 are still printed to standard error.  Output from @code{dumpdef} goes to
1026 this file when the debug level @code{o} is not set (@pxref{Debugmode}).
1027 If these options are not used, or
1028 if @var{file} is unspecified (only possible for @option{--debugfile}),
1029 debug output goes to standard error; if @var{file} is the empty string,
1030 debug output is discarded.  @xref{Debugfile}, for more details.  The
1031 option @option{--debugfile} may be given more than once, and order is
1032 significant with respect to file names.  The spellings @option{-o} and
1033 @option{--error-output} are misleading and
1034 inconsistent with other GNU tools; using those spellings will
1035 evoke a warning, and they may be withdrawn or change semantics in a
1036 future release.
1038 @item -l @var{num}
1039 @itemx --debuglen=@var{num}
1040 @itemx --arglength=@var{num}
1041 Restrict the size of the output generated by macro tracing or by
1042 @code{dumpdef} to @var{num} characters per string.  If unspecified or
1043 zero, output is unlimited.  @xref{Debuglen}, for more details.
1044 @var{num} can have an optional scaling suffix.  The spelling
1045 @option{--arglength} is deprecated, since it does not match the
1046 @code{debuglen} macro; using it will evoke a warning, and it may be
1047 withdrawn in a future release.
1048 @comment FIXME - Should we add an option that controls whether output
1049 @comment strings are sanitized with escape sequences, so that dumpdef is
1050 @comment truly one line per macro?
1051 @comment FIXME - see comment on --nesting-limit about NUM.
1053 @item -t @var{name}
1054 @itemx --trace=@var{name}
1055 @itemx --traceon=@var{name}
1056 This enables tracing for the macro @var{name}, at any point where it is
1057 defined.  @var{name} need not be defined when this option is given.
1058 This option may be given more than once, and order is significant with
1059 respect to file names.  @xref{Trace}, for more details.
1061 @item --traceoff=@var{name}
1062 This disables tracing for the macro @var{name}, at any point where it is
1063 defined.  @var{name} need not be defined when this option is given.
1064 This option may be given more than once, and order is significant with
1065 respect to file names.  @xref{Trace}, for more details.
1066 @end table
1068 @node Command line files
1069 @section Specifying input files on the command line
1071 @cindex command line, file names on the
1072 @cindex file names, on the command line
1073 The remaining arguments on the command line are taken to be input file
1074 names or module names (@pxref{Modules}).  Whether or not any modules
1075 are loaded from command line arguments, when no actual input file names
1076 are given, then standard input is read.  A file name of @file{-} can be
1077 used to denote standard input.  It is conventional, but not required,
1078 for input file names to end in @samp{.m4} and for module names to end
1079 in @samp{.la}.  The input files and modules are attended to in the
1080 sequence given.
1082 Standard input can be read more than once, so the file name @file{-}
1083 may appear multiple times on the command line; this makes a difference
1084 when input is from a terminal or other special file type.  It is an
1085 error if an input file ends in the middle of argument collection, a
1086 comment, or a quoted string.
1087 @comment FIXME - it would be nicer if we let these three things
1088 @comment continue across file boundaries, provided that we warn in
1089 @comment interactive use when switching to stdin in a non-default parse
1090 @comment state.
1092 Various options, such as @option{--define} (@option{-D}), @option{--undefine}
1093 (@option{-U}), @option{--synclines} (@option{-s}), @option{--trace}
1094 (@option{-t}), and @option{--regexp-syntax} (@option{-r}), only take
1095 effect after processing input from any file names that occur earlier
1096 on the command line.  For example, assume the file @file{foo} contains:
1098 @comment file: foo
1099 @example
1100 $ @kbd{cat foo}
1102 @end example
1104 The text @samp{bar} can then be redefined over multiple uses of
1105 @file{foo}:
1107 @comment options: -Dbar=hello foo -Dbar=world foo
1108 @example
1109 $ @kbd{m4 -Dbar=hello foo -Dbar=world foo}
1110 @result{}hello
1111 @result{}world
1112 @end example
1114 @cindex command line, module names on the
1115 @cindex module names, on the command line
1116 The use of loadable runtime modules in any sense is a GNU M4
1117 extension, so if @option{-G} is also passed or if the @env{POSIXLY_CORRECT}
1118 environment variable is set, even otherwise valid module names will be
1119 treated as though they were input file names (and no doubt cause havoc as
1120 M4 tries to scan and expand the contents as if it were written in @code{m4}).
1122 If none of the input files invoked @code{m4exit} (@pxref{M4exit}), the
1123 exit status of @code{m4} will be 0 for success, 1 for general failure
1124 (such as problems with reading an input file), and 63 for version
1125 mismatch (@pxref{Using frozen files}).
1127 If you need to read a file whose name starts with a @file{-}, you can
1128 specify it as @samp{./-file}, or use @option{--} to mark the end of
1129 options.
1131 @ignore
1132 @comment Test that 'm4 file/' detects that file is not a directory; we
1133 @comment can assume that the current directory contains a Makefile.
1134 @comment mingw fails with EINVAL rather than ENOTDIR.
1136 @comment status: 1
1137 @comment xerr: ignore
1138 @comment options: Makefile/
1139 @example
1140 @error{}m4: cannot open file 'Makefile/': No such file or directory
1141 @end example
1143 @comment Test that closed stderr does not cause a crash.  Not all
1144 @comment systems have the same message for EBADF.
1146 @comment xerr: ignore
1147 @example
1148 ifdef(`__unix__', ,
1149       `errprint(` skipping: syscmd does not have unix semantics
1150 ')m4exit(`77')')dnl
1151 syscmd(`echo | cat >&- 2>/dev/null')ifelse(sysval, `0',
1152        `errprint(` skipping: system does not allow closing stdout
1153 ')m4exit(`77')')dnl
1154 changequote(`[', `]')dnl
1155 syscmd([echo | ']__program__[' >&-])dnl
1156 @error{}m4: write error: Bad file descriptor
1157 sysval
1158 @result{}1
1159 @end example
1161 @example
1162 ifdef(`__unix__', ,
1163       `errprint(` skipping: syscmd does not have unix semantics
1164 ')m4exit(`77')')dnl
1165 syscmd(`echo | cat >&- 2>/dev/null')ifelse(sysval, `0',
1166        `errprint(` skipping: system does not allow closing stdout
1167 ')m4exit(`77')')dnl
1168 changequote(`[', `]')dnl
1169 syscmd([echo 'esyscmd(echo hi >&2 && echo err"print(bye
1170 )d"nl)dnl' > tmp.m4 \
1171   && ']__program__[' tmp.m4 <&- >&- \
1172   && rm tmp.m4])sysval
1173 @error{}hi
1174 @error{}bye
1175 @result{}0
1176 @end example
1178 @comment Test that we obey POSIX semantics with -D interspersed with
1179 @comment files, even with POSIXLY_CORRECT (BSD getopt gets it wrong).
1181 $ @kbd{m4 }
1182 @example
1183 ifdef(`__unix__', ,
1184       `errprint(` skipping: syscmd does not have unix semantics
1185 ')m4exit(`77')')dnl
1186 changequote(`[', `]')dnl
1187 syscmd([POSIXLY_CORRECT=1 ']__program__[' -Dbar=hello foo -Dbar=world foo])dnl
1188 @result{}hello
1189 @result{}world
1190 sysval
1191 @result{}0
1192 @end example
1193 @end ignore
1195 @node Syntax
1196 @chapter Lexical and syntactic conventions
1198 @cindex input tokens
1199 @cindex tokens
1200 As @code{m4} reads its input, it separates it into @dfn{tokens}.  A
1201 token is either a name, a quoted string, or any single character, that
1202 is not a part of either a name or a string.  Input to @code{m4} can also
1203 contain comments.  GNU @code{m4} does not yet understand
1204 multibyte locales; all operations are byte-oriented rather than
1205 character-oriented (although if your locale uses a single byte
1206 encoding, such as @sc{ISO-8859-1}, you will not notice a difference).
1207 However, @code{m4} is eight-bit clean, so you can
1208 use non-@sc{ascii} characters in quoted strings (@pxref{Changequote}),
1209 comments (@pxref{Changecom}), and macro names (@pxref{Indir}), with the
1210 exception of the @sc{nul} character (the zero byte @samp{'\0'}).
1212 @comment FIXME - each builtin needs to document how it handles NUL, then
1213 @comment update the above paragraph to mention that NUL is now handled
1214 @comment transparently.
1216 @menu
1217 * Names::                       Macro names
1218 * Quoted strings::              Quoting input to @code{m4}
1219 * Comments::                    Comments in @code{m4} input
1220 * Other tokens::                Other kinds of input tokens
1221 * Input processing::            How @code{m4} copies input to output
1222 * Regular expression syntax::   How @code{m4} interprets regular expressions
1223 @end menu
1225 @node Names
1226 @section Macro names
1228 @cindex names
1229 @cindex words
1230 A name is any sequence of letters, digits, and the character @samp{_}
1231 (underscore), where the first character is not a digit.  @code{m4} will
1232 use the longest such sequence found in the input.  If a name has a
1233 macro definition, it will be subject to macro expansion
1234 (@pxref{Macros}).  Names are case-sensitive.
1236 Examples of legal names are: @samp{foo}, @samp{_tmp}, and @samp{name01}.
1238 The definitions of letters, digits and other input characters can be
1239 changed at any time, using the builtin macro @code{changesyntax}.
1240 @xref{Changesyntax}, for more information.
1242 @node Quoted strings
1243 @section Quoting input to @code{m4}
1245 @cindex quoted string
1246 @cindex string, quoted
1247 A quoted string is a sequence of characters surrounded by quote
1248 strings, defaulting to
1249 @samp{`} (grave-accent, also known as back-tick, with UCS value U0060)
1250 and @samp{'} (apostrophe, also known as single-quote, with UCS value
1251 U0027), where the nested begin and end quotes within the
1252 string are balanced.  The value of a string token is the text, with one
1253 level of quotes stripped off.  Thus
1255 @comment ignore
1256 @example
1258 @result{}
1259 @end example
1261 @noindent
1262 is the empty string, and double-quoting turns into single-quoting.
1264 @comment ignore
1265 @example
1266 ``quoted''
1267 @result{}`quoted'
1268 @end example
1270 The quote characters can be changed at any time, using the builtin macros
1271 @code{changequote} (@pxref{Changequote}) or @code{changesyntax}
1272 (@pxref{Changesyntax}).
1274 @node Comments
1275 @section Comments in @code{m4} input
1277 @cindex comments
1278 Comments in @code{m4} are normally delimited by the characters @samp{#}
1279 and newline.  All characters between the comment delimiters are ignored,
1280 but the entire comment (including the delimiters) is passed through to
1281 the output, unless you supply the @option{--discard-comments} or
1282 @option{-c} option at the command line (@pxref{Operation modes, ,
1283 Invoking m4}).  When discarding comments, the comment delimiters are
1284 discarded, even if the close-comment string is a newline.
1286 Comments cannot be nested, so the first newline after a @samp{#} ends
1287 the comment.  The commenting effect of the begin-comment string
1288 can be inhibited by quoting it.
1290 @example
1291 $ @kbd{m4}
1292 `quoted text' # `commented text'
1293 @result{}quoted text # `commented text'
1294 `quoting inhibits' `#' `comments'
1295 @result{}quoting inhibits # comments
1296 @end example
1298 @comment options: -c
1299 @example
1300 $ @kbd{m4 -c}
1301 `quoted text' # `commented text'
1302 `quoting inhibits' `#' `comments'
1303 @result{}quoted text quoting inhibits # comments
1304 @end example
1306 The comment delimiters can be changed to any string at any time, using
1307 the builtin macros @code{changecom} (@pxref{Changecom}) or
1308 @code{changesyntax} (@pxref{Changesyntax}).
1310 @node Other tokens
1311 @section Other kinds of input tokens
1313 @cindex tokens, special
1314 Any character, that is neither a part of a name, nor of a quoted string,
1315 nor a comment, is a token by itself.  When not in the context of macro
1316 expansion, all of these tokens are just copied to output.  However,
1317 during macro expansion, whitespace characters (space, tab, newline,
1318 formfeed, carriage return, vertical tab), parentheses (@samp{(} and
1319 @samp{)}), comma (@samp{,}), and dollar (@samp{$}) have additional
1320 roles, explained later.  Which characters actually perform these roles
1321 can be adjusted with @code{changesyntax} (@pxref{Changesyntax}).
1323 @node Input processing
1324 @section How @code{m4} copies input to output
1326 As @code{m4} reads the input token by token, it will copy each token
1327 directly to the output immediately.
1329 The exception is when it finds a word with a macro definition.  In that
1330 case @code{m4} will calculate the macro's expansion, possibly reading
1331 more input to get the arguments.  It then inserts the expansion in front
1332 of the remaining input.  In other words, the resulting text from a macro
1333 call will be read and parsed into tokens again.
1335 @code{m4} expands a macro as soon as possible.  If it finds a macro call
1336 when collecting the arguments to another, it will expand the second call
1337 first.  This process continues until there are no more macro calls to
1338 expand and all the input has been consumed.
1340 For a running example, examine how @code{m4} handles this input:
1342 @comment ignore
1343 @example
1344 format(`Result is %d', eval(`2**15'))
1345 @end example
1347 @noindent
1348 First, @code{m4} sees that the token @samp{format} is a macro name, so
1349 it collects the tokens @samp{(}, @samp{`Result is %d'}, @samp{,},
1350 and @samp{@w{ }}, before encountering another potential macro.  Sure
1351 enough, @samp{eval} is a macro name, so the nested argument collection
1352 picks up @samp{(}, @samp{`2**15'}, and @samp{)}, invoking the eval macro
1353 with the lone argument of @samp{2**15}.  The expansion of
1354 @samp{eval(2**15)} is @samp{32768}, which is then rescanned as the five
1355 tokens @samp{3}, @samp{2}, @samp{7}, @samp{6}, and @samp{8}; and
1356 combined with the next @samp{)}, the format macro now has all its
1357 arguments, as if the user had typed:
1359 @comment ignore
1360 @example
1361 format(`Result is %d', 32768)
1362 @end example
1364 @noindent
1365 The format macro expands to @samp{Result is 32768}, and we have another
1366 round of scanning for the tokens @samp{Result}, @samp{@w{ }},
1367 @samp{is}, @samp{@w{ }}, @samp{3}, @samp{2}, @samp{7}, @samp{6}, and
1368 @samp{8}.  None of these are macros, so the final output is
1370 @comment ignore
1371 @example
1372 @result{}Result is 32768
1373 @end example
1375 As a more complicated example, we will contrast an actual code example
1376 from the Gnulib project@footnote{Derived from a patch in
1377 @uref{http://lists.gnu.org/archive/html/bug-gnulib/@/2007-01/@/msg00389.html},
1378 and a followup patch in
1379 @uref{http://lists.gnu.org/archive/html/bug-gnulib/@/2007-02/@/msg00000.html}},
1380 showing both a buggy approach and the desired results.  The user desires
1381 to output a shell assignment statement that takes its argument and turns
1382 it into a shell variable by converting it to uppercase and prepending a
1383 prefix.  The original attempt looks like this:
1385 @example
1386 changequote([,])dnl
1387 define([gl_STRING_MODULE_INDICATOR],
1388   [
1389     dnl comment
1390     GNULIB_]translit([$1],[a-z],[A-Z])[=1
1391   ])dnl
1392   gl_STRING_MODULE_INDICATOR([strcase])
1393 @result{} @w{ }
1394 @result{}        GNULIB_strcase=1
1395 @result{} @w{ }
1396 @end example
1398 Oops -- the argument did not get capitalized.  And although the manual
1399 is not able to easily show it, both lines that appear empty actually
1400 contain two trailing spaces.  By stepping through the parse, it is easy
1401 to see what happened.  First, @code{m4} sees the token
1402 @samp{changequote}, which it recognizes as a macro, followed by
1403 @samp{(}, @samp{[}, @samp{,}, @samp{]}, and @samp{)} to form the
1404 argument list.  The macro expands to the empty string, but changes the
1405 quoting characters to something more useful for generating shell code
1406 (unbalanced @samp{`} and @samp{'} appear all the time in shell scripts,
1407 but unbalanced @samp{[]} tend to be rare).  Also in the first line,
1408 @code{m4} sees the token @samp{dnl}, which it recognizes as a builtin
1409 macro that consumes the rest of the line, resulting in no output for
1410 that line.
1412 The second line starts a macro definition.  @code{m4} sees the token
1413 @samp{define}, which it recognizes as a macro, followed by a @samp{(},
1414 @samp{[gl_STRING_MODULE_INDICATOR]}, and @samp{,}.  Because an unquoted
1415 comma was encountered, the first argument is known to be the expansion
1416 of the single-quoted string token, or @samp{gl_STRING_MODULE_INDICATOR}.
1417 Next, @code{m4} sees @samp{@key{NL}}, @samp{ }, and @samp{ }, but this
1418 whitespace is discarded as part of argument collection.  Then comes a
1419 rather lengthy single-quoted string token, @samp{[@key{NL}@ @ @ @ dnl
1420 comment@key{NL}@ @ @ @ GNULIB_]}.  This is followed by the token
1421 @samp{translit}, which @code{m4} recognizes as a macro name, so a nested
1422 macro expansion has started.
1424 The arguments to the @code{translit} are found by the tokens @samp{(},
1425 @samp{[$1]}, @samp{,}, @samp{[a-z]}, @samp{,}, @samp{[A-Z]}, and finally
1426 @samp{)}.  All three string arguments are expanded (or in other words,
1427 the quotes are stripped), and since neither @samp{$} nor @samp{1} need
1428 capitalization, the result of the macro is @samp{$1}.  This expansion is
1429 rescanned, resulting in the two literal characters @samp{$} and
1430 @samp{1}.
1432 Scanning of the outer macro resumes, and picks up with
1433 @samp{[=1@key{NL}@ @ ]}, and finally @samp{)}.  The collected pieces of
1434 expanded text are concatenated, with the end result that the macro
1435 @samp{gl_STRING_MODULE_INDICATOR} is now defined to be the sequence
1436 @samp{@key{NL}@ @ @ @ dnl comment@key{NL}@ @ @ @ GNULIB_$1=1@key{NL}@ @ }.
1437 Once again, @samp{dnl} is recognized and avoids a newline in the output.
1439 The final line is then parsed, beginning with @samp{ } and @samp{ }
1440 that are output literally.  Then @samp{gl_STRING_MODULE_INDICATOR} is
1441 recognized as a macro name, with an argument list of @samp{(},
1442 @samp{[strcase]}, and @samp{)}.  Since the definition of the macro
1443 contains the sequence @samp{$1}, that sequence is replaced with the
1444 argument @samp{strcase} prior to starting the rescan.  The rescan sees
1445 @samp{@key{NL}} and four spaces, which are output literally, then
1446 @samp{dnl}, which discards the text @samp{ comment@key{NL}}.  Next
1447 comes four more spaces, also output literally, and the token
1448 @samp{GNULIB_strcase}, which resulted from the earlier parameter
1449 substitution.  Since that is not a macro name, it is output literally,
1450 followed by the literal tokens @samp{=}, @samp{1}, @samp{@key{NL}}, and
1451 two more spaces.  Finally, the original @samp{@key{NL}} seen after the
1452 macro invocation is scanned and output literally.
1454 Now for a corrected approach.  This rearranges the use of newlines and
1455 whitespace so that less whitespace is output (which, although harmless
1456 to shell scripts, can be visually unappealing), and fixes the quoting
1457 issues so that the capitalization occurs when the macro
1458 @samp{gl_STRING_MODULE_INDICATOR} is invoked, rather then when it is
1459 defined.  It also adds another layer of quoting to the first argument of
1460 @code{translit}, to ensure that the output will be rescanned as a string
1461 rather than a potential uppercase macro name needing further expansion.
1463 @example
1464 changequote([,])dnl
1465 define([gl_STRING_MODULE_INDICATOR],
1466   [dnl comment
1467   GNULIB_[]translit([[$1]], [a-z], [A-Z])=1dnl
1468 ])dnl
1469   gl_STRING_MODULE_INDICATOR([strcase])
1470 @result{}    GNULIB_STRCASE=1
1471 @end example
1473 The parsing of the first line is unchanged.  The second line sees the
1474 name of the macro to define, then sees the discarded @samp{@key{NL}}
1475 and two spaces, as before.  But this time, the next token is
1476 @samp{[dnl comment@key{NL}@ @ GNULIB_[]translit([[$1]], [a-z],
1477 [A-Z])=1dnl@key{NL}]}, which includes nested quotes, followed by
1478 @samp{)} to end the macro definition and @samp{dnl} to skip the
1479 newline.  No early expansion of @code{translit} occurs, so the entire
1480 string becomes the definition of the macro.
1482 The final line is then parsed, beginning with two spaces that are
1483 output literally, and an invocation of
1484 @code{gl_STRING_MODULE_INDICATOR} with the argument @samp{strcase}.
1485 Again, the @samp{$1} in the macro definition is substituted prior to
1486 rescanning.  Rescanning first encounters @samp{dnl}, and discards
1487 @samp{ comment@key{NL}}.  Then two spaces are output literally.  Next
1488 comes the token @samp{GNULIB_}, but that is not a macro, so it is
1489 output literally.  The token @samp{[]} is an empty string, so it does
1490 not affect output.  Then the token @samp{translit} is encountered.
1492 This time, the arguments to @code{translit} are parsed as @samp{(},
1493 @samp{[[strcase]]}, @samp{,}, @samp{ }, @samp{[a-z]}, @samp{,}, @samp{ },
1494 @samp{[A-Z]}, and @samp{)}.  The two spaces are discarded, and the
1495 translit results in the desired result @samp{[STRCASE]}.  This is
1496 rescanned, but since it is a string, the quotes are stripped and the
1497 only output is a literal @samp{STRCASE}.
1498 Then the scanner sees @samp{=} and @samp{1}, which are output
1499 literally, followed by @samp{dnl} which discards the rest of the
1500 definition of @code{gl_STRING_MODULE_INDICATOR}.  The newline at the
1501 end of output is the literal @samp{@key{NL}} that appeared after the
1502 invocation of the macro.
1504 The order in which @code{m4} expands the macros can be further explored
1505 using the trace facilities of GNU @code{m4} (@pxref{Trace}).
1507 @node Regular expression syntax
1508 @section How @code{m4} interprets regular expressions
1510 There are several contexts where @code{m4} parses an argument as a
1511 regular expression.  This section describes the various flavors of
1512 regular expressions.  @xref{Changeresyntax}.
1514 @include regexprops-generic.texi
1516 @node Macros
1517 @chapter How to invoke macros
1519 This chapter covers macro invocation, macro arguments and how macro
1520 expansion is treated.
1522 @menu
1523 * Invocation::                  Macro invocation
1524 * Inhibiting Invocation::       Preventing macro invocation
1525 * Macro Arguments::             Macro arguments
1526 * Quoting Arguments::           On Quoting Arguments to macros
1527 * Macro expansion::             Expanding macros
1528 @end menu
1530 @node Invocation
1531 @section Macro invocation
1533 @cindex macro invocation
1534 @cindex invoking macros
1535 Macro invocations has one of the forms
1537 @comment ignore
1538 @example
1539 name
1540 @end example
1542 @noindent
1543 which is a macro invocation without any arguments, or
1545 @comment ignore
1546 @example
1547 name(arg1, arg2, @dots{}, arg@var{n})
1548 @end example
1550 @noindent
1551 which is a macro invocation with @var{n} arguments.  Macros can have any
1552 number of arguments.  All arguments are strings, but different macros
1553 might interpret the arguments in different ways.
1555 The opening parenthesis @emph{must} follow the @var{name} directly, with
1556 no spaces in between.  If it does not, the macro is called with no
1557 arguments at all.
1559 For a macro call to have no arguments, the parentheses @emph{must} be
1560 left out.  The macro call
1562 @comment ignore
1563 @example
1564 name()
1565 @end example
1567 @noindent
1568 is a macro call with one argument, which is the empty string, not a call
1569 with no arguments.
1571 @node Inhibiting Invocation
1572 @section Preventing macro invocation
1574 An innovation of the @code{m4} language, compared to some of its
1575 predecessors (like Strachey's @code{GPM}, for example), is the ability
1576 to recognize macro calls without resorting to any special, prefixed
1577 invocation character.  While generally useful, this feature might
1578 sometimes be the source of spurious, unwanted macro calls.  So, GNU
1579 @code{m4} offers several mechanisms or techniques for inhibiting the
1580 recognition of names as macro calls.
1582 @cindex GNU extensions
1583 @cindex blind macro
1584 @cindex macro, blind
1585 First of all, many builtin macros cannot meaningfully be called without
1586 arguments.  As a GNU extension, for any of these macros,
1587 whenever an opening parenthesis does not immediately follow their name,
1588 the builtin macro call is not triggered.  This solves the most usual
1589 cases, like for @samp{include} or @samp{eval}.  Later in this document,
1590 the sentence ``This macro is recognized only with parameters'' refers to
1591 this specific provision of GNU M4, also known as a blind
1592 builtin macro.  For the builtins defined by POSIX that bear
1593 this disclaimer, POSIX specifically states that invoking those
1594 builtins without arguments is unspecified, because many other
1595 implementations simply invoke the builtin as though it were given one
1596 empty argument instead.
1598 @example
1599 $ @kbd{m4}
1600 eval
1601 @result{}eval
1602 eval(`1')
1603 @result{}1
1604 @end example
1606 There is also a command line option (@option{--prefix-builtins}, or
1607 @option{-P}, @pxref{Operation modes, , Invoking m4}) that renames all
1608 builtin macros with a prefix of @samp{m4_} at startup.  The option has
1609 no effect whatsoever on user defined macros.  For example, with this option,
1610 one has to write @code{m4_dnl} and even @code{m4_m4exit}.  It also has
1611 no effect on whether a macro requires parameters.
1613 @comment options: -P
1614 @example
1615 $ @kbd{m4 -P}
1616 eval
1617 @result{}eval
1618 eval(`1')
1619 @result{}eval(1)
1620 m4_eval
1621 @result{}m4_eval
1622 m4_eval(`1')
1623 @result{}1
1624 @end example
1626 Another alternative is to redefine problematic macros to a name less
1627 likely to cause conflicts, using @ref{Definitions}.  Or the parsing
1628 engine can be changed to redefine what constitutes a valid macro name,
1629 using @ref{Changesyntax}.
1631 Of course, the simplest way to prevent a name from being interpreted
1632 as a call to an existing macro is to quote it.  The remainder of
1633 this section studies a little more deeply how quoting affects macro
1634 invocation, and how quoting can be used to inhibit macro invocation.
1636 Even if quoting is usually done over the whole macro name, it can also
1637 be done over only a few characters of this name (provided, of course,
1638 that the unquoted portions are not also a macro).  It is also possible
1639 to quote the empty string, but this works only @emph{inside} the name.
1640 For example:
1642 @example
1643 `divert'
1644 @result{}divert
1645 `d'ivert
1646 @result{}divert
1647 di`ver't
1648 @result{}divert
1649 div`'ert
1650 @result{}divert
1651 @end example
1653 @noindent
1654 all yield the string @samp{divert}.  While in both:
1656 @example
1657 `'divert
1658 @result{}
1659 divert`'
1660 @result{}
1661 @end example
1663 @noindent
1664 the @code{divert} builtin macro will be called, which expands to the
1665 empty string.
1667 @cindex rescanning
1668 The output of macro evaluations is always rescanned.  In the following
1669 example, the input @samp{x`'y} yields the string @samp{bCD}, exactly as
1670 if @code{m4}
1671 has been given @w{@samp{substr(ab`'cde, `1', `3')}} as input:
1673 @example
1674 define(`cde', `CDE')
1675 @result{}
1676 define(`x', `substr(ab')
1677 @result{}
1678 define(`y', `cde, `1', `3')')
1679 @result{}
1680 x`'y
1681 @result{}bCD
1682 @end example
1684 Unquoted strings on either side of a quoted string are subject to
1685 being recognized as macro names.  In the following example, quoting the
1686 empty string allows for the second @code{macro} to be recognized as such:
1688 @example
1689 define(`macro', `m')
1690 @result{}
1691 macro(`m')macro
1692 @result{}mmacro
1693 macro(`m')`'macro
1694 @result{}mm
1695 @end example
1697 Quoting may prevent recognizing as a macro name the concatenation of a
1698 macro expansion with the surrounding characters.  In this example:
1700 @example
1701 define(`macro', `di$1')
1702 @result{}
1703 macro(`v')`ert'
1704 @result{}divert
1705 macro(`v')ert
1706 @result{}
1707 @end example
1709 @noindent
1710 the input will produce the string @samp{divert}.  When the quotes were
1711 removed, the @code{divert} builtin was called instead.
1713 @node Macro Arguments
1714 @section Macro arguments
1716 @cindex macros, arguments to
1717 @cindex arguments to macros
1718 When a name is seen, and it has a macro definition, it will be expanded
1719 as a macro.
1721 If the name is followed by an opening parenthesis, the arguments will be
1722 collected before the macro is called.  If too few arguments are
1723 supplied, the missing arguments are taken to be the empty string.
1724 However, some builtins are documented to behave differently for a
1725 missing optional argument than for an explicit empty string.  If there
1726 are too many arguments, the excess arguments are ignored.  Unquoted
1727 leading whitespace is stripped off all arguments, but whitespace
1728 generated by a macro expansion or occurring after a macro that expanded
1729 to an empty string remains intact.  Whitespace includes space, tab,
1730 newline, carriage return, vertical tab, and formfeed.
1732 @example
1733 define(`macro', `$1')
1734 @result{}
1735 macro( unquoted leading space lost)
1736 @result{}unquoted leading space lost
1737 macro(` quoted leading space kept')
1738 @result{} quoted leading space kept
1739 macro(
1740  divert `unquoted space kept after expansion')
1741 @result{} unquoted space kept after expansion
1742 macro(macro(`
1743 ')`whitespace from expansion kept')
1744 @result{}
1745 @result{}whitespace from expansion kept
1746 macro(`unquoted trailing whitespace kept'
1748 @result{}unquoted trailing whitespace kept
1749 @result{}
1750 @end example
1752 @cindex warnings, suppressing
1753 @cindex suppressing warnings
1754 Normally @code{m4} will issue warnings if a builtin macro is called
1755 with an inappropriate number of arguments, but it can be suppressed with
1756 the @option{--quiet} command line option (or @option{--silent}, or
1757 @option{-Q}, @pxref{Operation modes, , Invoking m4}).  For user
1758 defined macros, there is no check of the number of arguments given.
1760 @example
1761 $ @kbd{m4}
1762 index(`abc')
1763 @error{}m4:stdin:1: warning: index: too few arguments: 1 < 2
1764 @result{}0
1765 index(`abc',)
1766 @result{}0
1767 index(`abc', `b', `0', `ignored')
1768 @error{}m4:stdin:3: warning: index: extra arguments ignored: 4 > 3
1769 @result{}1
1770 @end example
1772 @comment options: -Q
1773 @example
1774 $ @kbd{m4 -Q}
1775 index(`abc')
1776 @result{}0
1777 index(`abc',)
1778 @result{}0
1779 index(`abc', `b', `', `ignored')
1780 @result{}1
1781 @end example
1783 Macros are expanded normally during argument collection, and whatever
1784 commas, quotes and parentheses that might show up in the resulting
1785 expanded text will serve to define the arguments as well.  Thus, if
1786 @var{foo} expands to @samp{, b, c}, the macro call
1788 @comment ignore
1789 @example
1790 bar(a foo, d)
1791 @end example
1793 @noindent
1794 is a macro call with four arguments, which are @samp{a }, @samp{b},
1795 @samp{c} and @samp{d}.  To understand why the first argument contains
1796 whitespace, remember that unquoted leading whitespace is never part
1797 of an argument, but trailing whitespace always is.
1799 It is possible for a macro's definition to change during argument
1800 collection, in which case the expansion uses the definition that was in
1801 effect at the time the opening @samp{(} was seen.
1803 @example
1804 define(`f', `1')
1805 @result{}
1806 f(define(`f', `2'))
1807 @result{}1
1809 @result{}2
1810 @end example
1812 It is an error if the end of file occurs while collecting arguments.
1814 @comment status: 1
1815 @example
1816 hello world
1817 @result{}hello world
1818 define(
1820 @error{}m4:stdin:2: define: end of file in argument list
1821 @end example
1823 @node Quoting Arguments
1824 @section On Quoting Arguments to macros
1826 @cindex quoted macro arguments
1827 @cindex macros, quoted arguments to
1828 @cindex arguments, quoted macro
1829 Each argument has unquoted leading whitespace removed.  Within each
1830 argument, all unquoted parentheses must match.  For example, if
1831 @var{foo} is a macro,
1833 @comment ignore
1834 @example
1835 foo(() (`(') `(')
1836 @end example
1838 @noindent
1839 is a macro call, with one argument, whose value is @samp{() (() (}.
1840 Commas separate arguments, except when they occur inside quotes,
1841 comments, or unquoted parentheses.  @xref{Pseudo Arguments}, for
1842 examples.
1844 It is common practice to quote all arguments to macros, unless you are
1845 sure you want the arguments expanded.  Thus, in the above
1846 example with the parentheses, the `right' way to do it is like this:
1848 @comment ignore
1849 @example
1850 foo(`() (() (')
1851 @end example
1853 @cindex quoting rule of thumb
1854 @cindex rule of thumb, quoting
1855 It is, however, in certain cases necessary (because nested expansion
1856 must occur to create the arguments for the outer macro) or convenient
1857 (because it uses fewer characters) to leave out quotes for some
1858 arguments, and there is nothing wrong in doing it.  It just makes life a
1859 bit harder, if you are not careful to follow a consistent quoting style.
1860 For consistency, this manual follows the rule of thumb that each layer
1861 of parentheses introduces another layer of single quoting, except when
1862 showing the consequences of quoting rules.  This is done even when the
1863 quoted string cannot be a macro, such as with integers when you have not
1864 changed the syntax via @code{changesyntax} (@pxref{Changesyntax}).
1866 The quoting rule of thumb of one level of quoting per parentheses has a
1867 nice property: when a macro name appears inside parentheses, you can
1868 determine when it will be expanded.  If it is not quoted, it will be
1869 expanded prior to the outer macro, so that its expansion becomes the
1870 argument.  If it is single-quoted, it will be expanded after the outer
1871 macro.  And if it is double-quoted, it will be used as literal text
1872 instead of a macro name.
1874 @example
1875 define(`active', `ACT, IVE')
1876 @result{}
1877 define(`show', `$1 $1')
1878 @result{}
1879 show(active)
1880 @result{}ACT ACT
1881 show(`active')
1882 @result{}ACT, IVE ACT, IVE
1883 show(``active'')
1884 @result{}active active
1885 @end example
1887 @node Macro expansion
1888 @section Macro expansion
1890 @cindex macros, expansion of
1891 @cindex expansion of macros
1892 When the arguments, if any, to a macro call have been collected, the
1893 macro is expanded, and the expansion text is pushed back onto the input
1894 (unquoted), and reread.  The expansion text from one macro call might
1895 therefore result in more macros being called, if the calls are included,
1896 completely or partially, in the first macro calls' expansion.
1898 Taking a very simple example, if @var{foo} expands to @samp{bar}, and
1899 @var{bar} expands to @samp{Hello world}, the input
1901 @comment options: -Dbar='Hello world' -Dfoo=bar
1902 @example
1903 $ @kbd{m4 -Dbar="Hello world" -Dfoo=bar}
1905 @result{}Hello world
1906 @end example
1908 @noindent
1909 will expand first to @samp{bar}, and when this is reread and
1910 expanded, into @samp{Hello world}.
1912 @node Definitions
1913 @chapter How to define new macros
1915 @cindex macros, how to define new
1916 @cindex defining new macros
1917 Macros can be defined, redefined and deleted in several different ways.
1918 Also, it is possible to redefine a macro without losing a previous
1919 value, and bring back the original value at a later time.
1921 @menu
1922 * Define::                      Defining a new macro
1923 * Arguments::                   Arguments to macros
1924 * Pseudo Arguments::            Special arguments to macros
1925 * Undefine::                    Deleting a macro
1926 * Defn::                        Renaming macros
1927 * Pushdef::                     Temporarily redefining macros
1928 * Renamesyms::                  Renaming macros with regular expressions
1930 * Indir::                       Indirect call of macros
1931 * Builtin::                     Indirect call of builtins
1932 * M4symbols::                   Getting the defined macro names
1933 @end menu
1935 @node Define
1936 @section Defining a macro
1938 The normal way to define or redefine macros is to use the builtin
1939 @code{define}:
1941 @deffn {Builtin (m4)} define (@var{name}, @ovar{expansion})
1942 Defines @var{name} to expand to @var{expansion}.  If
1943 @var{expansion} is not given, it is taken to be empty.
1945 The expansion of @code{define} is void.
1946 The macro @code{define} is recognized only with parameters.
1947 @end deffn
1948 @comment Other implementations, such as Solaris, can define a macro
1949 @comment with a builtin token attached to text:
1950 @comment  define(foo, a`'defn(`divnum')b)
1951 @comment  defn(`foo') => ab
1952 @comment  dumpdef(`foo') => foo: a<divnum>b
1953 @comment  len(defn(`foo')) => 3
1954 @comment  index(defn(`foo'), defn(`divnum')) => 1
1955 @comment  foo => a0b
1956 @comment It may be worth making some changes to support this behavior,
1957 @comment or something similar to it.
1958 @comment
1959 @comment But be sure it has sane semantics, with potentially deferred
1960 @comment expansion of builtins.  For example, this should not warn
1961 @comment about trying to access the definition of an undefined macro:
1962 @comment  define(`foo', `ifdef(`$1', 'defn(`defn')`)')foo(`oops')
1963 @comment Also, think how to handle conflicting argument counts:
1964 @comment  define(`bar', defn(`dnl', `len'))
1966 The following example defines the macro @var{foo} to expand to the text
1967 @samp{Hello World.}.
1969 @example
1970 define(`foo', `Hello world.')
1971 @result{}
1973 @result{}Hello world.
1974 @end example
1976 The empty line in the output is there because the newline is not
1977 a part of the macro definition, and it is consequently copied to
1978 the output.  This can be avoided by use of the macro @code{dnl}.
1979 @xref{Dnl}, for details.
1981 The first argument to @code{define} should be quoted; otherwise, if the
1982 macro is already defined, you will be defining a different macro.  This
1983 example shows the problems with underquoting, since we did not want to
1984 redefine @code{one}:
1986 @example
1987 define(foo, one)
1988 @result{}
1989 define(foo, two)
1990 @result{}
1992 @result{}two
1993 @end example
1995 @cindex GNU extensions
1996 GNU @code{m4} normally replaces only the @emph{topmost}
1997 definition of a macro if it has several definitions from @code{pushdef}
1998 (@pxref{Pushdef}).  Some other implementations of @code{m4} replace all
1999 definitions of a macro with @code{define}.  @xref{Incompatibilities},
2000 for more details.
2002 As a GNU extension, the first argument to @code{define} does
2003 not have to be a simple word.
2004 It can be any text string, even the empty string.  A macro with a
2005 non-standard name cannot be invoked in the normal way, as the name is
2006 not recognized.  It can only be referenced by the builtins @code{Indir}
2007 (@pxref{Indir}) and @code{Defn} (@pxref{Defn}).
2009 @cindex arrays
2010 Arrays and associative arrays can be simulated by using non-standard
2011 macro names.
2013 @deffn Composite array (@var{index})
2014 @deffnx Composite array_set (@var{index}, @ovar{value})
2015 Provide access to entries within an array.  @code{array} reads the entry
2016 at location @var{index}, and @code{array_set} assigns @var{value} to
2017 location @var{index}.
2018 @end deffn
2020 @example
2021 define(`array', `defn(format(``array[%d]'', `$1'))')
2022 @result{}
2023 define(`array_set', `define(format(``array[%d]'', `$1'), `$2')')
2024 @result{}
2025 array_set(`4', `array element no. 4')
2026 @result{}
2027 array_set(`17', `array element no. 17')
2028 @result{}
2029 array(`4')
2030 @result{}array element no. 4
2031 array(eval(`10 + 7'))
2032 @result{}array element no. 17
2033 @end example
2035 Change the @samp{%d} to @samp{%s} and it is an associative array.
2037 @node Arguments
2038 @section Arguments to macros
2040 @cindex macros, arguments to
2041 @cindex arguments to macros
2042 Macros can have arguments.  The @var{n}th argument is denoted by
2043 @code{$n} in the expansion text, and is replaced by the @var{n}th actual
2044 argument, when the macro is expanded.  Replacement of arguments happens
2045 before rescanning, regardless of how many nesting levels of quoting
2046 appear in the expansion.  Here is an example of a macro with
2047 two arguments.
2049 @deffn Composite exch (@var{arg1}, @var{arg2})
2050 Expands to @var{arg2} followed by @var{arg1}, effectively exchanging
2051 their order.
2052 @end deffn
2054 @example
2055 define(`exch', `$2, $1')
2056 @result{}
2057 exch(`arg1', `arg2')
2058 @result{}arg2, arg1
2059 @end example
2061 This can be used, for example, if you like the arguments to
2062 @code{define} to be reversed.
2064 @example
2065 define(`exch', `$2, $1')
2066 @result{}
2067 define(exch(``expansion text'', ``macro''))
2068 @result{}
2069 macro
2070 @result{}expansion text
2071 @end example
2073 @xref{Quoting Arguments}, for an explanation of the double quotes.
2074 (You should try and improve this example so that clients of @code{exch}
2075 do not have to double quote; or @pxref{Improved exch, , Answers}).
2077 @cindex GNU extensions
2078 GNU @code{m4} allows the number following the @samp{$} to
2079 consist of one
2080 or more digits, allowing macros to have any number of arguments.  This
2081 is not so in UNIX implementations of @code{m4}, which only recognize
2082 one digit.
2083 @comment FIXME - See Austin group XCU ERN 111.  POSIX says that $11 must
2084 @comment be the first argument concatenated with 1, and instead reserves
2085 @comment ${11} for implementation use.  Once this is implemented, the
2086 @comment documentation needs to reflect how these extended arguments
2087 @comment are handled, as well as backwards compatibility issues with
2088 @comment 1.4.x.  Also, consider adding further extensions such as
2089 @comment ${1-default}, which expands to `default' if $1 is empty.
2091 As a special case, the zeroth argument, @code{$0}, is always the name
2092 of the macro being expanded.
2094 @example
2095 define(`test', ``Macro name: $0'')
2096 @result{}
2097 test
2098 @result{}Macro name: test
2099 @end example
2101 If you want quoted text to appear as part of the expansion text,
2102 remember that quotes can be nested in quoted strings.  Thus, in
2104 @example
2105 define(`foo', `This is macro `foo'.')
2106 @result{}
2108 @result{}This is macro foo.
2109 @end example
2111 @noindent
2112 The @samp{foo} in the expansion text is @emph{not} expanded, since it is
2113 a quoted string, and not a name.
2115 @node Pseudo Arguments
2116 @section Special arguments to macros
2118 @cindex special arguments to macros
2119 @cindex macros, special arguments to
2120 @cindex arguments to macros, special
2121 There is a special notation for the number of actual arguments supplied,
2122 and for all the actual arguments.
2124 The number of actual arguments in a macro call is denoted by @code{$#}
2125 in the expansion text.
2127 @deffn Composite nargs (@dots{})
2128 Expands to a count of the number of arguments supplied.
2129 @end deffn
2131 @example
2132 define(`nargs', `$#')
2133 @result{}
2134 nargs
2135 @result{}0
2136 nargs()
2137 @result{}1
2138 nargs(`arg1', `arg2', `arg3')
2139 @result{}3
2140 nargs(`commas can be quoted, like this')
2141 @result{}1
2142 nargs(arg1#inside comments, commas do not separate arguments
2143 still arg1)
2144 @result{}1
2145 nargs((unquoted parentheses, like this, group arguments))
2146 @result{}1
2147 @end example
2149 Remember that @samp{#} defaults to the comment character; if you forget
2150 quotes to inhibit the comment behavior, your macro definition may not
2151 end where you expected.
2153 @example
2154 dnl Attempt to define a macro to just `$#'
2155 define(underquoted, $#)
2156 oops)
2157 @result{}
2158 underquoted
2159 @result{}0)
2160 @result{}oops
2161 @end example
2163 The notation @code{$*} can be used in the expansion text to denote all
2164 the actual arguments, unquoted, with commas in between.  For example
2166 @example
2167 define(`echo', `$*')
2168 @result{}
2169 echo(arg1,    arg2, arg3 , arg4)
2170 @result{}arg1,arg2,arg3 ,arg4
2171 @end example
2173 Often each argument should be quoted, and the notation @code{$@@} handles
2174 that.  It is just like @code{$*}, except that it quotes each argument.
2175 A simple example of that is:
2177 @example
2178 define(`echo', `$@@')
2179 @result{}
2180 echo(arg1,    arg2, arg3 , arg4)
2181 @result{}arg1,arg2,arg3 ,arg4
2182 @end example
2184 Where did the quotes go?  Of course, they were eaten, when the expanded
2185 text were reread by @code{m4}.  To show the difference, try
2187 @example
2188 define(`echo1', `$*')
2189 @result{}
2190 define(`echo2', `$@@')
2191 @result{}
2192 define(`foo', `This is macro `foo'.')
2193 @result{}
2194 echo1(foo)
2195 @result{}This is macro This is macro foo..
2196 echo1(`foo')
2197 @result{}This is macro foo.
2198 echo2(foo)
2199 @result{}This is macro foo.
2200 echo2(`foo')
2201 @result{}foo
2202 @end example
2204 @noindent
2205 @xref{Trace}, if you do not understand this.  As another example of the
2206 difference, remember that comments encountered in arguments are passed
2207 untouched to the macro, and that quoting disables comments.
2209 @example
2210 define(`echo1', `$*')
2211 @result{}
2212 define(`echo2', `$@@')
2213 @result{}
2214 define(`foo', `bar')
2215 @result{}
2216 echo1(#foo'foo
2217 foo)
2218 @result{}#foo'foo
2219 @result{}bar
2220 echo2(#foo'foo
2221 foo)
2222 @result{}#foobar
2223 @result{}bar'
2224 @end example
2226 A @samp{$} sign in the expansion text, that is not followed by anything
2227 @code{m4} understands, is simply copied to the macro expansion, as any
2228 other text is.
2230 @example
2231 define(`foo', `$$$ hello $$$')
2232 @result{}
2234 @result{}$$$ hello $$$
2235 @end example
2237 @cindex rescanning
2238 @cindex literal output
2239 @cindex output, literal
2240 If you want a macro to expand to something like @samp{$12}, the
2241 judicious use of nested quoting can put a safe character between the
2242 @code{$} and the next character, relying on the rescanning to remove the
2243 nested quote.  This will prevent @code{m4} from interpreting the
2244 @code{$} sign as a reference to an argument.
2246 @example
2247 define(`foo', `no nested quote: $1')
2248 @result{}
2249 foo(`arg')
2250 @result{}no nested quote: arg
2251 define(`foo', `nested quote around $: `$'1')
2252 @result{}
2253 foo(`arg')
2254 @result{}nested quote around $: $1
2255 define(`foo', `nested empty quote after $: $`'1')
2256 @result{}
2257 foo(`arg')
2258 @result{}nested empty quote after $: $1
2259 define(`foo', `nested quote around next character: $`1'')
2260 @result{}
2261 foo(`arg')
2262 @result{}nested quote around next character: $1
2263 define(`foo', `nested quote around both: `$1'')
2264 @result{}
2265 foo(`arg')
2266 @result{}nested quote around both: arg
2267 @end example
2269 @node Undefine
2270 @section Deleting a macro
2272 @cindex macros, how to delete
2273 @cindex deleting macros
2274 @cindex undefining macros
2275 A macro definition can be removed with @code{undefine}:
2277 @deffn {Builtin (m4)} undefine (@var{name}@dots{})
2278 For each argument, remove the macro @var{name}.  The macro names must
2279 necessarily be quoted, since they will be expanded otherwise.  If an
2280 argument is not a defined macro, then the @samp{d} debug level controls
2281 whether a warning is issued (@pxref{Debugmode}).
2283 The expansion of @code{undefine} is void.
2284 The macro @code{undefine} is recognized only with parameters.
2285 @end deffn
2287 @example
2288 foo bar blah
2289 @result{}foo bar blah
2290 define(`foo', `some')define(`bar', `other')define(`blah', `text')
2291 @result{}
2292 foo bar blah
2293 @result{}some other text
2294 undefine(`foo')
2295 @result{}
2296 foo bar blah
2297 @result{}foo other text
2298 undefine(`bar', `blah')
2299 @result{}
2300 foo bar blah
2301 @result{}foo bar blah
2302 @end example
2304 Undefining a macro inside that macro's expansion is safe; the macro
2305 still expands to the definition that was in effect at the @samp{(}.
2307 @example
2308 define(`f', ``$0':$1')
2309 @result{}
2310 f(f(f(undefine(`f')`hello world')))
2311 @result{}f:f:f:hello world
2312 f(`bye')
2313 @result{}f(bye)
2314 @end example
2316 As of M4 1.6, @code{undefine} can warn if @var{name} is not a macro, by
2317 using @code{debugmode} (@pxref{Debugmode}) or the command line option
2318 @option{-d} (@option{--debugmode}, @pxref{Debugging options, , Invoking
2319 m4}).
2321 @example
2322 $ @kbd{m4}
2323 undefine(`a')
2324 @error{}m4:stdin:1: warning: undefine: undefined macro 'a'
2325 @result{}
2326 debugmode(`-d')
2327 @result{}
2328 undefine(`a')
2329 @result{}
2330 @end example
2332 @node Defn
2333 @section Renaming macros
2335 @cindex macros, how to rename
2336 @cindex renaming macros
2337 @cindex macros, displaying definitions
2338 @cindex definitions, displaying macro
2339 It is possible to rename an already defined macro.  To do this, you need
2340 the builtin @code{defn}:
2342 @deffn {Builtin (m4)} defn (@var{name}@dots{})
2343 Expands to the @emph{quoted definition} of each @var{name}.  If an
2344 argument is not a defined macro, the expansion for that argument is
2345 empty, and the @samp{d} debug level controls whether a warning is issued
2346 (@pxref{Debugmode}).
2348 If @var{name} is a user-defined macro, the quoted definition is simply
2349 the quoted expansion text.  If, instead, @var{name} is a builtin, the
2350 expansion is a special token, which points to the builtin's internal
2351 definition.  This token meaningful primarily as the second argument to
2352 @code{define} (and @code{pushdef}), and is silently converted to an
2353 empty string in many other contexts.
2355 The macro @code{defn} is recognized only with parameters.
2356 @end deffn
2358 Its normal use is best understood through an example, which shows how to
2359 rename @code{undefine} to @code{zap}:
2361 @example
2362 define(`zap', defn(`undefine'))
2363 @result{}
2364 zap(`undefine')
2365 @result{}
2366 undefine(`zap')
2367 @result{}undefine(zap)
2368 @end example
2370 In this way, @code{defn} can be used to copy macro definitions, and also
2371 definitions of builtin macros.  Even if the original macro is removed,
2372 the other name can still be used to access the definition.
2374 The fact that macro definitions can be transferred also explains why you
2375 should use @code{$0}, rather than retyping a macro's name in its
2376 definition:
2378 @example
2379 define(`foo', `This is `$0'')
2380 @result{}
2381 define(`bar', defn(`foo'))
2382 @result{}
2384 @result{}This is bar
2385 @end example
2387 Macros used as string variables should be referred through @code{defn},
2388 to avoid unwanted expansion of the text:
2390 @example
2391 define(`string', `The macro dnl is very useful
2393 @result{}
2394 string
2395 @result{}The macro@w{ }
2396 defn(`string')
2397 @result{}The macro dnl is very useful
2398 @result{}
2399 @end example
2401 @cindex rescanning
2402 However, it is important to remember that @code{m4} rescanning is purely
2403 textual.  If an unbalanced end-quote string occurs in a macro
2404 definition, the rescan will see that embedded quote as the termination
2405 of the quoted string, and the remainder of the macro's definition will
2406 be rescanned unquoted.  Thus it is a good idea to avoid unbalanced
2407 end-quotes in macro definitions or arguments to macros.
2409 @example
2410 define(`foo', a'a)
2411 @result{}
2412 define(`a', `A')
2413 @result{}
2414 define(`echo', `$@@')
2415 @result{}
2417 @result{}A'A
2418 defn(`foo')
2419 @result{}aA'
2420 echo(foo)
2421 @result{}AA'
2422 @end example
2424 On the other hand, it is possible to exploit the fact that @code{defn}
2425 can concatenate multiple macros prior to the rescanning phase, in order
2426 to join the definitions of macros that, in isolation, have unbalanced
2427 quotes.  This is particularly useful when one has used several macros to
2428 accumulate text that M4 should rescan as a whole.  In the example below,
2429 note how the use of @code{defn} on @code{l} in isolation opens a string,
2430 which is not closed until the next line; but used on @code{l} and
2431 @code{r} together results in nested quoting.
2433 @example
2434 define(`l', `<[>')define(`r', `<]>')
2435 @result{}
2436 changequote(`[', `]')
2437 @result{}
2438 defn([l])defn([r])
2440 @result{}<[>]defn([r])
2441 @result{})
2442 defn([l], [r])
2443 @result{}<[>][<]>
2444 @end example
2446 @cindex builtins, special tokens
2447 @cindex tokens, builtin macro
2448 Using @code{defn} to generate special tokens for builtin macros will
2449 generate a warning in contexts where a macro name is expected.  But in
2450 contexts that operate on text, the builtin token is just silently
2451 converted to an empty string.  As of M4 1.6, expansion of user macros
2452 will also preserve builtin tokens.  However, any use of builtin tokens
2453 outside of the second argument to @code{define} and @code{pushdef} is
2454 generally not portable, since earlier GNU M4 versions, as well
2455 as other @code{m4} implementations, vary on how such tokens are treated.
2457 @example
2458 $ @kbd{m4 -d}
2459 defn(`defn')
2460 @result{}
2461 define(defn(`divnum'), `cannot redefine a builtin token')
2462 @error{}m4:stdin:2: warning: define: invalid macro name ignored
2463 @result{}
2464 divnum
2465 @result{}0
2466 len(defn(`divnum'))
2467 @result{}0
2468 define(`echo', `$@@')
2469 @result{}
2470 define(`mydivnum', shift(echo(`', defn(`divnum'))))
2471 @result{}
2472 mydivnum
2473 @result{}0
2474 define(`', `empty-$1')
2475 @result{}
2476 defn(defn(`divnum'))
2477 @error{}m4:stdin:9: warning: defn: invalid macro name ignored
2478 @result{}
2479 pushdef(defn(`divnum'), `oops')
2480 @error{}m4:stdin:10: warning: pushdef: invalid macro name ignored
2481 @result{}
2482 traceon(defn(`divnum'))
2483 @error{}m4:stdin:11: warning: traceon: invalid macro name ignored
2484 @result{}
2485 indir(defn(`divnum'), `string')
2486 @error{}m4:stdin:12: warning: indir: invalid macro name ignored
2487 @result{}
2488 indir(`', `string')
2489 @result{}empty-string
2490 traceoff(defn(`divnum'))
2491 @error{}m4:stdin:14: warning: traceoff: invalid macro name ignored
2492 @result{}
2493 popdef(defn(`divnum'))
2494 @error{}m4:stdin:15: warning: popdef: invalid macro name ignored
2495 @result{}
2496 dumpdef(defn(`divnum'))
2497 @error{}m4:stdin:16: warning: dumpdef: invalid macro name ignored
2498 @result{}
2499 undefine(defn(`divnum'))
2500 @error{}m4:stdin:17: warning: undefine: invalid macro name ignored
2501 @result{}
2502 dumpdef(`')
2503 @error{}:@tabchar{}`empty-$1'
2504 @result{}
2505 m4symbols(defn(`divnum'))
2506 @error{}m4:stdin:19: warning: m4symbols: invalid macro name ignored
2507 @result{}
2508 define(`foo', `define(`$1', $2)')dnl
2509 foo(`bar', defn(`divnum'))
2510 @result{}
2512 @result{}0
2513 @end example
2515 As of M4 1.6, @code{defn} can warn if @var{name} is not a macro, by
2516 using @code{debugmode} (@pxref{Debugmode}) or the command line option
2517 @option{-d} (@option{--debugmode}, @pxref{Debugging options, , Invoking
2518 m4}).  Also, @code{defn} with multiple arguments can join text with
2519 builtin tokens.  However, when defining a macro via @code{define} or
2520 @code{pushdef}, a warning is issued and the builtin token ignored if the
2521 builtin token does not occur in isolation.  A future version of
2522 GNU M4 may lift this restriction.
2524 @example
2525 $ @kbd{m4 -d}
2526 defn(`foo')
2527 @error{}m4:stdin:1: warning: defn: undefined macro 'foo'
2528 @result{}
2529 debugmode(`-d')
2530 @result{}
2531 defn(`foo')
2532 @result{}
2533 define(`a', `A')define(`AA', `b')
2534 @result{}
2535 traceon(`defn', `define')
2536 @result{}
2537 defn(`a', `divnum', `a')
2538 @error{}m4trace: -1- defn(`a', `divnum', `a') -> ``A'<divnum>`A''
2539 @result{}AA
2540 define(`mydivnum', defn(`divnum', `divnum'))mydivnum
2541 @error{}m4trace: -2- defn(`divnum', `divnum') -> `<divnum><divnum>'
2542 @error{}m4:stdin:7: warning: define: cannot concatenate builtins
2543 @error{}m4trace: -1- define(`mydivnum', `<divnum><divnum>') -> `'
2544 @result{}
2545 traceoff(`defn', `define')dumpdef(`mydivnum')
2546 @error{}mydivnum:@tabchar{}`'
2547 @result{}
2548 define(`mydivnum', defn(`divnum')defn(`divnum'))mydivnum
2549 @error{}m4:stdin:9: warning: define: cannot concatenate builtins
2550 @result{}
2551 define(`mydivnum', defn(`divnum')`a')mydivnum
2552 @error{}m4:stdin:10: warning: define: cannot concatenate builtins
2553 @result{}A
2554 define(`mydivnum', `a'defn(`divnum'))mydivnum
2555 @error{}m4:stdin:11: warning: define: cannot concatenate builtins
2556 @result{}A
2557 define(`q', ``$@@'')
2558 @result{}
2559 define(`foo', q(`a', defn(`divnum')))foo
2560 @error{}m4:stdin:13: warning: define: cannot concatenate builtins
2561 @result{}a,
2562 ifdef(`foo', `yes', `no')
2563 @result{}yes
2564 @end example
2566 @node Pushdef
2567 @section Temporarily redefining macros
2569 @cindex macros, temporary redefinition of
2570 @cindex temporary redefinition of macros
2571 @cindex redefinition of macros, temporary
2572 @cindex definition stack
2573 @cindex pushdef stack
2574 @cindex stack, macro definition
2575 It is possible to redefine a macro temporarily, reverting to the
2576 previous definition at a later time.  This is done with the builtins
2577 @code{pushdef} and @code{popdef}:
2579 @deffn {Builtin (m4)} pushdef (@var{name}, @ovar{expansion})
2580 @deffnx {Builtin (m4)} popdef (@var{name}@dots{})
2581 Analogous to @code{define} and @code{undefine}.
2583 These macros work in a stack-like fashion.  A macro is temporarily
2584 redefined with @code{pushdef}, which replaces an existing definition of
2585 @var{name}, while saving the previous definition, before the new one is
2586 installed.  If there is no previous definition, @code{pushdef} behaves
2587 exactly like @code{define}.
2589 If a macro has several definitions (of which only one is accessible),
2590 the topmost definition can be removed with @code{popdef}.  If there is
2591 no previous definition, @code{popdef} behaves like @code{undefine}, and
2592 if there is no definition at all, the @samp{d} debug level controls
2593 whether a warning is issued (@pxref{Debugmode}).
2595 The expansion of both @code{pushdef} and @code{popdef} is void.
2596 The macros @code{pushdef} and @code{popdef} are recognized only with
2597 parameters.
2598 @end deffn
2600 @example
2601 define(`foo', `Expansion one.')
2602 @result{}
2604 @result{}Expansion one.
2605 pushdef(`foo', `Expansion two.')
2606 @result{}
2608 @result{}Expansion two.
2609 pushdef(`foo', `Expansion three.')
2610 @result{}
2611 pushdef(`foo', `Expansion four.')
2612 @result{}
2613 popdef(`foo')
2614 @result{}
2616 @result{}Expansion three.
2617 popdef(`foo', `foo')
2618 @result{}
2620 @result{}Expansion one.
2621 popdef(`foo')
2622 @result{}
2624 @result{}foo
2625 @end example
2627 If a macro with several definitions is redefined with @code{define}, the
2628 topmost definition is @emph{replaced} with the new definition.  If it is
2629 removed with @code{undefine}, @emph{all} the definitions are removed,
2630 and not only the topmost one.  However, POSIX allows other
2631 implementations that treat @code{define} as replacing an entire stack
2632 of definitions with a single new definition, so to be portable to other
2633 implementations, it may be worth explicitly using @code{popdef} and
2634 @code{pushdef} rather than relying on the GNU behavior of
2635 @code{define}.
2637 @example
2638 define(`foo', `Expansion one.')
2639 @result{}
2641 @result{}Expansion one.
2642 pushdef(`foo', `Expansion two.')
2643 @result{}
2645 @result{}Expansion two.
2646 define(`foo', `Second expansion two.')
2647 @result{}
2649 @result{}Second expansion two.
2650 undefine(`foo')
2651 @result{}
2653 @result{}foo
2654 @end example
2656 @cindex local variables
2657 @cindex variables, local
2658 Local variables within macros are made with @code{pushdef} and
2659 @code{popdef}.  At the start of the macro a new definition is pushed,
2660 within the macro it is manipulated and at the end it is popped,
2661 revealing the former definition.
2663 It is possible to temporarily redefine a builtin with @code{pushdef}
2664 and @code{defn}.
2666 As of M4 1.6, @code{popdef} can warn if @var{name} is not a macro, by
2667 using @code{debugmode} (@pxref{Debugmode}) or the command line option
2668 @option{-d} (@option{--debugmode}, @pxref{Debugging options, , Invoking
2669 m4}).
2671 @example
2672 define(`a', `1')
2673 @result{}
2674 popdef
2675 @result{}popdef
2676 popdef(`a', `a')
2677 @error{}m4:stdin:3: warning: popdef: undefined macro 'a'
2678 @result{}
2679 debugmode(`-d')
2680 @result{}
2681 popdef(`a')
2682 @result{}
2683 @end example
2685 @node Renamesyms
2686 @section Renaming macros with regular expressions
2688 @cindex regular expressions
2689 @cindex macros, how to rename
2690 @cindex renaming macros
2691 @cindex GNU extensions
2692 Sometimes it is desirable to rename multiple symbols without having to
2693 use a long sequence of calls to @code{define}.  The @code{renamesyms}
2694 builtin allows this:
2696 @deffn {Builtin (gnu)} renamesyms (@var{regexp}, @var{replacement}, @
2697   @ovar{resyntax})
2698 Global renaming of macros is done by @code{renamesyms}, which selects
2699 all macros with names that match @var{regexp}, and renames each match
2700 according to @var{replacement}.  It is unspecified what happens if the
2701 rename causes multiple macros to map to the same name.
2702 @comment FIXME - right now, collisions cause a core dump on some platforms:
2703 @comment define(bar,1)define(baz,2)renamesyms(^ba., baa)dumpdef(`baa')
2705 If @var{resyntax} is given, the particular flavor of regular
2706 expression understood with respect to @var{regexp} can be changed from
2707 the current default.  @xref{Changeresyntax}, for details of the values
2708 that can be given for this argument.
2710 A macro that does not have a name that matches @var{regexp} is left
2711 with its original name.  If only part of the name matches, any part of
2712 the name that is not covered by @var{regexp} is copied to the
2713 replacement name.  Whenever a match is found in the name, the search
2714 proceeds from the end of the match, so no character in the original
2715 name can be substituted twice.  If @var{regexp} matches a string of
2716 zero length, the start position for the continued search is
2717 incremented to avoid infinite loops.
2719 Where a replacement is to be made, @var{replacement} replaces the
2720 matched text in the original name, with @samp{\@var{n}} substituted by
2721 the text matched by the @var{n}th parenthesized sub-expression of
2722 @var{regexp}, and @samp{\&} being the text matched by the entire
2723 regular expression.
2725 The expansion of @code{renamesyms} is void.
2726 The macro @code{renamesyms} is recognized only with parameters.
2727 This macro was added in M4 2.0.
2728 @end deffn
2730 The following example starts with a rename similar to the
2731 @option{--prefix-builtins} option (or @option{-P}), prefixing every
2732 macro with @code{m4_}.  However, note that @option{-P} only renames M4
2733 builtin macros, even if other macros were defined previously, while
2734 @code{renamesyms} will rename any macros that match when it runs,
2735 including text macros.  The rest of the example demonstrates the
2736 behavior of unanchored regular expressions in symbol renaming.
2738 @comment options: -Dfoo=bar -P
2739 @example
2740 $ @kbd{m4 -Dfoo=bar -P}
2742 @result{}bar
2743 m4_foo
2744 @result{}m4_foo
2745 m4_defn(`foo')
2746 @result{}bar
2747 @end example
2749 @example
2750 $ @kbd{m4}
2751 define(`foo', `bar')
2752 @result{}
2753 renamesyms(`^.*$', `m4_\&')
2754 @result{}
2756 @result{}foo
2757 m4_foo
2758 @result{}bar
2759 m4_defn(`m4_foo')
2760 @result{}bar
2761 m4_renamesyms(`f', `g')
2762 @result{}
2763 m4_igdeg(`m4_goo', `m4_goo')
2764 @result{}bar
2765 @end example
2767 If @var{resyntax} is given, @var{regexp} must be given according to
2768 the syntax chosen, though the default regular expression syntax
2769 remains unchanged for other invocations.  Here is a more realistic
2770 example that performs a similar renaming on macros, except that it
2771 ignores macros with names that begin with @samp{_}, and avoids creating
2772 macros with names that begin with @samp{m4_m4}.
2774 @example
2775 renamesyms(`^[^_]\w*$', `m4_\&')
2776 @result{}
2777 m4_renamesyms(`^m4_m4(\w*)$', `m4_\1', `POSIX_EXTENDED')
2778 @result{}
2779 m4_wrap(__line__
2781 @result{}
2783 @result{}3
2784 @end example
2786 When a symbol has multiple definitions, thanks to @code{pushdef}, the
2787 entire stack is renamed.
2789 @example
2790 pushdef(`foo', `1')pushdef(`foo', `2')
2791 @result{}
2792 renamesyms(`^foo$', `bar')
2793 @result{}
2795 @result{}2
2796 popdef(`bar')bar
2797 @result{}1
2798 popdef(`bar')bar
2799 @result{}bar
2800 @end example
2802 @node Indir
2803 @section Indirect call of macros
2805 @cindex indirect call of macros
2806 @cindex call of macros, indirect
2807 @cindex macros, indirect call of
2808 @cindex GNU extensions
2809 Any macro can be called indirectly with @code{indir}:
2811 @deffn {Builtin (gnu)} indir (@var{name}, @ovar{args@dots{}})
2812 Results in a call to the macro @var{name}, which is passed the rest of
2813 the arguments @var{args}.  If @var{name} is not defined, the expansion
2814 is void, and the @samp{d} debug level controls whether a warning is
2815 issued (@pxref{Debugmode}).
2817 The macro @code{indir} is recognized only with parameters.
2818 @end deffn
2820 This can be used to call macros with computed or ``invalid''
2821 names (@code{define} allows such names to be defined):
2823 @example
2824 define(`$$internal$macro', `Internal macro (name `$0')')
2825 @result{}
2826 $$internal$macro
2827 @result{}$$internal$macro
2828 indir(`$$internal$macro')
2829 @result{}Internal macro (name $$internal$macro)
2830 @end example
2832 The point is, here, that larger macro packages can have private macros
2833 defined, that will not be called by accident.  They can @emph{only} be
2834 called through the builtin @code{indir}.
2836 One other point to observe is that argument collection occurs before
2837 @code{indir} invokes @var{name}, so if argument collection changes the
2838 value of @var{name}, that will be reflected in the final expansion.
2839 This is different than the behavior when invoking macros directly,
2840 where the definition that was in effect before argument collection is
2841 used.
2843 @example
2844 $ @kbd{m4 -d}
2845 define(`f', `1')
2846 @result{}
2847 f(define(`f', `2'))
2848 @result{}1
2849 indir(`f', define(`f', `3'))
2850 @result{}3
2851 indir(`f', undefine(`f'))
2852 @error{}m4:stdin:4: warning: indir: undefined macro 'f'
2853 @result{}
2854 debugmode(`-d')
2855 @result{}
2856 indir(`f')
2857 @result{}
2858 @end example
2860 When handed the result of @code{defn} (@pxref{Defn}) as one of its
2861 arguments, @code{indir} defers to the invoked @var{name} for whether a
2862 token representing a builtin is recognized or flattened to the empty
2863 string.
2865 @example
2866 $ @kbd{m4 -d}
2867 indir(defn(`defn'), `divnum')
2868 @error{}m4:stdin:1: warning: indir: invalid macro name ignored
2869 @result{}
2870 indir(`define', defn(`defn'), `divnum')
2871 @error{}m4:stdin:2: warning: define: invalid macro name ignored
2872 @result{}
2873 indir(`define', `foo', defn(`divnum'))
2874 @result{}
2876 @result{}0
2877 indir(`divert', defn(`foo'))
2878 @error{}m4:stdin:5: warning: divert: empty string treated as 0
2879 @result{}
2880 @end example
2882 Warning messages issued on behalf of an indirect macro use an
2883 unambiguous representation of the macro name, using escape sequences
2884 similar to C strings, and with colons also quoted.
2886 @example
2887 define(`%%:\
2888 odd', defn(`divnum'))
2889 @result{}
2890 indir(`%%:\
2891 odd', `extra')
2892 @error{}m4:stdin:3: warning: %%\:\\\nodd: extra arguments ignored: 1 > 0
2893 @result{}0
2894 @end example
2896 @node Builtin
2897 @section Indirect call of builtins
2899 @cindex indirect call of builtins
2900 @cindex call of builtins, indirect
2901 @cindex builtins, indirect call of
2902 @cindex GNU extensions
2903 Builtin macros can be called indirectly with @code{builtin}:
2905 @deffn {Builtin (gnu)} builtin (@var{name}, @ovar{args@dots{}})
2906 @deffnx {Builtin (gnu)} builtin (@code{defn(`builtin')}, @var{name1})
2907 Results in a call to the builtin @var{name}, which is passed the
2908 rest of the arguments @var{args}.  If @var{name} does not name a
2909 builtin, the expansion is void, and the @samp{d} debug level controls
2910 whether a warning is issued (@pxref{Debugmode}).
2912 As a special case, if @var{name} is exactly the special token
2913 representing the @code{builtin} macro, as obtained by @code{defn}
2914 (@pxref{Defn}), then @var{args} must consist of a single @var{name1},
2915 and the expansion is the special token representing the builtin macro
2916 named by @var{name1}.
2918 The macro @code{builtin} is recognized only with parameters.
2919 @end deffn
2921 This can be used even if @var{name} has been given another definition
2922 that has covered the original, or been undefined so that no macro
2923 maps to the builtin.
2925 @example
2926 pushdef(`define', `hidden')
2927 @result{}
2928 undefine(`undefine')
2929 @result{}
2930 define(`foo', `bar')
2931 @result{}hidden
2933 @result{}foo
2934 builtin(`define', `foo', defn(`divnum'))
2935 @result{}
2937 @result{}0
2938 builtin(`define', `foo', `BAR')
2939 @result{}
2941 @result{}BAR
2942 undefine(`foo')
2943 @result{}undefine(foo)
2945 @result{}BAR
2946 builtin(`undefine', `foo')
2947 @result{}
2949 @result{}foo
2950 @end example
2952 The @var{name} argument only matches the original name of the builtin,
2953 even when the @option{--prefix-builtins} option (or @option{-P},
2954 @pxref{Operation modes, , Invoking m4}) is in effect.  This is different
2955 from @code{indir}, which only tracks current macro names.
2957 @comment options: -P
2958 @example
2959 $ @kbd{m4 -P}
2960 m4_builtin(`divnum')
2961 @result{}0
2962 m4_builtin(`m4_divnum')
2963 @error{}m4:stdin:2: warning: m4_builtin: undefined builtin 'm4_divnum'
2964 @result{}
2965 m4_indir(`divnum')
2966 @error{}m4:stdin:3: warning: m4_indir: undefined macro 'divnum'
2967 @result{}
2968 m4_indir(`m4_divnum')
2969 @result{}0
2970 m4_debugmode(`-d')
2971 @result{}
2972 m4_builtin(`m4_divnum')
2973 @result{}
2974 @end example
2976 Note that @code{indir} and @code{builtin} can be used to invoke builtins
2977 without arguments, even when they normally require parameters to be
2978 recognized; but it will provoke a warning, and the expansion will behave
2979 as though empty strings had been passed as the required arguments.
2981 @example
2982 builtin
2983 @result{}builtin
2984 builtin()
2985 @error{}m4:stdin:2: warning: builtin: undefined builtin ''
2986 @result{}
2987 builtin(`builtin')
2988 @error{}m4:stdin:3: warning: builtin: too few arguments: 0 < 1
2989 @result{}
2990 builtin(`builtin',)
2991 @error{}m4:stdin:4: warning: builtin: undefined builtin ''
2992 @result{}
2993 builtin(`builtin', ``'
2995 @error{}m4:stdin:5: warning: builtin: undefined builtin '`\'\n'
2996 @result{}
2997 indir(`index')
2998 @error{}m4:stdin:7: warning: index: too few arguments: 0 < 2
2999 @result{}0
3000 @end example
3002 Normally, once a builtin macro is undefined, the only way to retrieve
3003 its functionality is by defining a new macro that expands to
3004 @code{builtin} under the hood.  But this extra layer of expansion is
3005 slightly inefficient, not to mention the fact that it is not robust to
3006 changes in the current quoting scheme due to @code{changequote}
3007 (@pxref{Changequote}).  On the other hand, defining a macro to the
3008 special token produced by @code{defn} (@pxref{Defn}) is very efficient,
3009 and avoids the need for quoting within the macro definition; but
3010 @code{defn} only works if the desired macro is already defined by some
3011 other name.  So @code{builtin} provides a special case where it is
3012 possible to retrieve the same special token representing a builtin as
3013 what @code{defn} would provide, were the desired macro still defined.
3014 This feature is activated by passing @code{defn(`builtin')} as the first
3015 argument to builtin.  Normally, passing a special token representing a
3016 macro as @var{name} results in a warning and an empty expansion, but in
3017 this case, if the second argument @var{name1} names a valid builtin,
3018 there is no warning and the expansion is the appropriate special
3019 token.  In fact, with just the @code{builtin} macro accessible, it is
3020 possible to reconstitute the entire startup state of @code{m4}.
3022 In the example below, compare the number of macro invocations performed
3023 by @code{defn1} and @code{defn2}, and the differences once quoting is
3024 changed.
3026 @example
3027 $ @kbd{m4 -d}
3028 undefine(`defn')
3029 @result{}
3030 define(`foo', `bar')
3031 @result{}
3032 define(`defn1', `builtin(`defn', $@@)')
3033 @result{}
3034 define(`defn2', builtin(builtin(`defn', `builtin'), `defn'))
3035 @result{}
3036 dumpdef(`defn1', `defn2')
3037 @error{}defn1:@tabchar{}`builtin(`defn', $@@)'
3038 @error{}defn2:@tabchar{}<defn>
3039 @result{}
3040 traceon
3041 @result{}
3042 defn1(`foo')
3043 @error{}m4trace: -1- defn1(`foo') -> `builtin(`defn', `foo')'
3044 @error{}m4trace: -1- builtin(`defn', `foo') -> ``bar''
3045 @result{}bar
3046 defn2(`foo')
3047 @error{}m4trace: -1- defn2(`foo') -> ``bar''
3048 @result{}bar
3049 traceoff
3050 @error{}m4trace: -1- traceoff -> `'
3051 @result{}
3052 changequote(`[', `]')
3053 @result{}
3054 defn1([foo])
3055 @error{}m4:stdin:11: warning: builtin: undefined builtin '`defn\''
3056 @result{}
3057 defn2([foo])
3058 @result{}bar
3059 define([defn1], [builtin([defn], $@@)])
3060 @result{}
3061 defn1([foo])
3062 @result{}bar
3063 changequote
3064 @result{}
3065 defn1(`foo')
3066 @error{}m4:stdin:16: warning: builtin: undefined builtin '[defn]'
3067 @result{}
3068 @end example
3070 @node M4symbols
3071 @section Getting the defined macro names
3073 @cindex macro names, listing
3074 @cindex listing macro names
3075 @cindex currently defined macros
3076 @cindex GNU extensions
3077 The name of the currently defined macros can be accessed by
3078 @code{m4symbols}:
3080 @deffn {Builtin (gnu)} m4symbols (@ovar{names@dots{}})
3081 Without arguments, @code{m4symbols} expands to a sorted list of quoted
3082 strings, separated by commas.  This contrasts with @code{dumpdef}
3083 (@pxref{Dumpdef}), whose output cannot be accessed by @code{m4}
3084 programs.
3086 When given arguments, @code{m4symbols} returns the sorted subset of the
3087 @var{names} currently defined, and silently ignores the rest.
3088 This macro was added in M4 2.0.
3089 @end deffn
3091 @example
3092 m4symbols(`ifndef', `ifdef', `define', `undef')
3093 @result{}define,ifdef
3094 @end example
3096 @node Conditionals
3097 @chapter Conditionals, loops, and recursion
3099 Macros, expanding to plain text, perhaps with arguments, are not quite
3100 enough.  We would like to have macros expand to different things, based
3101 on decisions taken at run-time.  For that, we need some kind of conditionals.
3102 Also, we would like to have some kind of loop construct, so we could do
3103 something a number of times, or while some condition is true.
3105 @menu
3106 * Ifdef::                       Testing if a macro is defined
3107 * Ifelse::                      If-else construct, or multibranch
3108 * Shift::                       Recursion in @code{m4}
3109 * Forloop::                     Iteration by counting
3110 * Foreach::                     Iteration by list contents
3111 * Stacks::                      Working with definition stacks
3112 * Composition::                 Building macros with macros
3113 @end menu
3115 @node Ifdef
3116 @section Testing if a macro is defined
3118 @cindex conditionals
3119 There are two different builtin conditionals in @code{m4}.  The first is
3120 @code{ifdef}:
3122 @deffn {Builtin (m4)} ifdef (@var{name}, @var{string-1}, @ovar{string-2})
3123 If @var{name} is defined as a macro, @code{ifdef} expands to
3124 @var{string-1}, otherwise to @var{string-2}.  If @var{string-2} is
3125 omitted, it is taken to be the empty string (according to the normal
3126 rules).
3128 The macro @code{ifdef} is recognized only with parameters.
3129 @end deffn
3131 @example
3132 ifdef(`foo', ``foo' is defined', ``foo' is not defined')
3133 @result{}foo is not defined
3134 define(`foo', `')
3135 @result{}
3136 ifdef(`foo', ``foo' is defined', ``foo' is not defined')
3137 @result{}foo is defined
3138 ifdef(`no_such_macro', `yes', `no', `extra argument')
3139 @error{}m4:stdin:4: warning: ifdef: extra arguments ignored: 4 > 3
3140 @result{}no
3141 @end example
3143 As of M4 1.6, @code{ifdef} transparently handles builtin tokens
3144 generated by @code{defn} (@pxref{Defn}) that occur in either
3145 @var{string}, although a warning is issued for invalid macro names.
3147 @example
3148 define(`', `empty')
3149 @result{}
3150 ifdef(defn(`defn'), `yes', `no')
3151 @error{}m4:stdin:2: warning: ifdef: invalid macro name ignored
3152 @result{}no
3153 define(`foo', ifdef(`divnum', defn(`divnum'), `undefined'))
3154 @result{}
3156 @result{}0
3157 @end example
3159 @node Ifelse
3160 @section If-else construct, or multibranch
3162 @cindex comparing strings
3163 @cindex discarding input
3164 @cindex input, discarding
3165 The other conditional, @code{ifelse}, is much more powerful.  It can be
3166 used as a way to introduce a long comment, as an if-else construct, or
3167 as a multibranch, depending on the number of arguments supplied:
3169 @deffn {Builtin (m4)} ifelse (@var{comment})
3170 @deffnx {Builtin (m4)} ifelse (@var{string-1}, @var{string-2}, @var{equal}, @
3171   @ovar{not-equal})
3172 @deffnx {Builtin (m4)} ifelse (@var{string-1}, @var{string-2}, @var{equal-1}, @
3173   @var{string-3}, @var{string-4}, @var{equal-2}, @dots{}, @ovar{not-equal})
3174 Used with only one argument, the @code{ifelse} simply discards it and
3175 produces no output.
3177 If called with three or four arguments, @code{ifelse} expands into
3178 @var{equal}, if @var{string-1} and @var{string-2} are equal (character
3179 for character), otherwise it expands to @var{not-equal}.  A final fifth
3180 argument is ignored, after triggering a warning.
3182 If called with six or more arguments, and @var{string-1} and
3183 @var{string-2} are equal, @code{ifelse} expands into @var{equal-1},
3184 otherwise the first three arguments are discarded and the processing
3185 starts again.
3187 The macro @code{ifelse} is recognized only with parameters.
3188 @end deffn
3190 Using only one argument is a common @code{m4} idiom for introducing a
3191 block comment, as an alternative to repeatedly using @code{dnl}.  This
3192 special usage is recognized by GNU @code{m4}, so that in this
3193 case, the warning about missing arguments is never triggered.
3195 @example
3196 ifelse(`some comments')
3197 @result{}
3198 ifelse(`foo', `bar')
3199 @error{}m4:stdin:2: warning: ifelse: too few arguments: 2 < 3
3200 @result{}
3201 @end example
3203 Using three or four arguments provides decision points.
3205 @example
3206 ifelse(`foo', `bar', `true')
3207 @result{}
3208 ifelse(`foo', `foo', `true')
3209 @result{}true
3210 define(`foo', `bar')
3211 @result{}
3212 ifelse(foo, `bar', `true', `false')
3213 @result{}true
3214 ifelse(foo, `foo', `true', `false')
3215 @result{}false
3216 @end example
3218 @cindex macro, blind
3219 @cindex blind macro
3220 Notice how the first argument was used unquoted; it is common to compare
3221 the expansion of a macro with a string.  With this macro, you can now
3222 reproduce the behavior of blind builtins, where the macro is recognized
3223 only with arguments.
3225 @example
3226 define(`foo', `ifelse(`$#', `0', ``$0'', `arguments:$#')')
3227 @result{}
3229 @result{}foo
3230 foo()
3231 @result{}arguments:1
3232 foo(`a', `b', `c')
3233 @result{}arguments:3
3234 @end example
3236 For an example of a way to make defining blind macros easier, see
3237 @ref{Composition}.
3239 @cindex multibranches
3240 @cindex switch statement
3241 @cindex case statement
3242 The macro @code{ifelse} can take more than four arguments.  If given more
3243 than four arguments, @code{ifelse} works like a @code{case} or @code{switch}
3244 statement in traditional programming languages.  If @var{string-1} and
3245 @var{string-2} are equal, @code{ifelse} expands into @var{equal-1}, otherwise
3246 the procedure is repeated with the first three arguments discarded.  This
3247 calls for an example:
3249 @example
3250 ifelse(`foo', `bar', `third', `gnu', `gnats')
3251 @error{}m4:stdin:1: warning: ifelse: extra arguments ignored: 5 > 4
3252 @result{}gnu
3253 ifelse(`foo', `bar', `third', `gnu', `gnats', `sixth')
3254 @result{}
3255 ifelse(`foo', `bar', `third', `gnu', `gnats', `sixth', `seventh')
3256 @result{}seventh
3257 ifelse(`foo', `bar', `3', `gnu', `gnats', `6', `7', `8')
3258 @error{}m4:stdin:4: warning: ifelse: extra arguments ignored: 8 > 7
3259 @result{}7
3260 @end example
3262 As of M4 1.6, @code{ifelse} transparently handles builtin tokens
3263 generated by @code{defn} (@pxref{Defn}).  Because of this, it is always
3264 safe to compare two macro definitions, without worrying whether the
3265 macro might be a builtin.
3267 @example
3268 ifelse(defn(`defn'), `', `yes', `no')
3269 @result{}no
3270 ifelse(defn(`defn'), defn(`divnum'), `yes', `no')
3271 @result{}no
3272 ifelse(defn(`defn'), defn(`defn'), `yes', `no')
3273 @result{}yes
3274 define(`foo', ifelse(`', `', defn(`divnum')))
3275 @result{}
3277 @result{}0
3278 @end example
3280 Naturally, the normal case will be slightly more advanced than these
3281 examples.  A common use of @code{ifelse} is in macros implementing loops
3282 of various kinds.
3284 @node Shift
3285 @section Recursion in @code{m4}
3287 @cindex recursive macros
3288 @cindex macros, recursive
3289 There is no direct support for loops in @code{m4}, but macros can be
3290 recursive.  There is no limit on the number of recursion levels, other
3291 than those enforced by your hardware and operating system.
3293 @cindex loops
3294 Loops can be programmed using recursion and the conditionals described
3295 previously.
3297 There is a builtin macro, @code{shift}, which can, among other things,
3298 be used for iterating through the actual arguments to a macro:
3300 @deffn {Builtin (m4)} shift (@var{arg1}, @dots{})
3301 Takes any number of arguments, and expands to all its arguments except
3302 @var{arg1}, separated by commas, with each argument quoted.
3304 The macro @code{shift} is recognized only with parameters.
3305 @end deffn
3307 @example
3308 shift
3309 @result{}shift
3310 shift(`bar')
3311 @result{}
3312 shift(`foo', `bar', `baz')
3313 @result{}bar,baz
3314 @end example
3316 An example of the use of @code{shift} is this macro:
3318 @cindex reversing arguments
3319 @cindex arguments, reversing
3320 @deffn Composite reverse (@dots{})
3321 Takes any number of arguments, and reverses their order.
3322 @end deffn
3324 It is implemented as:
3326 @example
3327 define(`reverse', `ifelse(`$#', `0', , `$#', `1', ``$1'',
3328                           `reverse(shift($@@)), `$1'')')
3329 @result{}
3330 reverse
3331 @result{}
3332 reverse(`foo')
3333 @result{}foo
3334 reverse(`foo', `bar', `gnats', `and gnus')
3335 @result{}and gnus, gnats, bar, foo
3336 @end example
3338 While not a very interesting macro, it does show how simple loops can be
3339 made with @code{shift}, @code{ifelse} and recursion.  It also shows
3340 that @code{shift} is usually used with @samp{$@@}.  Another example of
3341 this is an implementation of a short-circuiting conditional operator.
3343 @cindex short-circuiting conditional
3344 @cindex conditional, short-circuiting
3345 @deffn Composite cond (@var{test-1}, @var{string-1}, @var{equal-1}, @
3346   @ovar{test-2}, @ovar{string-2}, @ovar{equal-2}, @dots{}, @ovar{not-equal})
3347 Similar to @code{ifelse}, where an equal comparison between the first
3348 two strings results in the third, otherwise the first three arguments
3349 are discarded and the process repeats.  The difference is that each
3350 @var{test-<n>} is expanded only when it is encountered.  This means that
3351 every third argument to @code{cond} is normally given one more level of
3352 quoting than the corresponding argument to @code{ifelse}.
3353 @end deffn
3355 Here is the implementation of @code{cond}, along with a demonstration of
3356 how it can short-circuit the side effects in @code{side}.  Notice how
3357 all the unquoted side effects happen regardless of how many comparisons
3358 are made with @code{ifelse}, compared with only the relevant effects
3359 with @code{cond}.
3361 @example
3362 define(`cond',
3363 `ifelse(`$#', `1', `$1',
3364         `ifelse($1, `$2', `$3',
3365                 `$0(shift(shift(shift($@@))))')')')dnl
3366 define(`side', `define(`counter', incr(counter))$1')dnl
3367 define(`example1',
3368 `define(`counter', `0')dnl
3369 ifelse(side(`$1'), `yes', `one comparison: ',
3370        side(`$1'), `no', `two comparisons: ',
3371        side(`$1'), `maybe', `three comparisons: ',
3372        `side(`default answer: ')')counter')dnl
3373 define(`example2',
3374 `define(`counter', `0')dnl
3375 cond(`side(`$1')', `yes', `one comparison: ',
3376      `side(`$1')', `no', `two comparisons: ',
3377      `side(`$1')', `maybe', `three comparisons: ',
3378      `side(`default answer: ')')counter')dnl
3379 example1(`yes')
3380 @result{}one comparison: 3
3381 example1(`no')
3382 @result{}two comparisons: 3
3383 example1(`maybe')
3384 @result{}three comparisons: 3
3385 example1(`feeling rather indecisive today')
3386 @result{}default answer: 4
3387 example2(`yes')
3388 @result{}one comparison: 1
3389 example2(`no')
3390 @result{}two comparisons: 2
3391 example2(`maybe')
3392 @result{}three comparisons: 3
3393 example2(`feeling rather indecisive today')
3394 @result{}default answer: 4
3395 @end example
3397 @cindex joining arguments
3398 @cindex arguments, joining
3399 @cindex concatenating arguments
3400 Another common task that requires iteration is joining a list of
3401 arguments into a single string.
3403 @deffn Composite join (@ovar{separator}, @ovar{args@dots{}})
3404 @deffnx Composite joinall (@ovar{separator}, @ovar{args@dots{}})
3405 Generate a single-quoted string, consisting of each @var{arg} separated
3406 by @var{separator}.  While @code{joinall} always outputs a
3407 @var{separator} between arguments, @code{join} avoids the
3408 @var{separator} for an empty @var{arg}.
3409 @end deffn
3411 Here are some examples of its usage, based on the implementation
3412 @file{m4-@value{VERSION}/@/doc/examples/@/join.m4} distributed in this
3413 package:
3415 @comment examples
3416 @example
3417 $ @kbd{m4 -I examples}
3418 include(`join.m4')
3419 @result{}
3420 join,join(`-'),join(`-', `'),join(`-', `', `')
3421 @result{},,,
3422 joinall,joinall(`-'),joinall(`-', `'),joinall(`-', `', `')
3423 @result{},,,-
3424 join(`-', `1')
3425 @result{}1
3426 join(`-', `1', `2', `3')
3427 @result{}1-2-3
3428 join(`', `1', `2', `3')
3429 @result{}123
3430 join(`-', `', `1', `', `', `2', `')
3431 @result{}1-2
3432 joinall(`-', `', `1', `', `', `2', `')
3433 @result{}-1---2-
3434 join(`,', `1', `2', `3')
3435 @result{}1,2,3
3436 define(`nargs', `$#')dnl
3437 nargs(join(`,', `1', `2', `3'))
3438 @result{}1
3439 @end example
3441 Examining the implementation shows some interesting points about several
3442 m4 programming idioms.
3444 @comment examples
3445 @example
3446 $ @kbd{m4 -I doc/examples}
3447 undivert(`join.m4')dnl
3448 @result{}divert(`-1')
3449 @result{}# join(sep, args) - join each non-empty ARG into a single
3450 @result{}# string, with each element separated by SEP
3451 @result{}define(`join',
3452 @result{}`ifelse(`$#', `2', ``$2'',
3453 @result{}  `ifelse(`$2', `', `', ``$2'_')$0(`$1', shift(shift($@@)))')')
3454 @result{}define(`_join',
3455 @result{}`ifelse(`$#$2', `2', `',
3456 @result{}  `ifelse(`$2', `', `', ``$1$2'')$0(`$1', shift(shift($@@)))')')
3457 @result{}# joinall(sep, args) - join each ARG, including empty ones,
3458 @result{}# into a single string, with each element separated by SEP
3459 @result{}define(`joinall', ``$2'_$0(`$1', shift($@@))')
3460 @result{}define(`_joinall',
3461 @result{}`ifelse(`$#', `2', `', ``$1$3'$0(`$1', shift(shift($@@)))')')
3462 @result{}divert`'dnl
3463 @end example
3465 First, notice that this implementation creates helper macros
3466 @code{_join} and @code{_joinall}.  This division of labor makes it
3467 easier to output the correct number of @var{separator} instances:
3468 @code{join} and @code{joinall} are responsible for the first argument,
3469 without a separator, while @code{_join} and @code{_joinall} are
3470 responsible for all remaining arguments, always outputting a separator
3471 when outputting an argument.
3473 Next, observe how @code{join} decides to iterate to itself, because the
3474 first @var{arg} was empty, or to output the argument and swap over to
3475 @code{_join}.  If the argument is non-empty, then the nested
3476 @code{ifelse} results in an unquoted @samp{_}, which is concatenated
3477 with the @samp{$0} to form the next macro name to invoke.  The
3478 @code{joinall} implementation is simpler since it does not have to
3479 suppress empty @var{arg}; it always executes once then defers to
3480 @code{_joinall}.
3482 Another important idiom is the idea that @var{separator} is reused for
3483 each iteration.  Each iteration has one less argument, but rather than
3484 discarding @samp{$1} by iterating with @code{$0(shift($@@))}, the macro
3485 discards @samp{$2} by using @code{$0(`$1', shift(shift($@@)))}.
3487 Next, notice that it is possible to compare more than one condition in a
3488 single @code{ifelse} test.  The test of @samp{$#$2} against @samp{2}
3489 allows @code{_join} to iterate for two separate reasons---either there
3490 are still more than two arguments, or there are exactly two arguments
3491 but the last argument is not empty.
3493 Finally, notice that these macros require exactly two arguments to
3494 terminate recursion, but that they still correctly result in empty
3495 output when given no @var{args} (i.e., zero or one macro argument).  On
3496 the first pass when there are too few arguments, the @code{shift}
3497 results in no output, but leaves an empty string to serve as the
3498 required second argument for the second pass.  Put another way,
3499 @samp{`$1', shift($@@)} is not the same as @samp{$@@}, since only the
3500 former guarantees at least two arguments.
3502 @cindex quote manipulation
3503 @cindex manipulating quotes
3504 Sometimes, a recursive algorithm requires adding quotes to each element,
3505 or treating multiple arguments as a single element:
3507 @deffn Composite quote (@dots{})
3508 @deffnx Composite dquote (@dots{})
3509 @deffnx Composite dquote_elt (@dots{})
3510 Takes any number of arguments, and adds quoting.  With @code{quote},
3511 only one level of quoting is added, effectively removing whitespace
3512 after commas and turning multiple arguments into a single string.  With
3513 @code{dquote}, two levels of quoting are added, one around each element,
3514 and one around the list.  And with @code{dquote_elt}, two levels of
3515 quoting are added around each element.
3516 @end deffn
3518 An actual implementation of these three macros is distributed as
3519 @file{m4-@value{VERSION}/@/doc/examples/@/quote.m4} in this package.
3520 First, let's examine their usage:
3522 @comment examples
3523 @example
3524 $ @kbd{m4 -I doc/examples}
3525 include(`quote.m4')
3526 @result{}
3527 -quote-dquote-dquote_elt-
3528 @result{}----
3529 -quote()-dquote()-dquote_elt()-
3530 @result{}--`'-`'-
3531 -quote(`1')-dquote(`1')-dquote_elt(`1')-
3532 @result{}-1-`1'-`1'-
3533 -quote(`1', `2')-dquote(`1', `2')-dquote_elt(`1', `2')-
3534 @result{}-1,2-`1',`2'-`1',`2'-
3535 define(`n', `$#')dnl
3536 -n(quote(`1', `2'))-n(dquote(`1', `2'))-n(dquote_elt(`1', `2'))-
3537 @result{}-1-1-2-
3538 dquote(dquote_elt(`1', `2'))
3539 @result{}``1'',``2''
3540 dquote_elt(dquote(`1', `2'))
3541 @result{}``1',`2''
3542 @end example
3544 The last two lines show that when given two arguments, @code{dquote}
3545 results in one string, while @code{dquote_elt} results in two.  Now,
3546 examine the implementation.  Note that @code{quote} and
3547 @code{dquote_elt} make decisions based on their number of arguments, so
3548 that when called without arguments, they result in nothing instead of a
3549 quoted empty string; this is so that it is possible to distinguish
3550 between no arguments and an empty first argument.  @code{dquote}, on the
3551 other hand, results in a string no matter what, since it is still
3552 possible to tell whether it was invoked without arguments based on the
3553 resulting string.
3555 @comment examples
3556 @example
3557 $ @kbd{m4 -I doc/examples}
3558 undivert(`quote.m4')dnl
3559 @result{}divert(`-1')
3560 @result{}# quote(args) - convert args to single-quoted string
3561 @result{}define(`quote', `ifelse(`$#', `0', `', ``$*'')')
3562 @result{}# dquote(args) - convert args to quoted list of quoted strings
3563 @result{}define(`dquote', ``$@@'')
3564 @result{}# dquote_elt(args) - convert args to list of double-quoted strings
3565 @result{}define(`dquote_elt', `ifelse(`$#', `0', `', `$#', `1', ```$1''',
3566 @result{}                             ```$1'',$0(shift($@@))')')
3567 @result{}divert`'dnl
3568 @end example
3570 It is worth pointing out that @samp{quote(@var{args})} is more efficient
3571 than @samp{joinall(`,', @var{args})} for producing the same output.
3573 @cindex nine arguments, more than
3574 @cindex more than nine arguments
3575 @cindex arguments, more than nine
3576 One more useful macro based on @code{shift} allows portably selecting
3577 an arbitrary argument (usually greater than the ninth argument), without
3578 relying on the GNU extension of multi-digit arguments
3579 (@pxref{Arguments}).
3581 @deffn Composite argn (@var{n}, @dots{})
3582 Expands to argument @var{n} out of the remaining arguments.  @var{n}
3583 must be a positive number.  Usually invoked as
3584 @samp{argn(`@var{n}',$@@)}.
3585 @end deffn
3587 It is implemented as:
3589 @example
3590 define(`argn', `ifelse(`$1', 1, ``$2'',
3591   `argn(decr(`$1'), shift(shift($@@)))')')
3592 @result{}
3593 argn(`1', `a')
3594 @result{}a
3595 define(`foo', `argn(`11', $@@)')
3596 @result{}
3597 foo(`a', `b', `c', `d', `e', `f', `g', `h', `i', `j', `k', `l')
3598 @result{}k
3599 @end example
3601 @node Forloop
3602 @section Iteration by counting
3604 @cindex for loops
3605 @cindex loops, counting
3606 @cindex counting loops
3607 Here is an example of a loop macro that implements a simple for loop.
3609 @deffn Composite forloop (@var{iterator}, @var{start}, @var{end}, @var{text})
3610 Takes the name in @var{iterator}, which must be a valid macro name, and
3611 successively assign it each integer value from @var{start} to @var{end},
3612 inclusive.  For each assignment to @var{iterator}, append @var{text} to
3613 the expansion of the @code{forloop}.  @var{text} may refer to
3614 @var{iterator}.  Any definition of @var{iterator} prior to this
3615 invocation is restored.
3616 @end deffn
3618 It can, for example, be used for simple counting:
3620 @comment examples
3621 @example
3622 $ @kbd{m4 -I doc/examples}
3623 include(`forloop.m4')
3624 @result{}
3625 forloop(`i', `1', `8', `i ')
3626 @result{}1 2 3 4 5 6 7 8@w{ }
3627 @end example
3629 For-loops can be nested, like:
3631 @comment examples
3632 @example
3633 $ @kbd{m4 -I doc/examples}
3634 include(`forloop.m4')
3635 @result{}
3636 forloop(`i', `1', `4', `forloop(`j', `1', `8', ` (i, j)')
3638 @result{} (1, 1) (1, 2) (1, 3) (1, 4) (1, 5) (1, 6) (1, 7) (1, 8)
3639 @result{} (2, 1) (2, 2) (2, 3) (2, 4) (2, 5) (2, 6) (2, 7) (2, 8)
3640 @result{} (3, 1) (3, 2) (3, 3) (3, 4) (3, 5) (3, 6) (3, 7) (3, 8)
3641 @result{} (4, 1) (4, 2) (4, 3) (4, 4) (4, 5) (4, 6) (4, 7) (4, 8)
3642 @result{}
3643 @end example
3645 The implementation of the @code{forloop} macro is fairly
3646 straightforward.  The @code{forloop} macro itself is simply a wrapper,
3647 which saves the previous definition of the first argument, calls the
3648 internal macro @code{@w{_forloop}}, and re-establishes the saved
3649 definition of the first argument.
3651 The macro @code{@w{_forloop}} expands the fourth argument once, and
3652 tests to see if the iterator has reached the final value.  If it has
3653 not finished, it increments the iterator (using the predefined macro
3654 @code{incr}, @pxref{Incr}), and recurses.
3656 Here is an actual implementation of @code{forloop}, distributed as
3657 @file{m4-@value{VERSION}/@/doc/examples/@/forloop.m4} in this package:
3659 @comment examples
3660 @example
3661 $ @kbd{m4 -I doc/examples}
3662 undivert(`forloop.m4')dnl
3663 @result{}divert(`-1')
3664 @result{}# forloop(var, from, to, stmt) - simple version
3665 @result{}define(`forloop', `pushdef(`$1', `$2')_forloop($@@)popdef(`$1')')
3666 @result{}define(`_forloop',
3667 @result{}       `$4`'ifelse($1, `$3', `', `define(`$1', incr($1))$0($@@)')')
3668 @result{}divert`'dnl
3669 @end example
3671 Notice the careful use of quotes.  Certain macro arguments are left
3672 unquoted, each for its own reason.  Try to find out @emph{why} these
3673 arguments are left unquoted, and see what happens if they are quoted.
3674 (As presented, these two macros are useful but not very robust for
3675 general use.  They lack even basic error handling for cases like
3676 @var{start} less than @var{end}, @var{end} not numeric, or
3677 @var{iterator} not being a macro name.  See if you can improve these
3678 macros; or @pxref{Improved forloop, , Answers}).
3680 @node Foreach
3681 @section Iteration by list contents
3683 @cindex for each loops
3684 @cindex loops, list iteration
3685 @cindex iterating over lists
3686 Here is an example of a loop macro that implements list iteration.
3688 @deffn Composite foreach (@var{iterator}, @var{paren-list}, @var{text})
3689 @deffnx Composite foreachq (@var{iterator}, @var{quote-list}, @var{text})
3690 Takes the name in @var{iterator}, which must be a valid macro name, and
3691 successively assign it each value from @var{paren-list} or
3692 @var{quote-list}.  In @code{foreach}, @var{paren-list} is a
3693 comma-separated list of elements contained in parentheses.  In
3694 @code{foreachq}, @var{quote-list} is a comma-separated list of elements
3695 contained in a quoted string.  For each assignment to @var{iterator},
3696 append @var{text} to the overall expansion.  @var{text} may refer to
3697 @var{iterator}.  Any definition of @var{iterator} prior to this
3698 invocation is restored.
3699 @end deffn
3701 As an example, this displays each word in a list inside of a sentence,
3702 using an implementation of @code{foreach} distributed as
3703 @file{m4-@value{VERSION}/@/doc/examples/@/foreach.m4}, and @code{foreachq}
3704 in @file{m4-@value{VERSION}/@/doc/examples/@/foreachq.m4}.
3706 @comment examples
3707 @example
3708 $ @kbd{m4 -I doc/examples}
3709 include(`foreach.m4')
3710 @result{}
3711 foreach(`x', (foo, bar, foobar), `Word was: x
3712 ')dnl
3713 @result{}Word was: foo
3714 @result{}Word was: bar
3715 @result{}Word was: foobar
3716 include(`foreachq.m4')
3717 @result{}
3718 foreachq(`x', `foo, bar, foobar', `Word was: x
3719 ')dnl
3720 @result{}Word was: foo
3721 @result{}Word was: bar
3722 @result{}Word was: foobar
3723 @end example
3725 It is possible to be more complex; each element of the @var{paren-list}
3726 or @var{quote-list} can itself be a list, to pass as further arguments
3727 to a helper macro.  This example generates a shell case statement:
3729 @comment examples
3730 @example
3731 $ @kbd{m4 -I doc/examples}
3732 include(`foreach.m4')
3733 @result{}
3734 define(`_case', `  $1)
3735     $2=" $1";;
3736 ')dnl
3737 define(`_cat', `$1$2')dnl
3738 case $`'1 in
3739 @result{}case $1 in
3740 foreach(`x', `(`(`a', `vara')', `(`b', `varb')', `(`c', `varc')')',
3741         `_cat(`_case', x)')dnl
3742 @result{}  a)
3743 @result{}    vara=" a";;
3744 @result{}  b)
3745 @result{}    varb=" b";;
3746 @result{}  c)
3747 @result{}    varc=" c";;
3748 esac
3749 @result{}esac
3750 @end example
3752 The implementation of the @code{foreach} macro is a bit more involved;
3753 it is a wrapper around two helper macros.  First, @code{@w{_arg1}} is
3754 needed to grab the first element of a list.  Second,
3755 @code{@w{_foreach}} implements the recursion, successively walking
3756 through the original list.  Here is a simple implementation of
3757 @code{foreach}:
3759 @comment examples
3760 @example
3761 $ @kbd{m4 -I doc/examples}
3762 undivert(`foreach.m4')dnl
3763 @result{}divert(`-1')
3764 @result{}# foreach(x, (item_1, item_2, ..., item_n), stmt)
3765 @result{}#   parenthesized list, simple version
3766 @result{}define(`foreach', `pushdef(`$1')_foreach($@@)popdef(`$1')')
3767 @result{}define(`_arg1', `$1')
3768 @result{}define(`_foreach', `ifelse(`$2', `()', `',
3769 @result{}  `define(`$1', _arg1$2)$3`'$0(`$1', (shift$2), `$3')')')
3770 @result{}divert`'dnl
3771 @end example
3773 Unfortunately, that implementation is not robust to macro names as list
3774 elements.  Each iteration of @code{@w{_foreach}} is stripping another
3775 layer of quotes, leading to erratic results if list elements are not
3776 already fully expanded.  The first cut at implementing @code{foreachq}
3777 takes this into account.  Also, when using quoted elements in a
3778 @var{paren-list}, the overall list must be quoted.  A @var{quote-list}
3779 has the nice property of requiring fewer characters to create a list
3780 containing the same quoted elements.  To see the difference between the
3781 two macros, we attempt to pass double-quoted macro names in a list,
3782 expecting the macro name on output after one layer of quotes is removed
3783 during list iteration and the final layer removed during the final
3784 rescan:
3786 @comment examples
3787 @example
3788 $ @kbd{m4 -I doc/examples}
3789 define(`a', `1')define(`b', `2')define(`c', `3')
3790 @result{}
3791 include(`foreach.m4')
3792 @result{}
3793 include(`foreachq.m4')
3794 @result{}
3795 foreach(`x', `(``a'', ``(b'', ``c)'')', `x
3797 @result{}1
3798 @result{}(2)1
3799 @result{}
3800 @result{}, x
3801 @result{})
3802 foreachq(`x', ```a'', ``(b'', ``c)''', `x
3803 ')dnl
3804 @result{}a
3805 @result{}(b
3806 @result{}c)
3807 @end example
3809 Obviously, @code{foreachq} did a better job; here is its implementation:
3811 @comment examples
3812 @example
3813 $ @kbd{m4 -I doc/examples}
3814 undivert(`foreachq.m4')dnl
3815 @result{}include(`quote.m4')dnl
3816 @result{}divert(`-1')
3817 @result{}# foreachq(x, `item_1, item_2, ..., item_n', stmt)
3818 @result{}#   quoted list, simple version
3819 @result{}define(`foreachq', `pushdef(`$1')_foreachq($@@)popdef(`$1')')
3820 @result{}define(`_arg1', `$1')
3821 @result{}define(`_foreachq', `ifelse(quote($2), `', `',
3822 @result{}  `define(`$1', `_arg1($2)')$3`'$0(`$1', `shift($2)', `$3')')')
3823 @result{}divert`'dnl
3824 @end example
3826 Notice that @code{@w{_foreachq}} had to use the helper macro
3827 @code{quote} defined earlier (@pxref{Shift}), to ensure that the
3828 embedded @code{ifelse} call does not go haywire if a list element
3829 contains a comma.  Unfortunately, this implementation of @code{foreachq}
3830 has its own severe flaw.  Whereas the @code{foreach} implementation was
3831 linear, this macro is quadratic in the number of list elements, and is
3832 much more likely to trip up the limit set by the command line option
3833 @option{--nesting-limit} (or @option{-L}, @pxref{Limits control, ,
3834 Invoking m4}).  Additionally, this implementation does not expand
3835 @samp{defn(`@var{iterator}')} very well, when compared with
3836 @code{foreach}.
3838 @comment examples
3839 @example
3840 $ @kbd{m4 -I doc/examples}
3841 include(`foreach.m4')include(`foreachq.m4')
3842 @result{}
3843 foreach(`name', `(`a', `b')', ` defn(`name')')
3844 @result{} a b
3845 foreachq(`name', ``a', `b'', ` defn(`name')')
3846 @result{} _arg1(`a', `b') _arg1(shift(`a', `b'))
3847 @end example
3849 It is possible to have robust iteration with linear behavior and sane
3850 @var{iterator} contents for either list style.  See if you can learn
3851 from the best elements of both of these implementations to create robust
3852 macros (or @pxref{Improved foreach, , Answers}).
3854 @node Stacks
3855 @section Working with definition stacks
3857 @cindex definition stack
3858 @cindex pushdef stack
3859 @cindex stack, macro definition
3860 Thanks to @code{pushdef}, manipulation of a stack is an intrinsic
3861 operation in @code{m4}.  Normally, only the topmost definition in a
3862 stack is important, but sometimes, it is desirable to manipulate the
3863 entire definition stack.
3865 @deffn Composite stack_foreach (@var{macro}, @var{action})
3866 @deffnx Composite stack_foreach_lifo (@var{macro}, @var{action})
3867 For each of the @code{pushdef} definitions associated with @var{macro},
3868 invoke the macro @var{action} with a single argument of that definition.
3869 @code{stack_foreach} visits the oldest definition first, while
3870 @code{stack_foreach_lifo} visits the current definition first.
3871 @var{action} should not modify or dereference @var{macro}.  There are a
3872 few special macros, such as @code{defn}, which cannot be used as the
3873 @var{macro} parameter.
3874 @end deffn
3876 A sample implementation of these macros is distributed in the file
3877 @file{m4-@value{VERSION}/@/doc/examples/@/stack.m4}.
3879 @comment examples
3880 @example
3881 $ @kbd{m4 -I doc/examples}
3882 include(`stack.m4')
3883 @result{}
3884 pushdef(`a', `1')pushdef(`a', `2')pushdef(`a', `3')
3885 @result{}
3886 define(`show', ``$1'
3888 @result{}
3889 stack_foreach(`a', `show')dnl
3890 @result{}1
3891 @result{}2
3892 @result{}3
3893 stack_foreach_lifo(`a', `show')dnl
3894 @result{}3
3895 @result{}2
3896 @result{}1
3897 @end example
3899 Now for the implementation.  Note the definition of a helper macro,
3900 @code{_stack_reverse}, which destructively swaps the contents of one
3901 stack of definitions into the reverse order in the temporary macro
3902 @samp{tmp-$1}.  By calling the helper twice, the original order is
3903 restored back into the macro @samp{$1}; since the operation is
3904 destructive, this explains why @samp{$1} must not be modified or
3905 dereferenced during the traversal.  The caller can then inject
3906 additional code to pass the definition currently being visited to
3907 @samp{$2}.  The choice of helper names is intentional; since @samp{-} is
3908 not valid as part of a macro name, there is no risk of conflict with a
3909 valid macro name, and the code is guaranteed to use @code{defn} where
3910 necessary.  Finally, note that any macro used in the traversal of a
3911 @code{pushdef} stack, such as @code{pushdef} or @code{defn}, cannot be
3912 handled by @code{stack_foreach}, since the macro would temporarily be
3913 undefined during the algorithm.
3915 @comment examples
3916 @example
3917 $ @kbd{m4 -I doc/examples}
3918 undivert(`stack.m4')dnl
3919 @result{}divert(`-1')
3920 @result{}# stack_foreach(macro, action)
3921 @result{}# Invoke ACTION with a single argument of each definition
3922 @result{}# from the definition stack of MACRO, starting with the oldest.
3923 @result{}define(`stack_foreach',
3924 @result{}`_stack_reverse(`$1', `tmp-$1')'dnl
3925 @result{}`_stack_reverse(`tmp-$1', `$1', `$2(defn(`$1'))')')
3926 @result{}# stack_foreach_lifo(macro, action)
3927 @result{}# Invoke ACTION with a single argument of each definition
3928 @result{}# from the definition stack of MACRO, starting with the newest.
3929 @result{}define(`stack_foreach_lifo',
3930 @result{}`_stack_reverse(`$1', `tmp-$1', `$2(defn(`$1'))')'dnl
3931 @result{}`_stack_reverse(`tmp-$1', `$1')')
3932 @result{}define(`_stack_reverse',
3933 @result{}`ifdef(`$1', `pushdef(`$2', defn(`$1'))$3`'popdef(`$1')$0($@@)')')
3934 @result{}divert`'dnl
3935 @end example
3937 @node Composition
3938 @section Building macros with macros
3940 @cindex macro composition
3941 @cindex composing macros
3942 Since m4 is a macro language, it is possible to write macros that
3943 can build other macros.  First on the list is a way to automate the
3944 creation of blind macros.
3946 @cindex macro, blind
3947 @cindex blind macro
3948 @deffn Composite define_blind (@var{name}, @ovar{value})
3949 Defines @var{name} as a blind macro, such that @var{name} will expand to
3950 @var{value} only when given explicit arguments.  @var{value} should not
3951 be the result of @code{defn} (@pxref{Defn}).  This macro is only
3952 recognized with parameters, and results in an empty string.
3953 @end deffn
3955 Defining a macro to define another macro can be a bit tricky.  We want
3956 to use a literal @samp{$#} in the argument to the nested @code{define}.
3957 However, if @samp{$} and @samp{#} are adjacent in the definition of
3958 @code{define_blind}, then it would be expanded as the number of
3959 arguments to @code{define_blind} rather than the intended number of
3960 arguments to @var{name}.  The solution is to pass the difficult
3961 characters through extra arguments to a helper macro
3962 @code{_define_blind}.  When composing macros, it is a common idiom to
3963 need a helper macro to concatenate text that forms parameters in the
3964 composed macro, rather than interpreting the text as a parameter of the
3965 composing macro.
3967 As for the limitation against using @code{defn}, there are two reasons.
3968 If a macro was previously defined with @code{define_blind}, then it can
3969 safely be renamed to a new blind macro using plain @code{define}; using
3970 @code{define_blind} to rename it just adds another layer of
3971 @code{ifelse}, occupying memory and slowing down execution.  And if a
3972 macro is a builtin, then it would result in an attempt to define a macro
3973 consisting of both text and a builtin token; this is not supported, and
3974 the builtin token is flattened to an empty string.
3976 With that explanation, here's the definition, and some sample usage.
3977 Notice that @code{define_blind} is itself a blind macro.
3979 @example
3980 $ @kbd{m4 -d}
3981 define(`define_blind', `ifelse(`$#', `0', ``$0'',
3982 `_$0(`$1', `$2', `$'`#', `$'`0')')')
3983 @result{}
3984 define(`_define_blind', `define(`$1',
3985 `ifelse(`$3', `0', ``$4'', `$2')')')
3986 @result{}
3987 define_blind
3988 @result{}define_blind
3989 define_blind(`foo', `arguments were $*')
3990 @result{}
3992 @result{}foo
3993 foo(`bar')
3994 @result{}arguments were bar
3995 define(`blah', defn(`foo'))
3996 @result{}
3997 blah
3998 @result{}blah
3999 blah(`a', `b')
4000 @result{}arguments were a,b
4001 defn(`blah')
4002 @result{}ifelse(`$#', `0', ``$0'', `arguments were $*')
4003 @end example
4005 @cindex currying arguments
4006 @cindex argument currying
4007 Another interesting composition tactic is argument @dfn{currying}, or
4008 factoring a macro that takes multiple arguments for use in a context
4009 that provides exactly one argument.
4011 @deffn Composite curry (@var{macro}, @dots{})
4012 Expand to a macro call that takes exactly one argument, then appends
4013 that argument to the original arguments and invokes @var{macro} with the
4014 resulting list of arguments.
4015 @end deffn
4017 A demonstration of currying makes the intent of this macro a little more
4018 obvious.  The macro @code{stack_foreach} mentioned earlier is an example
4019 of a context that provides exactly one argument to a macro name.  But
4020 coupled with currying, we can invoke @code{reverse} with two arguments
4021 for each definition of a macro stack.  This example uses the file
4022 @file{m4-@value{VERSION}/@/doc/examples/@/curry.m4} included in the
4023 distribution.
4025 @comment examples
4026 @example
4027 $ @kbd{m4 -I doc/examples}
4028 include(`curry.m4')include(`stack.m4')
4029 @result{}
4030 define(`reverse', `ifelse(`$#', `0', , `$#', `1', ``$1'',
4031                           `reverse(shift($@@)), `$1'')')
4032 @result{}
4033 pushdef(`a', `1')pushdef(`a', `2')pushdef(`a', `3')
4034 @result{}
4035 stack_foreach(`a', `:curry(`reverse', `4')')
4036 @result{}:1, 4:2, 4:3, 4
4037 curry(`curry', `reverse', `1')(`2')(`3')
4038 @result{}3, 2, 1
4039 @end example
4041 Now for the implementation.  Notice how @code{curry} leaves off with a
4042 macro name but no open parenthesis, while still in the middle of
4043 collecting arguments for @samp{$1}.  The macro @code{_curry} is the
4044 helper macro that takes one argument, then adds it to the list and
4045 finally supplies the closing parenthesis.  The use of a comma inside the
4046 @code{shift} call allows currying to also work for a macro that takes
4047 one argument, although it often makes more sense to invoke that macro
4048 directly rather than going through @code{curry}.
4050 @comment examples
4051 @example
4052 $ @kbd{m4 -I doc/examples}
4053 undivert(`curry.m4')dnl
4054 @result{}divert(`-1')
4055 @result{}# curry(macro, args)
4056 @result{}# Expand to a macro call that takes one argument, then invoke
4057 @result{}# macro(args, extra).
4058 @result{}define(`curry', `$1(shift($@@,)_$0')
4059 @result{}define(`_curry', ``$1')')
4060 @result{}divert`'dnl
4061 @end example
4063 Unfortunately, with M4 1.4.x, @code{curry} is unable to handle builtin
4064 tokens, which are silently flattened to the empty string when passed
4065 through another text macro.  The following example demonstrates a usage
4066 of @code{curry} that works in M4 1.6, but is not portable to earlier
4067 versions:
4069 @comment examples
4070 @example
4071 $ @kbd{m4 -I doc/examples}
4072 include(`curry.m4')
4073 @result{}
4074 curry(`define', `mylen')(defn(`len'))
4075 @result{}
4076 mylen(`abc')
4077 @result{}3
4078 @end example
4080 @cindex renaming macros
4081 @cindex copying macros
4082 @cindex macros, copying
4083 Putting the last few concepts together, it is possible to copy or rename
4084 an entire stack of macro definitions.
4086 @deffn Composite copy (@var{source}, @var{dest})
4087 @deffnx Composite rename (@var{source}, @var{dest})
4088 Ensure that @var{dest} is undefined, then define it to the same stack of
4089 definitions currently in @var{source}.  @code{copy} leaves @var{source}
4090 unchanged, while @code{rename} undefines @var{source}.  There are only a
4091 few macros, such as @code{copy} or @code{defn}, which cannot be copied
4092 via this macro.
4093 @end deffn
4095 The implementation is relatively straightforward (although since it uses
4096 @code{curry}, it is unable to copy builtin macros when used with M4
4097 1.4.x.  See if you can design a portable version that works across all
4098 M4 versions, or @pxref{Improved copy, , Answers}).
4100 @comment examples
4101 @example
4102 $ @kbd{m4 -I doc/examples}
4103 include(`curry.m4')include(`stack.m4')
4104 @result{}
4105 define(`rename', `copy($@@)undefine(`$1')')dnl
4106 define(`copy', `ifdef(`$2', `errprint(`$2 already defined
4107 ')m4exit(`1')',
4108    `stack_foreach(`$1', `curry(`pushdef', `$2')')')')dnl
4109 pushdef(`a', `1')pushdef(`a', defn(`divnum'))pushdef(`a', `2')
4110 @result{}
4111 copy(`a', `b')
4112 @result{}
4113 rename(`b', `c')
4114 @result{}
4115 a b c
4116 @result{}2 b 2
4117 popdef(`a', `c')a c
4118 @result{}0 0
4119 popdef(`a', `c')a c
4120 @result{}1 1
4121 @end example
4123 @node Debugging
4124 @chapter How to debug macros and input
4126 @cindex debugging macros
4127 @cindex macros, debugging
4128 When writing macros for @code{m4}, they often do not work as intended on
4129 the first try (as is the case with most programming languages).
4130 Fortunately, there is support for macro debugging in @code{m4}.
4132 @menu
4133 * Dumpdef::                     Displaying macro definitions
4134 * Trace::                       Tracing macro calls
4135 * Debugmode::                   Controlling debugging options
4136 * Debuglen::                    Limiting debug output
4137 * Debugfile::                   Saving debugging output
4138 @end menu
4140 @node Dumpdef
4141 @section Displaying macro definitions
4143 @cindex displaying macro definitions
4144 @cindex macros, displaying definitions
4145 @cindex definitions, displaying macro
4146 @cindex standard error, output to
4147 If you want to see what a name expands into, you can use the builtin
4148 @code{dumpdef}:
4150 @deffn {Builtin (m4)} dumpdef (@ovar{name@dots{}})
4151 Accepts any number of arguments.  If called without any arguments, it
4152 displays the definitions of all known names, otherwise it displays the
4153 definitions of each @var{name} given, sorted by name.  If a @var{name}
4154 is undefined, the @samp{d} debug level controls whether a warning is
4155 issued (@pxref{Debugmode}).  Likewise, the @samp{o} debug level controls
4156 whether the output is issued to standard error or the current debug
4157 file (@pxref{Debugfile}).
4159 The expansion of @code{dumpdef} is void.
4160 @end deffn
4162 @example
4163 $ @kbd{m4 -d}
4164 define(`foo', `Hello world.')
4165 @result{}
4166 dumpdef(`foo')
4167 @error{}foo:@tabchar{}`Hello world.'
4168 @result{}
4169 dumpdef(`define')
4170 @error{}define:@tabchar{}<define>
4171 @result{}
4172 @end example
4174 The last example shows how builtin macros definitions are displayed.
4175 The definition that is dumped corresponds to what would occur if the
4176 macro were to be called at that point, even if other definitions are
4177 still live due to redefining a macro during argument collection.
4179 @example
4180 $ @kbd{m4 -d}
4181 pushdef(`f', ``$0'1')pushdef(`f', ``$0'2')
4182 @result{}
4183 f(popdef(`f')dumpdef(`f'))
4184 @error{}f:@tabchar{}``$0'1'
4185 @result{}f2
4186 f(popdef(`f')dumpdef(`f'))
4187 @error{}m4:stdin:3: warning: dumpdef: undefined macro 'f'
4188 @result{}f1
4189 debugmode(`-d')
4190 @result{}
4191 dumpdef(`f')
4192 @result{}
4193 @end example
4195 @xref{Debugmode}, for information on how the @samp{m}, @samp{q}, and
4196 @samp{s} flags affect the details of the display.  Remember, the
4197 @samp{q} flag is implied when the @option{--debug} option (@option{-d},
4198 @pxref{Debugging options, , Invoking m4}) is used in the command line
4199 without arguments.  Also, @option{--debuglen} (@pxref{Debuglen}) can affect
4200 output, by truncating longer strings (but not builtin and module names).
4202 @comment options: -ds -l3
4203 @example
4204 $ @kbd{m4 -ds -l 3}
4205 pushdef(`foo', `1 long string')
4206 @result{}
4207 pushdef(`foo', defn(`divnum'))
4208 @result{}
4209 pushdef(`foo', `3')
4210 @result{}
4211 debugmode(`+m')
4212 @result{}
4213 dumpdef(`foo', `dnl', `indir', `__gnu__')
4214 @error{}__gnu__:@tabchar{}@{gnu@}
4215 @error{}dnl:@tabchar{}<dnl>@{m4@}
4216 @error{}foo:@tabchar{}3, <divnum>@{m4@}, 1 l...
4217 @error{}indir:@tabchar{}<indir>@{gnu@}
4218 @result{}
4219 debugmode(`-ms')debugmode(`+q')
4220 @result{}
4221 dumpdef(`foo')
4222 @error{}foo:@tabchar{}`3'
4223 @result{}
4224 @end example
4226 @node Trace
4227 @section Tracing macro calls
4229 @cindex tracing macro expansion
4230 @cindex macro expansion, tracing
4231 @cindex expansion, tracing macro
4232 @cindex standard error, output to
4233 It is possible to trace macro calls and expansions through the builtins
4234 @code{traceon} and @code{traceoff}:
4236 @deffn {Builtin (m4)} traceon (@ovar{names@dots{}})
4237 @deffnx {Builtin (m4)} traceoff (@ovar{names@dots{}})
4238 When called without any arguments, @code{traceon} and @code{traceoff}
4239 will turn tracing on and off, respectively, for all macros, identical to
4240 using the @samp{t} flag of @code{debugmode} (@pxref{Debugmode}).
4242 When called with arguments, only the macros listed in @var{names} are
4243 affected, whether or not they are currently defined.  A macro's
4244 expansion will be traced if global tracing is on, or if the individual
4245 macro tracing flag is set; to avoid tracing a macro, both the global
4246 flag and the macro must have tracing off.
4248 The expansion of @code{traceon} and @code{traceoff} is void.
4249 @end deffn
4251 Whenever a traced macro is called and the arguments have been collected,
4252 the call is displayed.  If the expansion of the macro call is not void,
4253 the expansion can be displayed after the call.  The output is printed
4254 to the current debug file (defaulting to standard error,
4255 @pxref{Debugfile}).
4257 @example
4258 $ @kbd{m4 -d}
4259 define(`foo', `Hello World.')
4260 @result{}
4261 define(`echo', `$@@')
4262 @result{}
4263 traceon(`foo', `echo')
4264 @result{}
4266 @error{}m4trace: -1- foo -> `Hello World.'
4267 @result{}Hello World.
4268 echo(`gnus', `and gnats')
4269 @error{}m4trace: -1- echo(`gnus', `and gnats') -> ``gnus',`and gnats''
4270 @result{}gnus,and gnats
4271 @end example
4273 The number between dashes is the depth of the expansion.  It is one most
4274 of the time, signifying an expansion at the outermost level, but it
4275 increases when macro arguments contain unquoted macro calls.  The
4276 maximum number that will appear between dashes is controlled by the
4277 option @option{--nesting-limit} (or @option{-L}, @pxref{Limits control,
4278 , Invoking m4}).  Additionally, the option @option{--trace} (or
4279 @option{-t}) can be used to invoke @code{traceon(@var{name})} before
4280 parsing input.
4282 @comment options: -d-V -L3 -tifelse
4283 @comment status: 1
4284 @example
4285 $ @kbd{m4 -L 3 -t ifelse}
4286 ifelse(`one level')
4287 @error{}m4trace: -1- ifelse
4288 @result{}
4289 ifelse(ifelse(ifelse(`three levels')))
4290 @error{}m4trace: -3- ifelse
4291 @error{}m4trace: -2- ifelse
4292 @error{}m4trace: -1- ifelse
4293 @result{}
4294 ifelse(ifelse(ifelse(ifelse(`four levels'))))
4295 @error{}m4:stdin:3: recursion limit of 3 exceeded, use -L<N> to change it
4296 @end example
4298 Tracing by name is an attribute that is preserved whether the macro is
4299 defined or not.  This allows the selection of macros to trace before
4300 those macros are defined.
4302 @example
4303 $ @kbd{m4 -d}
4304 traceoff(`foo')
4305 @result{}
4306 traceon(`foo')
4307 @result{}
4309 @result{}foo
4310 defn(`foo')
4311 @error{}m4:stdin:4: warning: defn: undefined macro 'foo'
4312 @result{}
4313 undefine(`foo')
4314 @error{}m4:stdin:5: warning: undefine: undefined macro 'foo'
4315 @result{}
4316 pushdef(`foo')
4317 @result{}
4318 popdef(`foo')
4319 @result{}
4320 popdef(`foo')
4321 @error{}m4:stdin:8: warning: popdef: undefined macro 'foo'
4322 @result{}
4323 define(`foo', `bar')
4324 @result{}
4326 @error{}m4trace: -1- foo -> `bar'
4327 @result{}bar
4328 undefine(`foo')
4329 @result{}
4330 ifdef(`foo', `yes', `no')
4331 @result{}no
4332 indir(`foo')
4333 @error{}m4:stdin:13: warning: indir: undefined macro 'foo'
4334 @result{}
4335 define(`foo', `blah')
4336 @result{}
4338 @error{}m4trace: -1- foo -> `blah'
4339 @result{}blah
4340 @end example
4342 Tracing even works on builtins.  However, @code{defn} (@pxref{Defn})
4343 does not transfer tracing status.
4345 @example
4346 $ @kbd{m4 -d}
4347 traceon(`traceon')
4348 @result{}
4349 traceon(`traceoff')
4350 @error{}m4trace: -1- traceon(`traceoff') -> `'
4351 @result{}
4352 traceoff(`traceoff')
4353 @error{}m4trace: -1- traceoff(`traceoff') -> `'
4354 @result{}
4355 traceoff(`traceon')
4356 @result{}
4357 traceon(`eval', `m4_divnum')
4358 @result{}
4359 define(`m4_eval', defn(`eval'))
4360 @result{}
4361 define(`m4_divnum', defn(`divnum'))
4362 @result{}
4363 eval(divnum)
4364 @error{}m4trace: -1- eval(`0') -> `0'
4365 @result{}0
4366 m4_eval(m4_divnum)
4367 @error{}m4trace: -2- m4_divnum -> `0'
4368 @result{}0
4369 @end example
4371 As of GNU M4 2.0, named macro tracing is independent of global
4372 tracing status; calling @code{traceoff} without arguments turns off the
4373 global trace flag, but does not turn off tracing for macros where
4374 tracing was requested by name.  Likewise, calling @code{traceon} without
4375 arguments will affect tracing of macros that are not defined yet.  This
4376 behavior matches traditional implementations of @code{m4}.
4378 @example
4379 $ @kbd{m4 -d}
4380 traceon
4381 @result{}
4382 define(`foo', `bar')
4383 @error{}m4trace: -1- define(`foo', `bar') -> `'
4384 @result{}
4385 foo # traced, even though foo was not defined at traceon
4386 @error{}m4trace: -1- foo -> `bar'
4387 @result{}bar # traced, even though foo was not defined at traceon
4388 traceoff(`foo')
4389 @error{}m4trace: -1- traceoff(`foo') -> `'
4390 @result{}
4391 foo # traced, since global tracing is still on
4392 @error{}m4trace: -1- foo -> `bar'
4393 @result{}bar # traced, since global tracing is still on
4394 traceon(`foo')
4395 @error{}m4trace: -1- traceon(`foo') -> `'
4396 @result{}
4397 traceoff
4398 @error{}m4trace: -1- traceoff -> `'
4399 @result{}
4400 foo # traced, since foo is now traced by name
4401 @error{}m4trace: -1- foo -> `bar'
4402 @result{}bar # traced, since foo is now traced by name
4403 traceoff(`foo')
4404 @result{}
4405 foo # untraced
4406 @result{}bar # untraced
4407 @end example
4409 However, GNU M4 prior to 2.0 had slightly different
4410 semantics, where @code{traceon} without arguments only affected symbols
4411 that were defined at that moment, and @code{traceoff} without arguments
4412 stopped all tracing, even when tracing was requested by macro name.  The
4413 addition of the macro @code{m4symbols} (@pxref{M4symbols}) in 2.0 makes it
4414 possible to write a file that approximates the older semantics
4415 regardless of which version of GNU M4 is in use.
4417 @comment options: -d-V
4418 @example
4419 $ @kbd{m4}
4420 ifdef(`m4symbols',
4421   `define(`traceon', `ifelse(`$#', `0', `builtin(`traceon', m4symbols)',
4422     `builtin(`traceon', $@@)')')dnl
4423 define(`traceoff', `ifelse(`$#', `0',
4424     `builtin(`traceoff')builtin(`traceoff', m4symbols)',
4425     `builtin(`traceoff', $@@)')')')dnl
4426 define(`a', `1')
4427 @result{}
4428 traceon # called before b is defined, so b is not traced
4429 @result{} # called before b is defined, so b is not traced
4430 define(`b', `2')
4431 @error{}m4trace: -1- define
4432 @result{}
4433 a b
4434 @error{}m4trace: -1- a
4435 @result{}1 2
4436 traceon(`b')
4437 @error{}m4trace: -1- traceon
4438 @error{}m4trace: -1- ifelse
4439 @error{}m4trace: -1- builtin
4440 @result{}
4441 a b
4442 @error{}m4trace: -1- a
4443 @error{}m4trace: -1- b
4444 @result{}1 2
4445 traceoff # stops tracing b, even though it was traced by name
4446 @error{}m4trace: -1- traceoff
4447 @error{}m4trace: -1- ifelse
4448 @error{}m4trace: -1- builtin
4449 @error{}m4trace: -2- m4symbols
4450 @error{}m4trace: -1- builtin
4451 @result{} # stops tracing b, even though it was traced by name
4452 a b
4453 @result{}1 2
4454 @end example
4456 @xref{Debugmode}, for information on controlling the details of the
4457 display.  The format of the trace output is not specified by
4458 POSIX, and varies between implementations of @code{m4}.
4460 Starting with M4 1.6, tracing also works via @code{indir}
4461 (@pxref{Indir}).  However, since tracing is an attribute tracked by
4462 macro names, and @code{builtin} bypasses macro names (@pxref{Builtin}),
4463 it is not possible for @code{builtin} to trace which subsidiary builtin
4464 it invokes.  If you are worried about tracking all invocations of a
4465 given builtin, you should also trace @code{builtin}, or enable global
4466 tracing (the @samp{t} debug level, @pxref{Debugmode}).
4468 @example
4469 $ @kbd{m4 -d}
4470 define(`my_defn', defn(`defn'))undefine(`defn')
4471 @result{}
4472 define(`foo', `bar')traceon(`foo', `defn', `my_defn')
4473 @result{}
4475 @error{}m4trace: -1- foo -> `bar'
4476 @result{}bar
4477 indir(`foo')
4478 @error{}m4trace: -1- foo -> `bar'
4479 @result{}bar
4480 my_defn(`foo')
4481 @error{}m4trace: -1- my_defn(`foo') -> ``bar''
4482 @result{}bar
4483 indir(`my_defn', `foo')
4484 @error{}m4trace: -1- my_defn(`foo') -> ``bar''
4485 @result{}bar
4486 builtin(`defn', `foo')
4487 @result{}bar
4488 debugmode(`+cxt')
4489 @result{}
4490 builtin(`defn', builtin(`shift', `', `foo'))
4491 @error{}m4trace: -1- id 12: builtin ... = <builtin>
4492 @error{}m4trace: -2- id 13: builtin ... = <builtin>
4493 @error{}m4trace: -2- id 13: builtin(`shift', `', `foo') -> ``foo''
4494 @error{}m4trace: -1- id 12: builtin(`defn', `foo') -> ``bar''
4495 @result{}bar
4496 indir(`my_defn', indir(`shift', `', `foo'))
4497 @error{}m4trace: -1- id 14: indir ... = <indir>
4498 @error{}m4trace: -2- id 15: indir ... = <indir>
4499 @error{}m4trace: -2- id 15: shift ... = <shift>
4500 @error{}m4trace: -2- id 15: shift(`', `foo') -> ``foo''
4501 @error{}m4trace: -2- id 15: indir(`shift', `', `foo') -> ``foo''
4502 @error{}m4trace: -1- id 14: my_defn ... = <defn>
4503 @error{}m4trace: -1- id 14: my_defn(`foo') -> ``bar''
4504 @error{}m4trace: -1- id 14: indir(`my_defn', `foo') -> ``bar''
4505 @result{}bar
4506 @end example
4508 @node Debugmode
4509 @section Controlling debugging options
4511 @cindex controlling debugging output
4512 @cindex debugging output, controlling
4513 The @option{--debug} option to @code{m4} (also spelled
4514 @option{--debugmode} or @option{-d}, @pxref{Debugging options, ,
4515 Invoking m4}) controls the amount of details presented in three
4516 categories of output.  Trace output is requested by @code{traceon}
4517 (@pxref{Trace}), and each line is prefixed by @samp{m4trace:} in
4518 relation to a macro invocation.  Debug output tracks useful events not
4519 associated with a macro invocation, and each line is prefixed by
4520 @samp{m4debug:}.  Finally, @code{dumpdef} (@pxref{Dumpdef}) output is
4521 affected, with no prefix added to the output lines.
4523 The @var{flags} following the option can be one or more of the
4524 following:
4526 @table @code
4527 @item a
4528 In trace output, show the actual arguments that were collected before
4529 invoking the macro.  Arguments are subject to length truncation
4530 specified by @code{debuglen} (@pxref{Debuglen}).
4532 @item c
4533 In trace output, show an additional line for each macro call, when the
4534 macro is seen, but before the arguments are collected, and show the
4535 definition of the macro that will be used for the expansion.  By
4536 default, only one line is printed, after all arguments are collected and
4537 the expansion determined.  The definition is subject to length
4538 truncation specified by @code{debuglen} (@pxref{Debuglen}).  This is
4539 often used with the @samp{x} flag.
4541 @item d
4542 Output a warning on any attempt to dereference an undefined macro via
4543 @code{builtin}, @code{defn}, @code{dumpdef}, @code{indir},
4544 @code{popdef}, or @code{undefine}.  Note that @code{indef},
4545 @code{m4symbols},
4546 @code{traceon}, and @code{traceoff} do not dereference undefined macros.
4547 Like any other warning, the warnings enabled by this flag go to standard
4548 error regardless of the current @code{debugfile} setting, and will
4549 change exit status if the command line option @option{--fatal-warnings}
4550 was specified.  This flag is useful in diagnosing spelling mistakes in
4551 macro names.  It is enabled by default when neither @option{--debug} nor
4552 @option{--fatal-warnings} are specified on the command line.
4554 @item e
4555 In trace output, show the expansion of each macro call.  The expansion
4556 is subject to length truncation specified by @code{debuglen}
4557 (@pxref{Debuglen}).
4559 @item f
4560 In debug and trace output, include the name of the current input file in
4561 the output line.
4563 @item i
4564 In debug output, print a message each time the current input file is
4565 changed.
4567 @item l
4568 In debug and trace output, include the current input line number in the
4569 output line.
4571 @item m
4572 In debug output, print a message each time a module is manipulated
4573 (@pxref{Modules}).  In trace output when the @samp{c} flag is in effect,
4574 and in dumpdef output, follow builtin macros with their module name,
4575 surrounded by braces (@samp{@{@}}).
4577 @item o
4578 Output @code{dumpdef} data to standard error instead of the current
4579 debug file.  This can be useful when post-processing trace output, where
4580 interleaving dumpdef and trace output can cause ambiguities.
4582 @item p
4583 In debug output, print a message when a named file is found through the
4584 path search mechanism (@pxref{Search Path}), giving the actual file name
4585 used.
4587 @item q
4588 In trace and dumpdef output, quote actual arguments and macro expansions
4589 in the display with the current quotes.  This is useful in connection
4590 with the @samp{a} and @samp{e} flags above.
4592 @item s
4593 In dumpdef output, show the entire stack of definitions associated with
4594 a symbol via @code{pushdef}.
4596 @item t
4597 In trace output, trace all macro calls made in this invocation of
4598 @code{m4}.  This is equivalent to using @code{traceon} without
4599 arguments.
4601 @item x
4602 In trace output, add a unique `macro call id' to each line of the trace
4603 output.  This is useful in connection with the @samp{c} flag above, to
4604 match where a macro is first recognized with where it is finally
4605 expanded, in spite of intermediate expansions that occur while
4606 collecting arguments.  It can also be used in isolation to determine how
4607 many macros have been expanded.
4609 @item V
4610 A shorthand for all of the above flags.
4611 @end table
4613 As special cases, if @var{flags} starts with a @samp{+}, the named flags
4614 are enabled without impacting other flags, and if it starts with a
4615 @samp{-}, the named flags are disabled without impacting other flags.
4616 Without either of these starting characters, @var{flags} simply replaces
4617 the previous setting.
4618 @comment FIXME - should we accept usage like debugmode(+fl-q)?  Also,
4619 @comment should we add debugmode(?) which expands to the current
4620 @comment enabled flags, and debugmode(e?) which expands to e if e is
4621 @comment currently enabled?
4623 If no flags are specified with the @option{--debug} option, the default is
4624 @samp{+adeq}.  Many examples in this manual show their output using
4625 default flags.
4627 @cindex GNU extensions
4628 There is a builtin macro @code{debugmode}, which allows on-the-fly control of
4629 the debugging output format:
4631 @deffn {Builtin (gnu)} debugmode (@ovar{flags})
4632 The argument @var{flags} should be a subset of the letters listed above.
4633 If no argument is present, all debugging flags are cleared (as if
4634 @var{flags} were an explicit @samp{-V}).  With an empty argument, the
4635 most common flags are enabled (as if @var{flags} were an explicit
4636 @samp{+adeq}).  If an unknown flag is encountered, an error is issued.
4638 The expansion of @code{debugmode} is void.
4639 @end deffn
4641 @comment options: -d-V
4642 @example
4643 $ @kbd{m4}
4644 define(`foo', `FOO$1')
4645 @result{}
4646 traceon(`foo', `divnum')
4647 @result{}
4648 debugmode()dnl same as debugmode(`+adeq')
4650 @error{}m4trace: -1- foo -> `FOO'
4651 @result{}FOO
4652 debugmode(`V')debugmode(`-q')
4653 @error{}m4trace:stdin:5: -1- id 7: debugmode ... = <debugmode>@{gnu@}
4654 @error{}m4trace:stdin:5: -1- id 7: debugmode(`-q') -> `'
4655 @result{}
4656 foo(
4657 `BAR')
4658 @error{}m4trace:stdin:6: -1- id 8: foo ... = FOO$1
4659 @error{}m4trace:stdin:6: -1- id 8: foo(BAR) -> FOOBAR
4660 @result{}FOOBAR
4661 debugmode`'dnl same as debugmode(`-V')
4662 @error{}m4trace:stdin:8: -1- id 9: debugmode ... = <debugmode>@{gnu@}
4663 @error{}m4trace:stdin:8: -1- id 9: debugmode ->@w{ }
4665 @error{}m4trace: -1- foo
4666 @result{}FOO
4667 debugmode(`+clmx')
4668 @result{}
4669 foo(divnum)
4670 @error{}m4trace:11: -1- id 13: foo ... = FOO$1
4671 @error{}m4trace:11: -2- id 14: divnum ... = <divnum>@{m4@}
4672 @error{}m4trace:11: -2- id 14: divnum
4673 @error{}m4trace:11: -1- id 13: foo
4674 @result{}FOO0
4675 debugmode(`-m')
4676 @result{}
4677 @end example
4679 This example shows the effects of the debug flags that are not related
4680 to macro tracing.
4682 @comment examples
4683 @comment options: -dip
4684 @example
4685 $ @kbd{m4 -dip -I doc/examples}
4686 @error{}m4debug: input read from 'stdin'
4687 define(`foo', `m4wrap(`wrapped text
4688 ')dnl')
4689 @result{}
4690 include(`incl.m4')dnl
4691 @error{}m4debug: path search for 'incl.m4' found 'doc/examples/incl.m4'
4692 @error{}m4debug: input read from 'doc/examples/incl.m4'
4693 @result{}Include file start
4694 @result{}Include file end
4695 @error{}m4debug: input reverted to stdin, line 3
4697 @error{}m4debug: input exhausted
4698 @error{}m4debug: input from m4wrap recursion level 1
4699 @result{}wrapped text
4700 @error{}m4debug: input from m4wrap exhausted
4701 @end example
4703 @node Debuglen
4704 @section Limiting debug output
4706 @cindex GNU extensions
4707 @cindex arglength
4708 @cindex debuglen
4709 @cindex limiting trace output length
4710 @cindex trace output, limiting length
4711 @cindex dumpdef output, limiting length
4712 When debugging, sometimes it is desirable to reduce the clutter of
4713 arbitrary-length strings, because the prefix carries enough information
4714 to understand the issues.  The builtin macro @code{debuglen}, along with
4715 the command line option counterpart @option{--debuglen} (or @option{-l},
4716 @pxref{Debugging options, , Invoking m4}), allow on-the-fly control of
4717 debugging string lengths:
4719 @deffn {Builtin (gnu)} debuglen (@var{len})
4720 The argument @var{len} is an integer that controls how much of
4721 arbitrary-length strings should be output during trace and dumpdef
4722 output.  If specified to a non-zero value, then strings longer than that
4723 length are truncated, and @samp{...} included in the output to show that
4724 truncation took place.  A warning is issued if @var{len} cannot be
4725 parsed as an integer.
4726 @comment FIXME - make this understand an optional suffix, similar to how
4727 @comment --debuglen does.  Also, we need a section documenting scaling
4728 @comment suffixes.
4729 @comment FIXME - should we allow len to be `?', meaning expand to the
4730 @comment current value?
4732 The macro @code{debuglen} is recognized only with parameters.
4733 @end deffn
4735 The following example demonstrates the behavior of length truncation.
4736 Note that each argument and the final result are individually truncated.
4737 Also, the special tokens for builtin functions are not truncated.
4739 @comment options: -l6 -techo -tdefn
4740 @example
4741 $ @kbd{m4 -d -l 6 -t echo -t defn}
4742 debuglen(`oops')
4743 @error{}m4:stdin:1: warning: debuglen: non-numeric argument 'oops'
4744 @result{}
4745 define(`echo', `$@@')
4746 @result{}
4747 echo(`1', `long string')
4748 @error{}m4trace: -1- echo(`1', `long s...') -> ``1',`l...'
4749 @result{}1,long string
4750 indir(`echo', defn(`changequote'))
4751 @error{}m4trace: -2- defn(`change...') -> `<changequote>'
4752 @error{}m4trace: -1- echo(<changequote>) -> ``<changequote>''
4753 @result{}
4754 debuglen
4755 @result{}debuglen
4756 debuglen(`0')
4757 @result{}
4758 echo(`long string')
4759 @error{}m4trace: -1- echo(`long string') -> ``long string''
4760 @result{}long string
4761 debuglen(`12')
4762 @result{}
4763 echo(`long string')
4764 @error{}m4trace: -1- echo(`long string') -> ``long string...'
4765 @result{}long string
4766 @end example
4768 @node Debugfile
4769 @section Saving debugging output
4771 @cindex saving debugging output
4772 @cindex debugging output, saving
4773 @cindex output, saving debugging
4774 @cindex GNU extensions
4775 Debug and tracing output can be redirected to files using either the
4776 @option{--debugfile} option to @code{m4} (@pxref{Debugging options, ,
4777 Invoking m4}), or with the builtin macro @code{debugfile}:
4779 @deffn {Builtin (gnu)} debugfile (@ovar{file})
4780 Send all further debug and trace output to @var{file}, opened in append
4781 mode.  If @var{file} is the empty string, debug and trace output are
4782 discarded.  If @code{debugfile} is called without any arguments, debug
4783 and trace output are sent to standard error.  Output from @code{dumpdef}
4784 is sent to this file if the debug level @code{o} is not set
4785 (@pxref{Debugmode}).  This does not affect
4786 warnings, error messages, or @code{errprint} output, which are
4787 always sent to standard error.  If @var{file} cannot be opened, the
4788 current debug file is unchanged, and an error is issued.
4790 When the @option{--safer} option (@pxref{Operation modes, , Invoking
4791 m4}) is in effect, @var{file} must be empty or omitted, since otherwise
4792 an input file could cause the modification of arbitrary files.
4794 The expansion of @code{debugfile} is void.
4795 @end deffn
4797 @example
4798 $ @kbd{m4 -d}
4799 traceon(`divnum')
4800 @result{}
4801 divnum(`extra')
4802 @error{}m4:stdin:2: warning: divnum: extra arguments ignored: 1 > 0
4803 @error{}m4trace: -1- divnum(`extra') -> `0'
4804 @result{}0
4805 debugfile()
4806 @result{}
4807 divnum(`extra')
4808 @error{}m4:stdin:4: warning: divnum: extra arguments ignored: 1 > 0
4809 @result{}0
4810 debugfile
4811 @result{}
4812 divnum
4813 @error{}m4trace: -1- divnum -> `0'
4814 @result{}0
4815 @end example
4817 Although the @option{--safer} option cripples @code{debugfile} to a
4818 limited subset of capabilities, you may still use the @option{--debugfile}
4819 option from the command line with no restrictions.
4821 @comment options: --safer --debugfile=trace -tfoo -Dfoo=bar -d+l
4822 @comment status: 1
4823 @example
4824 $ @kbd{m4 --safer --debugfile trace -t foo -D foo=bar -daelq}
4825 foo # traced to `trace'
4826 @result{}bar # traced to `trace'
4827 debugfile(`file')
4828 @error{}m4:stdin:2: debugfile: disabled by --safer
4829 @result{}
4830 foo # traced to `trace'
4831 @result{}bar # traced to `trace'
4832 debugfile()
4833 @result{}
4834 foo # trace discarded
4835 @result{}bar # trace discarded
4836 debugfile
4837 @result{}
4838 foo # traced to stderr
4839 @error{}m4trace:7: -1- foo -> `bar'
4840 @result{}bar # traced to stderr
4841 undivert(`trace')dnl
4842 @result{}m4trace:1: -1- foo -> `bar'
4843 @result{}m4trace:3: -1- foo -> `bar'
4844 @end example
4846 Sometimes it is useful to post-process trace output, even though there
4847 is no standardized format for trace output.  In this situation, forcing
4848 @code{dumpdef} to output to standard error instead of the default of the
4849 current debug file will avoid any ambiguities between the two types of
4850 output; it also allows debugging via @code{dumpdef} when debug output is
4851 discarded.
4853 @example
4854 $ @kbd{m4 -d}
4855 traceon(`divnum')
4856 @result{}
4857 divnum
4858 @error{}m4trace: -1- divnum -> `0'
4859 @result{}0
4860 dumpdef(`divnum')
4861 @error{}divnum:@tabchar{}<divnum>
4862 @result{}
4863 debugfile(`')
4864 @result{}
4865 divnum
4866 @result{}0
4867 dumpdef(`divnum')
4868 @result{}
4869 debugmode(`+o')
4870 @result{}
4871 divnum
4872 @result{}0
4873 dumpdef(`divnum')
4874 @error{}divnum:@tabchar{}<divnum>
4875 @result{}
4876 @end example
4878 @node Input Control
4879 @chapter Input control
4881 This chapter describes various builtin macros for controlling the input
4882 to @code{m4}.
4884 @menu
4885 * Dnl::                         Deleting whitespace in input
4886 * Changequote::                 Changing the quote characters
4887 * Changecom::                   Changing the comment delimiters
4888 * Changeresyntax::              Changing the regular expression syntax
4889 * Changesyntax::                Changing the lexical structure of the input
4890 * M4wrap::                      Saving text until end of input
4891 @end menu
4893 @node Dnl
4894 @section Deleting whitespace in input
4896 @cindex deleting whitespace in input
4897 @cindex discarding input
4898 @cindex input, discarding
4899 The builtin @code{dnl} stands for ``Discard to Next Line'':
4901 @deffn {Builtin (m4)} dnl
4902 All characters, up to and including the next newline, are discarded
4903 without performing any macro expansion.  A warning is issued if the end
4904 of the file is encountered without a newline.
4906 The expansion of @code{dnl} is void.
4907 @end deffn
4909 It is often used in connection with @code{define}, to remove the
4910 newline that follows the call to @code{define}.  Thus
4912 @example
4913 define(`foo', `Macro `foo'.')dnl A very simple macro, indeed.
4915 @result{}Macro foo.
4916 @end example
4918 The input up to and including the next newline is discarded, as opposed
4919 to the way comments are treated (@pxref{Comments}), when the command
4920 line option @option{--discard-comments} is not in effect
4921 (@pxref{Operation modes, , Invoking m4}).
4923 Usually, @code{dnl} is immediately followed by an end of line or some
4924 other whitespace.  GNU @code{m4} will produce a warning diagnostic if
4925 @code{dnl} is followed by an open parenthesis.  In this case, @code{dnl}
4926 will collect and process all arguments, looking for a matching close
4927 parenthesis.  All predictable side effects resulting from this
4928 collection will take place.  @code{dnl} will return no output.  The
4929 input following the matching close parenthesis up to and including the
4930 next newline, on whatever line containing it, will still be discarded.
4932 @example
4933 dnl(`args are ignored, but side effects occur',
4934 define(`foo', `like this')) while this text is ignored: undefine(`foo')
4935 @error{}m4:stdin:1: warning: dnl: extra arguments ignored: 2 > 0
4936 See how `foo' was defined, foo?
4937 @result{}See how foo was defined, like this?
4938 @end example
4940 If the end of file is encountered without a newline character, a
4941 warning is issued and dnl stops consuming input.
4943 @example
4944 m4wrap(`m4wrap(`2 hi
4945 ')0 hi dnl 1 hi')
4946 @result{}
4947 define(`hi', `HI')
4948 @result{}
4950 @error{}m4:stdin:1: warning: dnl: end of file treated as newline
4951 @result{}0 HI 2 HI
4952 @end example
4954 @node Changequote
4955 @section Changing the quote characters
4957 @cindex changing quote delimiters
4958 @cindex quote delimiters, changing
4959 @cindex delimiters, changing
4960 The default quote delimiters can be changed with the builtin
4961 @code{changequote}:
4963 @deffn {Builtin (m4)} changequote (@dvar{start, `}, @dvar{end, '})
4964 This sets @var{start} as the new begin-quote delimiter and @var{end} as
4965 the new end-quote delimiter.  If both arguments are missing, the default
4966 quotes (@code{`} and @code{'}) are used.  If @var{start} is void, then
4967 quoting is disabled.  Otherwise, if @var{end} is missing or void, the
4968 default end-quote delimiter (@code{'}) is used.  The quote delimiters
4969 can be of any length.
4971 The expansion of @code{changequote} is void.
4972 @end deffn
4974 @example
4975 changequote(`[', `]')
4976 @result{}
4977 define([foo], [Macro [foo].])
4978 @result{}
4980 @result{}Macro foo.
4981 @end example
4983 The quotation strings can safely contain eight-bit characters.
4984 If no single character is appropriate, @var{start} and @var{end} can be
4985 of any length.  Other implementations cap the delimiter length to five
4986 characters, but GNU has no inherent limit.
4988 @example
4989 changequote(`[[[', `]]]')
4990 @result{}
4991 define([[[foo]]], [[[Macro [[[[[foo]]]]].]]])
4992 @result{}
4994 @result{}Macro [[foo]].
4995 @end example
4997 Calling @code{changequote} with @var{start} as the empty string will
4998 effectively disable the quoting mechanism, leaving no way to quote text.
4999 However, using an empty string is not portable, as some other
5000 implementations of @code{m4} revert to the default quoting, while others
5001 preserve the prior non-empty delimiter.  If @var{start} is not empty,
5002 then an empty @var{end} will use the default end-quote delimiter of
5003 @samp{'}, as otherwise, it would be impossible to end a quoted string.
5004 Again, this is not portable, as some other @code{m4} implementations
5005 reuse @var{start} as the end-quote delimiter, while others preserve the
5006 previous non-empty value.  Omitting both arguments restores the default
5007 begin-quote and end-quote delimiters; fortunately this behavior is
5008 portable to all implementations of @code{m4}.
5010 @example
5011 define(`foo', `Macro `FOO'.')
5012 @result{}
5013 changequote(`', `')
5014 @result{}
5016 @result{}Macro `FOO'.
5017 `foo'
5018 @result{}`Macro `FOO'.'
5019 changequote(`,)
5020 @result{}
5022 @result{}Macro FOO.
5023 @end example
5025 There is no way in @code{m4} to quote a string containing an unmatched
5026 begin-quote, except using @code{changequote} to change the current
5027 quotes.
5029 If the quotes should be changed from, say, @samp{[} to @samp{[[},
5030 temporary quote characters have to be defined.  To achieve this, two
5031 calls of @code{changequote} must be made, one for the temporary quotes
5032 and one for the new quotes.
5034 Macros are recognized in preference to the begin-quote string, so if a
5035 prefix of @var{start} can be recognized as part of a potential macro
5036 name, the quoting mechanism is effectively disabled.  Unless you use
5037 @code{changesyntax} (@pxref{Changesyntax}), this means that @var{start}
5038 should not begin with a letter, digit, or @samp{_} (underscore).
5039 However, even though quoted strings are not recognized, the quote
5040 characters can still be discerned in macro expansion and in trace
5041 output.
5043 @example
5044 define(`echo', `$@@')
5045 @result{}
5046 define(`hi', `HI')
5047 @result{}
5048 changequote(`q', `Q')
5049 @result{}
5050 q hi Q hi
5051 @result{}q HI Q HI
5052 echo(hi)
5053 @result{}qHIQ
5054 changequote
5055 @result{}
5056 changequote(`-', `EOF')
5057 @result{}
5058 - hi EOF hi
5059 @result{} hi  HI
5060 changequote
5061 @result{}
5062 changequote(`1', `2')
5063 @result{}
5064 hi1hi2
5065 @result{}hi1hi2
5066 hi 1hi2
5067 @result{}HI hi
5068 @end example
5070 Quotes are recognized in preference to argument collection.  In
5071 particular, if @var{start} is a single @samp{(}, then argument
5072 collection is effectively disabled.  For portability with other
5073 implementations, it is a good idea to avoid @samp{(}, @samp{,}, and
5074 @samp{)} as the first character in @var{start}.
5076 @example
5077 define(`echo', `$#:$@@:')
5078 @result{}
5079 define(`hi', `HI')
5080 @result{}
5081 changequote(`(',`)')
5082 @result{}
5083 echo(hi)
5084 @result{}0::hi
5085 changequote
5086 @result{}
5087 changequote(`((', `))')
5088 @result{}
5089 echo(hi)
5090 @result{}1:HI:
5091 echo((hi))
5092 @result{}0::hi
5093 changequote
5094 @result{}
5095 changequote(`,', `)')
5096 @result{}
5097 echo(hi,hi)bye)
5098 @result{}1:HIhibye:
5099 @end example
5101 However, if you are not worried about portability, using @samp{(} and
5102 @samp{)} as quoting characters has an interesting property---you can use
5103 it to compute a quoted string containing the expansion of any quoted
5104 text, as long as the expansion results in both balanced quotes and
5105 balanced parentheses.  The trick is realizing @code{expand} uses
5106 @samp{$1} unquoted, to trigger its expansion using the normal quoting
5107 characters, but uses extra parentheses to group unquoted commas that
5108 occur in the expansion without consuming whitespace following those
5109 commas.  Then @code{_expand} uses @code{changequote} to convert the
5110 extra parentheses back into quoting characters.  Note that it takes two
5111 more @code{changequote} invocations to restore the original quotes.
5112 Contrast the behavior on whitespace when using @samp{$*}, via
5113 @code{quote}, to attempt the same task.
5115 @example
5116 changequote(`[', `]')dnl
5117 define([a], [1, (b)])dnl
5118 define([b], [2])dnl
5119 define([quote], [[$*]])dnl
5120 define([expand], [_$0(($1))])dnl
5121 define([_expand],
5122   [changequote([(], [)])$1changequote`'changequote(`[', `]')])dnl
5123 expand([a, a, [a, a], [[a, a]]])
5124 @result{}1, (2), 1, (2), a, a, [a, a]
5125 quote(a, a, [a, a], [[a, a]])
5126 @result{}1,(2),1,(2),a, a,[a, a]
5127 @end example
5129 If @var{end} is a prefix of @var{start}, the end-quote will be
5130 recognized in preference to a nested begin-quote.  In particular,
5131 changing the quotes to have the same string for @var{start} and
5132 @var{end} disables nesting of quotes.  When quote nesting is disabled,
5133 it is impossible to double-quote strings across macro expansions, so
5134 using the same string is not done very often.
5136 @example
5137 define(`hi', `HI')
5138 @result{}
5139 changequote(`""', `"')
5140 @result{}
5141 ""hi"""hi"
5142 @result{}hihi
5143 ""hi" ""hi"
5144 @result{}hi hi
5145 ""hi"" "hi"
5146 @result{}hi" "HI"
5147 changequote
5148 @result{}
5149 `hi`hi'hi'
5150 @result{}hi`hi'hi
5151 changequote(`"', `"')
5152 @result{}
5153 "hi"hi"hi"
5154 @result{}hiHIhi
5155 @end example
5157 It is an error if the end of file occurs within a quoted string.
5159 @comment status: 1
5160 @example
5161 `hello world'
5162 @result{}hello world
5163 `dangling quote
5165 @error{}m4:stdin:2: end of file in string
5166 @end example
5168 @comment status: 1
5169 @example
5170 ifelse(`dangling quote
5172 @error{}m4:stdin:1: ifelse: end of file in string
5173 @end example
5175 @node Changecom
5176 @section Changing the comment delimiters
5178 @cindex changing comment delimiters
5179 @cindex comment delimiters, changing
5180 @cindex delimiters, changing
5181 The default comment delimiters can be changed with the builtin
5182 macro @code{changecom}:
5184 @deffn {Builtin (m4)} changecom (@ovar{start}, @dvar{end, @key{NL}})
5185 This sets @var{start} as the new begin-comment delimiter and @var{end}
5186 as the new end-comment delimiter.  If both arguments are missing, or
5187 @var{start} is void, then comments are disabled.  Otherwise, if
5188 @var{end} is missing or void, the default end-comment delimiter of
5189 newline is used.  The comment delimiters can be of any length.
5191 The expansion of @code{changecom} is void.
5192 @end deffn
5194 @example
5195 define(`comment', `COMMENT')
5196 @result{}
5197 # A normal comment
5198 @result{}# A normal comment
5199 changecom(`/*', `*/')
5200 @result{}
5201 # Not a comment anymore
5202 @result{}# Not a COMMENT anymore
5203 But: /* this is a comment now */ while this is not a comment
5204 @result{}But: /* this is a comment now */ while this is not a COMMENT
5205 @end example
5207 @cindex comments, copied to output
5208 Note how comments are copied to the output, much as if they were quoted
5209 strings.  If you want the text inside a comment expanded, quote the
5210 begin-comment delimiter.
5212 Calling @code{changecom} without any arguments, or with @var{start} as
5213 the empty string, will effectively disable the commenting mechanism.  To
5214 restore the original comment start of @samp{#}, you must explicitly ask
5215 for it.  If @var{start} is not empty, then an empty @var{end} will use
5216 the default end-comment delimiter of newline, as otherwise, it would be
5217 impossible to end a comment.  However, this is not portable, as some
5218 other @code{m4} implementations preserve the previous non-empty
5219 delimiters instead.
5221 @example
5222 define(`comment', `COMMENT')
5223 @result{}
5224 changecom
5225 @result{}
5226 # Not a comment anymore
5227 @result{}# Not a COMMENT anymore
5228 changecom(`#', `')
5229 @result{}
5230 # comment again
5231 @result{}# comment again
5232 @end example
5234 The comment strings can safely contain eight-bit characters.
5235 If no single character is appropriate, @var{start} and @var{end} can be
5236 of any length.  Other implementations cap the delimiter length to five
5237 characters, but GNU has no inherent limit.
5239 As of M4 1.6, macros and quotes are recognized in preference to
5240 comments, so if a prefix of @var{start} can be recognized as part of a
5241 potential macro name, or confused with a quoted string, the comment
5242 mechanism is effectively disabled (earlier versions of GNU M4
5243 favored comments, but this was inconsistent with other implementations).
5244 Unless you use @code{changesyntax} (@pxref{Changesyntax}), this means
5245 that @var{start} should not begin with a letter, digit, or @samp{_}
5246 (underscore), and that neither the start-quote nor the start-comment
5247 string should be a prefix of the other.
5249 @example
5250 define(`hi', `HI')
5251 @result{}
5252 define(`hi1hi2', `hello')
5253 @result{}
5254 changecom(`q', `Q')
5255 @result{}
5256 q hi Q hi
5257 @result{}q HI Q HI
5258 changecom(`1', `2')
5259 @result{}
5260 hi1hi2
5261 @result{}hello
5262 hi 1hi2
5263 @result{}HI 1hi2
5264 changecom(`[[', `]]')
5265 @result{}
5266 changequote(`[[[', `]]]')
5267 @result{}
5268 [hi]
5269 @result{}[HI]
5270 [[hi]]
5271 @result{}[[hi]]
5272 [[[hi]]]
5273 @result{}hi
5274 changequote
5275 @result{}
5276 changecom(`[[[', `]]]')
5277 @result{}
5278 changequote(`[[', `]]')
5279 @result{}
5280 [[hi]]
5281 @result{}hi
5282 [[[hi]]]
5283 @result{}[hi]
5284 @end example
5286 Comments are recognized in preference to argument collection.  In
5287 particular, if @var{start} is a single @samp{(}, then argument
5288 collection is effectively disabled.  For portability with other
5289 implementations, it is a good idea to avoid @samp{(}, @samp{,}, and
5290 @samp{)} as the first character in @var{start}.
5292 @example
5293 define(`echo', `$#:$*:$@@:')
5294 @result{}
5295 define(`hi', `HI')
5296 @result{}
5297 changecom(`(',`)')
5298 @result{}
5299 echo(hi)
5300 @result{}0:::(hi)
5301 changecom
5302 @result{}
5303 changecom(`((', `))')
5304 @result{}
5305 echo(hi)
5306 @result{}1:HI:HI:
5307 echo((hi))
5308 @result{}0:::((hi))
5309 changecom(`,', `)')
5310 @result{}
5311 echo(hi,hi)bye)
5312 @result{}1:HI,hi)bye:HI,hi)bye:
5313 changecom
5314 @result{}
5315 echo(hi,`,`'hi',hi)
5316 @result{}3:HI,,HI,HI:HI,,`'hi,HI:
5317 echo(hi,`,`'hi',hi`'changecom(`,,', `hi'))
5318 @result{}3:HI,,`'hi,HI:HI,,`'hi,HI:
5319 @end example
5321 It is an error if the end of file occurs within a comment.
5323 @comment status: 1
5324 @example
5325 changecom(`/*', `*/')
5326 @result{}
5327 /*dangling comment
5329 @error{}m4:stdin:2: end of file in comment
5330 @end example
5332 @comment status: 1
5333 @example
5334 changecom(`/*', `*/')
5335 @result{}
5336 len(/*dangling comment
5338 @error{}m4:stdin:2: len: end of file in comment
5339 @end example
5341 @node Changeresyntax
5342 @section Changing the regular expression syntax
5344 @cindex regular expression syntax, changing
5345 @cindex basic regular expressions
5346 @cindex extended regular expressions
5347 @cindex regular expressions
5348 @cindex expressions, regular
5349 @cindex syntax, changing regular expression
5350 @cindex flavors of regular expressions
5351 @cindex GNU extensions
5352 The GNU extensions @code{patsubst}, @code{regexp}, and more
5353 recently, @code{renamesyms} each deal with regular expressions.  There
5354 are multiple flavors of regular expressions, so the
5355 @code{changeresyntax} builtin exists to allow choosing the default
5356 flavor:
5358 @deffn {Builtin (gnu)} changeresyntax (@var{resyntax})
5359 Changes the default regular expression syntax used by M4 according to
5360 the value of @var{resyntax}, equivalent to passing @var{resyntax} as the
5361 argument to the command line option @option{--regexp-syntax}
5362 (@pxref{Operation modes, , Invoking m4}).  If @var{resyntax} is empty,
5363 the default flavor is reverted to the @code{GNU_M4} style, compatible
5364 with emacs.
5366 @var{resyntax} can be any one of the values in the table below.  Case is
5367 not important, and @samp{-} or @samp{ } can be substituted for @samp{_} in
5368 the given names.  If @var{resyntax} is unrecognized, a warning is
5369 issued and the default flavor is not changed.
5371 @table @dfn
5372 @item AWK
5373 @xref{awk regular expression syntax}, for details.
5375 @item BASIC
5376 @itemx ED
5377 @itemx POSIX_BASIC
5378 @itemx SED
5379 @xref{posix-basic regular expression syntax}, for details.
5381 @item BSD_M4
5382 @item EXTENDED
5383 @itemx POSIX_EXTENDED
5384 @xref{posix-extended regular expression syntax}, for details.
5386 @item GNU_AWK
5387 @itemx GAWK
5388 @xref{gnu-awk regular expression syntax}, for details.
5390 @item GNU_EGREP
5391 @itemx EGREP
5392 @xref{egrep regular expression syntax}, for details.
5394 @item GNU_M4
5395 @item EMACS
5396 @itemx GNU_EMACS
5397 @xref{emacs regular expression syntax}, for details.  This is the
5398 default regular expression flavor.
5400 @item GREP
5401 @xref{grep regular expression syntax}, for details.
5403 @item MINIMAL
5404 @itemx POSIX_MINIMAL
5405 @itemx POSIX_MINIMAL_BASIC
5406 @xref{posix-minimal-basic regular expression syntax}, for details.
5408 @item POSIX_AWK
5409 @xref{posix-awk regular expression syntax}, for details.
5411 @item POSIX_EGREP
5412 @xref{posix-egrep regular expression syntax}, for details.
5413 @end table
5415 The expansion of @code{changeresyntax} is void.
5416 The macro @code{changeresyntax} is recognized only with parameters.
5417 This macro was added in M4 2.0.
5418 @end deffn
5420 For an example of how @var{resyntax} is recognized, the first three
5421 usages select the @samp{GNU_M4} regular expression flavor:
5423 @example
5424 changeresyntax(`gnu m4')
5425 @result{}
5426 changeresyntax(`GNU-m4')
5427 @result{}
5428 changeresyntax(`Gnu_M4')
5429 @result{}
5430 changeresyntax(`unknown')
5431 @error{}m4:stdin:4: warning: changeresyntax: bad syntax-spec: 'unknown'
5432 @result{}
5433 @end example
5435 Using @code{changeresyntax} makes it possible to omit the optional
5436 @var{resyntax} parameter to other macros, while still using a different
5437 regular expression flavor.
5439 @example
5440 patsubst(`ab', `a|b', `c')
5441 @result{}ab
5442 patsubst(`ab', `a\|b', `c')
5443 @result{}cc
5444 patsubst(`ab', `a|b', `c', `EXTENDED')
5445 @result{}cc
5446 changeresyntax(`EXTENDED')
5447 @result{}
5448 patsubst(`ab', `a|b', `c')
5449 @result{}cc
5450 patsubst(`ab', `a\|b', `c')
5451 @result{}ab
5452 @end example
5454 @node Changesyntax
5455 @section Changing the lexical structure of the input
5457 @cindex lexical structure of the input
5458 @cindex input, lexical structure of the
5459 @cindex syntax table
5460 @cindex changing syntax
5461 @cindex GNU extensions
5462 @quotation
5463 The macro @code{changesyntax} and all associated functionality is
5464 experimental (@pxref{Experiments}).  The functionality might change in
5465 the future.  Please direct your comments about it the same way you would
5466 do for bugs.
5467 @end quotation
5469 The input to @code{m4} is read character by character, and these
5470 characters are grouped together to form input tokens (such as macro
5471 names, strings, comments, etc.).
5473 Each token is parsed according to certain rules.  For example, a macro
5474 name starts with a letter or @samp{_} and consists of the longest
5475 possible string of letters, @samp{_} and digits.  But who is to decide
5476 what characters are letters, digits, quotes, white space?  Earlier the
5477 operating system decided, now you do.  The builtin macro
5478 @code{changesyntax} is used to change the way @code{m4} parses the input
5479 stream into tokens.
5481 @deffn {Builtin (gnu)} changesyntax (@var{syntax-spec}, @dots{})
5482 Each @var{syntax-spec} is a two-part string.  The first part is a
5483 command, consisting of a single character describing a syntax category,
5484 and an optional one-character action.  The action can be @samp{-} to
5485 remove the listed characters from that category, @samp{=} to set the
5486 category to the listed characters
5487 and reassign all other characters previously in that category to
5488 `Other', or @samp{+} to add the listed characters to the category
5489 without affecting other characters.  If an action is not specified, but
5490 additional characters are present, then @samp{=} is assumed.
5492 The remaining characters of each @var{syntax-spec} form the set of
5493 characters to perform the action on for that syntax category.  Character
5494 ranges are expanded as for @code{translit} (@pxref{Translit}).  To start
5495 the character set with @samp{-}, @samp{+}, or @samp{=}, an action must
5496 be specified.
5498 If @var{syntax-spec} is just a category, and no action or characters
5499 were specified, then all characters in that category are reset to their
5500 default state.  A warning is issued if the category character is not
5501 valid.  If @var{syntax-spec} is the empty string, then all categories
5502 are reset to their default state.
5504 Syntax categories are divided into basic and context.  Every input
5505 byte belongs to exactly one basic syntax category.  Additionally, any
5506 byte can be assigned to a context category regardless of its current
5507 basic category.  Context categories exist because a character can
5508 behave differently when parsed in isolation than when it occurs in
5509 context to close out a token started by another basic category (for
5510 example, @kbd{newline} defaults to the basic category `Whitespace' as
5511 well as the context category `End comment').
5513 The following table describes the case-insensitive designation for each
5514 syntax category (the first byte in @var{syntax-spec}), and a description
5515 of what each category controls.
5517 @multitable @columnfractions .06 .20 .13 .55
5518 @headitem Code @tab Category @tab Type @tab Description
5520 @item @kbd{W} @tab @dfn{Words} @tab Basic
5521 @tab Characters that can start a macro name.  Defaults to the letters as
5522 defined by the locale, and the character @samp{_}.
5524 @item @kbd{D} @tab @dfn{Digits} @tab Basic
5525 @tab Characters that, together with the letters, form the remainder of a
5526 macro name.  Defaults to the ten digits @samp{0}@dots{}@samp{9}, and any
5527 other digits defined by the locale.
5529 @item @kbd{S} @tab @dfn{White space} @tab Basic
5530 @tab Characters that should be trimmed from the beginning of each argument to
5531 a macro call.  The defaults are space, tab, newline, carriage return,
5532 form feed, and vertical tab, and any others as defined by the locale.
5534 @item @kbd{(} @tab @dfn{Open parenthesis} @tab Basic
5535 @tab Characters that open the argument list of a macro call.  The default is
5536 the single character @samp{(}.
5538 @item @kbd{)} @tab @dfn{Close parenthesis} @tab Basic
5539 @tab Characters that close the argument list of a macro call.  The default
5540 is the single character @samp{)}.
5542 @item @kbd{,} @tab @dfn{Argument separator} @tab Basic
5543 @tab Characters that separate the arguments of a macro call.  The default is
5544 the single character @samp{,}.
5546 @item @kbd{L} @tab @dfn{Left quote} @tab Basic
5547 @tab The set of characters that can start a single-character quoted string.
5548 The default is the single character @samp{`}.  For multiple-character
5549 quote delimiters, use @code{changequote} (@pxref{Changequote}).
5551 @item @kbd{R} @tab @dfn{Right quote} @tab Context
5552 @tab The set of characters that can end a single-character quoted string.
5553 The default is the single character @samp{'}.  For multiple-character
5554 quote delimiters, use @code{changequote} (@pxref{Changequote}).  Note
5555 that @samp{'} also defaults to the syntax category `Other', when it
5556 appears in isolation.
5558 @item @kbd{B} @tab @dfn{Begin comment} @tab Basic
5559 @tab The set of characters that can start a single-character comment.  The
5560 default is the single character @samp{#}.  For multiple-character
5561 comment delimiters, use @code{changecom} (@pxref{Changecom}).
5563 @item @kbd{E} @tab @dfn{End comment} @tab Context
5564 @tab The set of characters that can end a single-character comment.  The
5565 default is the single character @kbd{newline}.  For multiple-character
5566 comment delimiters, use @code{changecom} (@pxref{Changecom}).  Note that
5567 newline also defaults to the syntax category `White space', when it
5568 appears in isolation.
5570 @item @kbd{$} @tab @dfn{Dollar} @tab Context
5571 @tab Characters that can introduce an argument reference in the body of a
5572 macro.  The default is the single character @samp{$}.
5574 @comment FIXME - implement ${10} argument parsing.
5575 @item @kbd{@{} @tab @dfn{Left brace} @tab Context
5576 @tab Characters that introduce an extended argument reference in the body of
5577 a macro immediately after a character in the Dollar category.  The
5578 default is the single character @samp{@{}.
5580 @item @kbd{@}} @tab @dfn{Right brace} @tab Context
5581 @tab Characters that conclude an extended argument reference in the body of a
5582 macro.  The default is the single character @samp{@}}.
5584 @item @kbd{O} @tab @dfn{Other} @tab Basic
5585 @tab Characters that have no special syntactical meaning to @code{m4}.
5586 Defaults to all characters except those in the categories above.
5588 @item @kbd{A} @tab @dfn{Active} @tab Basic
5589 @tab Characters that themselves, alone, form macro names.  This is a
5590 GNU extension, and active characters have lower precedence
5591 than comments.  By default, no characters are active.
5593 @item @kbd{@@} @tab @dfn{Escape} @tab Basic
5594 @tab Characters that must precede macro names for them to be recognized.
5595 This is a GNU extension.  When an escape character is defined,
5596 then macros are not recognized unless the escape character is present;
5597 however, the macro name, visible by @samp{$0} in macro definitions, does
5598 not include the escape character.  By default, no characters are
5599 escapes.
5601 @comment FIXME - we should also consider supporting:
5602 @comment @item @kbd{I} @tab @dfn{Ignore} @tab Basic
5603 @comment @tab Characters that are ignored if they appear in
5604 @comment the input; perhaps defaulting to '\0'.
5605 @end multitable
5607 The expansion of @code{changesyntax} is void.
5608 The macro @code{changesyntax} is recognized only with parameters.  Use
5609 this macro with caution, as it is possible to change the syntax in such
5610 a way that no further macros can be recognized by @code{m4}.
5611 This macro was added in M4 2.0.
5612 @end deffn
5614 With @code{changesyntax} we can modify what characters form a word.  For
5615 example, we can make @samp{.} a valid character in a macro name, or even
5616 start a macro name with a number.
5618 @example
5619 define(`test.1', `TEST ONE')
5620 @result{}
5621 define(`1', `one')
5622 @result{}
5623 __file__
5624 @result{}stdin
5625 test.1
5626 @result{}test.1
5627 dnl Add `.' and remove `_'.
5628 changesyntax(`W+.', `W-_')
5629 @result{}
5630 __file__
5631 @result{}__file__
5632 test.1
5633 @result{}TEST ONE
5634 dnl Set words to include numbers.
5635 changesyntax(`W=a-zA-Z0-9_')
5636 @result{}
5637 __file__
5638 @result{}stdin
5639 test.1
5640 @result{}test.one
5641 dnl Reset words to default (a-zA-Z_).
5642 changesyntax(`W')
5643 @result{}
5644 __file__
5645 @result{}stdin
5646 test.1
5647 @result{}test.1
5648 @end example
5650 Another possibility is to change the syntax of a macro call.
5652 @example
5653 define(`test', `$#')
5654 @result{}
5655 test(a, b, c)
5656 @result{}3
5657 dnl Change macro syntax.
5658 changesyntax(`(<', `,|', `)>')
5659 @result{}
5660 test(a, b, c)
5661 @result{}0(a, b, c)
5662 test<a|b|c>
5663 @result{}3
5664 @end example
5666 Leading spaces are always removed from macro arguments in @code{m4}, but
5667 by changing the syntax categories we can avoid it.  The use of
5668 @code{format} is an alternative to using a literal tab character.
5670 @example
5671 define(`test', `$1$2$3')
5672 @result{}
5673 test(`a', `b', `c')
5674 @result{}abc
5675 dnl Don't ignore whitespace.
5676 changesyntax(`O 'format(``%c'', `9')`
5678 @result{}
5679 test(a, b,
5681 @result{}a b
5682 @result{}c
5683 @end example
5685 It is possible to redefine the @samp{$} used to indicate macro arguments
5686 in user defined macros.  Dollar class syntax elements are copied to the
5687 output if there is no valid expansion.
5689 @example
5690 define(`argref', `Dollar: $#, Question: ?#')
5691 @result{}
5692 argref(1, 2, 3)
5693 @result{}Dollar: 3, Question: ?#
5694 dnl Change argument identifier.
5695 changesyntax(`$?')
5696 @result{}
5697 argref(1,2,3)
5698 @result{}Dollar: $#, Question: 3
5699 define(`escape', `$?`'1$?1?')
5700 @result{}
5701 escape(foo)
5702 @result{}$?1$foo?
5703 dnl Multiple argument identifiers.
5704 changesyntax(`$+$')
5705 @result{}
5706 argref(1, 2, 3)
5707 @result{}Dollar: 3, Question: 3
5708 @end example
5710 Macro calls can be given a @TeX{} or Texinfo like syntax using an
5711 escape.  If one or more characters are defined as escapes, macro names
5712 are only recognized if preceded by an escape character.
5714 If the escape is not followed by what is normally a word (a letter
5715 optionally followed by letters and/or numerals), that single character
5716 is returned as a macro name.
5718 As always, words without a macro definition cause no error message.
5719 They and the escape character are simply output.
5721 @example
5722 define(`foo', `bar')
5723 @result{}
5724 dnl Require @@ escape before any macro.
5725 changesyntax(`@@@@')
5726 @result{}
5728 @result{}foo
5729 @@foo
5730 @result{}bar
5731 @@bar
5732 @result{}@@bar
5733 @@dnl Change escape character.
5734 @@changesyntax(`@@\', `O@@')
5735 @result{}
5737 @result{}foo
5738 @@foo
5739 @result{}@@foo
5740 \foo
5741 @result{}bar
5742 define(`#', `No comment')
5743 @result{}define(#, No comment)
5744 \define(`#', `No comment')
5745 @result{}
5746 \# \foo # Comment \foo
5747 @result{}No comment bar # Comment \foo
5748 @end example
5750 Active characters are known from @TeX{}.  In @code{m4} an active
5751 character is always seen as a one-letter word, and so, if it has a macro
5752 definition, the macro will be called.
5754 @example
5755 define(`@@', `TEST')
5756 @result{}
5757 define(`a@@a', `hello')
5758 @result{}
5759 define(`a', `A')
5760 @result{}
5762 @result{}@@
5763 a@@a
5764 @result{}A@@A
5765 dnl Make @@ active.
5766 changesyntax(`A@@')
5767 @result{}
5769 @result{}TEST
5770 a@@a
5771 @result{}ATESTa
5772 @end example
5774 There is obviously an overlap between @code{changesyntax} and
5775 @code{changequote}, since there are now two ways to modify quote
5776 delimiters.  To avoid incompatibilities, if the quotes are modified by
5777 @code{changequote}, any characters previously set to either quote
5778 delimiter by @code{changesyntax} are first demoted to the other category
5779 (@samp{O}), so the result is only a single set of quotes.  In the other
5780 direction, if quotes were already disabled, or if both the start and end
5781 delimiter set by @code{changequote} are single bytes, then
5782 @code{changesyntax} preserves those settings.  But if either delimiter
5783 occupies multiple bytes, @code{changesyntax} first disables both
5784 delimiters.  Quotes can be disabled via @code{changesyntax} by emptying
5785 the left quote basic category (@samp{L}).  Meanwhile, the right quote
5786 context category (@samp{R}) will never be empty; if a
5787 @code{changesyntax} action would otherwise leave that category empty,
5788 then the default end delimiter from @code{changequote} (@samp{'}) is
5789 used; thus, it is never possible to get @code{m4} in a state where a
5790 quoted string cannot be terminated.  These interactions apply to comment
5791 delimiters as well, @i{mutatis mutandis} with @code{changecom}.
5793 @example
5794 define(`test', `TEST')
5795 @result{}
5796 dnl Add additional single-byte delimiters.
5797 changesyntax(`L+<', `R+>')
5798 @result{}
5799 <test> `test' [test] <<test>>
5800 @result{}test test [TEST] <test>
5801 dnl Use standard interface, overriding changesyntax settings.
5802 changequote(<[>, `]')
5803 @result{}
5804 <test> `test' [test] <<test>>
5805 @result{}<TEST> `TEST' test <<TEST>>
5806 dnl Introduce multi-byte delimiters.
5807 changequote([<<], [>>])
5808 @result{}
5809 <test> `test' [test] <<test>>
5810 @result{}<TEST> `TEST' [TEST] test
5811 dnl Change end quote, effectively disabling quotes.
5812 changesyntax(<<R]>>)
5813 @result{}
5814 <test> `test' [test] <<test>>
5815 @result{}<TEST> `TEST' [TEST] <<TEST>>
5816 dnl Change beginning quote, make ] normal, thus making ' end quote.
5817 changesyntax(L`, R-])
5818 @result{}
5819 <test> `test' [test] <<test>>
5820 @result{}<TEST> test [TEST] <<TEST>>
5821 dnl Set multi-byte quote; unrelated changes don't impact it.
5822 changequote(`<<', `>>')changesyntax(<<@@\>>)
5823 @result{}
5824 <\test> `\test' [\test] <<\test>>
5825 @result{}<TEST> `TEST' [TEST] \test
5826 @end example
5828 If several characters are assigned to a category that forms single
5829 character tokens, all such characters are treated as equal.  Any open
5830 parenthesis will match any close parenthesis, etc.
5832 @example
5833 dnl Go crazy with symbols.
5834 changesyntax(`(@{<', `)@}>', `,;:', `O(,)')
5835 @result{}
5836 eval@{2**4-1; 2: 8>
5837 @result{}00001111
5838 @end example
5840 The syntax table is initialized to be backwards compatible, so if you
5841 never call @code{changesyntax}, nothing will have changed.
5843 For now, debugging output continues to use @kbd{(}, @kbd{,} and @kbd{)}
5844 to show macro calls; and macro expansions that result in a list of
5845 arguments (such as @samp{$@@} or @code{shift}) use @samp{,}, regardless
5846 of the current syntax settings.  However, this is likely to change in a
5847 future release, so it should not be relied on, particularly since it is
5848 next to impossible to write recursive macros if the argument separator
5849 doesn't match between expansion and rescanning.
5851 @c FIXME - changing syntax of , should not break iterative macros.
5852 @example
5853 $ @kbd{m4 -d}
5854 changesyntax(`,=|')traceon(`foo')define(`foo'|`$#:$@@')
5855 @result{}
5856 foo(foo(1|2|3))
5857 @error{}m4trace: -2- foo(`1', `2', `3') -> `3:`1',`2',`3''
5858 @error{}m4trace: -1- foo(`3:1,2,3') -> `1:`3:1,2,3''
5859 @result{}1:3:1,2,3
5860 @end example
5862 @node M4wrap
5863 @section Saving text until end of input
5865 @cindex saving input
5866 @cindex input, saving
5867 @cindex deferring expansion
5868 @cindex expansion, deferring
5869 It is possible to `save' some text until the end of the normal input has
5870 been seen.  Text can be saved, to be read again by @code{m4} when the
5871 normal input has been exhausted.  This feature is normally used to
5872 initiate cleanup actions before normal exit, e.g., deleting temporary
5873 files.
5875 To save input text, use the builtin @code{m4wrap}:
5877 @deffn {Builtin (m4)} m4wrap (@var{string}, @dots{})
5878 Stores @var{string} in a safe place, to be reread when end of input is
5879 reached.  As a GNU extension, additional arguments are
5880 concatenated with a space to the @var{string}.
5882 Successive invocations of @code{m4wrap} accumulate saved text in
5883 first-in, first-out order, as required by POSIX.
5885 The expansion of @code{m4wrap} is void.
5886 The macro @code{m4wrap} is recognized only with parameters.
5887 @end deffn
5889 @example
5890 define(`cleanup', `This is the `cleanup' action.
5892 @result{}
5893 m4wrap(`cleanup')
5894 @result{}
5895 This is the first and last normal input line.
5896 @result{}This is the first and last normal input line.
5898 @result{}This is the cleanup action.
5899 @end example
5901 The saved input is only reread when the end of normal input is seen, and
5902 not if @code{m4exit} is used to exit @code{m4}.
5904 It is safe to call @code{m4wrap} from wrapped text, where all the
5905 recursively wrapped text is deferred until the current wrapped text is
5906 exhausted.  As of M4 1.6, when @code{m4wrap} is not used recursively,
5907 the saved pieces of text are reread in the same order in which they were
5908 saved (FIFO---first in, first out), as required by POSIX.
5910 @example
5911 m4wrap(`1
5913 @result{}
5914 m4wrap(`2', `3
5916 @result{}
5918 @result{}1
5919 @result{}2 3
5920 @end example
5922 However, earlier versions had reverse ordering (LIFO---last in, first
5923 out), as this behavior is more like the semantics of the C function
5924 @code{atexit}.  It is possible to emulate POSIX behavior even
5925 with older versions of GNU M4 by including the file
5926 @file{m4-@value{VERSION}/@/doc/examples/@/wrapfifo.m4} from the
5927 distribution:
5929 @comment examples
5930 @example
5931 $ @kbd{m4 -I doc/examples}
5932 undivert(`wrapfifo.m4')dnl
5933 @result{}dnl Redefine m4wrap to have FIFO semantics.
5934 @result{}define(`_m4wrap_level', `0')dnl
5935 @result{}define(`m4wrap',
5936 @result{}`ifdef(`m4wrap'_m4wrap_level,
5937 @result{}       `define(`m4wrap'_m4wrap_level,
5938 @result{}               defn(`m4wrap'_m4wrap_level)`$1')',
5939 @result{}       `builtin(`m4wrap', `define(`_m4wrap_level',
5940 @result{}                                  incr(_m4wrap_level))dnl
5941 @result{}m4wrap'_m4wrap_level)dnl
5942 @result{}define(`m4wrap'_m4wrap_level, `$1')')')dnl
5943 include(`wrapfifo.m4')
5944 @result{}
5945 m4wrap(`a`'m4wrap(`c
5946 ', `d')')m4wrap(`b')
5947 @result{}
5949 @result{}abc
5950 @end example
5952 It is likewise possible to emulate LIFO behavior without resorting to
5953 the GNU M4 extension of @code{builtin}, by including the file
5954 @file{m4-@value{VERSION}/@/doc/examples/@/wraplifo.m4} from the
5955 distribution.  (Unfortunately, both examples shown here share some
5956 subtle bugs.  See if you can find and correct them; or @pxref{Improved
5957 m4wrap, , Answers}).
5959 @comment examples
5960 @example
5961 $ @kbd{m4 -I doc/examples}
5962 undivert(`wraplifo.m4')dnl
5963 @result{}dnl Redefine m4wrap to have LIFO semantics.
5964 @result{}define(`_m4wrap_level', `0')dnl
5965 @result{}define(`_m4wrap', defn(`m4wrap'))dnl
5966 @result{}define(`m4wrap',
5967 @result{}`ifdef(`m4wrap'_m4wrap_level,
5968 @result{}       `define(`m4wrap'_m4wrap_level,
5969 @result{}               `$1'defn(`m4wrap'_m4wrap_level))',
5970 @result{}       `_m4wrap(`define(`_m4wrap_level', incr(_m4wrap_level))dnl
5971 @result{}m4wrap'_m4wrap_level)dnl
5972 @result{}define(`m4wrap'_m4wrap_level, `$1')')')dnl
5973 include(`wraplifo.m4')
5974 @result{}
5975 m4wrap(`a`'m4wrap(`c
5976 ', `d')')m4wrap(`b')
5977 @result{}
5979 @result{}bac
5980 @end example
5982 Here is an example of implementing a factorial function using
5983 @code{m4wrap}:
5985 @example
5986 define(`f', `ifelse(`$1', `0', `Answer: 0!=1
5987 ', eval(`$1>1'), `0', `Answer: $2$1=eval(`$2$1')
5988 ', `m4wrap(`f(decr(`$1'), `$2$1*')')')')
5989 @result{}
5990 f(`10')
5991 @result{}
5993 @result{}Answer: 10*9*8*7*6*5*4*3*2*1=3628800
5994 @end example
5996 Invocations of @code{m4wrap} at the same recursion level are
5997 concatenated and rescanned as usual:
5999 @example
6000 define(`ab', `AB
6002 @result{}
6003 m4wrap(`a')m4wrap(`b')
6004 @result{}
6006 @result{}AB
6007 @end example
6009 @noindent
6010 however, the transition between recursion levels behaves like an end of
6011 file condition between two input files.
6013 @comment status: 1
6014 @example
6015 m4wrap(`m4wrap(`)')len(abc')
6016 @result{}
6018 @error{}m4:stdin:1: len: end of file in argument list
6019 @end example
6021 As of M4 1.6, @code{m4wrap} transparently handles builtin tokens
6022 generated by @code{defn} (@pxref{Defn}).  However, for portability, it
6023 is better to defer the evaluation of @code{defn} along with the rest of
6024 the wrapped text, as is done for @code{foo} in the example below, rather
6025 than computing the builtin token up front, as is done for @code{bar}.
6027 @example
6028 m4wrap(`define(`foo', defn(`divnum'))foo
6030 @result{}
6031 m4wrap(`define(`bar', ')m4wrap(defn(`divnum'))m4wrap(`)bar
6033 @result{}
6035 @result{}0
6036 @result{}0
6037 @end example
6039 @node File Inclusion
6040 @chapter File inclusion
6042 @cindex file inclusion
6043 @cindex inclusion, of files
6044 @code{m4} allows you to include named files at any point in the input.
6046 @menu
6047 * Include::                     Including named files and modules
6048 * Search Path::                 Searching for include files
6049 @end menu
6051 @node Include
6052 @section Including named files and modules
6054 There are two builtin macros in @code{m4} for including files:
6056 @deffn {Builtin (m4)} include (@var{file})
6057 @deffnx {Builtin (m4)} sinclude (@var{file})
6058 Both macros cause the file named @var{file} to be read by
6059 @code{m4}.  When the end of the file is reached, input is resumed from
6060 the previous input file.
6062 The expansion of @code{include} and @code{sinclude} is therefore the
6063 contents of @var{file}.
6065 If @var{file} does not exist, is a directory, or cannot otherwise be
6066 read, the expansion is void,
6067 and @code{include} will fail with an error while @code{sinclude} is
6068 silent.  The empty string counts as a file that does not exist.
6070 The macros @code{include} and @code{sinclude} are recognized only with
6071 parameters.
6072 @end deffn
6074 @comment status: 1
6075 @example
6076 include(`n')
6077 @error{}m4:stdin:1: include: cannot open file 'n': No such file or directory
6078 @result{}
6079 include()
6080 @error{}m4:stdin:2: include: cannot open file '': No such file or directory
6081 @result{}
6082 sinclude(`n')
6083 @result{}
6084 sinclude()
6085 @result{}
6086 @end example
6088 This section uses the @option{--include} command-line option (or
6089 @option{-I}, @pxref{Preprocessor features, , Invoking m4}) to grab
6090 files from the @file{m4-@value{VERSION}/@/doc/examples}
6091 directory shipped as part of the GNU @code{m4} package.  The
6092 file @file{m4-@value{VERSION}/@/doc/examples/@/incl.m4} in the distribution
6093 contains the lines:
6095 @comment ignore
6096 @example
6097 $ @kbd{cat doc/examples/incl.m4}
6098 @result{}Include file start
6099 @result{}foo
6100 @result{}Include file end
6101 @end example
6103 Normally file inclusion is used to insert the contents of a file
6104 into the input stream.  The contents of the file will be read by
6105 @code{m4} and macro calls in the file will be expanded:
6107 @comment examples
6108 @example
6109 $ @kbd{m4 -I doc/examples}
6110 define(`foo', `FOO')
6111 @result{}
6112 include(`incl.m4')
6113 @result{}Include file start
6114 @result{}FOO
6115 @result{}Include file end
6116 @result{}
6117 @end example
6119 The fact that @code{include} and @code{sinclude} expand to the contents
6120 of the file can be used to define macros that operate on entire files.
6121 Here is an example, which defines @samp{bar} to expand to the contents
6122 of @file{incl.m4}:
6124 @comment examples
6125 @example
6126 $ @kbd{m4 -I doc/examples}
6127 define(`bar', include(`incl.m4'))
6128 @result{}
6129 This is `bar':  >>bar<<
6130 @result{}This is bar:  >>Include file start
6131 @result{}foo
6132 @result{}Include file end
6133 @result{}<<
6134 @end example
6136 This use of @code{include} is not trivial, though, as files can contain
6137 quotes, commas, and parentheses, which can interfere with the way the
6138 @code{m4} parser works.  GNU M4 seamlessly concatenates
6139 the file contents with the next character, even if the included file
6140 ended in the middle of a comment, string, or macro call.  These
6141 conditions are only treated as end of file errors if specified as input
6142 files on the command line.
6144 In GNU M4, an alternative method of reading files is
6145 using @code{undivert} (@pxref{Undivert}) on a named file.
6147 In addition, as a GNU M4 extension, if the included file cannot
6148 be found exactly as given, various standard suffixes are appended.
6149 If the included file name is absolute (a full path from the root directory
6150 is given) then additional search directories are not examined, although
6151 suffixes will be tried if the file is not found exactly as given.
6152 For each directory that is searched (according to the absolute directory
6153 give in the file name, or else by directories listed in @env{M4PATH} and
6154 given with the @option{-I} and @option{-B} options), first the unchanged
6155 file name is tried, and then again with the suffixes @samp{.m4f} and
6156 @samp{.m4}.
6158 Furthermore, if no matching file has yet been found, before moving on to
6159 the next directory, @samp{.la} and the usual binary module suffix for
6160 the host platform (usually @samp{.so}) are also tried.  Matching with one
6161 of those suffixes will attempt to load the matched file as a dynamic
6162 module. @xref{Modules}, for more details.
6164 @node Search Path
6165 @section Searching for include files
6167 @cindex search path for included files
6168 @cindex included files, search path for
6169 @cindex GNU extensions
6170 GNU @code{m4} allows included files to be found in other directories
6171 than the current working directory.
6173 @cindex @env{M4PATH}
6174 If the @option{--prepend-include} or @option{-B} command-line option was
6175 provided (@pxref{Preprocessor features, , Invoking m4}), those
6176 directories are searched first, in reverse order that those options were
6177 listed on the command line.  Then @code{m4} looks in the current working
6178 directory.  Next comes the directories specified with the
6179 @option{--include} or @option{-I} option, in the order found on the
6180 command line.  Finally, if the @env{M4PATH} environment variable is set,
6181 it is expected to contain a colon-separated list of directories, which
6182 will be searched in order.
6184 If the automatic search for include-files causes trouble, the @samp{p}
6185 debug flag (@pxref{Debugmode}) can help isolate the problem.
6187 @node Diversions
6188 @chapter Diverting and undiverting output
6190 @cindex deferring output
6191 Diversions are a way of temporarily saving output.  The output of
6192 @code{m4} can at any time be diverted to a temporary file, and be
6193 reinserted into the output stream, @dfn{undiverted}, again at a later
6194 time.
6196 @cindex @env{TMPDIR}
6197 Numbered diversions are counted from 0 upwards, diversion number 0
6198 being the normal output stream.  GNU
6199 @code{m4} tries to keep diversions in memory.  However, there is a
6200 limit to the overall memory usable by all diversions taken together
6201 (512K, currently).  When this maximum is about to be exceeded,
6202 a temporary file is opened to receive the contents of the biggest
6203 diversion still in memory, freeing this memory for other diversions.
6204 When creating the temporary file, @code{m4} honors the value of the
6205 environment variable @env{TMPDIR}, and falls back to @file{/tmp}.
6206 Thus, the amount of available disk space provides the only real limit on
6207 the number and aggregate size of diversions.
6209 Diversions make it possible to generate output in a different order than
6210 the input was read.  It is possible to implement topological sorting
6211 dependencies.  For example, GNU Autoconf makes use of
6212 diversions under the hood to ensure that the expansion of a prerequisite
6213 macro appears in the output prior to the expansion of a dependent macro,
6214 regardless of which order the two macros were invoked in the user's
6215 input file.
6217 @menu
6218 * Divert::                      Diverting output
6219 * Undivert::                    Undiverting output
6220 * Divnum::                      Diversion numbers
6221 * Cleardivert::                 Discarding diverted text
6222 @end menu
6224 @node Divert
6225 @section Diverting output
6227 @cindex diverting output to files
6228 @cindex output, diverting to files
6229 @cindex files, diverting output to
6230 Output is diverted using @code{divert}:
6232 @deffn {Builtin (m4)} divert (@dvar{number, 0}, @ovar{text})
6233 The current diversion is changed to @var{number}.  If @var{number} is left
6234 out or empty, it is assumed to be zero.  If @var{number} cannot be
6235 parsed, the diversion is unchanged.
6237 @cindex GNU extensions
6238 As a GNU extension, if optional @var{text} is supplied and
6239 @var{number} was valid, then @var{text} is immediately output to the
6240 new diversion, regardless of whether the expansion of @code{divert}
6241 occurred while collecting arguments for another macro.
6243 The expansion of @code{divert} is void.
6244 @end deffn
6246 When all the @code{m4} input will have been processed, all existing
6247 diversions are automatically undiverted, in numerical order.
6249 @example
6250 divert(`1')
6251 This text is diverted.
6252 divert
6253 @result{}
6254 This text is not diverted.
6255 @result{}This text is not diverted.
6257 @result{}
6258 @result{}This text is diverted.
6259 @end example
6261 Several calls of @code{divert} with the same argument do not overwrite
6262 the previous diverted text, but append to it.  Diversions are printed
6263 after any wrapped text is expanded.
6265 @example
6266 define(`text', `TEXT')
6267 @result{}
6268 divert(`1')`diverted text.'
6269 divert
6270 @result{}
6271 m4wrap(`Wrapped text precedes ')
6272 @result{}
6274 @result{}Wrapped TEXT precedes diverted text.
6275 @end example
6277 @cindex discarding input
6278 @cindex input, discarding
6279 If output is diverted to a negative diversion, it is simply discarded.
6280 This can be used to suppress unwanted output.  A common example of
6281 unwanted output is the trailing newlines after macro definitions.  Here
6282 is a common programming idiom in @code{m4} for avoiding them.
6284 @example
6285 divert(`-1')
6286 define(`foo', `Macro `foo'.')
6287 define(`bar', `Macro `bar'.')
6288 divert
6289 @result{}
6290 @end example
6292 @cindex GNU extensions
6293 Traditional implementations only supported ten diversions.  But as a
6294 GNU extension, diversion numbers can be as large as positive
6295 integers will allow, rather than treating a multi-digit diversion number
6296 as a request to discard text.
6298 @example
6299 divert(eval(`1<<28'))world
6300 divert(`2')hello
6302 @result{}hello
6303 @result{}world
6304 @end example
6306 The ability to immediately output extra text is a GNU
6307 extension, but it can prove useful for ensuring that text goes to a
6308 particular diversion no matter how many pending macro expansions are in
6309 progress.  For a demonstration of why this is useful, it is important to
6310 understand in the example below why @samp{one} is output in diversion 2,
6311 not diversion 1, while @samp{three} and @samp{five} both end up in the
6312 correctly numbered diversion.  The key point is that when @code{divert}
6313 is executed unquoted as part of the argument collection of another
6314 macro, the side effect takes place immediately, but the text @samp{one}
6315 is not passed to any diversion until after the @samp{divert(`2')} and
6316 the enclosing @code{echo} have also taken place.  The example with
6317 @samp{three} shows how following the quoting rule of thumb delays the
6318 invocation of @code{divert} until it is not nested in any argument
6319 collection context, while the example with @samp{five} shows the use of
6320 the optional argument to speed up the output process.
6322 @example
6323 define(`echo', `$1')
6324 @result{}
6325 echo(divert(`1')`one'divert(`2'))`'dnl
6326 echo(`divert(`3')three`'divert(`4')')`'dnl
6327 echo(divert(`5', `five')divert(`6'))`'dnl
6328 divert
6329 @result{}
6330 undivert(`1')
6331 @result{}
6332 undivert(`2')
6333 @result{}one
6334 undivert(`3')
6335 @result{}three
6336 undivert(`4')
6337 @result{}
6338 undivert(`5')
6339 @result{}five
6340 undivert(`6')
6341 @result{}
6342 @end example
6344 Note that @code{divert} is an English word, but also an active macro
6345 without arguments.  When processing plain text, the word might appear in
6346 normal text and be unintentionally swallowed as a macro invocation.  One
6347 way to avoid this is to use the @option{-P} option to rename all
6348 builtins (@pxref{Operation modes, , Invoking m4}).  Another is to write
6349 a wrapper that requires a parameter to be recognized.
6351 @example
6352 We decided to divert the stream for irrigation.
6353 @result{}We decided to  the stream for irrigation.
6354 define(`divert', `ifelse(`$#', `0', ``$0'', `builtin(`$0', $@@)')')
6355 @result{}
6356 divert(`-1')
6357 Ignored text.
6358 divert(`0')
6359 @result{}
6360 We decided to divert the stream for irrigation.
6361 @result{}We decided to divert the stream for irrigation.
6362 @end example
6364 @node Undivert
6365 @section Undiverting output
6367 Diverted text can be undiverted explicitly using the builtin
6368 @code{undivert}:
6370 @deffn {Builtin (m4)} undivert (@ovar{diversions@dots{}})
6371 Undiverts the numeric @var{diversions} given by the arguments, in the
6372 order given.  If no arguments are supplied, all diversions are
6373 undiverted, in numerical order.
6375 @cindex file inclusion
6376 @cindex inclusion, of files
6377 @cindex GNU extensions
6378 As a GNU extension, @var{diversions} may contain non-numeric
6379 strings, which are treated as the names of files to copy into the output
6380 without expansion.  A warning is issued if a file could not be opened.
6382 The expansion of @code{undivert} is void.
6383 @end deffn
6385 @example
6386 divert(`1')
6387 This text is diverted.
6388 divert
6389 @result{}
6390 This text is not diverted.
6391 @result{}This text is not diverted.
6392 undivert(`1')
6393 @result{}
6394 @result{}This text is diverted.
6395 @result{}
6396 @end example
6398 Notice the last two blank lines.  One of them comes from the newline
6399 following @code{undivert}, the other from the newline that followed the
6400 @code{divert}!  A diversion often starts with a blank line like this.
6402 When diverted text is undiverted, it is @emph{not} reread by @code{m4},
6403 but rather copied directly to the current output, and it is therefore
6404 not an error to undivert into a diversion.  Undiverting the empty string
6405 is the same as specifying diversion 0; in either case nothing happens
6406 since the output has already been flushed.
6408 @example
6409 divert(`1')diverted text
6410 divert
6411 @result{}
6412 undivert()
6413 @result{}
6414 undivert(`0')
6415 @result{}
6416 undivert
6417 @result{}diverted text
6418 @result{}
6419 divert(`1')more
6420 divert(`2')undivert(`1')diverted text`'divert
6421 @result{}
6422 undivert(`1')
6423 @result{}
6424 undivert(`2')
6425 @result{}more
6426 @result{}diverted text
6427 @end example
6429 When a diversion has been undiverted, the diverted text is discarded,
6430 and it is not possible to bring back diverted text more than once.
6432 @example
6433 divert(`1')
6434 This text is diverted first.
6435 divert(`0')undivert(`1')dnl
6436 @result{}
6437 @result{}This text is diverted first.
6438 undivert(`1')
6439 @result{}
6440 divert(`1')
6441 This text is also diverted but not appended.
6442 divert(`0')undivert(`1')dnl
6443 @result{}
6444 @result{}This text is also diverted but not appended.
6445 @end example
6447 Attempts to undivert the current diversion are silently ignored.  Thus,
6448 when the current diversion is not 0, the current diversion does not get
6449 rearranged among the other diversions.
6451 @example
6452 divert(`1')one
6453 divert(`2')two
6454 divert(`3')three
6455 divert(`4')four
6456 divert(`5')five
6457 divert(`2')undivert(`5', `2', `4')dnl
6458 undivert`'dnl effectively undivert(`1', `2', `3', `4', `5')
6459 divert`'undivert`'dnl
6460 @result{}two
6461 @result{}five
6462 @result{}four
6463 @result{}one
6464 @result{}three
6465 @end example
6467 @cindex GNU extensions
6468 @cindex file inclusion
6469 @cindex inclusion, of files
6470 GNU @code{m4} allows named files to be undiverted.  Given a
6471 non-numeric argument, the contents of the file named will be copied,
6472 uninterpreted, to the current output.  This complements the builtin
6473 @code{include} (@pxref{Include}).  To illustrate the difference, assume
6474 the file @file{foo} contains:
6476 @comment file: foo
6477 @example
6478 $ @kbd{cat foo}
6480 @end example
6482 @noindent
6483 then
6485 @example
6486 define(`bar', `BAR')
6487 @result{}
6488 undivert(`foo')
6489 @result{}bar
6490 @result{}
6491 include(`foo')
6492 @result{}BAR
6493 @result{}
6494 @end example
6496 If the file is not found (or cannot be read), an error message is
6497 issued, and the expansion is void.  It is possible to intermix files
6498 and diversion numbers.
6500 @example
6501 divert(`1')diversion one
6502 divert(`2')undivert(`foo')dnl
6503 divert(`3')diversion three
6504 divert`'dnl
6505 undivert(`1', `2', `foo', `3')dnl
6506 @result{}diversion one
6507 @result{}bar
6508 @result{}bar
6509 @result{}diversion three
6510 @end example
6512 @node Divnum
6513 @section Diversion numbers
6515 @cindex diversion numbers
6516 The current diversion is tracked by the builtin @code{divnum}:
6518 @deffn {Builtin (m4)} divnum
6519 Expands to the number of the current diversion.
6520 @end deffn
6522 @example
6523 Initial divnum
6524 @result{}Initial 0
6525 divert(`1')
6526 Diversion one: divnum
6527 divert(`2')
6528 Diversion two: divnum
6530 @result{}
6531 @result{}Diversion one: 1
6532 @result{}
6533 @result{}Diversion two: 2
6534 @end example
6536 @node Cleardivert
6537 @section Discarding diverted text
6539 @cindex discarding diverted text
6540 @cindex diverted text, discarding
6541 Often it is not known, when output is diverted, whether the diverted
6542 text is actually needed.  Since all non-empty diversion are brought back
6543 on the main output stream when the end of input is seen, a method of
6544 discarding a diversion is needed.  If all diversions should be
6545 discarded, the easiest is to end the input to @code{m4} with
6546 @samp{divert(`-1')} followed by an explicit @samp{undivert}:
6548 @example
6549 divert(`1')
6550 Diversion one: divnum
6551 divert(`2')
6552 Diversion two: divnum
6553 divert(`-1')
6554 undivert
6556 @end example
6558 @noindent
6559 No output is produced at all.
6561 Clearing selected diversions can be done with the following macro:
6563 @deffn Composite cleardivert (@ovar{diversions@dots{}})
6564 Discard the contents of each of the listed numeric @var{diversions}.
6565 @end deffn
6567 @example
6568 define(`cleardivert',
6569 `pushdef(`_n', divnum)divert(`-1')undivert($@@)divert(_n)popdef(`_n')')
6570 @result{}
6571 @end example
6573 It is called just like @code{undivert}, but the effect is to clear the
6574 diversions, given by the arguments.  (This macro has a nasty bug!  You
6575 should try to see if you can find it and correct it; or @pxref{Improved
6576 cleardivert, , Answers}).
6578 @node Modules
6579 @chapter Extending M4 with dynamic runtime modules
6581 @cindex modules
6582 @cindex dynamic modules
6583 @cindex loadable modules
6584 GNU M4 1.4.x had a monolithic architecture.  All of its
6585 functionality was contained in a single binary, and additional macros
6586 could be added only by writing more code in the M4 language, or at the
6587 extreme by hacking the sources and recompiling the whole thing to make
6588 a custom M4 installation.
6590 Starting with release 2.0, M4 supports and is composed of loadable modules.
6591 Additional modules can be loaded into the running M4 interpreter as it is
6592 started up at the command line, or during normal expansion of macros.  This
6593 facilitates runtime extension of the M4 builtin macro list using compiled C
6594 code linked against a new shared library, typically named @file{libm4.so}.
6596 For example, you might want to add a @code{setenv} builtin to M4, to
6597 use before invoking @code{esyscmd}.  We might write a @file{setenv.c}
6598 something like this:
6600 @comment ignore
6601 @example
6602 #include "m4module.h"
6604 M4BUILTIN(setenv);
6606 m4_builtin m4_builtin_table[] =
6608   /* name      handler         flags             minargs maxargs */
6609   @{ "setenv", builtin_setenv, M4_BUILTIN_BLIND, 2,      3 @},
6611   @{ NULL,     NULL,           0,                0,      0 @}
6615  * setenv(NAME, VALUE, [OVERWRITE])
6616  **/
6617 M4BUILTIN_HANDLER (setenv)
6619   int overwrite = 1;
6621   if (argc >= 4)
6622     if (!m4_numeric_arg (context, argc, argv, 3, &overwrite))
6623       return;
6625   setenv (M4ARG (1), M4ARG (2), overwrite);
6627 @end example
6629 Then, having compiled and linked the module, in (somewhat contrived)
6630 M4 code:
6632 @comment ignore
6633 @example
6634 $ @kbd{m4 setenv}
6635 setenv(`PATH', `/sbin:/bin:/usr/sbin:/usr/bin')
6636 @result{}
6637 esyscmd(`ifconfig -a')dnl
6638 @result{}@dots{}
6639 @end example
6641 Or instead of loading the module from the M4 invocation, you can use
6642 the @code{include} builtin:
6644 @comment ignore
6645 @example
6646 $ @kbd{m4}
6647 include(`setenv')
6648 @result{}
6649 setenv(`PATH', `/sbin:/bin:/usr/sbin:/usr/bin')
6650 @result{}
6651 @end example
6653 Also, at run time, you can choose which core modules to load. SUSv3 M4
6654 functionality is contained in the module @samp{m4}, GNU extensions in the
6655 module @samp{gnu}, and so on. All of the builtin descriptions in this manual
6656 are annotated with the module from which they are loaded -- mostly from the
6657 module @samp{m4}.
6659 When you start GNU M4, the modules @samp{m4} and @samp{gnu} are
6660 loaded by default.  If you supply the @option{-G} option at startup, the
6661 module @samp{traditional} is loaded instead of @samp{gnu}.
6662 @xref{Compatibility}, for more details on the differences between these
6663 two modes of startup.
6665 @menu
6666 * M4modules::                   Listing loaded modules
6667 * Standard Modules::            Standard bundled modules
6668 @end menu
6670 @node M4modules
6671 @section Listing loaded modules
6673 @deffn {Builtin (gnu)} m4modules
6674 Expands to a quoted ordered list of currently loaded modules,
6675 with the most recently loaded module at the front of the list.  Loading
6676 a module multiple times will not affect the order of this list, the
6677 position depends on when the module was @emph{first} loaded.
6678 @end deffn
6680 For example, after GNU @code{m4} is started with no additional modules,
6681 @code{m4modules} will yield the following:
6683 @example
6684 $ @kbd{m4}
6685 m4modules
6686 @result{}gnu,m4
6687 @end example
6689 @node Standard Modules
6690 @section Standard bundled modules
6692 GNU @code{m4} ships with several bundled modules as standard.
6693 By convention, these modules define a text macro that can be tested
6694 with @code{ifdef} when they are loaded; only the @code{m4} module lacks
6695 this feature test macro, since it is not permitted by POSIX.
6696 Each of the feature test macros are intended to be used without
6697 arguments.
6699 @table @code
6700 @item m4
6701 Provides all of the builtins defined by POSIX.  This module
6702 is always loaded --- GNU @code{m4} would only be a very slow
6703 version of @command{cat} without the builtins supplied by this module.
6705 @item gnu
6706 Provides all of the GNU extensions, as defined by
6707 GNU M4 through the 1.4.x release series.  It also provides a
6708 couple of feature test macros:
6710 @deffn {Macro (gnu)} __gnu__
6711 Expands to the empty string, as an indication that the @samp{gnu}
6712 module is loaded.
6713 @end deffn
6715 @deffn {Macro (gnu)} __m4_version__
6716 Expands to an unquoted string containing the release version number of
6717 the running GNU @code{m4} executable.
6718 @end deffn
6720 This module is always loaded, unless the @option{-G} command line
6721 option is supplied at startup (@pxref{Limits control, , Invoking m4}).
6723 @item traditional
6724 This module provides compatibility with System V @code{m4}, for anything
6725 not specified by POSIX, and is loaded instead of the
6726 @samp{gnu} module if the @option{-G} command line option is specified.
6728 @deffn {Macro (traditional)} __traditional__
6729 Expands to the empty string, as an indication that the
6730 @samp{traditional} module is loaded.
6731 @end deffn
6733 @item mpeval
6734 This module provides the implementation for the experimental
6735 @code{mpeval} feature.  If the host machine does not have the
6736 GNU gmp library, the builtin will generate an error if called.
6737 @xref{Mpeval}, for more details.  The module also defines the following
6738 macro:
6740 @deffn {Macro (mpeval)} __mpeval__
6741 Expands to the empty string, as an indication that the @samp{mpeval}
6742 module is loaded.
6743 @end deffn
6744 @end table
6746 Here is an example of using the feature test macros.
6748 @example
6749 $ @kbd{m4}
6750 __gnu__-__traditional__
6751 @result{}-__traditional__
6752 ifdef(`__gnu__', `Extensions are active', `Minimal features')
6753 @result{}Extensions are active
6754 __gnu__(`ignored')
6755 @error{}m4:stdin:3: warning: __gnu__: extra arguments ignored: 1 > 0
6756 @result{}
6757 @end example
6759 @comment options: -G
6760 @example
6761 $ @kbd{m4 --traditional}
6762 __gnu__-__traditional__
6763 @result{}__gnu__-
6764 ifdef(`__gnu__', `Extensions are active', `Minimal features')
6765 @result{}Minimal features
6766 @end example
6768 Since the version string is unquoted and can potentially contain macro
6769 names (for example, a beta release could be numbered @samp{1.9b}), or be
6770 impacted by the use of @code{changesyntax}), the
6771 @code{__m4_version__} macro should generally be used via @code{defn}
6772 rather than directly invoked (@pxref{Defn}).  In general, feature tests
6773 are more reliable than version number checks, so exercise caution when
6774 using this macro.
6776 @comment This test is excluded from the testsuite since it depends on a
6777 @comment texinfo macro; but builtins.at covers the same thing.
6778 @comment ignore
6779 @example
6780 defn(`__m4_version__')
6781 @result{}@value{VERSION}
6782 @end example
6784 @node Text handling
6785 @chapter Macros for text handling
6787 There are a number of builtins in @code{m4} for manipulating text in
6788 various ways, extracting substrings, searching, substituting, and so on.
6790 @menu
6791 * Len::                         Calculating length of strings
6792 * Index macro::                 Searching for substrings
6793 * Regexp::                      Searching for regular expressions
6794 * Substr::                      Extracting substrings
6795 * Translit::                    Translating characters
6796 * Patsubst::                    Substituting text by regular expression
6797 * Format::                      Formatting strings (printf-like)
6798 @end menu
6800 @node Len
6801 @section Calculating length of strings
6803 @cindex length of strings
6804 @cindex strings, length of
6805 The length of a string can be calculated by @code{len}:
6807 @deffn {Builtin (m4)} len (@var{string})
6808 Expands to the length of @var{string}, as a decimal number.
6810 The macro @code{len} is recognized only with parameters.
6811 @end deffn
6813 @example
6814 len()
6815 @result{}0
6816 len(`abcdef')
6817 @result{}6
6818 @end example
6820 @node Index macro
6821 @section Searching for substrings
6823 @cindex substrings, locating
6824 Searching for substrings is done with @code{index}:
6826 @deffn {Builtin (m4)} index (@var{string}, @var{substring}, @ovar{offset})
6827 Expands to the index of the first occurrence of @var{substring} in
6828 @var{string}.  The first character in @var{string} has index 0.  If
6829 @var{substring} does not occur in @var{string}, @code{index} expands to
6830 @samp{-1}.  If @var{offset} is provided, it determines the index at
6831 which the search starts; a negative @var{offset} specifies the offset
6832 relative to the end of @var{string}.
6834 The macro @code{index} is recognized only with parameters.
6835 @end deffn
6837 @example
6838 index(`gnus, gnats, and armadillos', `nat')
6839 @result{}7
6840 index(`gnus, gnats, and armadillos', `dag')
6841 @result{}-1
6842 @end example
6844 Omitting @var{substring} evokes a warning, but still produces output;
6845 contrast this with an empty @var{substring}.
6847 @example
6848 index(`abc')
6849 @error{}m4:stdin:1: warning: index: too few arguments: 1 < 2
6850 @result{}0
6851 index(`abc', `')
6852 @result{}0
6853 index(`abc', `b')
6854 @result{}1
6855 @end example
6857 @cindex GNU extensions
6858 As an extension, an @var{offset} can be provided to limit the search to
6859 the tail of the @var{string}.  A negative offset is interpreted relative
6860 to the end of @var{string}, and it is not an error if @var{offset}
6861 exceeds the bounds of @var{string}.
6863 @example
6864 index(`aba', `a', `1')
6865 @result{}2
6866 index(`ababa', `ba', `-3')
6867 @result{}3
6868 index(`abc', `ab', `4')
6869 @result{}-1
6870 index(`abc', `bc', `-4')
6871 @result{}1
6872 @end example
6874 @ignore
6875 @comment Expose a bug in the strstr() algorithm present in glibc
6876 @comment 2.9 through 2.12 and in gnulib up to Sep 2010.
6878 @example
6879 index(`;:11-:12-:12-:12-:12-:12-:12-:12-:12.:12.:12.:12.:12.:12.:12.:12.:12-:',
6880 `:12-:12-:12-:12-:12-:12-:12-:12-')
6881 @result{}-1
6882 @end example
6884 @comment Expose a bug in the gnulib replacement strstr() algorithm
6885 @comment present from Jun 2010 to Feb 2011, including m4 1.4.15.
6887 @example
6888 index(`..wi.d.', `.d.')
6889 @result{}4
6890 @end example
6891 @end ignore
6893 @node Regexp
6894 @section Searching for regular expressions
6896 @cindex regular expressions
6897 @cindex expressions, regular
6898 @cindex GNU extensions
6899 Searching for regular expressions is done with the builtin
6900 @code{regexp}:
6902 @deffn {Builtin (gnu)} regexp (@var{string}, @var{regexp}, @var{resyntax})
6903 @deffnx {Builtin (gnu)} regexp (@var{string}, @var{regexp}, @
6904   @ovar{replacement}, @ovar{resyntax})
6905 Searches for @var{regexp} in @var{string}.
6907 If @var{resyntax} is given, the particular flavor of regular expression
6908 understood with respect to @var{regexp} can be changed from the current
6909 default.  @xref{Changeresyntax}, for details of the values that can be
6910 given for this argument.  If exactly three arguments given, then the
6911 third argument is treated as @var{resyntax} only if it matches a known
6912 syntax name, otherwise it is treated as @var{replacement}.
6914 If @var{replacement} is omitted, @code{regexp} expands to the index of
6915 the first match of @var{regexp} in @var{string}.  If @var{regexp} does
6916 not match anywhere in @var{string}, it expands to -1.
6918 If @var{replacement} is supplied, and there was a match, @code{regexp}
6919 changes the expansion to this argument, with @samp{\@var{n}} substituted
6920 by the text matched by the @var{n}th parenthesized sub-expression of
6921 @var{regexp}, up to nine sub-expressions.  The escape @samp{\&} is
6922 replaced by the text of the entire regular expression matched.  For
6923 all other characters, @samp{\} treats the next character literally.  A
6924 warning is issued if there were fewer sub-expressions than the
6925 @samp{\@var{n}} requested, or if there is a trailing @samp{\}.  If there
6926 was no match, @code{regexp} expands to the empty string.
6928 The macro @code{regexp} is recognized only with parameters.
6929 @end deffn
6931 @example
6932 regexp(`GNUs not Unix', `\<[a-z]\w+')
6933 @result{}5
6934 regexp(`GNUs not Unix', `\<Q\w*')
6935 @result{}-1
6936 regexp(`GNUs not Unix', `\w\(\w+\)$', `*** \& *** \1 ***')
6937 @result{}*** Unix *** nix ***
6938 regexp(`GNUs not Unix', `\<Q\w*', `*** \& *** \1 ***')
6939 @result{}
6940 @end example
6942 Here are some more examples on the handling of backslash:
6944 @example
6945 regexp(`abc', `\(b\)', `\\\10\a')
6946 @result{}\b0a
6947 regexp(`abc', `b', `\1\')
6948 @error{}m4:stdin:2: warning: regexp: sub-expression 1 not present
6949 @error{}m4:stdin:2: warning: regexp: trailing \ ignored in replacement
6950 @result{}
6951 regexp(`abc', `\(\(d\)?\)\(c\)', `\1\2\3\4\5\6')
6952 @error{}m4:stdin:3: warning: regexp: sub-expression 4 not present
6953 @error{}m4:stdin:3: warning: regexp: sub-expression 5 not present
6954 @error{}m4:stdin:3: warning: regexp: sub-expression 6 not present
6955 @result{}c
6956 @end example
6958 Omitting @var{regexp} evokes a warning, but still produces output;
6959 contrast this with an empty @var{regexp} argument.
6961 @example
6962 regexp(`abc')
6963 @error{}m4:stdin:1: warning: regexp: too few arguments: 1 < 2
6964 @result{}0
6965 regexp(`abc', `')
6966 @result{}0
6967 regexp(`abc', `', `\\def')
6968 @result{}\def
6969 @end example
6971 If @var{resyntax} is given, @var{regexp} must be given according to
6972 the syntax chosen, though the default regular expression syntax
6973 remains unchanged for other invocations:
6975 @example
6976 regexp(`GNUs not Unix', `\w(\w+)$', `*** \& *** \1 ***',
6977        `POSIX_EXTENDED')
6978 @result{}*** Unix *** nix ***
6979 regexp(`GNUs not Unix', `\w(\w+)$', `*** \& *** \1 ***')
6980 @result{}
6981 @end example
6983 Occasionally, you might want to pass an @var{resyntax} argument without
6984 wishing to give @var{replacement}.  If there are exactly three
6985 arguments, and the last argument is a valid @var{resyntax}, it is used
6986 as such, rather than as a replacement.
6988 @example
6989 regexp(`GNUs not Unix', `\w(\w+)$', `POSIX_EXTENDED')
6990 @result{}9
6991 regexp(`GNUs not Unix', `\w(\w+)$', `POSIX_EXTENDED', `POSIX_EXTENDED')
6992 @result{}POSIX_EXTENDED
6993 regexp(`GNUs not Unix', `\w(\w+)$', `POSIX_EXTENDED', `')
6994 @result{}
6995 regexp(`GNUs not Unix', `\w\(\w+\)$', `POSIX_EXTENDED', `')
6996 @result{}POSIX_EXTENDED
6997 @end example
6999 @node Substr
7000 @section Extracting substrings
7002 @cindex extracting substrings
7003 @cindex substrings, extracting
7004 Substrings are extracted with @code{substr}:
7006 @deffn {Builtin (m4)} substr (@var{string}, @var{from}, @ovar{length}, @
7007   @ovar{replace})
7008 Performs a substring operation on @var{string}.  If @var{from} is
7009 positive, it represents the 0-based index where the substring begins.
7010 If @var{length} is omitted, the substring ends at the end of
7011 @var{string}; if it is positive, @var{length} is added to the starting
7012 index to determine the ending index.
7014 @cindex GNU extensions
7015 As a GNU extension, if @var{from} is negative, it is added to
7016 the length of @var{string} to determine the starting index; if it is
7017 empty, the start of the string is used.  Likewise, if @var{length} is
7018 negative, it is added to the length of @var{string} to determine the
7019 ending index, and an emtpy @var{length} behaves like an omitted
7020 @var{length}.  It is not an error if either of the resulting indices lie
7021 outside the string, but the selected substring only contains the bytes
7022 of @var{string} that overlap the selected indices.  If the end point
7023 lies before the beginning point, the substring chosen is the empty
7024 string located at the starting index.
7026 If @var{replace} is omitted, then the expansion is only the selected
7027 substring, which may be empty.  As a GNU extension,if
7028 @var{replace} is provided, then the expansion is the original
7029 @var{string} with the selected substring replaced by @var{replace}.  The
7030 expansion is empty and a warning issued if @var{from} or @var{length}
7031 cannot be parsed, or if @var{replace} is provided but the selected
7032 indices do not overlap with @var{string}.
7034 The macro @code{substr} is recognized only with parameters.
7035 @end deffn
7037 @example
7038 substr(`gnus, gnats, and armadillos', `6')
7039 @result{}gnats, and armadillos
7040 substr(`gnus, gnats, and armadillos', `6', `5')
7041 @result{}gnats
7042 @end example
7044 Omitting @var{from} evokes a warning, but still produces output.  On the
7045 other hand, selecting a @var{from} or @var{length} that lies beyond
7046 @var{string} is not a problem.
7048 @example
7049 substr(`abc')
7050 @error{}m4:stdin:1: warning: substr: too few arguments: 1 < 2
7051 @result{}abc
7052 substr(`abc', `')
7053 @result{}abc
7054 substr(`abc', `4')
7055 @result{}
7056 substr(`abc', `1', `4')
7057 @result{}bc
7058 @end example
7060 Using negative values for @var{from} or @var{length} are GNU
7061 extensions, useful for accessing a fixed size tail of an
7062 arbitrary-length string.  Prior to M4 1.6, using these values would
7063 silently result in the empty string.  Some other implementations crash
7064 on negative values, and many treat an explicitly empty @var{length} as
7065 0, which is different from the omitted @var{length} implying the rest of
7066 the original @var{string}.
7068 @example
7069 substr(`abcde', `2', `')
7070 @result{}cde
7071 substr(`abcde', `-3')
7072 @result{}cde
7073 substr(`abcde', `', `-3')
7074 @result{}ab
7075 substr(`abcde', `-6')
7076 @result{}abcde
7077 substr(`abcde', `-6', `5')
7078 @result{}abcd
7079 substr(`abcde', `-7', `1')
7080 @result{}
7081 substr(`abcde', `1', `-2')
7082 @result{}bc
7083 substr(`abcde', `-4', `-1')
7084 @result{}bcd
7085 substr(`abcde', `4', `-3')
7086 @result{}
7087 substr(`abcdefghij', `-09', `08')
7088 @result{}bcdefghi
7089 @end example
7091 Another useful GNU extension, also added in M4 1.6, is the
7092 ability to replace a substring within the original @var{string}.  An
7093 empty length substring at the beginning or end of @var{string} is valid,
7094 but selecting a substring that does not overlap @var{string} causes a
7095 warning.
7097 @example
7098 substr(`abcde', `1', `3', `t')
7099 @result{}ate
7100 substr(`abcde', `5', `', `f')
7101 @result{}abcdef
7102 substr(`abcde', `-3', `-4', `f')
7103 @result{}abfcde
7104 substr(`abcde', `-6', `1', `f')
7105 @result{}fabcde
7106 substr(`abcde', `-7', `1', `f')
7107 @error{}m4:stdin:5: warning: substr: substring out of range
7108 @result{}
7109 substr(`abcde', `6', `', `f')
7110 @error{}m4:stdin:6: warning: substr: substring out of range
7111 @result{}
7112 @end example
7114 If backwards compabitility to M4 1.4.x behavior is necessary, the
7115 following macro is sufficient to do the job (mimicking warnings about
7116 empty @var{from} or @var{length} or an ignored fourth argument is left
7117 as an exercise to the reader).
7119 @example
7120 define(`substr', `ifelse(`$#', `0', ``$0'',
7121   eval(`2 < $#')`$3', `1', `',
7122   index(`$2$3', `-'), `-1', `builtin(`$0', `$1', `$2', `$3')')')
7123 @result{}
7124 substr(`abcde', `3')
7125 @result{}de
7126 substr(`abcde', `3', `')
7127 @result{}
7128 substr(`abcde', `-1')
7129 @result{}
7130 substr(`abcde', `1', `-1')
7131 @result{}
7132 substr(`abcde', `2', `1', `C')
7133 @result{}c
7134 @end example
7136 On the other hand, it is possible to portably emulate the GNU
7137 extension of negative @var{from} and @var{length} arguments across all
7138 @code{m4} implementations, albeit with a lot more overhead.  This
7139 example uses @code{incr} and @code{decr} to normalize @samp{-08} to
7140 something that a later @code{eval} will treat as a decimal value, rather
7141 than looking like an invalid octal number, while avoiding using these
7142 macros on an empty string.  The helper macro @code{_substr_normalize} is
7143 recursive, since it is easier to fix @var{length} after @var{from} has
7144 been normalized, with the final iteration supplying two non-negative
7145 arguments to the original builtin, now named @code{_substr}.
7147 @comment options: -daq -t_substr
7148 @example
7149 $ @kbd{m4 -daq -t _substr}
7150 define(`_substr', defn(`substr'))dnl
7151 define(`substr', `ifelse(`$#', `0', ``$0'',
7152   `_$0(`$1', _$0_normalize(len(`$1'),
7153     ifelse(`$2', `', `0', `incr(decr(`$2'))'),
7154     ifelse(`$3', `', `', `incr(decr(`$3'))')))')')dnl
7155 define(`_substr_normalize', `ifelse(
7156   eval(`$2 < 0 && $1 + $2 >= 0'), `1',
7157     `$0(`$1', eval(`$1 + $2'), `$3')',
7158   eval(`$2 < 0')`$3', `1', ``0', `$1'',
7159   eval(`$2 < 0 && $3 - 0 >= 0 && $1 + $2 + $3 - 0 >= 0'), `1',
7160     `$0(`$1', `0', eval(`$1 + $2 + $3 - 0'))',
7161   eval(`$2 < 0 && $3 - 0 >= 0'), `1', ``0', `0'',
7162   eval(`$2 < 0'), `1', `$0(`$1', `0', `$3')',
7163   `$3', `', ``$2', `$1'',
7164   eval(`$3 - 0 < 0 && $1 - $2 + $3 - 0 >= 0'), `1',
7165     ``$2', eval(`$1 - $2 + $3')',
7166   eval(`$3 - 0 < 0'), `1', ``$2', `0'',
7167   ``$2', `$3'')')dnl
7168 substr(`abcde', `2', `')
7169 @error{}m4trace: -1- _substr(`abcde', `2', `5')
7170 @result{}cde
7171 substr(`abcde', `-3')
7172 @error{}m4trace: -1- _substr(`abcde', `2', `5')
7173 @result{}cde
7174 substr(`abcde', `', `-3')
7175 @error{}m4trace: -1- _substr(`abcde', `0', `2')
7176 @result{}ab
7177 substr(`abcde', `-6')
7178 @error{}m4trace: -1- _substr(`abcde', `0', `5')
7179 @result{}abcde
7180 substr(`abcde', `-6', `5')
7181 @error{}m4trace: -1- _substr(`abcde', `0', `4')
7182 @result{}abcd
7183 substr(`abcde', `-7', `1')
7184 @error{}m4trace: -1- _substr(`abcde', `0', `0')
7185 @result{}
7186 substr(`abcde', `1', `-2')
7187 @error{}m4trace: -1- _substr(`abcde', `1', `2')
7188 @result{}bc
7189 substr(`abcde', `-4', `-1')
7190 @error{}m4trace: -1- _substr(`abcde', `1', `3')
7191 @result{}bcd
7192 substr(`abcde', `4', `-3')
7193 @error{}m4trace: -1- _substr(`abcde', `4', `0')
7194 @result{}
7195 substr(`abcdefghij', `-09', `08')
7196 @error{}m4trace: -1- _substr(`abcdefghij', `1', `8')
7197 @result{}bcdefghi
7198 @end example
7200 @node Translit
7201 @section Translating characters
7203 @cindex translating characters
7204 @cindex characters, translating
7205 Character translation is done with @code{translit}:
7207 @deffn {Builtin (m4)} translit (@var{string}, @var{chars}, @ovar{replacement})
7208 Expands to @var{string}, with each character that occurs in
7209 @var{chars} translated into the character from @var{replacement} with
7210 the same index.
7212 If @var{replacement} is shorter than @var{chars}, the excess characters
7213 of @var{chars} are deleted from the expansion; if @var{chars} is
7214 shorter, the excess characters in @var{replacement} are silently
7215 ignored.  If @var{replacement} is omitted, all characters in
7216 @var{string} that are present in @var{chars} are deleted from the
7217 expansion.  If a character appears more than once in @var{chars}, only
7218 the first instance is used in making the translation.  Only a single
7219 translation pass is made, even if characters in @var{replacement} also
7220 appear in @var{chars}.
7222 As a GNU extension, both @var{chars} and @var{replacement} can
7223 contain character-ranges, e.g., @samp{a-z} (meaning all lowercase
7224 letters) or @samp{0-9} (meaning all digits).  To include a dash @samp{-}
7225 in @var{chars} or @var{replacement}, place it first or last in the
7226 entire string, or as the last character of a range.  Back-to-back ranges
7227 can share a common endpoint.  It is not an error for the last character
7228 in the range to be `larger' than the first.  In that case, the range
7229 runs backwards, i.e., @samp{9-0} means the string @samp{9876543210}.
7230 The expansion of a range is dependent on the underlying encoding of
7231 characters, so using ranges is not always portable between machines.
7233 The macro @code{translit} is recognized only with parameters.
7234 @end deffn
7236 @example
7237 translit(`GNUs not Unix', `A-Z')
7238 @result{}s not nix
7239 translit(`GNUs not Unix', `a-z', `A-Z')
7240 @result{}GNUS NOT UNIX
7241 translit(`GNUs not Unix', `A-Z', `z-a')
7242 @result{}tmfs not fnix
7243 translit(`+,-12345', `+--1-5', `<;>a-c-a')
7244 @result{}<;>abcba
7245 translit(`abcdef', `aabdef', `bcged')
7246 @result{}bgced
7247 @end example
7249 In the @sc{ascii} encoding, the first example deletes all uppercase
7250 letters, the second converts lowercase to uppercase, and the third
7251 `mirrors' all uppercase letters, while converting them to lowercase.
7252 The two first cases are by far the most common, even though they are not
7253 portable to @sc{ebcdic} or other encodings.  The fourth example shows a
7254 range ending in @samp{-}, as well as back-to-back ranges.  The final
7255 example shows that @samp{a} is mapped to @samp{b}, not @samp{c}; the
7256 resulting @samp{b} is not further remapped to @samp{g}; the @samp{d} and
7257 @samp{e} are swapped, and the @samp{f} is discarded.
7259 Omitting @var{chars} evokes a warning, but still produces output.
7261 @example
7262 translit(`abc')
7263 @error{}m4:stdin:1: warning: translit: too few arguments: 1 < 2
7264 @result{}abc
7265 @end example
7267 @node Patsubst
7268 @section Substituting text by regular expression
7270 @cindex regular expressions
7271 @cindex expressions, regular
7272 @cindex pattern substitution
7273 @cindex substitution by regular expression
7274 @cindex GNU extensions
7275 Global substitution in a string is done by @code{patsubst}:
7277 @deffn {Builtin (gnu)} patsubst (@var{string}, @var{regexp}, @
7278   @ovar{replacement}, @ovar{resyntax})
7279 Searches @var{string} for matches of @var{regexp}, and substitutes
7280 @var{replacement} for each match.
7282 If @var{resyntax} is given, the particular flavor of regular expression
7283 understood with respect to @var{regexp} can be changed from the current
7284 default.  @xref{Changeresyntax}, for details of the values that can be
7285 given for this argument.  Unlike @var{regexp}, if exactly three
7286 arguments given, the third argument is always treated as
7287 @var{replacement}, even if it matches a known syntax name.
7289 The parts of @var{string} that are not covered by any match of
7290 @var{regexp} are copied to the expansion.  Whenever a match is found, the
7291 search proceeds from the end of the match, so a character from
7292 @var{string} will never be substituted twice.  If @var{regexp} matches a
7293 string of zero length, the start position for the search is incremented,
7294 to avoid infinite loops.
7296 When a replacement is to be made, @var{replacement} is inserted into
7297 the expansion, with @samp{\@var{n}} substituted by the text matched by
7298 the @var{n}th parenthesized sub-expression of @var{patsubst}, for up to
7299 nine sub-expressions.  The escape @samp{\&} is replaced by the text of
7300 the entire regular expression matched.  For all other characters,
7301 @samp{\} treats the next character literally.  A warning is issued if
7302 there were fewer sub-expressions than the @samp{\@var{n}} requested, or
7303 if there is a trailing @samp{\}.
7305 The @var{replacement} argument can be omitted, in which case the text
7306 matched by @var{regexp} is deleted.
7308 The macro @code{patsubst} is recognized only with parameters.
7309 @end deffn
7311 When used with two arguments, @code{regexp} returns the position of the
7312 match, but @code{patsubst} deletes the match:
7314 @example
7315 patsubst(`GNUs not Unix', `^', `OBS: ')
7316 @result{}OBS: GNUs not Unix
7317 patsubst(`GNUs not Unix', `\<', `OBS: ')
7318 @result{}OBS: GNUs OBS: not OBS: Unix
7319 patsubst(`GNUs not Unix', `\w*', `(\&)')
7320 @result{}(GNUs)() (not)() (Unix)()
7321 patsubst(`GNUs not Unix', `\w+', `(\&)')
7322 @result{}(GNUs) (not) (Unix)
7323 patsubst(`GNUs not Unix', `[A-Z][a-z]+')
7324 @result{}GN not@w{ }
7325 patsubst(`GNUs not Unix', `not', `NOT\')
7326 @error{}m4:stdin:6: warning: patsubst: trailing \ ignored in replacement
7327 @result{}GNUs NOT Unix
7328 @end example
7330 Here is a slightly more realistic example, which capitalizes individual
7331 words or whole sentences, by substituting calls of the macros
7332 @code{upcase} and @code{downcase} into the strings.
7334 @deffn Composite upcase (@var{text})
7335 @deffnx Composite downcase (@var{text})
7336 @deffnx Composite capitalize (@var{text})
7337 Expand to @var{text}, but with capitalization changed: @code{upcase}
7338 changes all letters to upper case, @code{downcase} changes all letters
7339 to lower case, and @code{capitalize} changes the first character of each
7340 word to upper case and the remaining characters to lower case.
7341 @end deffn
7343 First, an example of their usage, using implementations distributed in
7344 @file{m4-@value{VERSION}/@/doc/examples/@/capitalize.m4}.
7346 @comment examples
7347 @example
7348 $ @kbd{m4 -I doc/examples}
7349 include(`capitalize.m4')
7350 @result{}
7351 upcase(`GNUs not Unix')
7352 @result{}GNUS NOT UNIX
7353 downcase(`GNUs not Unix')
7354 @result{}gnus not unix
7355 capitalize(`GNUs not Unix')
7356 @result{}Gnus Not Unix
7357 @end example
7359 Now for the implementation.  There is a helper macro @code{_capitalize}
7360 which puts only its first word in mixed case.  Then @code{capitalize}
7361 merely parses out the words, and replaces them with an invocation of
7362 @code{_capitalize}.  (As presented here, the @code{capitalize} macro has
7363 some subtle flaws.  You should try to see if you can find and correct
7364 them; or @pxref{Improved capitalize, , Answers}).
7366 @comment examples
7367 @example
7368 $ @kbd{m4 -I doc/examples}
7369 undivert(`capitalize.m4')dnl
7370 @result{}divert(`-1')
7371 @result{}# upcase(text)
7372 @result{}# downcase(text)
7373 @result{}# capitalize(text)
7374 @result{}#   change case of text, simple version
7375 @result{}define(`upcase', `translit(`$*', `a-z', `A-Z')')
7376 @result{}define(`downcase', `translit(`$*', `A-Z', `a-z')')
7377 @result{}define(`_capitalize',
7378 @result{}       `regexp(`$1', `^\(\w\)\(\w*\)',
7379 @result{}               `upcase(`\1')`'downcase(`\2')')')
7380 @result{}define(`capitalize', `patsubst(`$1', `\w+', `_$0(`\&')')')
7381 @result{}divert`'dnl
7382 @end example
7384 If @var{resyntax} is given, @var{regexp} must be given according to
7385 the syntax chosen, though the default regular expression syntax
7386 remains unchanged for other invocations:
7388 @example
7389 define(`epatsubst',
7390        `builtin(`patsubst', `$1', `$2', `$3', `POSIX_EXTENDED')')dnl
7391 epatsubst(`bar foo baz Foo', `(\w*) (foo|Foo)', `_\1_')
7392 @result{}_bar_ _baz_
7393 patsubst(`bar foo baz Foo', `\(\w*\) \(foo\|Foo\)', `_\1_')
7394 @result{}_bar_ _baz_
7395 @end example
7397 While @code{regexp} replaces the whole input with the replacement as
7398 soon as there is a match, @code{patsubst} replaces each
7399 @emph{occurrence} of a match and preserves non-matching pieces:
7401 @example
7402 define(`patreg',
7403 `patsubst($@@)
7404 regexp($@@)')dnl
7405 patreg(`bar foo baz Foo', `foo\|Foo', `FOO')
7406 @result{}bar FOO baz FOO
7407 @result{}FOO
7408 patreg(`aba abb 121', `\(.\)\(.\)\1', `\2\1\2')
7409 @result{}bab abb 212
7410 @result{}bab
7411 @end example
7413 Omitting @var{regexp} evokes a warning, but still produces output;
7414 contrast this with an empty @var{regexp} argument.
7416 @example
7417 patsubst(`abc')
7418 @error{}m4:stdin:1: warning: patsubst: too few arguments: 1 < 2
7419 @result{}abc
7420 patsubst(`abc', `')
7421 @result{}abc
7422 patsubst(`abc', `', `\\-')
7423 @result{}\-a\-b\-c\-
7424 @end example
7426 @node Format
7427 @section Formatting strings (printf-like)
7429 @cindex formatted output
7430 @cindex output, formatted
7431 @cindex GNU extensions
7432 Formatted output can be made with @code{format}:
7434 @deffn {Builtin (gnu)} format (@var{format-string}, @dots{})
7435 Works much like the C function @code{printf}.  The first argument
7436 @var{format-string} can contain @samp{%} specifications which are
7437 satisfied by additional arguments, and the expansion of @code{format} is
7438 the formatted string.
7440 The macro @code{format} is recognized only with parameters.
7441 @end deffn
7443 Its use is best described by a few examples:
7445 @comment This test is a bit fragile, if someone tries to port to a
7446 @comment platform without infinity.
7447 @example
7448 define(`foo', `The brown fox jumped over the lazy dog')
7449 @result{}
7450 format(`The string "%s" uses %d characters', foo, len(foo))
7451 @result{}The string "The brown fox jumped over the lazy dog" uses 38 characters
7452 format(`%*.*d', `-1', `-1', `1')
7453 @result{}1
7454 format(`%.0f', `56789.9876')
7455 @result{}56790
7456 len(format(`%-*X', `5000', `1'))
7457 @result{}5000
7458 ifelse(format(`%010F', `infinity'), `       INF', `success',
7459        format(`%010F', `infinity'), `  INFINITY', `success',
7460        format(`%010F', `infinity'))
7461 @result{}success
7462 ifelse(format(`%.1A', `1.999'), `0X1.0P+1', `success',
7463        format(`%.1A', `1.999'), `0X2.0P+0', `success',
7464        format(`%.1A', `1.999'))
7465 @result{}success
7466 format(`%g', `0xa.P+1')
7467 @result{}20
7468 @end example
7470 Using the @code{forloop} macro defined earlier (@pxref{Forloop}), this
7471 example shows how @code{format} can be used to produce tabular output.
7473 @comment examples
7474 @example
7475 $ @kbd{m4 -I doc/examples}
7476 include(`forloop.m4')
7477 @result{}
7478 forloop(`i', `1', `10', `format(`%6d squared is %10d
7479 ', i, eval(i**2))')
7480 @result{}     1 squared is          1
7481 @result{}     2 squared is          4
7482 @result{}     3 squared is          9
7483 @result{}     4 squared is         16
7484 @result{}     5 squared is         25
7485 @result{}     6 squared is         36
7486 @result{}     7 squared is         49
7487 @result{}     8 squared is         64
7488 @result{}     9 squared is         81
7489 @result{}    10 squared is        100
7490 @result{}
7491 @end example
7493 The builtin @code{format} is modeled after the ANSI C @samp{printf}
7494 function, and supports these @samp{%} specifiers: @samp{c}, @samp{s},
7495 @samp{d}, @samp{o}, @samp{x}, @samp{X}, @samp{u}, @samp{a}, @samp{A},
7496 @samp{e}, @samp{E}, @samp{f}, @samp{F}, @samp{g}, @samp{G}, and
7497 @samp{%}; it supports field widths and precisions, and the flags
7498 @samp{+}, @samp{-}, @samp{ }, @samp{0}, @samp{#}, and @samp{'}.  For
7499 integer specifiers, the width modifiers @samp{hh}, @samp{h}, and
7500 @samp{l} are recognized, and for floating point specifiers, the width
7501 modifier @samp{l} is recognized.  Items not yet supported include
7502 positional arguments, the @samp{n}, @samp{p}, @samp{S}, and @samp{C}
7503 specifiers, the @samp{z}, @samp{t}, @samp{j}, @samp{L} and @samp{ll}
7504 modifiers, and any platform extensions available in the native
7505 @code{printf}.  For more details on the functioning of @code{printf},
7506 see the C Library Manual, or the POSIX specification (for
7507 example, @samp{%a} is supported even on platforms that haven't yet
7508 implemented C99 hexadecimal floating point output natively).
7510 @c FIXME - format still needs some improvements.
7511 Warnings are issued for unrecognized specifiers, an improper number of
7512 arguments, or difficulty parsing an argument according to the format
7513 string (such as overflow or extra characters).  It is anticipated that a
7514 future release of GNU @code{m4} will support more specifiers.
7515 Likewise, escape sequences are not yet recognized.
7517 @example
7518 format(`%p', `0')
7519 @error{}m4:stdin:1: warning: format: unrecognized specifier in '%p'
7520 @result{}
7521 format(`%*d', `')
7522 @error{}m4:stdin:2: warning: format: empty string treated as 0
7523 @error{}m4:stdin:2: warning: format: too few arguments: 2 < 3
7524 @result{}0
7525 format(`%.1f', `2a')
7526 @error{}m4:stdin:3: warning: format: non-numeric argument '2a'
7527 @result{}2.0
7528 @end example
7530 @ignore
7531 @comment Expose a crash with a bad format string fixed in 1.4.15.
7532 @comment Unfortunately, 8-bit bytes are hard to check for; but the
7533 @comment exit status is enough to sniff the crash in broken versions.
7535 @example
7536 format(`%'format(`%c', `128'))
7537 @result{}
7538 @error{}ignore
7539 @end example
7540 @end ignore
7542 @node Arithmetic
7543 @chapter Macros for doing arithmetic
7545 @cindex arithmetic
7546 @cindex integer arithmetic
7547 Integer arithmetic is included in @code{m4}, with a C-like syntax.  As
7548 convenient shorthands, there are builtins for simple increment and
7549 decrement operations.
7551 @menu
7552 * Incr::                        Decrement and increment operators
7553 * Eval::                        Evaluating integer expressions
7554 * Mpeval::                      Multiple precision arithmetic
7555 @end menu
7557 @node Incr
7558 @section Decrement and increment operators
7560 @cindex decrement operator
7561 @cindex increment operator
7562 Increment and decrement of integers are supported using the builtins
7563 @code{incr} and @code{decr}:
7565 @deffn {Builtin (m4)} incr (@var{number})
7566 @deffnx {Builtin (m4)} decr (@var{number})
7567 Expand to the numerical value of @var{number}, incremented
7568 or decremented, respectively, by one.  Except for the empty string, the
7569 expansion is empty if @var{number} could not be parsed.
7571 The macros @code{incr} and @code{decr} are recognized only with
7572 parameters.
7573 @end deffn
7575 @example
7576 incr(`4')
7577 @result{}5
7578 decr(`7')
7579 @result{}6
7580 incr()
7581 @error{}m4:stdin:3: warning: incr: empty string treated as 0
7582 @result{}1
7583 decr()
7584 @error{}m4:stdin:4: warning: decr: empty string treated as 0
7585 @result{}-1
7586 @end example
7588 The builtin macros @code{incr} and @code{decr} are recognized only when
7589 given arguments.
7591 @node Eval
7592 @section Evaluating integer expressions
7594 @cindex integer expression evaluation
7595 @cindex evaluation, of integer expressions
7596 @cindex expressions, evaluation of integer
7597 Integer expressions are evaluated with @code{eval}:
7599 @deffn {Builtin (m4)} eval (@var{expression}, @dvar{radix, 10}, @ovar{width})
7600 Expands to the value of @var{expression}.  The expansion is empty
7601 if a problem is encountered while parsing the arguments.  If specified,
7602 @var{radix} and @var{width} control the format of the output.
7604 Calculations are done with signed numbers, using at least 31-bit
7605 precision, but as a GNU extension, @code{m4} will use wider
7606 integers if available.  Precision is finite, based on the platform's
7607 notion of @code{intmax_t}, and overflow silently results in wraparound.
7608 A warning is issued if division by zero is attempted, or if
7609 @var{expression} could not be parsed.
7611 Expressions can contain the following operators, listed in order of
7612 decreasing precedence.
7614 @table @samp
7615 @item ()
7616 Parentheses
7617 @item +  -  ~  !
7618 Unary plus and minus, and bitwise and logical negation
7619 @item **
7620 Exponentiation
7621 @item *  /  %  \
7622 Multiplication, division, modulo, and ratio
7623 @item +  -
7624 Addition and subtraction
7625 @item <<  >>  >>>
7626 Shift left, shift right, unsigned shift right
7627 @item >  >=  <  <=
7628 Relational operators
7629 @item ==  !=
7630 Equality operators
7631 @item &
7632 Bitwise and
7633 @item ^
7634 Bitwise exclusive-or
7635 @item |
7636 Bitwise or
7637 @item &&
7638 Logical and
7639 @item ||
7640 Logical or
7641 @item ?:
7642 Conditional ternary
7643 @item ,
7644 Sequential evaluation
7645 @end table
7647 The macro @code{eval} is recognized only with parameters.
7648 @end deffn
7650 All binary operators, except exponentiation, are left associative.  C
7651 operators that perform variable assignment, such as @samp{+=} or
7652 @samp{--}, are not implemented, since @code{eval} only operates on
7653 constants, not variables.  Attempting to use them results in an error.
7654 @comment FIXME - since XCU ERN 137 is approved, we could provide an
7655 @comment extension that supported assignment operators.
7657 Note that some older @code{m4} implementations use @samp{^} as an
7658 alternate operator for the exponentiation, although POSIX
7659 requires the C behavior of bitwise exclusive-or.  The precedence of the
7660 negation operators, @samp{~} and @samp{!}, was traditionally lower than
7661 equality.  The unary operators could not be used reliably more than once
7662 on the same term without intervening parentheses.  The traditional
7663 precedence of the equality operators @samp{==} and @samp{!=} was
7664 identical instead of lower than the relational operators such as
7665 @samp{<}, even through GNU M4 1.4.8.  Starting with version
7666 1.4.9, GNU M4 correctly follows POSIX precedence
7667 rules.  M4 scripts designed to be portable between releases must be
7668 aware that parentheses may be required to enforce C precedence rules.
7669 Likewise, division by zero, even in the unused branch of a
7670 short-circuiting operator, is not always well-defined in other
7671 implementations.
7673 Following are some examples where the current version of M4 follows C
7674 precedence rules, but where older versions and some other
7675 implementations of @code{m4} require explicit parentheses to get the
7676 correct result:
7678 @example
7679 eval(`1 == 2 > 0')
7680 @result{}1
7681 eval(`(1 == 2) > 0')
7682 @result{}0
7683 eval(`! 0 * 2')
7684 @result{}2
7685 eval(`! (0 * 2)')
7686 @result{}1
7687 eval(`1 | 1 ^ 1')
7688 @result{}1
7689 eval(`(1 | 1) ^ 1')
7690 @result{}0
7691 eval(`+ + - ~ ! ~ 0')
7692 @result{}1
7693 eval(`++0')
7694 @error{}m4:stdin:8: warning: eval: invalid operator: '++0'
7695 @result{}
7696 eval(`1 = 1')
7697 @error{}m4:stdin:9: warning: eval: invalid operator: '1 = 1'
7698 @result{}
7699 eval(`0 |= 1')
7700 @error{}m4:stdin:10: warning: eval: invalid operator: '0 |= 1'
7701 @result{}
7702 eval(`2 || 1 / 0')
7703 @result{}1
7704 eval(`0 || 1 / 0')
7705 @error{}m4:stdin:12: warning: eval: divide by zero: '0 || 1 / 0'
7706 @result{}
7707 eval(`0 && 1 % 0')
7708 @result{}0
7709 eval(`2 && 1 % 0')
7710 @error{}m4:stdin:14: warning: eval: modulo by zero: '2 && 1 % 0'
7711 @result{}
7712 @end example
7714 @cindex GNU extensions
7715 As a GNU extension, @code{eval} supports several operators
7716 that do not appear in C@.  A right-associative exponentiation operator
7717 @samp{**} computes the value of the left argument raised to the right,
7718 modulo the numeric precision width.  If evaluated, the exponent must be
7719 non-negative, and at least one of the arguments must be non-zero, or a
7720 warning is issued.  An unsigned shift operator @samp{>>>} allows
7721 shifting a negative number as though it were an unsigned bit pattern,
7722 which shifts in 0 bits rather than twos-complement sign-extension.  A
7723 ratio operator @samp{\} behaves like normal division @samp{/} on
7724 integers, but is provided for symmetry with @code{mpeval}.
7725 Additionally, the C operators @samp{,} and @samp{?:} are supported.
7727 @example
7728 eval(`2 ** 3 ** 2')
7729 @result{}512
7730 eval(`(2 ** 3) ** 2')
7731 @result{}64
7732 eval(`0 ** 1')
7733 @result{}0
7734 eval(`2 ** 0')
7735 @result{}1
7736 eval(`0 ** 0')
7737 @result{}
7738 @error{}m4:stdin:5: warning: eval: divide by zero: '0 ** 0'
7739 eval(`4 ** -2')
7740 @error{}m4:stdin:6: warning: eval: negative exponent: '4 ** -2'
7741 @result{}
7742 eval(`2 || 4 ** -2')
7743 @result{}1
7744 eval(`(-1 >> 1) == -1')
7745 @result{}1
7746 eval(`(-1 >>> 1) > (1 << 30)')
7747 @result{}1
7748 eval(`6 \ 3')
7749 @result{}2
7750 eval(`1 ? 2 : 3')
7751 @result{}2
7752 eval(`0 ? 2 : 3')
7753 @result{}3
7754 eval(`1 ? 2 : 1/0')
7755 @result{}2
7756 eval(`0 ? 1/0 : 3')
7757 @result{}3
7758 eval(`4, 5')
7759 @result{}5
7760 @end example
7762 Within @var{expression}, (but not @var{radix} or @var{width}), numbers
7763 without a special prefix are decimal.  A simple @samp{0} prefix
7764 introduces an octal number.  @samp{0x} introduces a hexadecimal number.
7765 As GNU extensions, @samp{0b} introduces a binary number.
7766 @samp{0r} introduces a number expressed in any radix between 1 and 36:
7767 the prefix should be immediately followed by the decimal expression of
7768 the radix, a colon, then the digits making the number.  For radix 1,
7769 leading zeros are ignored, and all remaining digits must be @samp{1};
7770 for all other radices, the digits are @samp{0}, @samp{1}, @samp{2},
7771 @dots{}.  Beyond @samp{9}, the digits are @samp{a}, @samp{b} @dots{} up
7772 to @samp{z}.  Lower and upper case letters can be used interchangeably
7773 in numbers prefixes and as number digits.
7775 Parentheses may be used to group subexpressions whenever needed.  For the
7776 relational operators, a true relation returns @code{1}, and a false
7777 relation return @code{0}.
7779 Here are a few examples of use of @code{eval}.
7781 @example
7782 eval(`-3 * 5')
7783 @result{}-15
7784 eval(`-99 / 10')
7785 @result{}-9
7786 eval(`-99 % 10')
7787 @result{}-9
7788 eval(`99 % -10')
7789 @result{}9
7790 eval(index(`Hello world', `llo') >= 0)
7791 @result{}1
7792 eval(`0r1:0111 + 0b100 + 0r3:12')
7793 @result{}12
7794 define(`square', `eval(`($1) ** 2')')
7795 @result{}
7796 square(`9')
7797 @result{}81
7798 square(square(`5')` + 1')
7799 @result{}676
7800 define(`foo', `666')
7801 @result{}
7802 eval(`foo / 6')
7803 @error{}m4:stdin:11: warning: eval: bad expression: 'foo / 6'
7804 @result{}
7805 eval(foo / 6)
7806 @result{}111
7807 @end example
7809 As the last two lines show, @code{eval} does not handle macro
7810 names, even if they expand to a valid expression (or part of a valid
7811 expression).  Therefore all macros must be expanded before they are
7812 passed to @code{eval}.
7813 @comment update this if we add support for variables.
7815 Some calculations are not portable to other implementations, since they
7816 have undefined semantics in C, but GNU @code{m4} has
7817 well-defined behavior on overflow.  When shifting, an out-of-range shift
7818 amount is implicitly brought into the range of the precision using
7819 modulo arithmetic (for example, on 32-bit integers, this would be an
7820 implicit bit-wise and with 0x1f).  This example should work whether your
7821 platform uses 32-bit integers, 64-bit integers, or even some other
7822 atypical size.
7824 @example
7825 define(`max_int', eval(`-1 >>> 1'))
7826 @result{}
7827 define(`min_int', eval(max_int` + 1'))
7828 @result{}
7829 eval(min_int` < 0')
7830 @result{}1
7831 eval(max_int` > 0')
7832 @result{}1
7833 ifelse(eval(min_int` / -1'), min_int, `overflow occurred')
7834 @result{}overflow occurred
7835 eval(`0x80000000 % -1')
7836 @result{}0
7837 eval(`-4 >> 1')
7838 @result{}-2
7839 eval(`-4 >> 'eval(len(eval(max_int, `2'))` + 2'))
7840 @result{}-2
7841 @end example
7843 If @var{radix} is specified, it specifies the radix to be used in the
7844 expansion.  The default radix is 10; this is also the case if
7845 @var{radix} is the empty string.  A warning results if the radix is
7846 outside the range of 1 through 36, inclusive.  The result of @code{eval}
7847 is always taken to be signed.  No radix prefix is output, and for
7848 radices greater than 10, the digits are lower case (although some
7849 other implementations use upper case).  The output is unquoted, and
7850 subject to further macro expansion.  The @var{width}
7851 argument specifies the minimum output width, excluding any negative
7852 sign.  The result is zero-padded to extend the expansion to the
7853 requested width.  A warning results if the width is negative.  If
7854 @var{radix} or @var{width} is out of bounds, the expansion of
7855 @code{eval} is empty.
7857 @example
7858 eval(`666', `10')
7859 @result{}666
7860 eval(`666', `11')
7861 @result{}556
7862 eval(`666', `6')
7863 @result{}3030
7864 eval(`666', `6', `10')
7865 @result{}0000003030
7866 eval(`-666', `6', `10')
7867 @result{}-0000003030
7868 eval(`10', `', `0')
7869 @result{}10
7870 `0r1:'eval(`10', `1', `11')
7871 @result{}0r1:01111111111
7872 eval(`10', `16')
7873 @result{}a
7874 eval(`1', `37')
7875 @error{}m4:stdin:9: warning: eval: radix out of range: 37
7876 @result{}
7877 eval(`1', , `-1')
7878 @error{}m4:stdin:10: warning: eval: negative width: -1
7879 @result{}
7880 eval()
7881 @error{}m4:stdin:11: warning: eval: empty string treated as 0
7882 @result{}0
7883 eval(` ')
7884 @error{}m4:stdin:12: warning: eval: empty string treated as 0
7885 @result{}0
7886 define(`a', `hi')eval(` 10 ', `16')
7887 @result{}hi
7888 @end example
7890 @node Mpeval
7891 @section Multiple precision arithmetic
7893 When @code{m4} is compiled with a multiple precision arithmetic library
7894 (@pxref{Experiments}), a builtin @code{mpeval} is defined.
7896 @deffn {Builtin (mpeval)} mpeval (@var{expression}, @dvar{radix, 10}, @
7897   @ovar{width})
7898 Behaves similarly to @code{eval}, except the calculations are done with
7899 infinite precision, and rational numbers are supported.  Numbers may be
7900 of any length.
7902 The macro @code{mpeval} is recognized only with parameters.
7903 @end deffn
7905 For the most part, using @code{mpeval} is similar to using @code{eval}:
7907 @comment options: mpeval -
7908 @example
7909 $ @kbd{m4 mpeval -}
7910 mpeval(`(1 << 70) + 2 ** 68 * 3', `16')
7911 @result{}700000000000000000
7912 `0r24:'mpeval(`0r36:zYx', `24', `5')
7913 @result{}0r24:038m9
7914 @end example
7916 The ratio operator, @samp{\}, is provided with the same precedence as
7917 division, and rationally divides two numbers and canonicalizes the
7918 result, whereas the division operator @samp{/} always returns the
7919 integer quotient of the division.  To convert a rational value to
7920 integral, divide (@samp{/}) by 1.  Some operators, such as @samp{%},
7921 @samp{<<}, @samp{>>}, @samp{~}, @samp{&}, @samp{|} and @samp{^} operate
7922 only on integers and will truncate any rational remainder.  The unsigned
7923 shift operator, @samp{>>>}, behaves identically with regular right
7924 shifts, @samp{>>}, since with infinite precision, it is not possible to
7925 convert a negative number to a positive using shifts.  The
7926 exponentiation operator, @samp{**}, assumes that the exponent is
7927 integral, but allows negative exponents.  With the short-circuit logical
7928 operators, @samp{||} and @samp{&&}, a non-zero result preserves the
7929 value of the argument that ended evaluation, rather than collapsing to
7930 @samp{1}.  The operators @samp{?:} and @samp{,} are always available,
7931 even in POSIX mode, since @code{mpeval} does not have to
7932 conform to the POSIX rules for @code{eval}.
7934 @comment options: mpeval -
7935 @example
7936 $ @kbd{m4 mpeval -}
7937 mpeval(`2 / 4')
7938 @result{}0
7939 mpeval(`2 \ 4')
7940 @result{}1\2
7941 mpeval(`2 || 3')
7942 @result{}2
7943 mpeval(`1 && 3')
7944 @result{}3
7945 mpeval(`-1 >> 1')
7946 @result{}-1
7947 mpeval(`-1 >>> 1')
7948 @result{}-1
7949 @end example
7951 @node Shell commands
7952 @chapter Macros for running shell commands
7954 @cindex UNIX commands, running
7955 @cindex executing shell commands
7956 @cindex running shell commands
7957 @cindex shell commands, running
7958 @cindex commands, running shell
7959 There are a few builtin macros in @code{m4} that allow you to run shell
7960 commands from within @code{m4}.
7962 Note that the definition of a valid shell command is system dependent.
7963 On UNIX systems, this is the typical @command{/bin/sh}.  But on other
7964 systems, such as native Windows, the shell has a different syntax of
7965 commands that it understands.  Some examples in this chapter assume
7966 @command{/bin/sh}, and also demonstrate how to quit early with a known
7967 exit value if this is not the case.
7969 @menu
7970 * Platform macros::             Determining the platform
7971 * Syscmd::                      Executing simple commands
7972 * Esyscmd::                     Reading the output of commands
7973 * Sysval::                      Exit status
7974 * Mkstemp::                     Making temporary files
7975 * Mkdtemp::                     Making temporary directories
7976 @end menu
7978 @node Platform macros
7979 @section Determining the platform
7981 @cindex platform macros
7982 Sometimes it is desirable for an input file to know which platform
7983 @code{m4} is running on.  GNU @code{m4} provides several
7984 macros that are predefined to expand to the empty string; checking for
7985 their existence will confirm platform details.
7987 @deffn {Optional builtin (gnu)} __os2__
7988 @deffnx {Optional builtin (traditional)} os2
7989 @deffnx {Optional builtin (gnu)} __unix__
7990 @deffnx {Optional builtin (traditional)} unix
7991 @deffnx {Optional builtin (gnu)} __windows__
7992 @deffnx {Optional builtin (traditional)} windows
7993 Each of these macros is conditionally defined as needed to describe the
7994 environment of @code{m4}.  If defined, each macro expands to the empty
7995 string.
7996 @end deffn
7998 On UNIX systems, GNU @code{m4} will define @code{@w{__unix__}}
7999 in the @samp{gnu} module, and @code{unix} in the @samp{traditional}
8000 module.
8002 On native Windows systems, GNU @code{m4} will define
8003 @code{@w{__windows__}} in the @samp{gnu} module, and @code{windows} in
8004 the @samp{traditional} module.
8006 On OS/2 systems, GNU @code{m4} will define @code{@w{__os2__}}
8007 in the @samp{gnu} module, and @code{os2} in the @samp{traditional}
8008 module.
8010 If GNU M4 does not provide a platform macro for your system,
8011 please report that as a bug.
8013 @example
8014 define(`provided', `0')
8015 @result{}
8016 ifdef(`__unix__', `define(`provided', incr(provided))')
8017 @result{}
8018 ifdef(`__windows__', `define(`provided', incr(provided))')
8019 @result{}
8020 ifdef(`__os2__', `define(`provided', incr(provided))')
8021 @result{}
8022 provided
8023 @result{}1
8024 @end example
8026 @node Syscmd
8027 @section Executing simple commands
8029 Any shell command can be executed, using @code{syscmd}:
8031 @deffn {Builtin (m4)} syscmd (@var{shell-command})
8032 Executes @var{shell-command} as a shell command.
8034 The expansion of @code{syscmd} is void, @emph{not} the output from
8035 @var{shell-command}!  Output or error messages from @var{shell-command}
8036 are not read by @code{m4}.  @xref{Esyscmd}, if you need to process the
8037 command output.
8039 Prior to executing the command, @code{m4} flushes its buffers.
8040 The default standard input, output and error of @var{shell-command} are
8041 the same as those of @code{m4}.
8043 By default, the @var{shell-command} will be used as the argument to the
8044 @option{-c} option of the @command{/bin/sh} shell (or the version of
8045 @command{sh} specified by @samp{command -p getconf PATH}, if your system
8046 supports that).  If you prefer a different shell, the
8047 @command{configure} script can be given the option
8048 @option{--with-syscmd-shell=@var{location}} to set the location of an
8049 alternative shell at GNU @code{m4} installation; the
8050 alternative shell must still support @option{-c}.
8052 When the @option{--safer} option (@pxref{Operation modes, , Invoking
8053 m4}) is in effect, @code{syscmd} results in an error, since otherwise an
8054 input file could execute arbitrary code.
8056 The macro @code{syscmd} is recognized only with parameters.
8057 @end deffn
8059 @example
8060 define(`foo', `FOO')
8061 @result{}
8062 syscmd(`echo foo')
8063 @result{}foo
8064 @result{}
8065 @end example
8067 Note how the expansion of @code{syscmd} keeps the trailing newline of
8068 the command, as well as using the newline that appeared after the macro.
8070 The following is an example of @var{shell-command} using the same
8071 standard input as @code{m4}:
8073 @comment The testsuite does not know how to parse pipes from the
8074 @comment texinfo.  Fortunately, there are other tests in the testsuite
8075 @comment that test this same feature.
8076 @comment ignore
8077 @example
8078 $ @kbd{echo "m4wrap(\`syscmd(\`cat')')" | m4}
8079 @result{}
8080 @end example
8082 It tells @code{m4} to read all of its input before executing the wrapped
8083 text, then hands a valid (albeit emptied) pipe as standard input for the
8084 @code{cat} subcommand.  Therefore, you should be careful when using
8085 standard input (either by specifying no files, or by passing @samp{-} as
8086 a file name on the command line, @pxref{Command line files, , Invoking
8087 m4}), and also invoking subcommands via @code{syscmd} or @code{esyscmd}
8088 that consume data from standard input.  When standard input is a
8089 seekable file, the subprocess will pick up with the next character not
8090 yet processed by @code{m4}; when it is a pipe or other non-seekable
8091 file, there is no guarantee how much data will already be buffered by
8092 @code{m4} and thus unavailable to the child.
8094 Following is an example of how potentially unsafe actions can be
8095 suppressed.
8097 @comment options: --safer
8098 @comment status: 1
8099 @example
8100 $ @kbd{m4 --safer}
8101 syscmd(`echo hi')
8102 @error{}m4:stdin:1: syscmd: disabled by --safer
8103 @result{}
8104 @end example
8106 @node Esyscmd
8107 @section Reading the output of commands
8109 @cindex GNU extensions
8110 If you want @code{m4} to read the output of a shell command, use
8111 @code{esyscmd}:
8113 @deffn {Builtin (gnu)} esyscmd (@var{shell-command})
8114 Expands to the standard output of the shell command
8115 @var{shell-command}.
8117 Prior to executing the command, @code{m4} flushes its buffers.
8118 The default standard input and standard error of @var{shell-command} are
8119 the same as those of @code{m4}.  The error output of @var{shell-command}
8120 is not a part of the expansion: it will appear along with the error
8121 output of @code{m4}.
8123 By default, the @var{shell-command} will be used as the argument to the
8124 @option{-c} option of the @command{/bin/sh} shell (or the version of
8125 @command{sh} specified by @samp{command -p getconf PATH}, if your system
8126 supports that).  If you prefer a different shell, the
8127 @command{configure} script can be given the option
8128 @option{--with-syscmd-shell=@var{location}} to set the location of an
8129 alternative shell at GNU @code{m4} installation; the
8130 alternative shell must still support @option{-c}.
8132 When the @option{--safer} option (@pxref{Operation modes, , Invoking
8133 m4}) is in effect, @code{esyscmd} results in an error, since otherwise
8134 an input file could execute arbitrary code.
8136 The macro @code{esyscmd} is recognized only with parameters.
8137 @end deffn
8139 @example
8140 define(`foo', `FOO')
8141 @result{}
8142 esyscmd(`echo foo')
8143 @result{}FOO
8144 @result{}
8145 @end example
8147 Note how the expansion of @code{esyscmd} keeps the trailing newline of
8148 the command, as well as using the newline that appeared after the macro.
8150 Just as with @code{syscmd}, care must be exercised when sharing standard
8151 input between @code{m4} and the child process of @code{esyscmd}.
8152 Likewise, potentially unsafe actions can be suppressed.
8154 @comment options: --safer
8155 @comment status: 1
8156 @example
8157 $ @kbd{m4 --safer}
8158 esyscmd(`echo hi')
8159 @error{}m4:stdin:1: esyscmd: disabled by --safer
8160 @result{}
8161 @end example
8163 @node Sysval
8164 @section Exit status
8166 @cindex UNIX commands, exit status from
8167 @cindex exit status from shell commands
8168 @cindex shell commands, exit status from
8169 @cindex commands, exit status from shell
8170 @cindex status of shell commands
8171 To see whether a shell command succeeded, use @code{sysval}:
8173 @deffn {Builtin (m4)} sysval
8174 Expands to the exit status of the last shell command run with
8175 @code{syscmd} or @code{esyscmd}.  Expands to 0 if no command has been
8176 run yet.
8177 @end deffn
8179 @example
8180 sysval
8181 @result{}0
8182 syscmd(`false')
8183 @result{}
8184 ifelse(sysval, `0', `zero', `non-zero')
8185 @result{}non-zero
8186 syscmd(`exit 2')
8187 @result{}
8188 sysval
8189 @result{}2
8190 syscmd(`true')
8191 @result{}
8192 sysval
8193 @result{}0
8194 esyscmd(`false')
8195 @result{}
8196 ifelse(sysval, `0', `zero', `non-zero')
8197 @result{}non-zero
8198 esyscmd(`echo dnl && exit 127')
8199 @result{}
8200 sysval
8201 @result{}127
8202 esyscmd(`true')
8203 @result{}
8204 sysval
8205 @result{}0
8206 @end example
8208 @code{sysval} results in 127 if there was a problem executing the
8209 command, for example, if the system-imposed argument length is exceeded,
8210 or if there were not enough resources to fork.  It is not possible to
8211 distinguish between failed execution and successful execution that had
8212 an exit status of 127, unless there was output from the child process.
8214 On UNIX platforms, where it is possible to detect when command execution
8215 is terminated by a signal, rather than a normal exit, the result is the
8216 signal number shifted left by eight bits.
8218 @comment This test has difficulties being portable, even on platforms
8219 @comment where syscmd invokes /bin/sh.  Kill is not portable with signal
8220 @comment names.  According to autoconf, the only portable signal numbers
8221 @comment are 1 (HUP), 2 (INT), 9 (KILL), 13 (PIPE) and 15 (TERM).  But
8222 @comment all shells handle SIGINT, and ksh handles HUP (as in, the shell
8223 @comment exits normally rather than letting the signal terminate it).
8224 @comment Also, TERM is flaky, as it can also kill the running m4 on
8225 @comment systems where /bin/sh does not create its own process group.
8226 @comment And PIPE is unreliable, since people tend to run with it
8227 @comment ignored, with m4 inheriting that choice.  That leaves KILL as
8228 @comment the only signal we can reliably test.
8229 @example
8230 dnl This test assumes kill is a shell builtin, and that signals are
8231 dnl recognizable.
8232 ifdef(`__unix__', ,
8233       `errprint(` skipping: syscmd does not have unix semantics
8234 ')m4exit(`77')')dnl
8235 syscmd(`kill -9 $$')
8236 @result{}
8237 sysval
8238 @result{}2304
8239 syscmd()
8240 @result{}
8241 sysval
8242 @result{}0
8243 esyscmd(`kill -9 $$')
8244 @result{}
8245 sysval
8246 @result{}2304
8247 @end example
8249 When the @option{--safer} option (@pxref{Operation modes, , Invoking
8250 m4}) is in effect, @code{sysval} will always remain at its default value
8251 of zero.
8253 @comment options: --safer
8254 @comment status: 1
8255 @example
8256 $ @kbd{m4 --safer}
8257 sysval
8258 @result{}0
8259 syscmd(`false')
8260 @error{}m4:stdin:2: syscmd: disabled by --safer
8261 @result{}
8262 sysval
8263 @result{}0
8264 @end example
8266 @node Mkstemp
8267 @section Making temporary files
8269 @cindex temporary file names
8270 @cindex files, names of temporary
8271 Commands specified to @code{syscmd} or @code{esyscmd} might need a
8272 temporary file, for output or for some other purpose.  There is a
8273 builtin macro, @code{mkstemp}, for making a temporary file:
8275 @deffn {Builtin (m4)} mkstemp (@var{template})
8276 @deffnx {Builtin (m4)} maketemp (@var{template})
8277 Expands to the quoted name of a new, empty file, made from the string
8278 @var{template}, which should end with the string @samp{XXXXXX}.  The six
8279 @samp{X} characters are then replaced with random characters matching
8280 the regular expression @samp{[a-zA-Z0-9._-]}, in order to make the file
8281 name unique.  If fewer than six @samp{X} characters are found at the end
8282 of @code{template}, the result will be longer than the template.  The
8283 created file will have access permissions as if by @kbd{chmod =rw,go=},
8284 meaning that the current umask of the @code{m4} process is taken into
8285 account, and at most only the current user can read and write the file.
8287 The traditional behavior, standardized by POSIX, is that
8288 @code{maketemp} merely replaces the trailing @samp{X} with the process
8289 id, without creating a file or quoting the expansion, and without
8290 ensuring that the resulting
8291 string is a unique file name.  In part, this means that using the same
8292 @var{template} twice in the same input file will result in the same
8293 expansion.  This behavior is a security hole, as it is very easy for
8294 another process to guess the name that will be generated, and thus
8295 interfere with a subsequent use of @code{syscmd} trying to manipulate
8296 that file name.  Hence, POSIX has recommended that all new
8297 implementations of @code{m4} provide the secure @code{mkstemp} builtin,
8298 and that users of @code{m4} check for its existence.
8300 The expansion is void and an error issued if a temporary file could
8301 not be created.
8303 When the @option{--safer} option (@pxref{Operation modes, Invoking m4})
8304 is in effect, @code{mkstemp} and GNU-mode @code{maketemp}
8305 result in an error, since otherwise an input file could perform a mild
8306 denial-of-service attack by filling up a disk with multiple empty files.
8308 The macros @code{mkstemp} and @code{maketemp} are recognized only with
8309 parameters.
8310 @end deffn
8312 If you try this next example, you will most likely get different output
8313 for the two file names, since the replacement characters are randomly
8314 chosen:
8316 @comment ignore
8317 @example
8318 $ @kbd{m4}
8319 define(`tmp', `oops')
8320 @result{}
8321 maketemp(`/tmp/fooXXXXXX')
8322 @error{}m4:stdin:1: warning: maketemp: recommend using mkstemp instead
8323 @result{}/tmp/fooa07346
8324 ifdef(`mkstemp', `define(`maketemp', defn(`mkstemp'))',
8325       `define(`mkstemp', defn(`maketemp'))dnl
8326 errprint(`warning: potentially insecure maketemp implementation
8327 ')')
8328 @result{}
8329 mkstemp(`doc')
8330 @result{}docQv83Uw
8331 @end example
8333 @comment options: --safer
8334 @comment status: 1
8335 @example
8336 $ @kbd{m4 --safer}
8337 maketemp(`/tmp/fooXXXXXX')
8338 @error{}m4:stdin:1: warning: maketemp: recommend using mkstemp instead
8339 @error{}m4:stdin:1: maketemp: disabled by --safer
8340 @result{}
8341 mkstemp(`/tmp/fooXXXXXX')
8342 @error{}m4:stdin:2: mkstemp: disabled by --safer
8343 @result{}
8344 @end example
8346 @cindex GNU extensions
8347 Unless you use the @option{--traditional} command line option (or
8348 @option{-G}, @pxref{Limits control, , Invoking m4}), the GNU
8349 version of @code{maketemp} is secure.  This means that using the same
8350 template to multiple calls will generate multiple files.  However, we
8351 recommend that you use the new @code{mkstemp} macro, introduced in
8352 GNU M4 1.4.8, which is secure even in traditional mode.  Also,
8353 as of M4 1.4.11, the secure implementation quotes the resulting file
8354 name, so that you are guaranteed to know what file was created even if
8355 the random file name happens to match an existing macro.  Notice that
8356 this example is careful to use @code{defn} to avoid unintended expansion
8357 of @samp{foo}.
8359 @example
8360 $ @kbd{m4}
8361 define(`foo', `errprint(`oops')')
8362 @result{}
8363 syscmd(`rm -f foo-??????')sysval
8364 @result{}0
8365 define(`file1', maketemp(`foo-XXXXXX'))dnl
8366 @error{}m4:stdin:3: warning: maketemp: recommend using mkstemp instead
8367 ifelse(esyscmd(`echo \` foo-?????? \''), `foo-??????',
8368        `no file', `created')
8369 @result{}created
8370 define(`file2', maketemp(`foo-XX'))dnl
8371 @error{}m4:stdin:6: warning: maketemp: recommend using mkstemp instead
8372 define(`file3', mkstemp(`foo-XXXXXX'))dnl
8373 ifelse(len(defn(`file1')), len(defn(`file2')),
8374        `same length', `different')
8375 @result{}same length
8376 ifelse(defn(`file1'), defn(`file2'), `same', `different file')
8377 @result{}different file
8378 ifelse(defn(`file2'), defn(`file3'), `same', `different file')
8379 @result{}different file
8380 ifelse(defn(`file1'), defn(`file3'), `same', `different file')
8381 @result{}different file
8382 syscmd(`rm 'defn(`file1') defn(`file2') defn(`file3'))
8383 @result{}
8384 sysval
8385 @result{}0
8386 @end example
8388 @comment options: -G
8389 @example
8390 $ @kbd{m4 -G}
8391 syscmd(`rm -f foo-*')sysval
8392 @result{}0
8393 define(`file1', maketemp(`foo-XXXXXX'))dnl
8394 @error{}m4:stdin:2: warning: maketemp: recommend using mkstemp instead
8395 define(`file2', maketemp(`foo-XXXXXX'))dnl
8396 @error{}m4:stdin:3: warning: maketemp: recommend using mkstemp instead
8397 ifelse(file1, file2, `same', `different file')
8398 @result{}same
8399 len(maketemp(`foo-XXXXX'))
8400 @error{}m4:stdin:5: warning: maketemp: recommend using mkstemp instead
8401 @result{}9
8402 define(`abc', `def')
8403 @result{}
8404 maketemp(`foo-abc')
8405 @result{}foo-def
8406 @error{}m4:stdin:7: warning: maketemp: recommend using mkstemp instead
8407 syscmd(`test -f foo-*')sysval
8408 @result{}1
8409 @end example
8411 @node Mkdtemp
8412 @section Making temporary directories
8414 @cindex temporary directory
8415 @cindex directories, temporary
8416 @cindex GNU extensions
8417 Commands specified to @code{syscmd} or @code{esyscmd} might need a
8418 temporary directory, for holding multiple temporary files; such a
8419 directory can be created with @code{mkdtemp}:
8421 @deffn {Builtin (gnu)} mkdtemp (@var{template})
8422 Expands to the quoted name of a new, empty directory, made from the string
8423 @var{template}, which should end with the string @samp{XXXXXX}.  The six
8424 @samp{X} characters are then replaced with random characters matching
8425 the regular expression @samp{[a-zA-Z0-9._-]}, in order to make the name
8426 unique.  If fewer than six @samp{X} characters are found at the end of
8427 @code{template}, the result will be longer than the template.  The
8428 created directory will have access permissions as if by @kbd{chmod
8429 =rwx,go=}, meaning that the current umask of the @code{m4} process is
8430 taken into account, and at most only the current user can read, write,
8431 and search the directory.
8433 The expansion is void and an error issued if a temporary directory could
8434 not be created.
8436 When the @option{--safer} option (@pxref{Operation modes, Invoking m4})
8437 is in effect, @code{mkdtemp} results in an error, since otherwise an
8438 input file could perform a mild denial-of-service attack by filling up a
8439 disk with multiple directories.
8441 The macro @code{mkdtemp} is recognized only with parameters.
8442 This macro was added in M4 2.0.
8443 @end deffn
8445 If you try this next example, you will most likely get different output
8446 for the directory names, since the replacement characters are randomly
8447 chosen:
8449 @comment ignore
8450 @example
8451 $ @kbd{m4}
8452 define(`tmp', `oops')
8453 @result{}
8454 mkdtemp(`/tmp/fooXXXXXX')
8455 @result{}/tmp/foo2h89Vo
8456 mkdtemp(`dir)
8457 @result{}dirrg079A
8458 @end example
8460 @comment options: --safer
8461 @comment status: 1
8462 @example
8463 $ @kbd{m4 --safer}
8464 mkdtemp(`/tmp/fooXXXXXX')
8465 @error{}m4:stdin:1: mkdtemp: disabled by --safer
8466 @result{}
8467 @end example
8469 Multiple calls with the same template will generate multiple
8470 directories.
8472 @example
8473 $ @kbd{m4}
8474 syscmd(`echo foo??????')dnl
8475 @result{}foo??????
8476 define(`dir1', mkdtemp(`fooXXXXXX'))dnl
8477 ifelse(esyscmd(`echo foo??????'), `foo??????', `no dir', `created')
8478 @result{}created
8479 define(`dir2', mkdtemp(`fooXXXXXX'))dnl
8480 ifelse(dir1, dir2, `same', `different directories')
8481 @result{}different directories
8482 syscmd(`rmdir 'dir1 dir2)
8483 @result{}
8484 sysval
8485 @result{}0
8486 @end example
8488 @node Miscellaneous
8489 @chapter Miscellaneous builtin macros
8491 This chapter describes various builtins, that do not really belong in
8492 any of the previous chapters.
8494 @menu
8495 * Errprint::                    Printing error messages
8496 * Location::                    Printing current location
8497 * M4exit::                      Exiting from @code{m4}
8498 * Syncoutput::                  Turning on and off sync lines
8499 @end menu
8501 @node Errprint
8502 @section Printing error messages
8504 @cindex printing error messages
8505 @cindex error messages, printing
8506 @cindex messages, printing error
8507 @cindex standard error, output to
8508 You can print error messages using @code{errprint}:
8510 @deffn {Builtin (m4)} errprint (@var{message}, @dots{})
8511 Prints @var{message} and the rest of the arguments to standard error,
8512 separated by spaces.  Standard error is used, regardless of the
8513 @option{--debugfile} option (@pxref{Debugging options, , Invoking m4}).
8515 The expansion of @code{errprint} is void.
8516 The macro @code{errprint} is recognized only with parameters.
8517 @end deffn
8519 @example
8520 errprint(`Invalid arguments to forloop
8522 @error{}Invalid arguments to forloop
8523 @result{}
8524 errprint(`1')errprint(`2',`3
8526 @error{}12 3
8527 @result{}
8528 @end example
8530 A trailing newline is @emph{not} printed automatically, so it should be
8531 supplied as part of the argument, as in the example.  Unfortunately, the
8532 exact output of @code{errprint} is not very portable to other @code{m4}
8533 implementations: POSIX requires that all arguments be printed,
8534 but some implementations of @code{m4} only print the first.
8535 Furthermore, some BSD implementations always append a newline
8536 for each @code{errprint} call, regardless of whether the last argument
8537 already had one, and POSIX is silent on whether this is
8538 acceptable.
8540 @node Location
8541 @section Printing current location
8543 @cindex location, input
8544 @cindex input location
8545 To make it possible to specify the location of an error, three
8546 utility builtins exist:
8548 @deffn {Builtin (gnu)} __file__
8549 @deffnx {Builtin (gnu)} __line__
8550 @deffnx {Builtin (gnu)} __program__
8551 Expand to the quoted name of the current input file, the
8552 current input line number in that file, and the quoted name of the
8553 current invocation of @code{m4}.
8554 @end deffn
8556 @example
8557 errprint(__program__:__file__:__line__: `input error
8559 @error{}m4:stdin:1: input error
8560 @result{}
8561 @end example
8563 Line numbers start at 1 for each file.  If the file was found due to the
8564 @option{-I} option or @env{M4PATH} environment variable, that is
8565 reflected in the file name.  Synclines, via @code{syncoutput}
8566 (@pxref{Syncoutput}) or the command line option @option{--synclines}
8567 (or @option{-s}, @pxref{Preprocessor features, , Invoking m4}), and the
8568 @samp{f} and @samp{l} flags of @code{debugmode} (@pxref{Debugmode}),
8569 also use this notion of current file and line.  Redefining the three
8570 location macros has no effect on syncline, debug, warning, or error
8571 message output.
8573 This example reuses the file @file{incl.m4} mentioned earlier
8574 (@pxref{Include}):
8576 @comment examples
8577 @example
8578 $ @kbd{m4 -I doc/examples}
8579 define(`foo', ``$0' called at __file__:__line__')
8580 @result{}
8582 @result{}foo called at stdin:2
8583 include(`incl.m4')
8584 @result{}Include file start
8585 @result{}foo called at doc/examples/incl.m4:2
8586 @result{}Include file end
8587 @result{}
8588 @end example
8590 The location of macros invoked during the rescanning of macro expansion
8591 text corresponds to the location in the file where the expansion was
8592 triggered, regardless of how many newline characters the expansion text
8593 contains.  As of GNU M4 1.4.8, the location of text wrapped
8594 with @code{m4wrap} (@pxref{M4wrap}) is the point at which the
8595 @code{m4wrap} was invoked.  Previous versions, however, behaved as
8596 though wrapped text came from line 0 of the file ``''.
8598 @example
8599 define(`echo', `$@@')
8600 @result{}
8601 define(`foo', `echo(__line__
8602 __line__)')
8603 @result{}
8604 echo(__line__
8605 __line__)
8606 @result{}4
8607 @result{}5
8608 m4wrap(`foo
8610 @result{}
8611 foo(errprint(__line__
8612 __line__
8614 @error{}8
8615 @error{}9
8616 @result{}8
8617 @result{}8
8618 __line__
8619 @result{}11
8620 m4wrap(`__line__
8622 @result{}
8624 @result{}6
8625 @result{}6
8626 @result{}12
8627 @end example
8629 The @code{@w{__program__}} macro behaves like @samp{$0} in shell
8630 terminology.  If you invoke @code{m4} through an absolute path or a link
8631 with a different spelling, rather than by relying on a @env{PATH} search
8632 for plain @samp{m4}, it will affect how @code{@w{__program__}} expands.
8633 The intent is that you can use it to produce error messages with the
8634 same formatting that @code{m4} produces internally.  It can also be used
8635 within @code{syscmd} (@pxref{Syscmd}) to pick the same version of
8636 @code{m4} that is currently running, rather than whatever version of
8637 @code{m4} happens to be first in @env{PATH}.  It was first introduced in
8638 GNU M4 1.4.6.
8640 @node M4exit
8641 @section Exiting from @code{m4}
8643 @cindex exiting from @code{m4}
8644 @cindex status, setting @code{m4} exit
8645 If you need to exit from @code{m4} before the entire input has been
8646 read, you can use @code{m4exit}:
8648 @deffn {Builtin (m4)} m4exit (@ovar{code})
8649 Causes @code{m4} to exit, with exit status @var{code}.  If @var{code} is
8650 left out, the exit status is zero.  If @var{code} cannot be parsed, or
8651 is outside the range of 0 to 255, the exit status is one.  No further
8652 input is read, and all wrapped and diverted text is discarded.
8653 @end deffn
8655 @example
8656 m4wrap(`This text is lost due to `m4exit'.')
8657 @result{}
8658 divert(`1') So is this.
8659 divert
8660 @result{}
8661 m4exit And this is never read.
8662 @end example
8664 A common use of this is to abort processing:
8666 @deffn Composite fatal_error (@var{message})
8667 Abort processing with an error message and non-zero status.  Prefix
8668 @var{message} with details about where the error occurred, and print the
8669 resulting string to standard error.
8670 @end deffn
8672 @comment status: 1
8673 @example
8674 define(`fatal_error',
8675        `errprint(__program__:__file__:__line__`: fatal error: $*
8676 ')m4exit(`1')')
8677 @result{}
8678 fatal_error(`this is a BAD one, buster')
8679 @error{}m4:stdin:4: fatal error: this is a BAD one, buster
8680 @end example
8682 After this macro call, @code{m4} will exit with exit status 1.  This macro
8683 is only intended for error exits, since the normal exit procedures are
8684 not followed, i.e., diverted text is not undiverted, and saved text
8685 (@pxref{M4wrap}) is not reread.  (This macro could be made more robust
8686 to earlier versions of @code{m4}.  You should try to see if you can find
8687 weaknesses and correct them; or @pxref{Improved fatal_error, , Answers}).
8689 Note that it is still possible for the exit status to be different than
8690 what was requested by @code{m4exit}.  If @code{m4} detects some other
8691 error, such as a write error on standard output, the exit status will be
8692 non-zero even if @code{m4exit} requested zero.
8694 If standard input is seekable, then the file will be positioned at the
8695 next unread character.  If it is a pipe or other non-seekable file,
8696 then there are no guarantees how much data @code{m4} might have read
8697 into buffers, and thus discarded.
8699 @node Syncoutput
8700 @section Turning on and off sync lines
8702 @cindex toggling synchronization lines
8703 @cindex synchronization lines
8704 @cindex location, input
8705 @cindex input location
8706 It is possible to adjust whether synclines are printed to output:
8708 @deffn {Builtin (gnu)} syncoutput (@var{truth})
8709 If @var{truth} matches the extended regular expression
8710 @samp{^[1yY]|^([oO][nN])}, it causes @code{m4} to emit sync lines of the
8711 form: @samp{#line <number> ["<file>"]}.
8713 If @var{truth} is empty, or matches the extended regular expression
8714 @samp{^[0nN]|^([oO][fF])}, it causes @code{m4} to turn sync lines off.
8716 All other arguments are ignored and issue a warning.
8718 The macro @code{syncoutput} is recognized only with parameters.
8719 This macro was added in M4 2.0.
8720 @end deffn
8722 @example
8723 define(`twoline', `1
8725 @result{}
8726 changecom(`/*', `*/')
8727 @result{}
8728 define(`comment', `/*1
8729 2*/')
8730 @result{}
8731 twoline
8732 @result{}1
8733 @result{}2
8734 dnl no line
8735 syncoutput(`on')
8736 @result{}#line 8 "stdin"
8737 @result{}
8738 twoline
8739 @result{}1
8740 @result{}#line 9
8741 @result{}2
8742 dnl no line
8743 hello
8744 @result{}#line 11
8745 @result{}hello
8746 comment
8747 @result{}/*1
8748 @result{}2*/
8749 one comment `two
8750 three'
8751 @result{}#line 13
8752 @result{}one /*1
8753 @result{}2*/ two
8754 @result{}three
8755 goodbye
8756 @result{}#line 15
8757 @result{}goodbye
8758 syncoutput(`off')
8759 @result{}
8760 twoline
8761 @result{}1
8762 @result{}2
8763 syncoutput(`blah')
8764 @error{}m4:stdin:18: warning: syncoutput: unknown directive 'blah'
8765 @result{}
8766 @end example
8768 Notice that a syncline is output any time a single source line expands
8769 to multiple output lines, or any time multiple source lines expand to a
8770 single output line.  When there is a one-for-one correspondence, no
8771 additional synclines are needed.
8773 Synchronization lines can be used to track where input comes from; an
8774 optional file designation is printed when the syncline algorithm
8775 detects that consecutive output lines come from different files.  You
8776 can also use the @option{--synclines} command-line option (or
8777 @option{-s}, @pxref{Preprocessor features, , Invoking m4}) to start
8778 with synchronization on.  This example reuses the file @file{incl.m4}
8779 mentioned earlier (@pxref{Include}):
8781 @comment examples
8782 @comment options: -s
8783 @example
8784 $ @kbd{m4 --synclines -I doc/examples}
8785 include(`incl.m4')
8786 @result{}#line 1 "doc/examples/incl.m4"
8787 @result{}Include file start
8788 @result{}foo
8789 @result{}Include file end
8790 @result{}#line 1 "stdin"
8791 @result{}
8792 @end example
8794 @node Frozen files
8795 @chapter Fast loading of frozen state
8797 Some bigger @code{m4} applications may be built over a common base
8798 containing hundreds of definitions and other costly initializations.
8799 Usually, the common base is kept in one or more declarative files,
8800 which files are listed on each @code{m4} invocation prior to the
8801 user's input file, or else each input file uses @code{include}.
8803 Reading the common base of a big application, over and over again, may
8804 be time consuming.  GNU @code{m4} offers some machinery to
8805 speed up the start of an application using lengthy common bases.
8807 @menu
8808 * Using frozen files::          Using frozen files
8809 * Frozen file format 1::        Frozen file format 1
8810 * Frozen file format 2::        Frozen file format 2
8811 @end menu
8813 @node Using frozen files
8814 @section Using frozen files
8816 @cindex fast loading of frozen files
8817 @cindex frozen files for fast loading
8818 @cindex initialization, frozen state
8819 @cindex dumping into frozen file
8820 @cindex reloading a frozen file
8821 @cindex GNU extensions
8822 Suppose a user has a library of @code{m4} initializations in
8823 @file{base.m4}, which is then used with multiple input files:
8825 @comment ignore
8826 @example
8827 $ @kbd{m4 base.m4 input1.m4}
8828 $ @kbd{m4 base.m4 input2.m4}
8829 $ @kbd{m4 base.m4 input3.m4}
8830 @end example
8832 Rather than spending time parsing the fixed contents of @file{base.m4}
8833 every time, the user might rather execute:
8835 @comment ignore
8836 @example
8837 $ @kbd{m4 -F base.m4f base.m4}
8838 @end example
8840 @noindent
8841 once, and further execute, as often as needed:
8843 @comment ignore
8844 @example
8845 $ @kbd{m4 -R base.m4f input1.m4}
8846 $ @kbd{m4 -R base.m4f input2.m4}
8847 $ @kbd{m4 -R base.m4f input3.m4}
8848 @end example
8850 @noindent
8851 with the varying input.  The first call, containing the @option{-F}
8852 option, only reads and executes file @file{base.m4}, defining
8853 various application macros and computing other initializations.
8854 Once the input file @file{base.m4} has been completely processed, GNU
8855 @code{m4} produces in @file{base.m4f} a @dfn{frozen} file, that is, a
8856 file which contains a kind of snapshot of the @code{m4} internal state.
8858 Later calls, containing the @option{-R} option, are able to reload
8859 the internal state of @code{m4}, from @file{base.m4f},
8860 @emph{prior} to reading any other input files.  This means
8861 instead of starting with a virgin copy of @code{m4}, input will be
8862 read after having effectively recovered the effect of a prior run.
8863 In our example, the effect is the same as if file @file{base.m4} has
8864 been read anew.  However, this effect is achieved a lot faster.
8866 Only one frozen file may be created or read in any one @code{m4}
8867 invocation.  It is not possible to recover two frozen files at once.
8868 However, frozen files may be updated incrementally, through using
8869 @option{-R} and @option{-F} options simultaneously.  For example, if
8870 some care is taken, the command:
8872 @comment ignore
8873 @example
8874 $ @kbd{m4 file1.m4 file2.m4 file3.m4 file4.m4}
8875 @end example
8877 @noindent
8878 could be broken down in the following sequence, accumulating the same
8879 output:
8881 @comment ignore
8882 @example
8883 $ @kbd{m4 -F file1.m4f file1.m4}
8884 $ @kbd{m4 -R file1.m4f -F file2.m4f file2.m4}
8885 $ @kbd{m4 -R file2.m4f -F file3.m4f file3.m4}
8886 $ @kbd{m4 -R file3.m4f file4.m4}
8887 @end example
8889 Some care is necessary because the frozen file does not save all state
8890 information.  Stacks of macro definitions via @code{pushdef} are
8891 accurately stored, along with all renamed or undefined builtins, as are
8892 the current syntax rules such as from @code{changequote}.  However, the
8893 value of @code{sysval} and text saved in @code{m4wrap} are not currently
8894 preserved.  Also, changing command line options between runs may cause
8895 unexpected behavior.  A future release of GNU M4 may improve
8896 on the quality of frozen files.
8898 When an @code{m4} run is to be frozen, the automatic undiversion
8899 which takes place at end of execution is inhibited.  Instead, all
8900 positively numbered diversions are saved into the frozen file.
8901 The active diversion number is also transmitted.
8903 A frozen file to be reloaded need not reside in the current directory.
8904 It is looked up the same way as an @code{include} file (@pxref{Search
8905 Path}).
8907 If the frozen file was generated with a newer version of @code{m4}, and
8908 contains directives that an older @code{m4} cannot parse, attempting to
8909 load the frozen file with option @option{-R} will cause @code{m4} to
8910 exit with status 63 to indicate version mismatch.
8912 @node Frozen file format 1
8913 @section Frozen file format 1
8915 @cindex frozen file format 1
8916 @cindex file format, frozen file version 1
8917 Frozen files are sharable across architectures.  It is safe to write
8918 a frozen file on one machine and read it on another, given that the
8919 second machine uses the same or newer version of GNU @code{m4}.
8920 It is conventional, but not required, to give a frozen file the suffix
8921 of @code{.m4f}.
8923 Older versions of GNU @code{m4} create frozen files with
8924 syntax version 1.  These files can be read by the current version, but
8925 are no longer produced.  Version 1 files are mostly text files, although
8926 any macros or diversions that contained nonprintable characters or long
8927 lines cause the resulting frozen file to do likewise, since there are no
8928 escape sequences.  The file can be edited to change the state that
8929 @code{m4} will start with.  It is composed of several directives, each
8930 starting with a single letter and ending with a newline (@key{NL}).
8931 Wherever a directive is expected, the character @samp{#} can be used
8932 instead to introduce a comment line; empty lines are also ignored if
8933 they are not part of an embedded string.
8935 In the following descriptions, each @var{len} refers to the length of a
8936 corresponding subsequent @var{str}.  Numbers are always expressed in
8937 decimal, and an omitted number defaults to 0.  The valid directives in
8938 version 1 are:
8940 @table @code
8941 @item V @var{number} @key{NL}
8942 Confirms the format of the file.  Version 1 is recognized when
8943 @var{number} is 1.  This directive must be the first non-comment in the
8944 file, and may not appear more than once.
8946 @item C @var{len1} , @var{len2} @key{NL} @var{str1} @var{str2} @key{NL}
8947 Uses @var{str1} and @var{str2} as the begin-comment and
8948 end-comment strings.  If omitted, then @samp{#} and @key{NL} are the
8949 comment delimiters.
8951 @item D @var{number}, @var{len} @key{NL} @var{str} @key{NL}
8952 Selects diversion @var{number}, making it current, then copy @var{str}
8953 in the current diversion.  @var{number} may be a negative number for a
8954 diversion that discards text.  To merely specify an active selection,
8955 use this command with an empty @var{str}.  With 0 as the diversion
8956 @var{number}, @var{str} will be issued on standard output at reload
8957 time.  GNU @code{m4} will not produce the @samp{D} directive
8958 with non-zero length for diversion 0, but this can be done with manual
8959 edits.  This directive may appear more than once for the same diversion,
8960 in which case the diversion is the concatenation of the various uses.
8961 If omitted, then diversion 0 is current.
8963 @item F @var{len1} , @var{len2} @key{NL} @var{str1} @var{str2} @key{NL}
8964 Defines, through @code{pushdef}, a definition for @var{str1} expanding
8965 to the function whose builtin name is @var{str2}.  If the builtin does
8966 not exist (for example, if the frozen file was produced by a copy of
8967 @code{m4} compiled with the now-abandoned @code{changeword} support),
8968 the reload is silent, but any subsequent use of the definition of
8969 @var{str1} will result in a warning.  This directive may appear more
8970 than once for the same name, and its order, along with @samp{T}, is
8971 important.  If omitted, you will have no access to any builtins.
8973 @item Q @var{len1} , @var{len2} @key{NL} @var{str1} @var{str2} @key{NL}
8974 Uses @var{str1} and @var{str2} as the begin-quote and end-quote
8975 strings.  If omitted, then @samp{`} and @samp{'} are the quote
8976 delimiters.
8978 @item T @var{len1} , @var{len2} @key{NL} @var{str1} @var{str2} @key{NL}
8979 Defines, though @code{pushdef}, a definition for @var{str1}
8980 expanding to the text given by @var{str2}.  This directive may appear
8981 more than once for the same name, and its order, along with @samp{F}, is
8982 important.
8983 @end table
8985 When loading format 1, the syntax categories @samp{@{} and @samp{@}} are
8986 disabled (reverting braces to be treated like plain characters).  This
8987 is because frozen files created with M4 1.4.x did not understand
8988 @samp{$@{@dots{}@}} extended argument notation, and a frozen macro that
8989 contained this character sequence should not behave differently just
8990 because a newer version of M4 reloaded the file.
8992 @node Frozen file format 2
8993 @section Frozen file format 2
8995 @cindex frozen file format 2
8996 @cindex file format, frozen file version 2
8997 The syntax of version 1 has some drawbacks; if any macro or diversion
8998 contained non-printable characters or long lines, the resulting frozen
8999 file would not qualify as a text file, making it harder to edit with
9000 some vendor tools.  The concatenation of multiple strings on a single
9001 line, such as for the @samp{T} directive, makes distinguishing the two
9002 strings a bit more difficult.  Finally, the format lacks support for
9003 several items of @code{m4} state, such that a reloaded file did not
9004 always behave the same as the original file.
9006 These shortcomings have been addressed in version 2 of the frozen file
9007 syntax.  New directives have been added, and existing directives have
9008 additional, and sometimes optional, parameters.  All @var{str} instances
9009 in the grammar are now followed by @key{NL}, which makes the split
9010 between consecutive strings easier to recognize.  Strings may now
9011 contain escape sequences modeled after C, such as @samp{\n} for newline
9012 or @samp{\0} for @sc{nul}, so that the frozen file can be pure
9013 @sc{ascii} (although when hand-editing a frozen file, it is still
9014 acceptable to use the original byte rather than an escape sequence for
9015 all bytes except @samp{\}).  Also in the context of a @var{str}, the
9016 escape sequence @samp{\@key{NL}} is discarded, allowing a user to split
9017 lines that are too long for some platform tools.
9019 @table @code
9020 @item V @var{number} @key{NL}
9021 Confirms the format of the file.  @code{m4} @value{VERSION} only creates
9022 frozen files where @var{number} is 2.  This directive must be the first
9023 non-comment in the file, and may not appear more than once.
9025 @item C @var{len1} , @var{len2} @key{NL} @var{str1} @key{NL} @var{str2} @key{NL}
9026 Uses @var{str1} and @var{str2} as the begin-comment and
9027 end-comment strings.  If omitted, then @samp{#} and @key{NL} are the
9028 comment delimiters.
9030 @item d @var{len} @key{NL} @var{str} @key{NL}
9031 Sets the debug flags, using @var{str} as the argument to
9032 @code{debugmode}.  If omitted, then the debug flags start in their
9033 default disabled state.
9035 @item D @var{number} , @var{len} @key{NL} @var{str} @key{NL}
9036 Selects diversion @var{number}, making it current, then copy @var{str}
9037 in the current diversion.  @var{number} may be a negative number for a
9038 diversion that discards text.  To merely specify an active selection,
9039 use this command with an empty @var{string}.  With 0 as the diversion
9040 @var{number}, @var{str} will be issued on standard output at reload
9041 time.  GNU @code{m4} will not produce the @samp{D} directive
9042 with non-zero length for diversion 0, but this can be done with manual
9043 edits.  This directive may appear more than once for the same diversion,
9044 in which case the diversion is the concatenation of the various uses.
9045 If omitted, then diversion 0 is current.
9047 @comment FIXME - the first usage, with only one string, is not supported
9048 @comment in the current code
9049 @c @item F @var{len1} @key{NL} @var{str1} @key{NL}
9050 @item F @var{len1} , @var{len2} @key{NL} @var{str1} @key{NL} @var{str2} @key{NL}
9051 @itemx F @var{len1} , @var{len2} , @var{len3} @key{NL} @var{str1} @key{NL} @var{str2} @key{NL} @var{str3} @key{NL}
9052 Defines, through @code{pushdef}, a definition for @var{str1} expanding
9053 to the function whose builtin name is given by @var{str2} (defaulting to
9054 @var{str1} if not present).  With two arguments, the builtin name is
9055 searched for among the intrinsic builtin functions only; with three
9056 arguments, the builtin name is searched for amongst the builtin
9057 functions defined by the module named by @var{str3}.
9059 @item M @var{len} @key{NL} @var{str} @key{NL}
9060 Names a module which will be searched for according to the module search
9061 path and loaded.  Modules loaded from a frozen file don't add their
9062 builtin entries to the symbol table.  Modules must be loaded prior to
9063 specifying module-specific builtins via the three-argument @code{F} or
9064 @code{T}.
9066 @item Q @var{len1} , @var{len2} @key{NL} @var{str1} @key{NL} @var{str2} @key{NL}
9067 Uses @var{str1} and @var{str2} as the begin-quote and end-quote strings.
9068 If omitted, then @samp{`} and @samp{'} are the quote delimiters.
9070 @item R @var{len} @key{NL} @var{str} @key{NL}
9071 Sets the default regexp syntax, where @var{str} encodes one of the
9072 regular expression syntaxes supported by GNU M4.
9073 @xref{Changeresyntax}, for more details.
9075 @item S @var{syntax-code} @var{len} @key{NL} @var{str} @key{NL}
9076 Defines, through @code{changesyntax}, a syntax category for each of the
9077 characters in @var{str}.  The @var{syntax-code} must be one of the
9078 characters described in @ref{Changesyntax}.
9080 @item t @var{len} @key{NL} @var{str} @key{NL}
9081 Enables tracing for any macro named @var{str}, similar to using the
9082 @code{traceon} builtin.  This option may occur more than once for
9083 multiple macros; if omitted, no macro starts out as traced.
9085 @item T @var{len1} , @var{len2} @key{NL} @var{str1} @key{NL} @var{str2} @key{NL}
9086 @itemx T @var{len1} , @var{len2} , @var{len3} @key{NL} @var{str1} @key{NL} @var{str2} @key{NL} @var{str3} @key{NL}
9087 Defines, though @code{pushdef}, a definition for @var{str1} expanding to
9088 the text given by @var{str2}.  This directive may appear more than once
9089 for the same name, and its order, along with @samp{F}, is important.  If
9090 present, the optional third argument associates the macro with a module
9091 named by @var{str3}.
9092 @end table
9094 @node Compatibility
9095 @chapter Compatibility with other versions of @code{m4}
9097 @cindex compatibility
9098 This chapter describes the many of the differences between this
9099 implementation of @code{m4}, and of other implementations found under
9100 UNIX, such as System V Release 4, Solaris, and BSD flavors.
9101 In particular, it lists the known differences and extensions to
9102 POSIX.  However, the list is not necessarily comprehensive.
9104 At the time of this writing, POSIX 2001 (also known as IEEE
9105 Std 1003.1-2001) is the latest standard, although a new version of
9106 POSIX is under development and includes several proposals for
9107 modifying what @code{m4} is required to do.  The requirements for
9108 @code{m4} are shared between SUSv3 and POSIX, and
9109 can be viewed at
9110 @uref{http://www.opengroup.org/onlinepubs/@/000095399/@/utilities/@/m4.html}.
9112 @menu
9113 * Extensions::                  Extensions in GNU M4
9114 * Incompatibilities::           Other incompatibilities
9115 * Experiments::                 Experimental features in GNU M4
9116 @end menu
9118 @node Extensions
9119 @section Extensions in GNU M4
9121 @cindex GNU extensions
9122 @cindex POSIX
9123 @cindex @env{POSIXLY_CORRECT}
9124 This version of @code{m4} contains a few facilities that do not exist
9125 in System V @code{m4}.  These extra facilities are all suppressed by
9126 using the @option{-G} command line option, unless overridden by other
9127 command line options.
9128 Most of these extensions are compatible with
9129 @uref{http://www.unix.org/single_unix_specification/,
9130 POSIX}; the few exceptions are suppressed if the
9131 @env{POSIXLY_CORRECT} environment variable is set.
9133 @itemize @bullet
9134 @item
9135 In the @code{$@var{n}} notation for macro arguments, @var{n} can contain
9136 several digits, while the System V @code{m4} only accepts one digit.
9137 This allows macros in GNU @code{m4} to take any number of
9138 arguments, and not only nine (@pxref{Arguments}).
9139 POSIX does not allow this extension, so it is disabled if
9140 @env{POSIXLY_CORRECT} is set.
9141 @c FIXME - update this bullet when ${11} is implemented.
9143 @item
9144 The @code{divert} (@pxref{Divert}) macro can manage more than 9
9145 diversions.  GNU @code{m4} treats all positive numbers as valid
9146 diversions, rather than discarding diversions greater than 9.
9148 @item
9149 Files included with @code{include} and @code{sinclude} are sought in a
9150 user specified search path, if they are not found in the working
9151 directory.  The search path is specified by the @option{-I} option and the
9152 @samp{M4PATH} environment variable (@pxref{Search Path}).
9154 @item
9155 Arguments to @code{undivert} can be non-numeric, in which case the named
9156 file will be included uninterpreted in the output (@pxref{Undivert}).
9158 @item
9159 Formatted output is supported through the @code{format} builtin, which
9160 is modeled after the C library function @code{printf} (@pxref{Format}).
9162 @item
9163 Searches and text substitution through regular expressions are supported
9164 by the @code{regexp} (@pxref{Regexp}) and @code{patsubst}
9165 (@pxref{Patsubst}) builtins.
9167 The syntax of regular expressions in M4 has never been clearly
9168 formalized.  While OpenBSD M4 uses extended regular
9169 expressions for @code{regexp} and @code{patsubst}, GNU M4
9170 defaults to basic regular expressions, but provides
9171 @code{changeresyntax} (@pxref{Changeresyntax}) to change the flavor of
9172 regular expression syntax in use.
9174 @item
9175 The output of shell commands can be read into @code{m4} with
9176 @code{esyscmd} (@pxref{Esyscmd}).
9178 @item
9179 There is indirect access to any builtin macro with @code{builtin}
9180 (@pxref{Builtin}).
9182 @item
9183 Macros can be called indirectly through @code{indir} (@pxref{Indir}).
9185 @item
9186 The name of the program, the current input file, and the current input
9187 line number are accessible through the builtins @code{@w{__program__}},
9188 @code{@w{__file__}}, and @code{@w{__line__}} (@pxref{Location}).
9190 @item
9191 The generation of sync lines can be controlled through @code{syncoutput}
9192 (@pxref{Syncoutput}).
9194 @item
9195 The format of the output from @code{dumpdef} and macro tracing can be
9196 controlled with @code{debugmode} (@pxref{Debugmode}).
9198 @item
9199 The destination of trace and debug output can be controlled with
9200 @code{debugfile} (@pxref{Debugfile}).
9202 @item
9203 The @code{maketemp} (@pxref{Mkstemp}) macro behaves like @code{mkstemp},
9204 creating a new file with a unique name on every invocation, rather than
9205 following the insecure behavior of replacing the trailing @samp{X}
9206 characters with the @code{m4} process id.  POSIX does not
9207 allow this extension, so @code{maketemp} is insecure if
9208 @env{POSIXLY_CORRECT} is set, but you should be using @code{mkstemp} in
9209 the first place.
9211 @item
9212 POSIX only requires support for the command line options
9213 @option{-s}, @option{-D}, and @option{-U}, so all other options accepted
9214 by GNU M4 are extensions.  @xref{Invoking m4}, for a
9215 description of these options.
9217 @item
9218 The debugging and tracing facilities in GNU @code{m4} are much
9219 more extensive than in most other versions of @code{m4}.
9221 @item
9222 Some traditional implementations only allow reading standard input
9223 once, but GNU @code{m4} correctly handles multiple instances
9224 of @samp{-} on the command line.
9226 @item
9227 POSIX requires @code{m4wrap} (@pxref{M4wrap}) to act in FIFO
9228 (first-in, first-out) order, and most other implementations obey this.
9229 However, versions of GNU @code{m4} earlier than 1.6 used
9230 LIFO order.  Furthermore, POSIX states that only the first
9231 argument to @code{m4wrap} is saved for later evaluation, but
9232 GNU @code{m4} saves and processes all arguments, with output
9233 separated by spaces.
9235 @item
9236 POSIX states that builtins that require arguments, but are
9237 called without arguments, have undefined behavior.  Traditional
9238 implementations simply behave as though empty strings had been passed.
9239 For example, @code{a`'define`'b} would expand to @code{ab}.  But
9240 GNU @code{m4} ignores certain builtins if they have missing
9241 arguments, giving @code{adefineb} for the above example.
9242 @end itemize
9244 @node Incompatibilities
9245 @section Other incompatibilities
9247 There are a few other incompatibilities between this implementation of
9248 @code{m4}, and what POSIX requires, or what the System V
9249 version implemented.
9251 @itemize @bullet
9252 @item
9253 Traditional implementations handle @code{define(`f',`1')} (@pxref{Define})
9254 by undefining the entire stack of previous definitions, and if doing
9255 @code{undefine(`f')} first.  GNU @code{m4} replaces just the top
9256 definition on the stack, as if doing @code{popdef(`f')} followed by
9257 @code{pushdef(`f',`1')}.  POSIX allows either behavior.
9259 @item
9260 At one point, POSIX required @code{changequote(@var{arg})}
9261 (@pxref{Changequote}) to use newline as the close quote, but this was a
9262 bug, and the next version of POSIX is anticipated to state
9263 that using empty strings or just one argument is unspecified.
9264 Meanwhile, the GNU @code{m4} behavior of treating an empty
9265 end-quote delimiter as @samp{'} is not portable, as Solaris treats it as
9266 repeating the start-quote delimiter, and BSD treats it as leaving the
9267 previous end-quote delimiter unchanged.  For predictable results, never
9268 call changequote with just one argument, or with empty strings for
9269 arguments.
9271 @item
9272 At one point, POSIX required @code{changecom(@var{arg},)}
9273 (@pxref{Changecom}) to make it impossible to end a comment, but this is
9274 a bug, and the next version of POSIX is anticipated to state
9275 that using empty strings is unspecified.  Meanwhile, the GNU
9276 @code{m4} behavior of treating an empty end-comment delimiter as newline
9277 is not portable, as BSD treats it as leaving the previous end-comment
9278 delimiter unchanged.  It is also impossible in BSD implementations to
9279 disable comments, even though that is required by POSIX.  For
9280 predictable results, never call changecom with empty strings for
9281 arguments.
9283 @item
9284 Traditional implementations allow argument collection, but not string
9285 and comment processing, to span file boundaries.  Thus, if @file{a.m4}
9286 contains @samp{len(}, and @file{b.m4} contains @samp{abc)},
9287 @kbd{m4 a.m4 b.m4} outputs @samp{3} with traditional @code{m4}, but
9288 gives an error message that the end of file was encountered inside a
9289 macro with GNU @code{m4}.  On the other hand, traditional
9290 implementations do end of file processing for files included with
9291 @code{include} or @code{sinclude} (@pxref{Include}), while GNU
9292 @code{m4} seamlessly integrates the content of those files.  Thus
9293 @code{include(`a.m4')include(`b.m4')} will output @samp{3} instead of
9294 giving an error.
9296 @item
9297 POSIX requires @code{eval} (@pxref{Eval}) to treat all
9298 operators with the same precedence as C@.  However, earlier versions of
9299 GNU @code{m4} followed the traditional behavior of other
9300 @code{m4} implementations, where bitwise and logical negation (@samp{~}
9301 and @samp{!}) have lower precedence than equality operators; and where
9302 equality operators (@samp{==} and @samp{!=}) had the same precedence as
9303 relational operators (such as @samp{<}).  Use explicit parentheses to
9304 ensure proper precedence.  As extensions to POSIX,
9305 GNU @code{m4} gives well-defined semantics to operations that
9306 C leaves undefined, such as when overflow occurs, when shifting negative
9307 numbers, or when performing division by zero.  POSIX also
9308 requires @samp{=} to cause an error, but many traditional
9309 implementations allowed it as an alias for @samp{==}.
9311 @item
9312 POSIX 2001 requires @code{translit} (@pxref{Translit}) to
9313 treat each character of the second and third arguments literally.
9314 However, it is anticipated that the next version of POSIX will
9315 allow the GNU @code{m4} behavior of treating @samp{-} as a
9316 range operator.
9318 @item
9319 POSIX requires @code{m4} to honor the locale environment
9320 variables of @env{LANG}, @env{LC_ALL}, @env{LC_CTYPE},
9321 @env{LC_MESSAGES}, and @env{NLSPATH}, but this has not yet been
9322 implemented in GNU @code{m4}.
9324 @item
9325 GNU @code{m4} implements sync lines differently from System V
9326 @code{m4}, when text is being diverted.  GNU @code{m4} outputs
9327 the sync lines when the text is being diverted, and System V @code{m4}
9328 when the diverted text is being brought back.
9330 The problem is which lines and file names should be attached to text
9331 that is being, or has been, diverted.  System V @code{m4} regards all
9332 the diverted text as being generated by the source line containing the
9333 @code{undivert} call, whereas GNU @code{m4} regards the
9334 diverted text as being generated at the time it is diverted.
9336 The sync line option is used mostly when using @code{m4} as
9337 a front end to a compiler.  If a diverted line causes a compiler error,
9338 the error messages should most probably refer to the place where the
9339 diversion was made, and not where it was inserted again.
9341 @comment options: -s
9342 @example
9343 divert(2)2
9344 divert(1)1
9345 divert`'0
9346 @result{}#line 3 "stdin"
9347 @result{}0
9349 @result{}#line 2 "stdin"
9350 @result{}1
9351 @result{}#line 1 "stdin"
9352 @result{}2
9353 @end example
9355 @comment FIXME - this needs to be fixed before 2.0.
9356 The current @code{m4} implementation has a limitation that the syncline
9357 output at the start of each diversion occurs no matter what, even if the
9358 previous diversion did not end with a newline.  This goes contrary to
9359 the claim that synclines appear on a line by themselves, so this
9360 limitation may be corrected in a future version of @code{m4}.  In the
9361 meantime, when using @option{-s}, it is wisest to make sure all
9362 diversions end with newline.
9364 @item
9365 GNU @code{m4} makes no attempt at prohibiting self-referential
9366 definitions like:
9368 @comment ignore
9369 @example
9370 define(`x', `x')
9371 @result{}
9372 define(`x', `x ')
9373 @result{}
9374 @end example
9376 @cindex rescanning
9377 There is nothing inherently wrong with defining @samp{x} to
9378 return @samp{x}.  The wrong thing is to expand @samp{x} unquoted,
9379 because that would cause an infinite rescan loop.
9380 In @code{m4}, one might use macros to hold strings, as we do for
9381 variables in other programming languages, further checking them with:
9383 @comment ignore
9384 @example
9385 ifelse(defn(`@var{holder}'), `@var{value}', @dots{})
9386 @end example
9388 @noindent
9389 In cases like this one, an interdiction for a macro to hold its own name
9390 would be a useless limitation.  Of course, this leaves more rope for the
9391 GNU @code{m4} user to hang himself!  Rescanning hangs may be
9392 avoided through careful programming, a little like for endless loops in
9393 traditional programming languages.
9395 @item
9396 POSIX states that only unquoted leading newlines and blanks
9397 (that is, space and tab) are ignored when collecting macro arguments.
9398 However, this appears to be a bug in POSIX, since most
9399 traditional implementations also ignore all whitespace (formfeed,
9400 carriage return, and vertical tab).  GNU @code{m4} follows
9401 tradition and ignores all leading unquoted whitespace.
9402 @end itemize
9404 @node Experiments
9405 @section Experimental features in GNU M4
9407 Certain features of GNU @code{m4} are experimental.
9409 Some are only available if activated by an option given to
9410 @file{m4-@value{VERSION}/@/configure} at GNU @code{m4} installation
9411 time.  The functionality
9412 might change or even go away in the future.  @emph{Do not rely on it}.
9413 Please direct your comments about it the same way you would do for bugs.
9415 @section Changesyntax
9417 An experimental feature, which improves the flexibility of @code{m4},
9418 allows for changing the way the input is parsed (@pxref{Changesyntax}).
9419 No compile time option is needed for @code{changesyntax}.  The
9420 implementation is careful to not slow down @code{m4} parsing, unlike the
9421 withdrawn experiment of @code{changeword} that appeared earlier in M4
9422 1.4.x.
9424 @section Multiple precision arithmetic
9426 Another experimental feature, which would improve @code{m4} usefulness,
9427 allows for multiple precision rational arithmetic similar to
9428 @code{eval}.  You must have the GNU multi-precision (gmp)
9429 library installed, and should use @kbd{./configure --with-gmp} if you
9430 want this feature compiled in.  The current implementation is unproven
9431 and might go away.  Do not count on it yet.
9433 @node Answers
9434 @chapter Correct version of some examples
9436 Some of the examples in this manuals are buggy or not very robust, for
9437 demonstration purposes.  Improved versions of these composite macros are
9438 presented here.
9440 @menu
9441 * Improved exch::               Solution for @code{exch}
9442 * Improved forloop::            Solution for @code{forloop}
9443 * Improved foreach::            Solution for @code{foreach}
9444 * Improved copy::               Solution for @code{copy}
9445 * Improved m4wrap::             Solution for @code{m4wrap}
9446 * Improved cleardivert::        Solution for @code{cleardivert}
9447 * Improved capitalize::         Solution for @code{capitalize}
9448 * Improved fatal_error::        Solution for @code{fatal_error}
9449 @end menu
9451 @node Improved exch
9452 @section Solution for @code{exch}
9454 The @code{exch} macro (@pxref{Arguments}) as presented requires clients
9455 to double quote their arguments.  A nicer definition, which lets
9456 clients follow the rule of thumb of one level of quoting per level of
9457 parentheses, involves adding quotes in the definition of @code{exch}, as
9458 follows:
9460 @example
9461 define(`exch', ``$2', `$1'')
9462 @result{}
9463 define(exch(`expansion text', `macro'))
9464 @result{}
9465 macro
9466 @result{}expansion text
9467 @end example
9469 @node Improved forloop
9470 @section Solution for @code{forloop}
9472 The @code{forloop} macro (@pxref{Forloop}) as presented earlier can go
9473 into an infinite loop if given an iterator that is not parsed as a macro
9474 name.  It does not do any sanity checking on its numeric bounds, and
9475 only permits decimal numbers for bounds.  Here is an improved version,
9476 shipped as @file{m4-@value{VERSION}/@/doc/examples/@/forloop2.m4}; this
9477 version also optimizes overhead by calling four macros instead of six
9478 per iteration (excluding those in @var{text}), by not dereferencing the
9479 @var{iterator} in the helper @code{@w{_forloop}}.
9481 @comment examples
9482 @example
9483 $ @kbd{m4 -I doc/examples}
9484 undivert(`forloop2.m4')dnl
9485 @result{}divert(`-1')
9486 @result{}# forloop(var, from, to, stmt) - improved version:
9487 @result{}#   works even if VAR is not a strict macro name
9488 @result{}#   performs sanity check that FROM is larger than TO
9489 @result{}#   allows complex numerical expressions in TO and FROM
9490 @result{}define(`forloop', `ifelse(eval(`($2) <= ($3)'), `1',
9491 @result{}  `pushdef(`$1')_$0(`$1', eval(`$2'),
9492 @result{}    eval(`$3'), `$4')popdef(`$1')')')
9493 @result{}define(`_forloop',
9494 @result{}  `define(`$1', `$2')$4`'ifelse(`$2', `$3', `',
9495 @result{}    `$0(`$1', incr(`$2'), `$3', `$4')')')
9496 @result{}divert`'dnl
9497 include(`forloop2.m4')
9498 @result{}
9499 forloop(`i', `2', `1', `no iteration occurs')
9500 @result{}
9501 forloop(`', `1', `2', ` odd iterator name')
9502 @result{} odd iterator name odd iterator name
9503 forloop(`i', `5 + 5', `0xc', ` 0x`'eval(i, `16')')
9504 @result{} 0xa 0xb 0xc
9505 forloop(`i', `a', `b', `non-numeric bounds')
9506 @error{}m4:stdin:6: warning: eval: bad input: '(a) <= (b)'
9507 @result{}
9508 @end example
9510 One other change to notice is that the improved version used @samp{_$0}
9511 rather than @samp{_foreach} to invoke the helper routine.  In general,
9512 this is a good practice to follow, because then the set of macros can be
9513 uniformly transformed.  The following example shows a transformation
9514 that doubles the current quoting and appends a suffix @samp{2} to each
9515 transformed macro.  If @code{foreach} refers to the literal
9516 @samp{_foreach}, then @code{foreach2} invokes @code{_foreach} instead of
9517 the intended @code{_foreach2}, and the mixing of quoting paradigms leads
9518 to an infinite recursion loop in this example.
9520 @comment options: -L9
9521 @comment status: 1
9522 @comment examples
9523 @example
9524 $ @kbd{m4 -d -L 9 -I doc/examples}
9525 define(`arg1', `$1')include(`forloop2.m4')include(`quote.m4')
9526 @result{}
9527 define(`double', `define(`$1'`2',
9528   arg1(patsubst(dquote(defn(`$1')), `[`']', `\&\&')))')
9529 @result{}
9530 double(`forloop')double(`_forloop')defn(`forloop2')
9531 @result{}ifelse(eval(``($2) <= ($3)''), ``1'',
9532 @result{}  ``pushdef(``$1'')_$0(``$1'', eval(``$2''),
9533 @result{}    eval(``$3''), ``$4'')popdef(``$1'')'')
9534 forloop(i, 1, 5, `ifelse(')forloop(i, 1, 5, `)')
9535 @result{}
9536 changequote(`[', `]')changequote([``], [''])
9537 @result{}
9538 forloop2(i, 1, 5, ``ifelse('')forloop2(i, 1, 5, ``)'')
9539 @result{}
9540 changequote`'include(`forloop.m4')
9541 @result{}
9542 double(`forloop')double(`_forloop')defn(`forloop2')
9543 @result{}pushdef(``$1'', ``$2'')_forloop($@@)popdef(``$1'')
9544 forloop(i, 1, 5, `ifelse(')forloop(i, 1, 5, `)')
9545 @result{}
9546 changequote(`[', `]')changequote([``], [''])
9547 @result{}
9548 forloop2(i, 1, 5, ``ifelse('')forloop2(i, 1, 5, ``)'')
9549 @error{}m4:stdin:12: recursion limit of 9 exceeded, use -L<N> to change it
9550 @end example
9552 One more optimization is still possible.  Instead of repeatedly
9553 assigning a variable then invoking or dereferencing it, it is possible
9554 to pass the current iterator value as a single argument.  Coupled with
9555 @code{curry} if other arguments are needed (@pxref{Composition}), or
9556 with helper macros if the argument is needed in more than one place in
9557 the expansion, the output can be generated with three, rather than four,
9558 macros of overhead per iteration.  Notice how the file
9559 @file{m4-@value{VERSION}/@/doc/examples/@/forloop3.m4} rearranges the
9560 arguments of the helper @code{_forloop} to take two arguments that are
9561 placed around the current value.  By splitting a balanced set of
9562 parantheses across multiple arguments, the helper macro can now be
9563 shared by @code{forloop} and the new @code{forloop_arg}.
9565 @comment examples
9566 @example
9567 $ @kbd{m4 -I doc/examples}
9568 include(`forloop3.m4')
9569 @result{}
9570 undivert(`forloop3.m4')dnl
9571 @result{}divert(`-1')
9572 @result{}# forloop_arg(from, to, macro) - invoke MACRO(value) for
9573 @result{}#   each value between FROM and TO, without define overhead
9574 @result{}define(`forloop_arg', `ifelse(eval(`($1) <= ($2)'), `1',
9575 @result{}  `_forloop(`$1', eval(`$2'), `$3(', `)')')')
9576 @result{}# forloop(var, from, to, stmt) - refactored to share code
9577 @result{}define(`forloop', `ifelse(eval(`($2) <= ($3)'), `1',
9578 @result{}  `pushdef(`$1')_forloop(eval(`$2'), eval(`$3'),
9579 @result{}    `define(`$1',', `)$4')popdef(`$1')')')
9580 @result{}define(`_forloop',
9581 @result{}  `$3`$1'$4`'ifelse(`$1', `$2', `',
9582 @result{}    `$0(incr(`$1'), `$2', `$3', `$4')')')
9583 @result{}divert`'dnl
9584 forloop(`i', `1', `3', ` i')
9585 @result{} 1 2 3
9586 define(`echo', `$@@')
9587 @result{}
9588 forloop_arg(`1', `3', ` echo')
9589 @result{} 1 2 3
9590 include(`curry.m4')
9591 @result{}
9592 forloop_arg(`1', `3', `curry(`pushdef', `a')')
9593 @result{}
9595 @result{}3
9596 popdef(`a')a
9597 @result{}2
9598 popdef(`a')a
9599 @result{}1
9600 popdef(`a')a
9601 @result{}a
9602 @end example
9604 Of course, it is possible to make even more improvements, such as
9605 adding an optional step argument, or allowing iteration through
9606 descending sequences.  GNU Autoconf provides some of these
9607 additional bells and whistles in its @code{m4_for} macro.
9609 @node Improved foreach
9610 @section Solution for @code{foreach}
9612 The @code{foreach} and @code{foreachq} macros (@pxref{Foreach}) as
9613 presented earlier each have flaws.  First, we will examine and fix the
9614 quadratic behavior of @code{foreachq}:
9616 @comment examples
9617 @example
9618 $ @kbd{m4 -I doc/examples}
9619 include(`foreachq.m4')
9620 @result{}
9621 traceon(`shift')debugmode(`aq')
9622 @result{}
9623 foreachq(`x', ``1', `2', `3', `4'', `x
9624 ')dnl
9625 @result{}1
9626 @error{}m4trace: -3- shift(`1', `2', `3', `4')
9627 @error{}m4trace: -2- shift(`1', `2', `3', `4')
9628 @result{}2
9629 @error{}m4trace: -4- shift(`1', `2', `3', `4')
9630 @error{}m4trace: -3- shift(`2', `3', `4')
9631 @error{}m4trace: -3- shift(`1', `2', `3', `4')
9632 @error{}m4trace: -2- shift(`2', `3', `4')
9633 @result{}3
9634 @error{}m4trace: -5- shift(`1', `2', `3', `4')
9635 @error{}m4trace: -4- shift(`2', `3', `4')
9636 @error{}m4trace: -3- shift(`3', `4')
9637 @error{}m4trace: -4- shift(`1', `2', `3', `4')
9638 @error{}m4trace: -3- shift(`2', `3', `4')
9639 @error{}m4trace: -2- shift(`3', `4')
9640 @result{}4
9641 @error{}m4trace: -6- shift(`1', `2', `3', `4')
9642 @error{}m4trace: -5- shift(`2', `3', `4')
9643 @error{}m4trace: -4- shift(`3', `4')
9644 @error{}m4trace: -3- shift(`4')
9645 @end example
9647 @cindex quadratic behavior, avoiding
9648 @cindex avoiding quadratic behavior
9649 Each successive iteration was adding more quoted @code{shift}
9650 invocations, and the entire list contents were passing through every
9651 iteration.  In general, when recursing, it is a good idea to make the
9652 recursion use fewer arguments, rather than adding additional quoted
9653 uses of @code{shift}.  By doing so, @code{m4} uses less memory, invokes
9654 fewer macros, is less likely to run into machine limits, and most
9655 importantly, performs faster.  The fixed version of @code{foreachq} can
9656 be found in @file{m4-@value{VERSION}/@/doc/examples/@/foreachq2.m4}:
9658 @comment examples
9659 @example
9660 $ @kbd{m4 -I doc/examples}
9661 include(`foreachq2.m4')
9662 @result{}
9663 undivert(`foreachq2.m4')dnl
9664 @result{}include(`quote.m4')dnl
9665 @result{}divert(`-1')
9666 @result{}# foreachq(x, `item_1, item_2, ..., item_n', stmt)
9667 @result{}#   quoted list, improved version
9668 @result{}define(`foreachq', `pushdef(`$1')_$0($@@)popdef(`$1')')
9669 @result{}define(`_arg1q', ``$1'')
9670 @result{}define(`_rest', `ifelse(`$#', `1', `', `dquote(shift($@@))')')
9671 @result{}define(`_foreachq', `ifelse(`$2', `', `',
9672 @result{}  `define(`$1', _arg1q($2))$3`'$0(`$1', _rest($2), `$3')')')
9673 @result{}divert`'dnl
9674 traceon(`shift')debugmode(`aq')
9675 @result{}
9676 foreachq(`x', ``1', `2', `3', `4'', `x
9677 ')dnl
9678 @result{}1
9679 @error{}m4trace: -3- shift(`1', `2', `3', `4')
9680 @result{}2
9681 @error{}m4trace: -3- shift(`2', `3', `4')
9682 @result{}3
9683 @error{}m4trace: -3- shift(`3', `4')
9684 @result{}4
9685 @end example
9687 Note that the fixed version calls unquoted helper macros in
9688 @code{@w{_foreachq}} to trim elements immediately; those helper macros
9689 in turn must re-supply the layer of quotes lost in the macro invocation.
9690 Contrast the use of @code{@w{_arg1q}}, which quotes the first list
9691 element, with @code{@w{_arg1}} of the earlier implementation that
9692 returned the first list element directly.  Additionally, by calling the
9693 helper method immediately, the @samp{defn(`@var{iterator}')} no longer
9694 contains unexpanded macros.
9696 The astute m4 programmer might notice that the solution above still uses
9697 more macro invocations than strictly necessary.  Note that @samp{$2},
9698 which contains an arbitrarily long quoted list, is expanded and
9699 rescanned three times per iteration of @code{_foreachq}.  Furthermore,
9700 every iteration of the algorithm effectively unboxes then reboxes the
9701 list, which costs a couple of macro invocations.  It is possible to
9702 rewrite the algorithm by swapping the order of the arguments to
9703 @code{_foreachq} in order to operate on an unboxed list in the first
9704 place, and by using the fixed-length @samp{$#} instead of an arbitrary
9705 length list as the key to end recursion.  The result is an overhead of
9706 six macro invocations per loop (excluding any macros in @var{text}),
9707 instead of eight.  This alternative approach is available as
9708 @file{m4-@value{VERSION}/@/doc/examples/@/foreach3.m4}:
9710 @comment examples
9711 @example
9712 $ @kbd{m4 -I doc/examples}
9713 include(`foreachq3.m4')
9714 @result{}
9715 undivert(`foreachq3.m4')dnl
9716 @result{}divert(`-1')
9717 @result{}# foreachq(x, `item_1, item_2, ..., item_n', stmt)
9718 @result{}#   quoted list, alternate improved version
9719 @result{}define(`foreachq', `ifelse(`$2', `', `',
9720 @result{}  `pushdef(`$1')_$0(`$1', `$3', `', $2)popdef(`$1')')')
9721 @result{}define(`_foreachq', `ifelse(`$#', `3', `',
9722 @result{}  `define(`$1', `$4')$2`'$0(`$1', `$2',
9723 @result{}    shift(shift(shift($@@))))')')
9724 @result{}divert`'dnl
9725 traceon(`shift')debugmode(`aq')
9726 @result{}
9727 foreachq(`x', ``1', `2', `3', `4'', `x
9728 ')dnl
9729 @result{}1
9730 @error{}m4trace: -4- shift(`x', `x
9731 @error{}', `', `1', `2', `3', `4')
9732 @error{}m4trace: -3- shift(`x
9733 @error{}', `', `1', `2', `3', `4')
9734 @error{}m4trace: -2- shift(`', `1', `2', `3', `4')
9735 @result{}2
9736 @error{}m4trace: -4- shift(`x', `x
9737 @error{}', `1', `2', `3', `4')
9738 @error{}m4trace: -3- shift(`x
9739 @error{}', `1', `2', `3', `4')
9740 @error{}m4trace: -2- shift(`1', `2', `3', `4')
9741 @result{}3
9742 @error{}m4trace: -4- shift(`x', `x
9743 @error{}', `2', `3', `4')
9744 @error{}m4trace: -3- shift(`x
9745 @error{}', `2', `3', `4')
9746 @error{}m4trace: -2- shift(`2', `3', `4')
9747 @result{}4
9748 @error{}m4trace: -4- shift(`x', `x
9749 @error{}', `3', `4')
9750 @error{}m4trace: -3- shift(`x
9751 @error{}', `3', `4')
9752 @error{}m4trace: -2- shift(`3', `4')
9753 @end example
9755 Prior to M4 1.6, every instance of @samp{$@@} was rescanned as it was
9756 encountered.  Thus, the @file{foreachq3.m4} alternative used much less
9757 memory than @file{foreachq2.m4}, and executed as much as 10% faster,
9758 since each iteration encountered fewer @samp{$@@}.  However, the
9759 implementation of rescanning every byte in @samp{$@@} was quadratic in
9760 the number of bytes scanned (for example, making the broken version in
9761 @file{foreachq.m4} cubic, rather than quadratic, in behavior).  Once the
9762 underlying M4 implementation was improved in 1.6 to reuse results of
9763 previous scans, both styles of @code{foreachq} become linear in the
9764 number of bytes scanned, but the @file{foreachq3.m4} version remains
9765 noticeably faster because of fewer macro invocations.  Notice how the
9766 implementation injects an empty argument prior to expanding @samp{$2}
9767 within @code{foreachq}; the helper macro @code{_foreachq} then ignores
9768 the third argument altogether, and ends recursion when there are three
9769 arguments left because there was nothing left to pass through
9770 @code{shift}.  Thus, each iteration only needs one @code{ifelse}, rather
9771 than the two conditionals used in the version from @file{foreachq2.m4}.
9773 @cindex nine arguments, more than
9774 @cindex more than nine arguments
9775 @cindex arguments, more than nine
9776 So far, all of the implementations of @code{foreachq} presented have
9777 been quadratic with M4 1.4.x.  But @code{forloop} is linear, because
9778 each iteration parses a constant amount of arguments.  So, it is
9779 possible to design a variant that uses @code{forloop} to do the
9780 iteration, then uses @samp{$@@} only once at the end, giving a linear
9781 result even with older M4 implementations.  This implementation relies
9782 on the GNU extension that @samp{$10} expands to the tenth
9783 argument rather than the first argument concatenated with @samp{0}.  The
9784 trick is to define an intermediate macro that repeats the text
9785 @code{m4_define(`$1', `$@var{n}')$2`'}, with @samp{n} set to successive
9786 integers corresponding to each argument.  The helper macro
9787 @code{_foreachq_} is needed in order to generate the literal sequences
9788 such as @samp{$1} into the intermediate macro, rather than expanding
9789 them as the arguments of @code{_foreachq}.  With this approach, no
9790 @code{shift} calls are even needed!  However, when linear recursion is
9791 available in new enough M4, the time and memory cost of using
9792 @code{forloop} to build an intermediate macro outweigh the costs of any
9793 of the previous implementations (there are seven macros of overhead per
9794 iteration instead of six in @file{foreachq3.m4}, and the entire
9795 intermediate macro must be built in memory before any iteration is
9796 expanded).  Additionally, this approach will need adjustment when a
9797 future version of M4 follows POSIX by no longer treating
9798 @samp{$10} as the tenth argument; the anticipation is that
9799 @samp{$@{10@}} can be used instead, although that alternative syntax is
9800 not yet supported.
9802 @comment examples
9803 @example
9804 $ @kbd{m4 -I doc/examples}
9805 include(`foreachq4.m4')
9806 @result{}
9807 undivert(`foreachq4.m4')dnl
9808 @result{}include(`forloop2.m4')dnl
9809 @result{}divert(`-1')
9810 @result{}# foreachq(x, `item_1, item_2, ..., item_n', stmt)
9811 @result{}#   quoted list, version based on forloop
9812 @result{}define(`foreachq',
9813 @result{}`ifelse(`$2', `', `', `_$0(`$1', `$3', $2)')')
9814 @result{}define(`_foreachq',
9815 @result{}`pushdef(`$1', forloop(`$1', `3', `$#',
9816 @result{}  `$0_(`1', `2', indir(`$1'))')`popdef(
9817 @result{}    `$1')')indir(`$1', $@@)')
9818 @result{}define(`_foreachq_',
9819 @result{}``define(`$$1', `$$3')$$2`''')
9820 @result{}divert`'dnl
9821 traceon(`shift')debugmode(`aq')
9822 @result{}
9823 foreachq(`x', ``1', `2', `3', `4'', `x
9824 ')dnl
9825 @result{}1
9826 @result{}2
9827 @result{}3
9828 @result{}4
9829 @end example
9831 For yet another approach, the improved version of @code{foreach},
9832 available in @file{m4-@value{VERSION}/@/doc/examples/@/foreach2.m4},
9833 simply overquotes the arguments to @code{@w{_foreach}} to begin with,
9834 using @code{dquote_elt}.  Then @code{@w{_foreach}} can just use
9835 @code{@w{_arg1}} to remove the extra layer of quoting that was added up
9836 front:
9838 @comment examples
9839 @example
9840 $ @kbd{m4 -I doc/examples}
9841 include(`foreach2.m4')
9842 @result{}
9843 undivert(`foreach2.m4')dnl
9844 @result{}include(`quote.m4')dnl
9845 @result{}divert(`-1')
9846 @result{}# foreach(x, (item_1, item_2, ..., item_n), stmt)
9847 @result{}#   parenthesized list, improved version
9848 @result{}define(`foreach', `pushdef(`$1')_$0(`$1',
9849 @result{}  (dquote(dquote_elt$2)), `$3')popdef(`$1')')
9850 @result{}define(`_arg1', `$1')
9851 @result{}define(`_foreach', `ifelse(`$2', `(`')', `',
9852 @result{}  `define(`$1', _arg1$2)$3`'$0(`$1', (dquote(shift$2)), `$3')')')
9853 @result{}divert`'dnl
9854 traceon(`shift')debugmode(`aq')
9855 @result{}
9856 foreach(`x', `(`1', `2', `3', `4')', `x
9857 ')dnl
9858 @error{}m4trace: -4- shift(`1', `2', `3', `4')
9859 @error{}m4trace: -4- shift(`2', `3', `4')
9860 @error{}m4trace: -4- shift(`3', `4')
9861 @result{}1
9862 @error{}m4trace: -3- shift(``1'', ``2'', ``3'', ``4'')
9863 @result{}2
9864 @error{}m4trace: -3- shift(``2'', ``3'', ``4'')
9865 @result{}3
9866 @error{}m4trace: -3- shift(``3'', ``4'')
9867 @result{}4
9868 @error{}m4trace: -3- shift(``4'')
9869 @end example
9871 It is likewise possible to write a variant of @code{foreach} that
9872 performs in linear time on M4 1.4.x; the easiest method is probably
9873 writing a version of @code{foreach} that unboxes its list, then invokes
9874 @code{_foreachq} as previously defined in @file{foreachq4.m4}.
9876 @cindex filtering defined symbols
9877 @cindex subset of defined symbols
9878 @cindex defined symbols, filtering
9879 With a robust @code{foreachq} implementation, it is possible to create a
9880 filter on a list of defined symbols.  This next example will find all
9881 symbols that contain @samp{if} or @samp{def}, via two different
9882 approaches.  In the first approach, @code{dquote_elt} is used to
9883 overquote each list element, then @code{dquote} forms the list; that
9884 way, the iterator @code{macro} can be expanded in place because its
9885 contents are already quoted.  This approach also uses a self-modifying
9886 macro @code{sep} to provide the correct number of commas.  In the second
9887 approach, the iterator @code{macro} contains live text, so it must be
9888 used with @code{defn} to avoid unintentional expansion.  The correct
9889 number of commas is achieved by using @code{shift} to ignore the first
9890 one, although a leading space still remains.
9892 @comment examples
9893 @example
9894 $ @kbd{m4 -I doc/examples}
9895 include(`quote.m4')include(`foreachq2.m4')
9896 @result{}
9897 pushdef(`sep', `define(`sep', ``, '')')
9898 @result{}
9899 foreachq(`macro', dquote(dquote_elt(m4symbols)),
9900   `regexp(macro, `.*if.*', `sep`\&'')')
9901 @result{}ifdef, ifelse, shift
9902 popdef(`sep')
9903 @result{}
9904 shift(foreachq(`macro', dquote(m4symbols),
9905   `regexp(defn(`macro'), `def', `,` ''dquote(defn(`macro')))'))
9906 @result{} define, defn, dumpdef, ifdef, popdef, pushdef, undefine
9907 @end example
9909 In summary, recursion over list elements is trickier than it appeared at
9910 first glance, but provides a powerful idiom within @code{m4} processing.
9911 As a final demonstration, both list styles are now able to handle
9912 several scenarios that would wreak havoc on one or both of the original
9913 implementations.  This points out one other difference between the
9914 list styles.  @code{foreach} evaluates unquoted list elements only once,
9915 in preparation for calling @code{@w{_foreach}}, similary for
9916 @code{foreachq} as provided by @file{foreachq3.m4} or
9917 @file{foreachq4.m4}.  But
9918 @code{foreachq}, as provided by @file{foreachq2.m4},
9919 evaluates unquoted list elements twice while visiting the first list
9920 element, once in @code{@w{_arg1q}} and once in @code{@w{_rest}}.  When
9921 deciding which list style to use, one must take into account whether
9922 repeating the side effects of unquoted list elements will have any
9923 detrimental effects.
9925 @comment examples
9926 @example
9927 $ @kbd{m4 -d -I doc/examples}
9928 include(`foreach2.m4')
9929 @result{}
9930 include(`foreachq2.m4')
9931 @result{}
9932 dnl 0-element list:
9933 foreach(`x', `', `<x>') / foreachq(`x', `', `<x>')
9934 @result{} /@w{ }
9935 dnl 1-element list of empty element
9936 foreach(`x', `()', `<x>') / foreachq(`x', ``'', `<x>')
9937 @result{}<> / <>
9938 dnl 2-element list of empty elements
9939 foreach(`x', `(`',`')', `<x>') / foreachq(`x', ``',`'', `<x>')
9940 @result{}<><> / <><>
9941 dnl 1-element list of a comma
9942 foreach(`x', `(`,')', `<x>') / foreachq(`x', ``,'', `<x>')
9943 @result{}<,> / <,>
9944 dnl 2-element list of unbalanced parentheses
9945 foreach(`x', `(`(', `)')', `<x>') / foreachq(`x', ``(', `)'', `<x>')
9946 @result{}<(><)> / <(><)>
9947 define(`ab', `oops')dnl using defn(`iterator')
9948 foreach(`x', `(`a', `b')', `defn(`x')') /dnl
9949  foreachq(`x', ``a', `b'', `defn(`x')')
9950 @result{}ab / ab
9951 define(`active', `ACT, IVE')
9952 @result{}
9953 traceon(`active')
9954 @result{}
9955 dnl list of unquoted macros; expansion occurs before recursion
9956 foreach(`x', `(active, active)', `<x>
9957 ')dnl
9958 @error{}m4trace: -4- active -> `ACT, IVE'
9959 @error{}m4trace: -4- active -> `ACT, IVE'
9960 @result{}<ACT>
9961 @result{}<IVE>
9962 @result{}<ACT>
9963 @result{}<IVE>
9964 foreachq(`x', `active, active', `<x>
9965 ')dnl
9966 @error{}m4trace: -3- active -> `ACT, IVE'
9967 @error{}m4trace: -3- active -> `ACT, IVE'
9968 @result{}<ACT>
9969 @error{}m4trace: -3- active -> `ACT, IVE'
9970 @error{}m4trace: -3- active -> `ACT, IVE'
9971 @result{}<IVE>
9972 @result{}<ACT>
9973 @result{}<IVE>
9974 dnl list of quoted macros; expansion occurs during recursion
9975 foreach(`x', `(`active', `active')', `<x>
9976 ')dnl
9977 @error{}m4trace: -1- active -> `ACT, IVE'
9978 @result{}<ACT, IVE>
9979 @error{}m4trace: -1- active -> `ACT, IVE'
9980 @result{}<ACT, IVE>
9981 foreachq(`x', ``active', `active'', `<x>
9982 ')dnl
9983 @error{}m4trace: -1- active -> `ACT, IVE'
9984 @result{}<ACT, IVE>
9985 @error{}m4trace: -1- active -> `ACT, IVE'
9986 @result{}<ACT, IVE>
9987 dnl list of double-quoted macro names; no expansion
9988 foreach(`x', `(``active'', ``active'')', `<x>
9989 ')dnl
9990 @result{}<active>
9991 @result{}<active>
9992 foreachq(`x', ```active'', ``active''', `<x>
9993 ')dnl
9994 @result{}<active>
9995 @result{}<active>
9996 @end example
9998 @node Improved copy
9999 @section Solution for @code{copy}
10001 The macro @code{copy} presented above works with M4 1.6 and newer, but
10002 is unable to handle builtin tokens with M4 1.4.x, because it tries to
10003 pass the builtin token through the macro @code{curry}, where it is
10004 silently flattened to an empty string (@pxref{Composition}).  Rather
10005 than using the problematic @code{curry} to work around the limitation
10006 that @code{stack_foreach} expects to invoke a macro that takes exactly
10007 one argument, we can write a new macro that lets us form the exact
10008 two-argument @code{pushdef} call sequence needed, so that we are no
10009 longer passing a builtin token through a text macro.
10011 @deffn Composite stack_foreach_sep (@var{macro}, @var{pre}, @var{post}, @
10012   @var{sep})
10013 @deffnx Composite stack_foreach_sep_lifo (@var{macro}, @var{pre}, @
10014   @var{post}, @var{sep})
10015 For each of the @code{pushdef} definitions associated with @var{macro},
10016 expand the sequence @samp{@var{pre}`'definition`'@var{post}}.
10017 Additionally, expand @var{sep} between definitions.
10018 @code{stack_foreach_sep} visits the oldest definition first, while
10019 @code{stack_foreach_sep_lifo} visits the current definition first.  The
10020 expansion may dereference @var{macro}, but should not modify it.  There
10021 are a few special macros, such as @code{defn}, which cannot be used as
10022 the @var{macro} parameter.
10023 @end deffn
10025 Note that @code{stack_foreach(`@var{macro}', `@var{action}')} is
10026 equivalent to @code{stack_foreach_sep(`@var{macro}', `@var{action}(',
10027 `)')}.  By supplying explicit parentheses, split among the @var{pre} and
10028 @var{post} arguments to @code{stack_foreach_sep}, it is now possible to
10029 construct macro calls with more than one argument, without passing
10030 builtin tokens through a macro call.  It is likewise possible to
10031 directly reference the stack definitions without a macro call, by
10032 leaving @var{pre} and @var{post} empty.  Thus, in addition to fixing
10033 @code{copy} on builtin tokens, it also executes with fewer macro
10034 invocations.
10036 The new macro also adds a separator that is only output after the first
10037 iteration of the helper @code{_stack_reverse_sep}, implemented by
10038 prepending the original @var{sep} to @var{pre} and omitting a @var{sep}
10039 argument in subsequent iterations.  Note that the empty string that
10040 separates @var{sep} from @var{pre} is provided as part of the fourth
10041 argument when originally calling @code{_stack_reverse_sep}, and not by
10042 writing @code{$4`'$3} as the third argument in the recursive call; while
10043 the other approach would give the same output, it does so at the expense
10044 of increasing the argument size on each iteration of
10045 @code{_stack_reverse_sep}, which results in quadratic instead of linear
10046 execution time.  The improved stack walking macros are available in
10047 @file{m4-@value{VERSION}/@/doc/examples/@/stack_sep.m4}:
10049 @comment examples
10050 @example
10051 $ @kbd{m4 -I doc/examples}
10052 include(`stack_sep.m4')
10053 @result{}
10054 define(`copy', `ifdef(`$2', `errprint(`$2 already defined
10055 ')m4exit(`1')',
10056    `stack_foreach_sep(`$1', `pushdef(`$2',', `)')')')dnl
10057 pushdef(`a', `1')pushdef(`a', defn(`divnum'))
10058 @result{}
10059 copy(`a', `b')
10060 @result{}
10062 @result{}0
10063 popdef(`b')
10064 @result{}
10066 @result{}1
10067 pushdef(`c', `1')pushdef(`c', `2')
10068 @result{}
10069 stack_foreach_sep_lifo(`c', `', `', `, ')
10070 @result{}2, 1
10071 undivert(`stack_sep.m4')dnl
10072 @result{}divert(`-1')
10073 @result{}# stack_foreach_sep(macro, pre, post, sep)
10074 @result{}# Invoke PRE`'defn`'POST with a single argument of each definition
10075 @result{}# from the definition stack of MACRO, starting with the oldest, and
10076 @result{}# separated by SEP between definitions.
10077 @result{}define(`stack_foreach_sep',
10078 @result{}`_stack_reverse_sep(`$1', `tmp-$1')'dnl
10079 @result{}`_stack_reverse_sep(`tmp-$1', `$1', `$2`'defn(`$1')$3', `$4`'')')
10080 @result{}# stack_foreach_sep_lifo(macro, pre, post, sep)
10081 @result{}# Like stack_foreach_sep, but starting with the newest definition.
10082 @result{}define(`stack_foreach_sep_lifo',
10083 @result{}`_stack_reverse_sep(`$1', `tmp-$1', `$2`'defn(`$1')$3', `$4`'')'dnl
10084 @result{}`_stack_reverse_sep(`tmp-$1', `$1')')
10085 @result{}define(`_stack_reverse_sep',
10086 @result{}`ifdef(`$1', `pushdef(`$2', defn(`$1'))$3`'popdef(`$1')$0(
10087 @result{}  `$1', `$2', `$4$3')')')
10088 @result{}divert`'dnl
10089 @end example
10091 @node Improved m4wrap
10092 @section Solution for @code{m4wrap}
10094 The replacement @code{m4wrap} versions presented above, designed to
10095 guarantee FIFO or LIFO order regardless of the underlying M4
10096 implementation, share a bug when dealing with wrapped text that looks
10097 like parameter expansion.  Note how the invocation of
10098 @code{m4wrap@var{n}} interprets these parameters, while using the
10099 builtin preserves them for their intended use.
10101 @comment examples
10102 @example
10103 $ @kbd{m4 -I doc/examples}
10104 include(`wraplifo.m4')
10105 @result{}
10106 m4wrap(`define(`foo', ``$0:'-$1-$*-$#-')foo(`a', `b')
10108 @result{}
10109 builtin(`m4wrap', ``'define(`bar', ``$0:'-$1-$*-$#-')bar(`a', `b')
10111 @result{}
10113 @result{}m4wrap0:---0-
10114 @result{}bar:-a-a,b-2-
10115 @end example
10117 Additionally, the computation of @code{_m4wrap_level} and creation of
10118 multiple @code{m4wrap@var{n}} placeholders in the original examples is
10119 more expensive in time and memory than strictly necessary.  Notice how
10120 the improved version grabs the wrapped text via @code{defn} to avoid
10121 parameter expansion, then undefines @code{_m4wrap_text}, before
10122 stripping a level of quotes with @code{_arg1} to expand the text.  That
10123 way, each level of wrapping reuses the single placeholder, which starts
10124 each nesting level in an undefined state.
10126 Finally, it is worth emulating the GNU M4 extension of saving
10127 all arguments to @code{m4wrap}, separated by a space, rather than saving
10128 just the first argument.  This is done with the @code{join} macro
10129 documented previously (@pxref{Shift}).  The improved LIFO example is
10130 shipped as @file{m4-@value{VERSION}/@/doc/examples/@/wraplifo2.m4}, and
10131 can easily be converted to a FIFO solution by swapping the adjacent
10132 invocations of @code{joinall} and @code{defn}.
10134 @comment examples
10135 @example
10136 $ @kbd{m4 -I doc/examples}
10137 include(`wraplifo2.m4')
10138 @result{}
10139 undivert(`wraplifo2.m4')dnl
10140 @result{}dnl Redefine m4wrap to have LIFO semantics, improved example.
10141 @result{}include(`join.m4')dnl
10142 @result{}define(`_m4wrap', defn(`m4wrap'))dnl
10143 @result{}define(`_arg1', `$1')dnl
10144 @result{}define(`m4wrap',
10145 @result{}`ifdef(`_$0_text',
10146 @result{}       `define(`_$0_text', joinall(` ', $@@)defn(`_$0_text'))',
10147 @result{}       `_$0(`_arg1(defn(`_$0_text')undefine(`_$0_text'))')dnl
10148 @result{}define(`_$0_text', joinall(` ', $@@))')')dnl
10149 m4wrap(`define(`foo', ``$0:'-$1-$*-$#-')foo(`a', `b')
10151 @result{}
10152 m4wrap(`lifo text
10153 m4wrap(`nested', `', `$@@
10154 ')')
10155 @result{}
10157 @result{}lifo text
10158 @result{}foo:-a-a,b-2-
10159 @result{}nested  $@@
10160 @end example
10162 @node Improved cleardivert
10163 @section Solution for @code{cleardivert}
10165 The @code{cleardivert} macro (@pxref{Cleardivert}) cannot, as it stands, be
10166 called without arguments to clear all pending diversions.  That is
10167 because using undivert with an empty string for an argument is different
10168 than using it with no arguments at all.  Compare the earlier definition
10169 with one that takes the number of arguments into account:
10171 @example
10172 define(`cleardivert',
10173   `pushdef(`_n', divnum)divert(`-1')undivert($@@)divert(_n)popdef(`_n')')
10174 @result{}
10175 divert(`1')one
10176 divert
10177 @result{}
10178 cleardivert
10179 @result{}
10180 undivert
10181 @result{}one
10182 @result{}
10183 define(`cleardivert',
10184   `pushdef(`_num', divnum)divert(`-1')ifelse(`$#', `0',
10185     `undivert`'', `undivert($@@)')divert(_num)popdef(`_num')')
10186 @result{}
10187 divert(`2')two
10188 divert
10189 @result{}
10190 cleardivert
10191 @result{}
10192 undivert
10193 @result{}
10194 @end example
10196 @node Improved capitalize
10197 @section Solution for @code{capitalize}
10199 The @code{capitalize} macro (@pxref{Patsubst}) as presented earlier does
10200 not allow clients to follow the quoting rule of thumb.  Consider the
10201 three macros @code{active}, @code{Active}, and @code{ACTIVE}, and the
10202 difference between calling @code{capitalize} with the expansion of a
10203 macro, expanding the result of a case change, and changing the case of a
10204 double-quoted string:
10206 @comment examples
10207 @example
10208 $ @kbd{m4 -I doc/examples}
10209 include(`capitalize.m4')dnl
10210 define(`active', `act1, ive')dnl
10211 define(`Active', `Act2, Ive')dnl
10212 define(`ACTIVE', `ACT3, IVE')dnl
10213 upcase(active)
10214 @result{}ACT1,IVE
10215 upcase(`active')
10216 @result{}ACT3, IVE
10217 upcase(``active'')
10218 @result{}ACTIVE
10219 downcase(ACTIVE)
10220 @result{}act3,ive
10221 downcase(`ACTIVE')
10222 @result{}act1, ive
10223 downcase(``ACTIVE'')
10224 @result{}active
10225 capitalize(active)
10226 @result{}Act1
10227 capitalize(`active')
10228 @result{}Active
10229 capitalize(``active'')
10230 @result{}_capitalize(`active')
10231 define(`A', `OOPS')
10232 @result{}
10233 capitalize(active)
10234 @result{}OOPSct1
10235 capitalize(`active')
10236 @result{}OOPSctive
10237 @end example
10239 First, when @code{capitalize} is called with more than one argument, it
10240 was throwing away later arguments, whereas @code{upcase} and
10241 @code{downcase} used @samp{$*} to collect them all.  The fix is simple:
10242 use @samp{$*} consistently.
10244 Next, with single-quoting, @code{capitalize} outputs a single character,
10245 a set of quotes, then the rest of the characters, making it impossible
10246 to invoke @code{Active} after the fact, and allowing the alternate macro
10247 @code{A} to interfere.  Here, the solution is to use additional quoting
10248 in the helper macros, then pass the final over-quoted output string
10249 through @code{_arg1} to remove the extra quoting and finally invoke the
10250 concatenated portions as a single string.
10252 Finally, when passed a double-quoted string, the nested macro
10253 @code{_capitalize} is never invoked because it ended up nested inside
10254 quotes.  This one is the toughest to fix.  In short, we have no idea how
10255 many levels of quotes are in effect on the substring being altered by
10256 @code{patsubst}.  If the replacement string cannot be expressed entirely
10257 in terms of literal text and backslash substitutions, then we need a
10258 mechanism to guarantee that the helper macros are invoked outside of
10259 quotes.  In other words, this sounds like a job for @code{changequote}
10260 (@pxref{Changequote}).  By changing the active quoting characters, we
10261 can guarantee that replacement text injected by @code{patsubst} always
10262 occurs in the middle of a string that has exactly one level of
10263 over-quoting using alternate quotes; so the replacement text closes the
10264 quoted string, invokes the helper macros, then reopens the quoted
10265 string.  In turn, that means the replacement text has unbalanced quotes,
10266 necessitating another round of @code{changequote}.
10268 In the fixed version below, (also shipped as
10269 @file{m4-@value{VERSION}/@/doc/examples/@/capitalize.m4}),
10270 @code{capitalize} uses the alternate quotes of @samp{<<[} and @samp{]>>}
10271 (the longer strings are chosen so as to be less likely to appear in the
10272 text being converted).  The helpers @code{_to_alt} and @code{_from_alt}
10273 merely reduce the number of characters required to perform a
10274 @code{changequote}, since the definition changes twice.  The outermost
10275 pair means that @code{patsubst} and @code{_capitalize_alt} are invoked
10276 with alternate quoting; the innermost pair is used so that the third
10277 argument to @code{patsubst} can contain an unbalanced
10278 @samp{]>>}/@samp{<<[} pair.  Note that @code{upcase} and @code{downcase}
10279 must be redefined as @code{_upcase_alt} and @code{_downcase_alt}, since
10280 they contain nested quotes but are invoked with the alternate quoting
10281 scheme in effect.
10283 @comment examples
10284 @example
10285 $ @kbd{m4 -I doc/examples}
10286 include(`capitalize2.m4')dnl
10287 define(`active', `act1, ive')dnl
10288 define(`Active', `Act2, Ive')dnl
10289 define(`ACTIVE', `ACT3, IVE')dnl
10290 define(`A', `OOPS')dnl
10291 capitalize(active; `active'; ``active''; ```actIVE''')
10292 @result{}Act1,Ive; Act2, Ive; Active; `Active'
10293 undivert(`capitalize2.m4')dnl
10294 @result{}divert(`-1')
10295 @result{}# upcase(text)
10296 @result{}# downcase(text)
10297 @result{}# capitalize(text)
10298 @result{}#   change case of text, improved version
10299 @result{}define(`upcase', `translit(`$*', `a-z', `A-Z')')
10300 @result{}define(`downcase', `translit(`$*', `A-Z', `a-z')')
10301 @result{}define(`_arg1', `$1')
10302 @result{}define(`_to_alt', `changequote(`<<[', `]>>')')
10303 @result{}define(`_from_alt', `changequote(<<[`]>>, <<[']>>)')
10304 @result{}define(`_upcase_alt', `translit(<<[$*]>>, <<[a-z]>>, <<[A-Z]>>)')
10305 @result{}define(`_downcase_alt', `translit(<<[$*]>>, <<[A-Z]>>, <<[a-z]>>)')
10306 @result{}define(`_capitalize_alt',
10307 @result{}  `regexp(<<[$1]>>, <<[^\(\w\)\(\w*\)]>>,
10308 @result{}    <<[_upcase_alt(<<[<<[\1]>>]>>)_downcase_alt(<<[<<[\2]>>]>>)]>>)')
10309 @result{}define(`capitalize',
10310 @result{}  `_arg1(_to_alt()patsubst(<<[<<[$*]>>]>>, <<[\w+]>>,
10311 @result{}    _from_alt()`]>>_$0_alt(<<[\&]>>)<<['_to_alt())_from_alt())')
10312 @result{}divert`'dnl
10313 @end example
10315 @node Improved fatal_error
10316 @section Solution for @code{fatal_error}
10318 The @code{fatal_error} macro (@pxref{M4exit}) is not robust to versions
10319 of GNU M4 earlier than 1.4.8, where invoking @code{@w{__file__}}
10320 (@pxref{Location}) inside @code{m4wrap} would result in an empty string,
10321 and @code{@w{__line__}} resulted in @samp{0} even though all files start
10322 at line 1.  Furthermore, versions earlier than 1.4.6 did not support the
10323 @code{@w{__program__}} macro.  If you want @code{fatal_error} to work
10324 across the entire 1.4.x release series, a better implementation would
10327 @comment status: 1
10328 @example
10329 define(`fatal_error',
10330   `errprint(ifdef(`__program__', `__program__', ``m4'')'dnl
10331 `:ifelse(__line__, `0', `',
10332     `__file__:__line__:')` fatal error: $*
10333 ')m4exit(`1')')
10334 @result{}
10335 m4wrap(`divnum(`demo of internal message')
10336 fatal_error(`inside wrapped text')')
10337 @result{}
10339 @error{}m4:stdin:6: warning: divnum: extra arguments ignored: 1 > 0
10340 @result{}0
10341 @error{}m4:stdin:6: fatal error: inside wrapped text
10342 @end example
10344 @c ========================================================== Appendices
10346 @node Copying This Package
10347 @appendix How to make copies of the overall M4 package
10348 @cindex License, code
10350 This appendix covers the license for copying the source code of the
10351 overall M4 package.  This manual is under a different set of
10352 restrictions, covered later (@pxref{Copying This Manual}).
10354 @menu
10355 * GNU General Public License::  License for copying the M4 package
10356 @end menu
10358 @node GNU General Public License
10359 @appendixsec License for copying the M4 package
10360 @cindex GPL, GNU General Public License
10361 @cindex GNU General Public License
10362 @cindex General Public License (GPL), GNU
10363 @include gpl-3.0.texi
10365 @node Copying This Manual
10366 @appendix How to make copies of this manual
10367 @cindex License, manual
10369 This appendix covers the license for copying this manual.  Note that
10370 some of the longer examples in this manual are also distributed in the
10371 directory @file{m4-@value{VERSION}/@/doc/examples/}, where a more
10372 permissive license is in effect when copying just the examples.
10374 @menu
10375 * GNU Free Documentation License::  License for copying this manual
10376 @end menu
10378 @node GNU Free Documentation License
10379 @appendixsec License for copying this manual
10380 @cindex FDL, GNU Free Documentation License
10381 @cindex GNU Free Documentation License
10382 @cindex Free Documentation License (FDL), GNU
10383 @include fdl-1.3.texi
10385 @node Indices
10386 @appendix Indices of concepts and macros
10388 @menu
10389 * Macro index::                 Index for all @code{m4} macros
10390 * Concept index::               Index for many concepts
10391 @end menu
10393 @node Macro index
10394 @appendixsec Index for all @code{m4} macros
10396 This index covers all @code{m4} builtins, as well as several useful
10397 composite macros.  References are exclusively to the places where a
10398 macro is introduced the first time.
10400 @printindex fn
10402 @node Concept index
10403 @appendixsec Index for many concepts
10405 @printindex cp
10407 @bye
10409 @c Local Variables:
10410 @c fill-column: 72
10411 @c ispell-local-dictionary: "american"
10412 @c indent-tabs-mode: nil
10413 @c whitespace-check-buffer-indent: nil
10414 @c End: