1 This is m4.info, produced by makeinfo version 4.13 from m4.texinfo.
3 This manual (28 February 2011) is for GNU M4 (version 1.4.16), a
4 package containing an implementation of the m4 macro language.
6 Copyright (C) 1989-1994, 2004-2011 Free Software Foundation, Inc.
8 Permission is granted to copy, distribute and/or modify this
9 document under the terms of the GNU Free Documentation License,
10 Version 1.3 or any later version published by the Free Software
11 Foundation; with no Invariant Sections, no Front-Cover Texts, and
12 no Back-Cover Texts. A copy of the license is included in the
13 section entitled "GNU Free Documentation License."
15 INFO-DIR-SECTION Text creation and manipulation
17 * M4: (m4). A powerful macro processor.
21 File: m4.info, Node: Top, Next: Preliminaries, Up: (dir)
26 This manual (28 February 2011) is for GNU M4 (version 1.4.16), a
27 package containing an implementation of the m4 macro language.
29 Copyright (C) 1989-1994, 2004-2011 Free Software Foundation, Inc.
31 Permission is granted to copy, distribute and/or modify this
32 document under the terms of the GNU Free Documentation License,
33 Version 1.3 or any later version published by the Free Software
34 Foundation; with no Invariant Sections, no Front-Cover Texts, and
35 no Back-Cover Texts. A copy of the license is included in the
36 section entitled "GNU Free Documentation License."
38 GNU `m4' is an implementation of the traditional UNIX macro
39 processor. It is mostly SVR4 compatible, although it has some
40 extensions (for example, handling more than 9 positional parameters to
41 macros). `m4' also has builtin functions for including files, running
42 shell commands, doing arithmetic, etc. Autoconf needs GNU `m4' for
43 generating `configure' scripts, but not for running them.
45 GNU `m4' was originally written by Rene' Seindal, with subsequent
46 changes by Franc,ois Pinard and other volunteers on the Internet. All
47 names and email addresses can be found in the files `m4-1.4.16/AUTHORS'
48 and `m4-1.4.16/THANKS' from the GNU M4 distribution.
50 This is release 1.4.16. It is now considered stable: future
51 releases in the 1.4.x series are only meant to fix bugs, increase speed,
52 or improve documentation. However...
54 An experimental feature, which would improve `m4' usefulness, allows
55 for changing the syntax for what is a "word" in `m4'. You should use:
56 ./configure --enable-changeword
57 if you want this feature compiled in. The current implementation
58 slows down `m4' considerably and is hardly acceptable. In the future,
59 `m4' 2.0 will come with a different set of new features that provide
60 similar capabilities, but without the inefficiencies, so changeword
61 will go away and _you should not count on it_.
65 * Preliminaries:: Introduction and preliminaries
66 * Invoking m4:: Invoking `m4'
67 * Syntax:: Lexical and syntactic conventions
69 * Macros:: How to invoke macros
70 * Definitions:: How to define new macros
71 * Conditionals:: Conditionals, loops, and recursion
73 * Debugging:: How to debug macros and input
75 * Input Control:: Input control
76 * File Inclusion:: File inclusion
77 * Diversions:: Diverting and undiverting output
79 * Text handling:: Macros for text handling
80 * Arithmetic:: Macros for doing arithmetic
81 * Shell commands:: Macros for running shell commands
82 * Miscellaneous:: Miscellaneous builtin macros
83 * Frozen files:: Fast loading of frozen state
85 * Compatibility:: Compatibility with other versions of `m4'
86 * Answers:: Correct version of some examples
88 * Copying This Package:: How to make copies of the overall M4 package
89 * Copying This Manual:: How to make copies of this manual
90 * Indices:: Indices of concepts and macros
92 --- The Detailed Node Listing ---
94 Introduction and preliminaries
96 * Intro:: Introduction to `m4'
97 * History:: Historical references
98 * Bugs:: Problems and bugs
99 * Manual:: Using this manual
103 * Operation modes:: Command line options for operation modes
104 * Preprocessor features:: Command line options for preprocessor features
105 * Limits control:: Command line options for limits control
106 * Frozen state:: Command line options for frozen state
107 * Debugging options:: Command line options for debugging
108 * Command line files:: Specifying input files on the command line
110 Lexical and syntactic conventions
112 * Names:: Macro names
113 * Quoted strings:: Quoting input to `m4'
114 * Comments:: Comments in `m4' input
115 * Other tokens:: Other kinds of input tokens
116 * Input processing:: How `m4' copies input to output
120 * Invocation:: Macro invocation
121 * Inhibiting Invocation:: Preventing macro invocation
122 * Macro Arguments:: Macro arguments
123 * Quoting Arguments:: On Quoting Arguments to macros
124 * Macro expansion:: Expanding macros
126 How to define new macros
128 * Define:: Defining a new macro
129 * Arguments:: Arguments to macros
130 * Pseudo Arguments:: Special arguments to macros
131 * Undefine:: Deleting a macro
132 * Defn:: Renaming macros
133 * Pushdef:: Temporarily redefining macros
135 * Indir:: Indirect call of macros
136 * Builtin:: Indirect call of builtins
138 Conditionals, loops, and recursion
140 * Ifdef:: Testing if a macro is defined
141 * Ifelse:: If-else construct, or multibranch
142 * Shift:: Recursion in `m4'
143 * Forloop:: Iteration by counting
144 * Foreach:: Iteration by list contents
145 * Stacks:: Working with definition stacks
146 * Composition:: Building macros with macros
148 How to debug macros and input
150 * Dumpdef:: Displaying macro definitions
151 * Trace:: Tracing macro calls
152 * Debug Levels:: Controlling debugging output
153 * Debug Output:: Saving debugging output
157 * Dnl:: Deleting whitespace in input
158 * Changequote:: Changing the quote characters
159 * Changecom:: Changing the comment delimiters
160 * Changeword:: Changing the lexical structure of words
161 * M4wrap:: Saving text until end of input
165 * Include:: Including named files
166 * Search Path:: Searching for include files
168 Diverting and undiverting output
170 * Divert:: Diverting output
171 * Undivert:: Undiverting output
172 * Divnum:: Diversion numbers
173 * Cleardivert:: Discarding diverted text
175 Macros for text handling
177 * Len:: Calculating length of strings
178 * Index macro:: Searching for substrings
179 * Regexp:: Searching for regular expressions
180 * Substr:: Extracting substrings
181 * Translit:: Translating characters
182 * Patsubst:: Substituting text by regular expression
183 * Format:: Formatting strings (printf-like)
185 Macros for doing arithmetic
187 * Incr:: Decrement and increment operators
188 * Eval:: Evaluating integer expressions
190 Macros for running shell commands
192 * Platform macros:: Determining the platform
193 * Syscmd:: Executing simple commands
194 * Esyscmd:: Reading the output of commands
195 * Sysval:: Exit status
196 * Mkstemp:: Making temporary files
198 Miscellaneous builtin macros
200 * Errprint:: Printing error messages
201 * Location:: Printing current location
202 * M4exit:: Exiting from `m4'
204 Fast loading of frozen state
206 * Using frozen files:: Using frozen files
207 * Frozen file format:: Frozen file format
209 Compatibility with other versions of `m4'
211 * Extensions:: Extensions in GNU M4
212 * Incompatibilities:: Facilities in System V m4 not in GNU M4
213 * Other Incompatibilities:: Other incompatibilities
215 Correct version of some examples
217 * Improved exch:: Solution for `exch'
218 * Improved forloop:: Solution for `forloop'
219 * Improved foreach:: Solution for `foreach'
220 * Improved copy:: Solution for `copy'
221 * Improved m4wrap:: Solution for `m4wrap'
222 * Improved cleardivert:: Solution for `cleardivert'
223 * Improved capitalize:: Solution for `capitalize'
224 * Improved fatal_error:: Solution for `fatal_error'
226 How to make copies of the overall M4 package
228 * GNU General Public License:: License for copying the M4 package
230 How to make copies of this manual
232 * GNU Free Documentation License:: License for copying this manual
234 Indices of concepts and macros
236 * Macro index:: Index for all `m4' macros
237 * Concept index:: Index for many concepts
240 File: m4.info, Node: Preliminaries, Next: Invoking m4, Prev: Top, Up: Top
242 1 Introduction and preliminaries
243 ********************************
245 This first chapter explains what GNU `m4' is, where `m4' comes from,
246 how to read and use this documentation, how to call the `m4' program,
247 and how to report bugs about it. It concludes by giving tips for
248 reading the remainder of the manual.
250 The following chapters then detail all the features of the `m4'
255 * Intro:: Introduction to `m4'
256 * History:: Historical references
257 * Bugs:: Problems and bugs
258 * Manual:: Using this manual
261 File: m4.info, Node: Intro, Next: History, Up: Preliminaries
263 1.1 Introduction to `m4'
264 ========================
266 `m4' is a macro processor, in the sense that it copies its input to the
267 output, expanding macros as it goes. Macros are either builtin or
268 user-defined, and can take any number of arguments. Besides just doing
269 macro expansion, `m4' has builtin functions for including named files,
270 running shell commands, doing integer arithmetic, manipulating text in
271 various ways, performing recursion, etc.... `m4' can be used either as
272 a front-end to a compiler, or as a macro processor in its own right.
274 The `m4' macro processor is widely available on all UNIXes, and has
275 been standardized by POSIX. Usually, only a small percentage of users
276 are aware of its existence. However, those who find it often become
277 committed users. The popularity of GNU Autoconf, which requires GNU
278 `m4' for _generating_ `configure' scripts, is an incentive for many to
279 install it, while these people will not themselves program in `m4'.
280 GNU `m4' is mostly compatible with the System V, Release 3 version,
281 except for some minor differences. *Note Compatibility::, for more
284 Some people find `m4' to be fairly addictive. They first use `m4'
285 for simple problems, then take bigger and bigger challenges, learning
286 how to write complex sets of `m4' macros along the way. Once really
287 addicted, users pursue writing of sophisticated `m4' applications even
288 to solve simple problems, devoting more time debugging their `m4'
289 scripts than doing real work. Beware that `m4' may be dangerous for
290 the health of compulsive programmers.
293 File: m4.info, Node: History, Next: Bugs, Prev: Intro, Up: Preliminaries
295 1.2 Historical references
296 =========================
298 `GPM' was an important ancestor of `m4'. See C. Strachey: "A General
299 Purpose Macro generator", Computer Journal 8,3 (1965), pp. 225 ff.
300 `GPM' is also succinctly described into David Gries classic "Compiler
301 Construction for Digital Computers".
303 The classic B. Kernighan and P.J. Plauger: "Software Tools",
304 Addison-Wesley, Inc. (1976) describes and implements a Unix
305 macro-processor language, which inspired Dennis Ritchie to write `m3',
306 a macro processor for the AP-3 minicomputer.
308 Kernighan and Ritchie then joined forces to develop the original
309 `m4', as described in "The M4 Macro Processor", Bell Laboratories
310 (1977). It had only 21 builtin macros.
312 While `GPM' was more _pure_, `m4' is meant to deal with the true
313 intricacies of real life: macros can be recognized without being
314 pre-announced, skipping whitespace or end-of-lines is easier, more
315 constructs are builtin instead of derived, etc.
317 Originally, the Kernighan and Plauger macro-processor, and then
318 `m3', formed the engine for the Rational FORTRAN preprocessor, that is,
319 the `Ratfor' equivalent of `cpp'. Later, `m4' was used as a front-end
320 for `Ratfor', `C' and `Cobol'.
322 Rene' Seindal released his implementation of `m4', GNU `m4', in
323 1990, with the aim of removing the artificial limitations in many of
324 the traditional `m4' implementations, such as maximum line length,
325 macro size, or number of macros.
327 The late Professor A. Dain Samples described and implemented a
328 further evolution in the form of `M5': "User's Guide to the M5 Macro
329 Language: 2nd edition", Electronic Announcement on comp.compilers
332 Franc,ois Pinard took over maintenance of GNU `m4' in 1992, until
333 1994 when he released GNU `m4' 1.4, which was the stable release for 10
334 years. It was at this time that GNU Autoconf decided to require GNU
335 `m4' as its underlying engine, since all other implementations of `m4'
336 had too many limitations.
338 More recently, in 2004, Paul Eggert released 1.4.1 and 1.4.2 which
339 addressed some long standing bugs in the venerable 1.4 release. Then in
340 2005, Gary V. Vaughan collected together the many patches to GNU `m4'
341 1.4 that were floating around the net and released 1.4.3 and 1.4.4.
342 And in 2006, Eric Blake joined the team and prepared patches for the
343 release of 1.4.5, 1.4.6, 1.4.7, and 1.4.8. More bug fixes were
344 incorporated in 2007, with releases 1.4.9 and 1.4.10. Eric continued
345 with some portability fixes for 1.4.11 and 1.4.12 in 2008, 1.4.13 in
346 2009, 1.4.14 and 1.4.15 in 2010, and 1.4.16 in 2011.
348 Meanwhile, development has continued on new features for `m4', such
349 as dynamic module loading and additional builtins. When complete, GNU
350 `m4' 2.0 will start a new series of releases.
353 File: m4.info, Node: Bugs, Next: Manual, Prev: History, Up: Preliminaries
355 1.3 Problems and bugs
356 =====================
358 If you have problems with GNU M4 or think you've found a bug, please
359 report it. Before reporting a bug, make sure you've actually found a
360 real bug. Carefully reread the documentation and see if it really says
361 you can do what you're trying to do. If it's not clear whether you
362 should be able to do something or not, report that too; it's a bug in
365 Before reporting a bug or trying to fix it yourself, try to isolate
366 it to the smallest possible input file that reproduces the problem.
367 Then send us the input file and the exact results `m4' gave you. Also
368 say what you expected to occur; this will help us decide whether the
369 problem was really in the documentation.
371 Once you've got a precise problem, send e-mail to <bug-m4@gnu.org>.
372 Please include the version number of `m4' you are using. You can get
373 this information with the command `m4 --version'. Also provide details
374 about the platform you are executing on.
376 Non-bug suggestions are always welcome as well. If you have
377 questions about things that are unclear in the documentation or are
378 just obscure features, please report them too.
381 File: m4.info, Node: Manual, Prev: Bugs, Up: Preliminaries
383 1.4 Using this manual
384 =====================
386 This manual contains a number of examples of `m4' input and output, and
387 a simple notation is used to distinguish input, output and error
388 messages from `m4'. Examples are set out from the normal text, and
389 shown in a fixed width font, like this
391 This is an example of an example!
393 To distinguish input from output, all output from `m4' is prefixed
394 by the string `=>', and all error messages by the string `error-->'.
395 When showing how command line options affect matters, the command line
396 is shown with a prompt `$ like this', otherwise, you can assume that a
397 simple `m4' invocation will work. Thus:
399 $ command line to invoke m4
400 Example of input line
401 =>Output line from m4
402 error-->and an error message
404 The sequence `^D' in an example indicates the end of the input file.
405 The sequence `<NL>' refers to the newline character. The majority of
406 these examples are self-contained, and you can run them with similar
407 results by invoking `m4 -d'. In fact, the testsuite that is bundled in
408 the GNU M4 package consists of the examples in this document! Some of
409 the examples assume that your current directory is located where you
410 unpacked the installation, so if you plan on following along, you may
411 find it helpful to do this now:
415 As each of the predefined macros in `m4' is described, a prototype
416 call of the macro will be shown, giving descriptive names to the
419 -- Composite: example (STRING, [COUNT = `1'], [ARGUMENT]...)
420 This is a sample prototype. There is not really a macro named
421 `example', but this documents that if there were, it would be a
422 Composite macro, rather than a Builtin. It requires at least one
423 argument, STRING. Remember that in `m4', there must not be a
424 space between the macro name and the opening parenthesis, unless
425 it was intended to call the macro without any arguments. The
426 brackets around COUNT and ARGUMENT show that these arguments are
427 optional. If COUNT is omitted, the macro behaves as if count were
428 `1', whereas if ARGUMENT is omitted, the macro behaves as if it
429 were the empty string. A blank argument is not the same as an
430 omitted argument. For example, `example(`a')', `example(`a',`1')',
431 and `example(`a',`1',)' would behave identically with COUNT set to
432 `1'; while `example(`a',)' and `example(`a',`')' would explicitly
433 pass the empty string for COUNT. The ellipses (`...') show that
434 the macro processes additional arguments after ARGUMENT, rather
437 All macro arguments in `m4' are strings, but some are given special
438 interpretation, e.g., as numbers, file names, regular expressions, etc.
439 The documentation for each macro will state how the parameters are
440 interpreted, and what happens if the argument cannot be parsed
441 according to the desired interpretation. Unless specified otherwise, a
442 parameter specified to be a number is parsed as a decimal, even if the
443 argument has leading zeros; and parsing the empty string as a number
444 results in 0 rather than an error, although a warning will be issued.
446 This document consistently writes and uses "builtin", without a
447 hyphen, as if it were an English word. This is how the `builtin'
448 primitive is spelled within `m4'.
451 File: m4.info, Node: Invoking m4, Next: Syntax, Prev: Preliminaries, Up: Top
456 The format of the `m4' command is:
458 `m4' [OPTION...] [FILE...]
460 All options begin with `-', or if long option names are used, with
461 `--'. A long option name need not be written completely, any
462 unambiguous prefix is sufficient. POSIX requires `m4' to recognize
463 arguments intermixed with files, even when `POSIXLY_CORRECT' is set in
464 the environment. Most options take effect at startup regardless of
465 their position, but some are documented below as taking effect after
466 any files that occurred earlier in the command line. The argument `--'
467 is a marker to denote the end of options.
469 With short options, options that do not take arguments may be
470 combined into a single command line argument with subsequent options,
471 options with mandatory arguments may be provided either as a single
472 command line argument or as two arguments, and options with optional
473 arguments must be provided as a single argument. In other words, `m4
474 -QPDfoo -d a -df' is equivalent to `m4 -Q -P -D foo -d -df -- ./a',
475 although the latter form is considered canonical.
477 With long options, options with mandatory arguments may be provided
478 with an equal sign (`=') in a single argument, or as two arguments, and
479 options with optional arguments must be provided as a single argument.
480 In other words, `m4 --def foo --debug a' is equivalent to `m4
481 --define=foo --debug= -- ./a', although the latter form is considered
482 canonical (not to mention more robust, in case a future version of `m4'
483 introduces an option named `--default').
485 `m4' understands the following options, grouped by functionality.
489 * Operation modes:: Command line options for operation modes
490 * Preprocessor features:: Command line options for preprocessor features
491 * Limits control:: Command line options for limits control
492 * Frozen state:: Command line options for frozen state
493 * Debugging options:: Command line options for debugging
494 * Command line files:: Specifying input files on the command line
497 File: m4.info, Node: Operation modes, Next: Preprocessor features, Up: Invoking m4
499 2.1 Command line options for operation modes
500 ============================================
502 Several options control the overall operation of `m4':
505 Print a help summary on standard output, then immediately exit
506 `m4' without reading any input files or performing any other
510 Print the version number of the program on standard output, then
511 immediately exit `m4' without reading any input files or
512 performing any other actions.
516 Controls the effect of warnings. If unspecified, then execution
517 continues and exit status is unaffected when a warning is printed.
518 If specified exactly once, warnings become fatal; when one is
519 issued, execution continues, but the exit status will be non-zero.
520 If specified multiple times, then execution halts with non-zero
521 status the first time a warning is issued. The introduction of
522 behavior levels is new to M4 1.4.9; for behavior consistent with
523 earlier versions, you should specify `-E' twice.
528 Makes this invocation of `m4' interactive. This means that all
529 output will be unbuffered, and interrupts will be ignored. The
530 spelling `-e' exists for compatibility with other `m4'
531 implementations, and issues a warning because it may be withdrawn
532 in a future version of GNU M4.
536 Internally modify _all_ builtin macro names so they all start with
537 the prefix `m4_'. For example, using this option, one should write
538 `m4_define' instead of `define', and `m4___file__' instead of
539 `__file__'. This option has no effect if `-R' is also specified.
544 Suppress warnings, such as missing or superfluous arguments in
545 macro calls, or treating the empty string as zero.
547 `--warn-macro-sequence[=REGEXP]'
548 Issue a warning if the regular expression REGEXP has a non-empty
549 match in any macro definition (either by `define' or `pushdef').
550 Empty matches are ignored; therefore, supplying the empty string
551 as REGEXP disables any warning. If the optional REGEXP is not
552 supplied, then the default regular expression is
553 `\$\({[^}]*}\|[0-9][0-9]+\)' (a literal `$' followed by multiple
554 digits or by an open brace), since these sequences will change
555 semantics in the default operation of GNU M4 2.0 (due to a change
556 in how more than 9 arguments in a macro definition will be
557 handled, *note Arguments::). Providing an alternate regular
558 expression can provide a useful reverse lookup feature of finding
559 where a macro is defined to have a given definition.
562 `--word-regexp=REGEXP'
563 Use REGEXP as an alternative syntax for macro names. This
564 experimental option will not be present in all GNU `m4'
565 implementations (*note Changeword::).
568 File: m4.info, Node: Preprocessor features, Next: Limits control, Prev: Operation modes, Up: Invoking m4
570 2.2 Command line options for preprocessor features
571 ==================================================
573 Several options allow `m4' to behave more like a preprocessor. Macro
574 definitions and deletions can be made on the command line, the search
575 path can be altered, and the output file can track where the input came
576 from. These features occur with the following options:
579 `--define=NAME[=VALUE]'
580 This enters NAME into the symbol table. If `=VALUE' is missing,
581 the value is taken to be the empty string. The VALUE can be any
582 string, and the macro can be defined to take arguments, just as if
583 it was defined from within the input. This option may be given
584 more than once; order with respect to file names is significant,
585 and redefining the same NAME loses the previous value.
588 `--include=DIRECTORY'
589 Make `m4' search DIRECTORY for included files that are not found
590 in the current working directory. *Note Search Path::, for more
591 details. This option may be given more than once.
595 Generate synchronization lines, for use by the C preprocessor or
596 other similar tools. Order is significant with respect to file
597 names. This option is useful, for example, when `m4' is used as a
598 front end to a compiler. Source file name and line number
599 information is conveyed by directives of the form `#line LINENUM
600 "FILE"', which are inserted as needed into the middle of the
601 output. Such directives mean that the following line originated
602 or was expanded from the contents of input file FILE at line
603 LINENUM. The `"FILE"' part is often omitted when the file name
604 did not change from the previous directive.
606 Synchronization directives are always given on complete lines by
607 themselves. When a synchronization discrepancy occurs in the
608 middle of an output line, the associated synchronization directive
609 is delayed until the next newline that does not occur in the
610 middle of a quoted string or comment.
616 changecom(`/*', `*/')
618 define(`comment', `/*1
645 This deletes any predefined meaning NAME might have. Obviously,
646 only predefined macros can be deleted in this way. This option
647 may be given more than once; undefining a NAME that does not have a
648 definition is silently ignored. Order is significant with respect
652 File: m4.info, Node: Limits control, Next: Frozen state, Prev: Preprocessor features, Up: Invoking m4
654 2.3 Command line options for limits control
655 ===========================================
657 There are some limits within `m4' that can be tuned. For
658 compatibility, `m4' also accepts some options that control limits in
659 other implementations, but which are automatically unbounded (limited
660 only by your hardware and operating system constraints) in GNU `m4'.
664 Enable all the extensions in this implementation. In this release
665 of M4, this option is always on by default; it is currently only
666 useful when overriding a prior use of `--traditional'. However,
667 having GNU behavior as default makes it impossible to write a
668 strictly POSIX-compliant client that avoids all incompatible GNU
669 M4 extensions, since such a client would have to use the non-POSIX
670 command-line option to force full POSIX behavior. Thus, a future
671 version of M4 will be changed to implicitly use the option
672 `--traditional' if the environment variable `POSIXLY_CORRECT' is
673 set. Projects that intentionally use GNU extensions should
674 consider using `--gnu' to state their intentions, so that the
675 project will not mysteriously break if the user upgrades to a
676 newer M4 and has `POSIXLY_CORRECT' set in their environment.
680 Suppress all the extensions made in this implementation, compared
681 to the System V version. *Note Compatibility::, for a list of
686 Make the internal hash table for symbol lookup be NUM entries big.
687 For better performance, the number should be prime, but this is not
688 checked. The default is 509 entries. It should not be necessary
689 to increase this value, unless you define an excessive number of
693 `--nesting-limit=NUM'
694 Artificially limit the nesting of macro calls to NUM levels,
695 stopping program execution if this limit is ever exceeded. When
696 not specified, nesting defaults to unlimited on platforms that can
697 detect stack overflow, and to 1024 levels otherwise. A value of
698 zero means unlimited; but then heavily nested code could
699 potentially cause a stack overflow.
701 The precise effect of this option is more correctly associated
702 with textual nesting than dynamic recursion. It has been useful
703 when some complex `m4' input was generated by mechanical means, and
704 also in diagnosing recursive algorithms that do not scale well.
705 Most users never need to change this option from its default.
707 This option does _not_ have the ability to break endless
708 rescanning loops, since these do not necessarily consume much
709 memory or stack space. Through clever usage of rescanning loops,
710 one can request complex, time-consuming computations from `m4'
711 with useful results. Putting limitations in this area would break
712 `m4' power. There are many pathological cases:
713 `define(`a', `a')a' is only the simplest example (but *note
714 Compatibility::). Expecting GNU `m4' to detect these would be a
715 little like expecting a compiler system to detect and diagnose
716 endless loops: it is a quite _hard_ problem in general, if not
722 These options are present for compatibility with System V `m4', but
723 do nothing in this implementation. They may disappear in future
724 releases, and issue a warning to that effect.
728 These options are present only for compatibility with previous
729 versions of GNU `m4', and were controlling the number of possible
730 diversions which could be used at the same time. They do nothing,
731 because there is no fixed limit anymore. They may disappear in
732 future releases, and issue a warning to that effect.
735 File: m4.info, Node: Frozen state, Next: Debugging options, Prev: Limits control, Up: Invoking m4
737 2.4 Command line options for frozen state
738 =========================================
740 GNU `m4' comes with a feature of freezing internal state (*note Frozen
741 files::). This can be used to speed up `m4' execution when reusing a
742 common initialization script.
745 `--freeze-state=FILE'
746 Once execution is finished, write out the frozen state on the
747 specified FILE. It is conventional, but not required, for FILE to
751 `--reload-state=FILE'
752 Before execution starts, recover the internal state from the
753 specified frozen FILE. The options `-D', `-U', and `-t' take
754 effect after state is reloaded, but before the input files are
758 File: m4.info, Node: Debugging options, Next: Command line files, Prev: Frozen state, Up: Invoking m4
760 2.5 Command line options for debugging
761 ======================================
763 Finally, there are several options for aiding in debugging `m4' scripts.
767 Set the debug-level according to the flags FLAGS. The debug-level
768 controls the format and amount of information presented by the
769 debugging functions. *Note Debug Levels::, for more details on
770 the format and meaning of FLAGS. If omitted, FLAGS defaults to
775 `--error-output=FILE'
776 Redirect `dumpdef' output, debug messages, and trace output to the
777 named FILE. Warnings, error messages, and `errprint' output are
778 still printed to standard error. If these options are not used, or
779 if FILE is unspecified (only possible for `--debugfile'), debug
780 output goes to standard error; if FILE is the empty string, debug
781 output is discarded. *Note Debug Output::, for more details. The
782 option `--debugfile' may be given more than once, and order is
783 significant with respect to file names. The spellings `-o' and
784 `--error-output' are misleading and inconsistent with other GNU
785 tools; for now they are silently accepted as synonyms of
786 `--debugfile' and only recognized once, but in a future version of
787 M4, using them will cause a warning to be issued.
791 Restrict the size of the output generated by macro tracing to NUM
792 characters per trace line. If unspecified or zero, output is
793 unlimited. *Note Debug Levels::, for more details.
797 This enables tracing for the macro NAME, at any point where it is
798 defined. NAME need not be defined when this option is given.
799 This option may be given more than once, and order is significant
800 with respect to file names. *Note Trace::, for more details.
803 File: m4.info, Node: Command line files, Prev: Debugging options, Up: Invoking m4
805 2.6 Specifying input files on the command line
806 ==============================================
808 The remaining arguments on the command line are taken to be input file
809 names. If no names are present, standard input is read. A file name
810 of `-' is taken to mean standard input. It is conventional, but not
811 required, for input files to end in `.m4'.
813 The input files are read in the sequence given. Standard input can
814 be read more than once, so the file name `-' may appear multiple times
815 on the command line; this makes a difference when input is from a
816 terminal or other special file type. It is an error if an input file
817 ends in the middle of argument collection, a comment, or a quoted
820 The options `--define' (`-D'), `--undefine' (`-U'), `--synclines'
821 (`-s'), and `--trace' (`-t') only take effect after processing input
822 from any file names that occur earlier on the command line. For
823 example, assume the file `foo' contains:
828 The text `bar' can then be redefined over multiple uses of `foo':
830 $ m4 -Dbar=hello foo -Dbar=world foo
834 If none of the input files invoked `m4exit' (*note M4exit::), the
835 exit status of `m4' will be 0 for success, 1 for general failure (such
836 as problems with reading an input file), and 63 for version mismatch
837 (*note Using frozen files::).
839 If you need to read a file whose name starts with a `-', you can
840 specify it as `./-file', or use `--' to mark the end of options.
843 File: m4.info, Node: Syntax, Next: Macros, Prev: Invoking m4, Up: Top
845 3 Lexical and syntactic conventions
846 ***********************************
848 As `m4' reads its input, it separates it into "tokens". A token is
849 either a name, a quoted string, or any single character, that is not a
850 part of either a name or a string. Input to `m4' can also contain
851 comments. GNU `m4' does not yet understand multibyte locales; all
852 operations are byte-oriented rather than character-oriented (although
853 if your locale uses a single byte encoding, such as ISO-8859-1, you
854 will not notice a difference). However, `m4' is eight-bit clean, so
855 you can use non-ASCII characters in quoted strings (*note
856 Changequote::), comments (*note Changecom::), and macro names (*note
857 Indir::), with the exception of the NUL character (the zero byte
862 * Names:: Macro names
863 * Quoted strings:: Quoting input to `m4'
864 * Comments:: Comments in `m4' input
865 * Other tokens:: Other kinds of input tokens
866 * Input processing:: How `m4' copies input to output
869 File: m4.info, Node: Names, Next: Quoted strings, Up: Syntax
874 A name is any sequence of letters, digits, and the character `_'
875 (underscore), where the first character is not a digit. `m4' will use
876 the longest such sequence found in the input. If a name has a macro
877 definition, it will be subject to macro expansion (*note Macros::).
878 Names are case-sensitive.
880 Examples of legal names are: `foo', `_tmp', and `name01'.
883 File: m4.info, Node: Quoted strings, Next: Comments, Prev: Names, Up: Syntax
885 3.2 Quoting input to `m4'
886 =========================
888 A quoted string is a sequence of characters surrounded by quote
889 strings, defaulting to ``' and `'', where the nested begin and end
890 quotes within the string are balanced. The value of a string token is
891 the text, with one level of quotes stripped off. Thus
896 is the empty string, and double-quoting turns into single-quoting.
901 The quote characters can be changed at any time, using the builtin
902 macro `changequote'. *Note Changequote::, for more information.
905 File: m4.info, Node: Comments, Next: Other tokens, Prev: Quoted strings, Up: Syntax
907 3.3 Comments in `m4' input
908 ==========================
910 Comments in `m4' are normally delimited by the characters `#' and
911 newline. All characters between the comment delimiters are ignored,
912 but the entire comment (including the delimiters) is passed through to
913 the output--comments are _not_ discarded by `m4'.
915 Comments cannot be nested, so the first newline after a `#' ends the
916 comment. The commenting effect of the begin-comment string can be
917 inhibited by quoting it.
920 `quoted text' # `commented text'
921 =>quoted text # `commented text'
922 `quoting inhibits' `#' `comments'
923 =>quoting inhibits # comments
925 The comment delimiters can be changed to any string at any time,
926 using the builtin macro `changecom'. *Note Changecom::, for more
930 File: m4.info, Node: Other tokens, Next: Input processing, Prev: Comments, Up: Syntax
932 3.4 Other kinds of input tokens
933 ===============================
935 Any character, that is neither a part of a name, nor of a quoted string,
936 nor a comment, is a token by itself. When not in the context of macro
937 expansion, all of these tokens are just copied to output. However,
938 during macro expansion, whitespace characters (space, tab, newline,
939 formfeed, carriage return, vertical tab), parentheses (`(' and `)'),
940 comma (`,'), and dollar (`$') have additional roles, explained later.
943 File: m4.info, Node: Input processing, Prev: Other tokens, Up: Syntax
945 3.5 How `m4' copies input to output
946 ===================================
948 As `m4' reads the input token by token, it will copy each token
949 directly to the output immediately.
951 The exception is when it finds a word with a macro definition. In
952 that case `m4' will calculate the macro's expansion, possibly reading
953 more input to get the arguments. It then inserts the expansion in front
954 of the remaining input. In other words, the resulting text from a macro
955 call will be read and parsed into tokens again.
957 `m4' expands a macro as soon as possible. If it finds a macro call
958 when collecting the arguments to another, it will expand the second call
959 first. This process continues until there are no more macro calls to
960 expand and all the input has been consumed.
962 For a running example, examine how `m4' handles this input:
964 format(`Result is %d', eval(`2**15'))
966 First, `m4' sees that the token `format' is a macro name, so it
967 collects the tokens `(', ``Result is %d'', `,', and ` ', before
968 encountering another potential macro. Sure enough, `eval' is a macro
969 name, so the nested argument collection picks up `(', ``2**15'', and
970 `)', invoking the eval macro with the lone argument of `2**15'. The
971 expansion of `eval(2**15)' is `32768', which is then rescanned as the
972 five tokens `3', `2', `7', `6', and `8'; and combined with the next
973 `)', the format macro now has all its arguments, as if the user had
976 format(`Result is %d', 32768)
978 The format macro expands to `Result is 32768', and we have another
979 round of scanning for the tokens `Result', ` ', `is', ` ', `3', `2',
980 `7', `6', and `8'. None of these are macros, so the final output is
984 As a more complicated example, we will contrast an actual code
985 example from the Gnulib project(1), showing both a buggy approach and
986 the desired results. The user desires to output a shell assignment
987 statement that takes its argument and turns it into a shell variable by
988 converting it to uppercase and prepending a prefix. The original
989 attempt looks like this:
992 define([gl_STRING_MODULE_INDICATOR],
995 GNULIB_]translit([$1],[a-z],[A-Z])[=1
997 gl_STRING_MODULE_INDICATOR([strcase])
1002 Oops - the argument did not get capitalized. And although the manual
1003 is not able to easily show it, both lines that appear empty actually
1004 contain two trailing spaces. By stepping through the parse, it is easy
1005 to see what happened. First, `m4' sees the token `changequote', which
1006 it recognizes as a macro, followed by `(', `[', `,', `]', and `)' to
1007 form the argument list. The macro expands to the empty string, but
1008 changes the quoting characters to something more useful for generating
1009 shell code (unbalanced ``' and `'' appear all the time in shell scripts,
1010 but unbalanced `[]' tend to be rare). Also in the first line, `m4'
1011 sees the token `dnl', which it recognizes as a builtin macro that
1012 consumes the rest of the line, resulting in no output for that line.
1014 The second line starts a macro definition. `m4' sees the token
1015 `define', which it recognizes as a macro, followed by a `(',
1016 `[gl_STRING_MODULE_INDICATOR]', and `,'. Because an unquoted comma was
1017 encountered, the first argument is known to be the expansion of the
1018 single-quoted string token, or `gl_STRING_MODULE_INDICATOR'. Next,
1019 `m4' sees `<NL>', ` ', and ` ', but this whitespace is discarded as
1020 part of argument collection. Then comes a rather lengthy single-quoted
1021 string token, `[<NL> dnl comment<NL> GNULIB_]'. This is followed
1022 by the token `translit', which `m4' recognizes as a macro name, so a
1023 nested macro expansion has started.
1025 The arguments to the `translit' are found by the tokens `(', `[$1]',
1026 `,', `[a-z]', `,', `[A-Z]', and finally `)'. All three string
1027 arguments are expanded (or in other words, the quotes are stripped),
1028 and since neither `$' nor `1' need capitalization, the result of the
1029 macro is `$1'. This expansion is rescanned, resulting in the two
1030 literal characters `$' and `1'.
1032 Scanning of the outer macro resumes, and picks up with `[=1<NL> ]',
1033 and finally `)'. The collected pieces of expanded text are
1034 concatenated, with the end result that the macro
1035 `gl_STRING_MODULE_INDICATOR' is now defined to be the sequence `<NL>
1036 dnl comment<NL> GNULIB_$1=1<NL> '. Once again, `dnl' is recognized
1037 and avoids a newline in the output.
1039 The final line is then parsed, beginning with ` ' and ` ' that are
1040 output literally. Then `gl_STRING_MODULE_INDICATOR' is recognized as a
1041 macro name, with an argument list of `(', `[strcase]', and `)'. Since
1042 the definition of the macro contains the sequence `$1', that sequence
1043 is replaced with the argument `strcase' prior to starting the rescan.
1044 The rescan sees `<NL>' and four spaces, which are output literally, then
1045 `dnl', which discards the text ` comment<NL>'. Next comes four more
1046 spaces, also output literally, and the token `GNULIB_strcase', which
1047 resulted from the earlier parameter substitution. Since that is not a
1048 macro name, it is output literally, followed by the literal tokens `=',
1049 `1', `<NL>', and two more spaces. Finally, the original `<NL>' seen
1050 after the macro invocation is scanned and output literally.
1052 Now for a corrected approach. This rearranges the use of newlines
1053 and whitespace so that less whitespace is output (which, although
1054 harmless to shell scripts, can be visually unappealing), and fixes the
1055 quoting issues so that the capitalization occurs when the macro
1056 `gl_STRING_MODULE_INDICATOR' is invoked, rather then when it is
1057 defined. It also adds another layer of quoting to the first argument of
1058 `translit', to ensure that the output will be rescanned as a string
1059 rather than a potential uppercase macro name needing further expansion.
1062 define([gl_STRING_MODULE_INDICATOR],
1064 GNULIB_[]translit([[$1]], [a-z], [A-Z])=1dnl
1066 gl_STRING_MODULE_INDICATOR([strcase])
1069 The parsing of the first line is unchanged. The second line sees the
1070 name of the macro to define, then sees the discarded `<NL>' and two
1071 spaces, as before. But this time, the next token is `[dnl comment<NL>
1072 GNULIB_[]translit([[$1]], [a-z], [A-Z])=1dnl<NL>]', which includes
1073 nested quotes, followed by `)' to end the macro definition and `dnl' to
1074 skip the newline. No early expansion of `translit' occurs, so the
1075 entire string becomes the definition of the macro.
1077 The final line is then parsed, beginning with two spaces that are
1078 output literally, and an invocation of `gl_STRING_MODULE_INDICATOR'
1079 with the argument `strcase'. Again, the `$1' in the macro definition
1080 is substituted prior to rescanning. Rescanning first encounters `dnl',
1081 and discards ` comment<NL>'. Then two spaces are output literally.
1082 Next comes the token `GNULIB_', but that is not a macro, so it is
1083 output literally. The token `[]' is an empty string, so it does not
1084 affect output. Then the token `translit' is encountered.
1086 This time, the arguments to `translit' are parsed as `(',
1087 `[[strcase]]', `,', ` ', `[a-z]', `,', ` ', `[A-Z]', and `)'. The two
1088 spaces are discarded, and the translit results in the desired result
1089 `[STRCASE]'. This is rescanned, but since it is a string, the quotes
1090 are stripped and the only output is a literal `STRCASE'. Then the
1091 scanner sees `=' and `1', which are output literally, followed by `dnl'
1092 which discards the rest of the definition of
1093 `gl_STRING_MODULE_INDICATOR'. The newline at the end of output is the
1094 literal `<NL>' that appeared after the invocation of the macro.
1096 The order in which `m4' expands the macros can be further explored
1097 using the trace facilities of GNU `m4' (*note Trace::).
1099 ---------- Footnotes ----------
1101 (1) Derived from a patch in
1102 `http://lists.gnu.org/archive/html/bug-gnulib/2007-01/msg00389.html',
1103 and a followup patch in
1104 `http://lists.gnu.org/archive/html/bug-gnulib/2007-02/msg00000.html'
1107 File: m4.info, Node: Macros, Next: Definitions, Prev: Syntax, Up: Top
1109 4 How to invoke macros
1110 **********************
1112 This chapter covers macro invocation, macro arguments and how macro
1113 expansion is treated.
1117 * Invocation:: Macro invocation
1118 * Inhibiting Invocation:: Preventing macro invocation
1119 * Macro Arguments:: Macro arguments
1120 * Quoting Arguments:: On Quoting Arguments to macros
1121 * Macro expansion:: Expanding macros
1124 File: m4.info, Node: Invocation, Next: Inhibiting Invocation, Up: Macros
1126 4.1 Macro invocation
1127 ====================
1129 Macro invocations has one of the forms
1133 which is a macro invocation without any arguments, or
1135 name(arg1, arg2, ..., argN)
1137 which is a macro invocation with N arguments. Macros can have any
1138 number of arguments. All arguments are strings, but different macros
1139 might interpret the arguments in different ways.
1141 The opening parenthesis _must_ follow the NAME directly, with no
1142 spaces in between. If it does not, the macro is called with no
1145 For a macro call to have no arguments, the parentheses _must_ be
1146 left out. The macro call
1150 is a macro call with one argument, which is the empty string, not a call
1154 File: m4.info, Node: Inhibiting Invocation, Next: Macro Arguments, Prev: Invocation, Up: Macros
1156 4.2 Preventing macro invocation
1157 ===============================
1159 An innovation of the `m4' language, compared to some of its
1160 predecessors (like Strachey's `GPM', for example), is the ability to
1161 recognize macro calls without resorting to any special, prefixed
1162 invocation character. While generally useful, this feature might
1163 sometimes be the source of spurious, unwanted macro calls. So, GNU
1164 `m4' offers several mechanisms or techniques for inhibiting the
1165 recognition of names as macro calls.
1167 First of all, many builtin macros cannot meaningfully be called
1168 without arguments. As a GNU extension, for any of these macros,
1169 whenever an opening parenthesis does not immediately follow their name,
1170 the builtin macro call is not triggered. This solves the most usual
1171 cases, like for `include' or `eval'. Later in this document, the
1172 sentence "This macro is recognized only with parameters" refers to this
1173 specific provision of GNU M4, also known as a blind builtin macro. For
1174 the builtins defined by POSIX that bear this disclaimer, POSIX
1175 specifically states that invoking those builtins without arguments is
1176 unspecified, because many other implementations simply invoke the
1177 builtin as though it were given one empty argument instead.
1185 There is also a command line option (`--prefix-builtins', or `-P',
1186 *note Invoking m4: Operation modes.) that renames all builtin macros
1187 with a prefix of `m4_' at startup. The option has no effect whatsoever
1188 on user defined macros. For example, with this option, one has to
1189 write `m4_dnl' and even `m4_m4exit'. It also has no effect on whether
1190 a macro requires parameters.
1202 Another alternative is to redefine problematic macros to a name less
1203 likely to cause conflicts, *Note Definitions::.
1205 If your version of GNU `m4' has the `changeword' feature compiled
1206 in, it offers far more flexibility in specifying the syntax of macro
1207 names, both builtin or user-defined. *Note Changeword::, for more
1208 information on this experimental feature.
1210 Of course, the simplest way to prevent a name from being interpreted
1211 as a call to an existing macro is to quote it. The remainder of this
1212 section studies a little more deeply how quoting affects macro
1213 invocation, and how quoting can be used to inhibit macro invocation.
1215 Even if quoting is usually done over the whole macro name, it can
1216 also be done over only a few characters of this name (provided, of
1217 course, that the unquoted portions are not also a macro). It is also
1218 possible to quote the empty string, but this works only _inside_ the
1230 all yield the string `divert'. While in both:
1237 the `divert' builtin macro will be called, which expands to the empty
1240 The output of macro evaluations is always rescanned. In the
1241 following example, the input `x`'y' yields the string `bCD', exactly as
1242 if `m4' has been given `substr(ab`'cde, `1', `3')' as input:
1244 define(`cde', `CDE')
1246 define(`x', `substr(ab')
1248 define(`y', `cde, `1', `3')')
1253 Unquoted strings on either side of a quoted string are subject to
1254 being recognized as macro names. In the following example, quoting the
1255 empty string allows for the second `macro' to be recognized as such:
1257 define(`macro', `m')
1264 Quoting may prevent recognizing as a macro name the concatenation of
1265 a macro expansion with the surrounding characters. In this example:
1267 define(`macro', `di$1')
1274 the input will produce the string `divert'. When the quotes were
1275 removed, the `divert' builtin was called instead.
1278 File: m4.info, Node: Macro Arguments, Next: Quoting Arguments, Prev: Inhibiting Invocation, Up: Macros
1283 When a name is seen, and it has a macro definition, it will be expanded
1286 If the name is followed by an opening parenthesis, the arguments
1287 will be collected before the macro is called. If too few arguments are
1288 supplied, the missing arguments are taken to be the empty string.
1289 However, some builtins are documented to behave differently for a
1290 missing optional argument than for an explicit empty string. If there
1291 are too many arguments, the excess arguments are ignored. Unquoted
1292 leading whitespace is stripped off all arguments, but whitespace
1293 generated by a macro expansion or occurring after a macro that expanded
1294 to an empty string remains intact. Whitespace includes space, tab,
1295 newline, carriage return, vertical tab, and formfeed.
1297 define(`macro', `$1')
1299 macro( unquoted leading space lost)
1300 =>unquoted leading space lost
1301 macro(` quoted leading space kept')
1302 => quoted leading space kept
1304 divert `unquoted space kept after expansion')
1305 => unquoted space kept after expansion
1307 ')`whitespace from expansion kept')
1309 =>whitespace from expansion kept
1310 macro(`unquoted trailing whitespace kept'
1312 =>unquoted trailing whitespace kept
1315 Normally `m4' will issue warnings if a builtin macro is called with
1316 an inappropriate number of arguments, but it can be suppressed with the
1317 `--quiet' command line option (or `--silent', or `-Q', *note Invoking
1318 m4: Operation modes.). For user defined macros, there is no check of
1319 the number of arguments given.
1323 error-->m4:stdin:1: Warning: too few arguments to builtin `index'
1327 index(`abc', `b', `ignored')
1328 error-->m4:stdin:3: Warning: excess arguments to builtin `index' ignored
1336 index(`abc', `b', `ignored')
1339 Macros are expanded normally during argument collection, and whatever
1340 commas, quotes and parentheses that might show up in the resulting
1341 expanded text will serve to define the arguments as well. Thus, if FOO
1342 expands to `, b, c', the macro call
1346 is a macro call with four arguments, which are `a ', `b', `c' and `d'.
1347 To understand why the first argument contains whitespace, remember that
1348 unquoted leading whitespace is never part of an argument, but trailing
1349 whitespace always is.
1351 It is possible for a macro's definition to change during argument
1352 collection, in which case the expansion uses the definition that was in
1353 effect at the time the opening `(' was seen.
1362 It is an error if the end of file occurs while collecting arguments.
1368 error-->m4:stdin:2: ERROR: end of file in argument list
1371 File: m4.info, Node: Quoting Arguments, Next: Macro expansion, Prev: Macro Arguments, Up: Macros
1373 4.4 On Quoting Arguments to macros
1374 ==================================
1376 Each argument has unquoted leading whitespace removed. Within each
1377 argument, all unquoted parentheses must match. For example, if FOO is
1382 is a macro call, with one argument, whose value is `() (() ('. Commas
1383 separate arguments, except when they occur inside quotes, comments, or
1384 unquoted parentheses. *Note Pseudo Arguments::, for examples.
1386 It is common practice to quote all arguments to macros, unless you
1387 are sure you want the arguments expanded. Thus, in the above example
1388 with the parentheses, the `right' way to do it is like this:
1392 It is, however, in certain cases necessary (because nested expansion
1393 must occur to create the arguments for the outer macro) or convenient
1394 (because it uses fewer characters) to leave out quotes for some
1395 arguments, and there is nothing wrong in doing it. It just makes life a
1396 bit harder, if you are not careful to follow a consistent quoting style.
1397 For consistency, this manual follows the rule of thumb that each layer
1398 of parentheses introduces another layer of single quoting, except when
1399 showing the consequences of quoting rules. This is done even when the
1400 quoted string cannot be a macro, such as with integers when you have not
1401 changed the syntax via `changeword' (*note Changeword::).
1403 The quoting rule of thumb of one level of quoting per parentheses
1404 has a nice property: when a macro name appears inside parentheses, you
1405 can determine when it will be expanded. If it is not quoted, it will be
1406 expanded prior to the outer macro, so that its expansion becomes the
1407 argument. If it is single-quoted, it will be expanded after the outer
1408 macro. And if it is double-quoted, it will be used as literal text
1409 instead of a macro name.
1411 define(`active', `ACT, IVE')
1413 define(`show', `$1 $1')
1423 File: m4.info, Node: Macro expansion, Prev: Quoting Arguments, Up: Macros
1428 When the arguments, if any, to a macro call have been collected, the
1429 macro is expanded, and the expansion text is pushed back onto the input
1430 (unquoted), and reread. The expansion text from one macro call might
1431 therefore result in more macros being called, if the calls are included,
1432 completely or partially, in the first macro calls' expansion.
1434 Taking a very simple example, if FOO expands to `bar', and BAR
1435 expands to `Hello', the input
1437 $ m4 -Dbar=Hello -Dfoo=bar
1441 will expand first to `bar', and when this is reread and expanded, into
1445 File: m4.info, Node: Definitions, Next: Conditionals, Prev: Macros, Up: Top
1447 5 How to define new macros
1448 **************************
1450 Macros can be defined, redefined and deleted in several different ways.
1451 Also, it is possible to redefine a macro without losing a previous
1452 value, and bring back the original value at a later time.
1456 * Define:: Defining a new macro
1457 * Arguments:: Arguments to macros
1458 * Pseudo Arguments:: Special arguments to macros
1459 * Undefine:: Deleting a macro
1460 * Defn:: Renaming macros
1461 * Pushdef:: Temporarily redefining macros
1463 * Indir:: Indirect call of macros
1464 * Builtin:: Indirect call of builtins
1467 File: m4.info, Node: Define, Next: Arguments, Up: Definitions
1469 5.1 Defining a macro
1470 ====================
1472 The normal way to define or redefine macros is to use the builtin
1475 -- Builtin: define (NAME, [EXPANSION])
1476 Defines NAME to expand to EXPANSION. If EXPANSION is not given,
1477 it is taken to be empty.
1479 The expansion of `define' is void. The macro `define' is
1480 recognized only with parameters.
1482 The following example defines the macro FOO to expand to the text
1485 define(`foo', `Hello world.')
1490 The empty line in the output is there because the newline is not a
1491 part of the macro definition, and it is consequently copied to the
1492 output. This can be avoided by use of the macro `dnl'. *Note Dnl::,
1495 The first argument to `define' should be quoted; otherwise, if the
1496 macro is already defined, you will be defining a different macro. This
1497 example shows the problems with underquoting, since we did not want to
1507 GNU `m4' normally replaces only the _topmost_ definition of a macro
1508 if it has several definitions from `pushdef' (*note Pushdef::). Some
1509 other implementations of `m4' replace all definitions of a macro with
1510 `define'. *Note Incompatibilities::, for more details.
1512 As a GNU extension, the first argument to `define' does not have to
1513 be a simple word. It can be any text string, even the empty string. A
1514 macro with a non-standard name cannot be invoked in the normal way, as
1515 the name is not recognized. It can only be referenced by the builtins
1516 `indir' (*note Indir::) and `defn' (*note Defn::).
1518 Arrays and associative arrays can be simulated by using non-standard
1521 -- Composite: array (INDEX)
1522 -- Composite: array_set (INDEX, [VALUE])
1523 Provide access to entries within an array. `array' reads the entry
1524 at location INDEX, and `array_set' assigns VALUE to location INDEX.
1526 define(`array', `defn(format(``array[%d]'', `$1'))')
1528 define(`array_set', `define(format(``array[%d]'', `$1'), `$2')')
1530 array_set(`4', `array element no. 4')
1532 array_set(`17', `array element no. 17')
1535 =>array element no. 4
1536 array(eval(`10 + 7'))
1537 =>array element no. 17
1539 Change the `%d' to `%s' and it is an associative array.
1542 File: m4.info, Node: Arguments, Next: Pseudo Arguments, Prev: Define, Up: Definitions
1544 5.2 Arguments to macros
1545 =======================
1547 Macros can have arguments. The Nth argument is denoted by `$n' in the
1548 expansion text, and is replaced by the Nth actual argument, when the
1549 macro is expanded. Replacement of arguments happens before rescanning,
1550 regardless of how many nesting levels of quoting appear in the
1551 expansion. Here is an example of a macro with two arguments.
1553 -- Composite: exch (ARG1, ARG2)
1554 Expands to ARG2 followed by ARG1, effectively exchanging their
1557 define(`exch', `$2, $1')
1559 exch(`arg1', `arg2')
1562 This can be used, for example, if you like the arguments to `define'
1565 define(`exch', `$2, $1')
1567 define(exch(``expansion text'', ``macro''))
1572 *Note Quoting Arguments::, for an explanation of the double quotes.
1573 (You should try and improve this example so that clients of `exch' do
1574 not have to double quote; or *note Answers: Improved exch.).
1576 As a special case, the zeroth argument, `$0', is always the name of
1577 the macro being expanded.
1579 define(`test', ``Macro name: $0'')
1584 If you want quoted text to appear as part of the expansion text,
1585 remember that quotes can be nested in quoted strings. Thus, in
1587 define(`foo', `This is macro `foo'.')
1590 =>This is macro foo.
1592 The `foo' in the expansion text is _not_ expanded, since it is a quoted
1593 string, and not a name.
1595 GNU `m4' allows the number following the `$' to consist of one or
1596 more digits, allowing macros to have any number of arguments. The
1597 extension of accepting multiple digits is incompatible with POSIX, and
1598 is different than traditional implementations of `m4', which only
1599 recognize one digit. Therefore, future versions of GNU M4 will phase
1600 out this feature. To portably access beyond the ninth argument, you
1601 can use the `argn' macro documented later (*note Shift::).
1603 POSIX also states that `$' followed immediately by `{' in a macro
1604 definition is implementation-defined. This version of M4 passes the
1605 literal characters `${' through unchanged, but M4 2.0 will implement an
1606 optional feature similar to `sh', where `${11}' expands to the eleventh
1607 argument, to replace the current recognition of `$11'. Meanwhile, if
1608 you want to guarantee that you will get a literal `${' in output when
1609 expanding a macro, even when you upgrade to M4 2.0, you can use nested
1610 quoting to your advantage:
1612 define(`foo', `single quoted $`'{1} output')
1614 define(`bar', ``double quoted $'`{2} output'')
1617 =>single quoted ${1} output
1619 =>double quoted ${2} output
1621 To help you detect places in your M4 input files that might change in
1622 behavior due to the changed behavior of M4 2.0, you can use the
1623 `--warn-macro-sequence' command-line option (*note Invoking m4:
1624 Operation modes.) with the default regular expression. This will add a
1625 warning any time a macro definition includes `$' followed by multiple
1626 digits, or by `{'. The warning is not enabled by default, because it
1627 triggers a number of warnings in Autoconf 2.61 (and Autoconf uses `-E'
1628 to treat warnings as errors), and because it will still be possible to
1629 restore older behavior in M4 2.0.
1631 $ m4 --warn-macro-sequence
1632 define(`foo', `$001 ${1} $1')
1633 error-->m4:stdin:1: Warning: definition of `foo' contains sequence `$001'
1634 error-->m4:stdin:1: Warning: definition of `foo' contains sequence `${1}'
1640 File: m4.info, Node: Pseudo Arguments, Next: Undefine, Prev: Arguments, Up: Definitions
1642 5.3 Special arguments to macros
1643 ===============================
1645 There is a special notation for the number of actual arguments supplied,
1646 and for all the actual arguments.
1648 The number of actual arguments in a macro call is denoted by `$#' in
1651 -- Composite: nargs (...)
1652 Expands to a count of the number of arguments supplied.
1654 define(`nargs', `$#')
1660 nargs(`arg1', `arg2', `arg3')
1662 nargs(`commas can be quoted, like this')
1664 nargs(arg1#inside comments, commas do not separate arguments
1667 nargs((unquoted parentheses, like this, group arguments))
1670 Remember that `#' defaults to the comment character; if you forget
1671 quotes to inhibit the comment behavior, your macro definition may not
1672 end where you expected.
1674 dnl Attempt to define a macro to just `$#'
1675 define(underquoted, $#)
1682 The notation `$*' can be used in the expansion text to denote all
1683 the actual arguments, unquoted, with commas in between. For example
1685 define(`echo', `$*')
1687 echo(arg1, arg2, arg3 , arg4)
1688 =>arg1,arg2,arg3 ,arg4
1690 Often each argument should be quoted, and the notation `$@' handles
1691 that. It is just like `$*', except that it quotes each argument. A
1692 simple example of that is:
1694 define(`echo', `$@')
1696 echo(arg1, arg2, arg3 , arg4)
1697 =>arg1,arg2,arg3 ,arg4
1699 Where did the quotes go? Of course, they were eaten, when the
1700 expanded text were reread by `m4'. To show the difference, try
1702 define(`echo1', `$*')
1704 define(`echo2', `$@')
1706 define(`foo', `This is macro `foo'.')
1709 =>This is macro This is macro foo..
1711 =>This is macro foo.
1713 =>This is macro foo.
1717 *Note Trace::, if you do not understand this. As another example of the
1718 difference, remember that comments encountered in arguments are passed
1719 untouched to the macro, and that quoting disables comments.
1721 define(`echo1', `$*')
1723 define(`echo2', `$@')
1725 define(`foo', `bar')
1736 A `$' sign in the expansion text, that is not followed by anything
1737 `m4' understands, is simply copied to the macro expansion, as any other
1740 define(`foo', `$$$ hello $$$')
1745 If you want a macro to expand to something like `$12', the judicious
1746 use of nested quoting can put a safe character between the `$' and the
1747 next character, relying on the rescanning to remove the nested quote.
1748 This will prevent `m4' from interpreting the `$' sign as a reference to
1751 define(`foo', `no nested quote: $1')
1754 =>no nested quote: arg
1755 define(`foo', `nested quote around $: `$'1')
1758 =>nested quote around $: $1
1759 define(`foo', `nested empty quote after $: $`'1')
1762 =>nested empty quote after $: $1
1763 define(`foo', `nested quote around next character: $`1'')
1766 =>nested quote around next character: $1
1767 define(`foo', `nested quote around both: `$1'')
1770 =>nested quote around both: arg
1773 File: m4.info, Node: Undefine, Next: Defn, Prev: Pseudo Arguments, Up: Definitions
1775 5.4 Deleting a macro
1776 ====================
1778 A macro definition can be removed with `undefine':
1780 -- Builtin: undefine (NAME...)
1781 For each argument, remove the macro NAME. The macro names must
1782 necessarily be quoted, since they will be expanded otherwise.
1784 The expansion of `undefine' is void. The macro `undefine' is
1785 recognized only with parameters.
1789 define(`foo', `some')define(`bar', `other')define(`blah', `text')
1797 undefine(`bar', `blah')
1802 Undefining a macro inside that macro's expansion is safe; the macro
1803 still expands to the definition that was in effect at the `('.
1805 define(`f', ``$0':$1')
1807 f(f(f(undefine(`f')`hello world')))
1812 It is not an error for NAME to have no macro definition. In that
1813 case, `undefine' does nothing.
1816 File: m4.info, Node: Defn, Next: Pushdef, Prev: Undefine, Up: Definitions
1821 It is possible to rename an already defined macro. To do this, you need
1824 -- Builtin: defn (NAME...)
1825 Expands to the _quoted definition_ of each NAME. If an argument
1826 is not a defined macro, the expansion for that argument is empty.
1828 If NAME is a user-defined macro, the quoted definition is simply
1829 the quoted expansion text. If, instead, there is only one NAME
1830 and it is a builtin, the expansion is a special token, which
1831 points to the builtin's internal definition. This token is only
1832 meaningful as the second argument to `define' (and `pushdef'), and
1833 is silently converted to an empty string in most other contexts.
1834 Combining a builtin with anything else is not supported; a warning
1835 is issued and the builtin is omitted from the final expansion.
1837 The macro `defn' is recognized only with parameters.
1839 Its normal use is best understood through an example, which shows
1840 how to rename `undefine' to `zap':
1842 define(`zap', defn(`undefine'))
1849 In this way, `defn' can be used to copy macro definitions, and also
1850 definitions of builtin macros. Even if the original macro is removed,
1851 the other name can still be used to access the definition.
1853 The fact that macro definitions can be transferred also explains why
1854 you should use `$0', rather than retyping a macro's name in its
1857 define(`foo', `This is `$0'')
1859 define(`bar', defn(`foo'))
1864 Macros used as string variables should be referred through `defn',
1865 to avoid unwanted expansion of the text:
1867 define(`string', `The macro dnl is very useful
1873 =>The macro dnl is very useful
1876 However, it is important to remember that `m4' rescanning is purely
1877 textual. If an unbalanced end-quote string occurs in a macro
1878 definition, the rescan will see that embedded quote as the termination
1879 of the quoted string, and the remainder of the macro's definition will
1880 be rescanned unquoted. Thus it is a good idea to avoid unbalanced
1881 end-quotes in macro definitions or arguments to macros.
1887 define(`echo', `$@')
1896 On the other hand, it is possible to exploit the fact that `defn'
1897 can concatenate multiple macros prior to the rescanning phase, in order
1898 to join the definitions of macros that, in isolation, have unbalanced
1899 quotes. This is particularly useful when one has used several macros to
1900 accumulate text that M4 should rescan as a whole. In the example below,
1901 note how the use of `defn' on `l' in isolation opens a string, which is
1902 not closed until the next line; but used on `l' and `r' together
1903 results in nested quoting.
1905 define(`l', `<[>')define(`r', `<]>')
1907 changequote(`[', `]')
1916 Using `defn' to generate special tokens for builtin macros outside
1917 of expected contexts can sometimes trigger warnings. But most of the
1918 time, such tokens are silently converted to the empty string.
1923 define(defn(`divnum'), `cannot redefine a builtin token')
1924 error-->m4:stdin:2: Warning: define: invalid macro name ignored
1931 Also note that `defn' with multiple arguments can only join text
1932 macros, not builtins, although a future version of GNU M4 may lift this
1936 define(`a', `A')define(`AA', `b')
1938 traceon(`defn', `define')
1940 defn(`a', `divnum', `a')
1941 error-->m4:stdin:3: Warning: cannot concatenate builtin `divnum'
1942 error-->m4trace: -1- defn(`a', `divnum', `a') -> ``A'`A''
1944 define(`mydivnum', defn(`divnum', `divnum'))mydivnum
1945 error-->m4:stdin:4: Warning: cannot concatenate builtin `divnum'
1946 error-->m4:stdin:4: Warning: cannot concatenate builtin `divnum'
1947 error-->m4trace: -2- defn(`divnum', `divnum')
1948 error-->m4trace: -1- define(`mydivnum', `')
1950 traceoff(`defn', `define')
1954 File: m4.info, Node: Pushdef, Next: Indir, Prev: Defn, Up: Definitions
1956 5.6 Temporarily redefining macros
1957 =================================
1959 It is possible to redefine a macro temporarily, reverting to the
1960 previous definition at a later time. This is done with the builtins
1961 `pushdef' and `popdef':
1963 -- Builtin: pushdef (NAME, [EXPANSION])
1964 -- Builtin: popdef (NAME...)
1965 Analogous to `define' and `undefine'.
1967 These macros work in a stack-like fashion. A macro is temporarily
1968 redefined with `pushdef', which replaces an existing definition of
1969 NAME, while saving the previous definition, before the new one is
1970 installed. If there is no previous definition, `pushdef' behaves
1971 exactly like `define'.
1973 If a macro has several definitions (of which only one is
1974 accessible), the topmost definition can be removed with `popdef'.
1975 If there is no previous definition, `popdef' behaves like
1978 The expansion of both `pushdef' and `popdef' is void. The macros
1979 `pushdef' and `popdef' are recognized only with parameters.
1981 define(`foo', `Expansion one.')
1985 pushdef(`foo', `Expansion two.')
1989 pushdef(`foo', `Expansion three.')
1991 pushdef(`foo', `Expansion four.')
1997 popdef(`foo', `foo')
2006 If a macro with several definitions is redefined with `define', the
2007 topmost definition is _replaced_ with the new definition. If it is
2008 removed with `undefine', _all_ the definitions are removed, and not
2009 only the topmost one. However, POSIX allows other implementations that
2010 treat `define' as replacing an entire stack of definitions with a
2011 single new definition, so to be portable to other implementations, it
2012 may be worth explicitly using `popdef' and `pushdef' rather than
2013 relying on the GNU behavior of `define'.
2015 define(`foo', `Expansion one.')
2019 pushdef(`foo', `Expansion two.')
2023 define(`foo', `Second expansion two.')
2026 =>Second expansion two.
2032 Local variables within macros are made with `pushdef' and `popdef'.
2033 At the start of the macro a new definition is pushed, within the macro
2034 it is manipulated and at the end it is popped, revealing the former
2037 It is possible to temporarily redefine a builtin with `pushdef' and
2041 File: m4.info, Node: Indir, Next: Builtin, Prev: Pushdef, Up: Definitions
2043 5.7 Indirect call of macros
2044 ===========================
2046 Any macro can be called indirectly with `indir':
2048 -- Builtin: indir (NAME, [ARGS...])
2049 Results in a call to the macro NAME, which is passed the rest of
2050 the arguments ARGS. If NAME is not defined, an error message is
2051 printed, and the expansion is void.
2053 The macro `indir' is recognized only with parameters.
2055 This can be used to call macros with computed or "invalid" names
2056 (`define' allows such names to be defined):
2058 define(`$$internal$macro', `Internal macro (name `$0')')
2062 indir(`$$internal$macro')
2063 =>Internal macro (name $$internal$macro)
2065 The point is, here, that larger macro packages can have private
2066 macros defined, that will not be called by accident. They can _only_ be
2067 called through the builtin `indir'.
2069 One other point to observe is that argument collection occurs before
2070 `indir' invokes NAME, so if argument collection changes the value of
2071 NAME, that will be reflected in the final expansion. This is different
2072 than the behavior when invoking macros directly, where the definition
2073 that was in effect before argument collection is used.
2080 indir(`f', define(`f', `3'))
2082 indir(`f', undefine(`f'))
2083 error-->m4:stdin:4: undefined macro `f'
2086 When handed the result of `defn' (*note Defn::) as one of its
2087 arguments, `indir' defers to the invoked NAME for whether a token
2088 representing a builtin is recognized or flattened to the empty string.
2091 indir(defn(`defn'), `divnum')
2092 error-->m4:stdin:1: Warning: indir: invalid macro name ignored
2094 indir(`define', defn(`defn'), `divnum')
2095 error-->m4:stdin:2: Warning: define: invalid macro name ignored
2097 indir(`define', `foo', defn(`divnum'))
2101 indir(`divert', defn(`foo'))
2102 error-->m4:stdin:5: empty string treated as 0 in builtin `divert'
2106 File: m4.info, Node: Builtin, Prev: Indir, Up: Definitions
2108 5.8 Indirect call of builtins
2109 =============================
2111 Builtin macros can be called indirectly with `builtin':
2113 -- Builtin: builtin (NAME, [ARGS...])
2114 Results in a call to the builtin NAME, which is passed the rest of
2115 the arguments ARGS. If NAME does not name a builtin, an error
2116 message is printed, and the expansion is void.
2118 The macro `builtin' is recognized only with parameters.
2120 This can be used even if NAME has been given another definition that
2121 has covered the original, or been undefined so that no macro maps to
2124 pushdef(`define', `hidden')
2126 undefine(`undefine')
2128 define(`foo', `bar')
2132 builtin(`define', `foo', defn(`divnum'))
2136 builtin(`define', `foo', `BAR')
2144 builtin(`undefine', `foo')
2149 The NAME argument only matches the original name of the builtin,
2150 even when the `--prefix-builtins' option (or `-P', *note Invoking m4:
2151 Operation modes.) is in effect. This is different from `indir', which
2152 only tracks current macro names.
2155 m4_builtin(`divnum')
2157 m4_builtin(`m4_divnum')
2158 error-->m4:stdin:2: undefined builtin `m4_divnum'
2161 error-->m4:stdin:3: undefined macro `divnum'
2163 m4_indir(`m4_divnum')
2166 Note that `indir' and `builtin' can be used to invoke builtins
2167 without arguments, even when they normally require parameters to be
2168 recognized; but it will provoke a warning, and result in a void
2174 error-->m4:stdin:2: undefined builtin `'
2177 error-->m4:stdin:3: Warning: too few arguments to builtin `builtin'
2180 error-->m4:stdin:4: undefined builtin `'
2182 builtin(`builtin', ``'
2184 error-->m4:stdin:5: undefined builtin ``'
2188 error-->m4:stdin:7: Warning: too few arguments to builtin `index'
2192 File: m4.info, Node: Conditionals, Next: Debugging, Prev: Definitions, Up: Top
2194 6 Conditionals, loops, and recursion
2195 ************************************
2197 Macros, expanding to plain text, perhaps with arguments, are not quite
2198 enough. We would like to have macros expand to different things, based
2199 on decisions taken at run-time. For that, we need some kind of
2200 conditionals. Also, we would like to have some kind of loop construct,
2201 so we could do something a number of times, or while some condition is
2206 * Ifdef:: Testing if a macro is defined
2207 * Ifelse:: If-else construct, or multibranch
2208 * Shift:: Recursion in `m4'
2209 * Forloop:: Iteration by counting
2210 * Foreach:: Iteration by list contents
2211 * Stacks:: Working with definition stacks
2212 * Composition:: Building macros with macros
2215 File: m4.info, Node: Ifdef, Next: Ifelse, Up: Conditionals
2217 6.1 Testing if a macro is defined
2218 =================================
2220 There are two different builtin conditionals in `m4'. The first is
2223 -- Builtin: ifdef (NAME, STRING-1, [STRING-2])
2224 If NAME is defined as a macro, `ifdef' expands to STRING-1,
2225 otherwise to STRING-2. If STRING-2 is omitted, it is taken to be
2226 the empty string (according to the normal rules).
2228 The macro `ifdef' is recognized only with parameters.
2230 ifdef(`foo', ``foo' is defined', ``foo' is not defined')
2231 =>foo is not defined
2234 ifdef(`foo', ``foo' is defined', ``foo' is not defined')
2236 ifdef(`no_such_macro', `yes', `no', `extra argument')
2237 error-->m4:stdin:4: Warning: excess arguments to builtin `ifdef' ignored
2241 File: m4.info, Node: Ifelse, Next: Shift, Prev: Ifdef, Up: Conditionals
2243 6.2 If-else construct, or multibranch
2244 =====================================
2246 The other conditional, `ifelse', is much more powerful. It can be used
2247 as a way to introduce a long comment, as an if-else construct, or as a
2248 multibranch, depending on the number of arguments supplied:
2250 -- Builtin: ifelse (COMMENT)
2251 -- Builtin: ifelse (STRING-1, STRING-2, EQUAL, [NOT-EQUAL])
2252 -- Builtin: ifelse (STRING-1, STRING-2, EQUAL-1, STRING-3, STRING-4,
2253 EQUAL-2, ..., [NOT-EQUAL])
2254 Used with only one argument, the `ifelse' simply discards it and
2257 If called with three or four arguments, `ifelse' expands into
2258 EQUAL, if STRING-1 and STRING-2 are equal (character for
2259 character), otherwise it expands to NOT-EQUAL. A final fifth
2260 argument is ignored, after triggering a warning.
2262 If called with six or more arguments, and STRING-1 and STRING-2
2263 are equal, `ifelse' expands into EQUAL-1, otherwise the first
2264 three arguments are discarded and the processing starts again.
2266 The macro `ifelse' is recognized only with parameters.
2268 Using only one argument is a common `m4' idiom for introducing a
2269 block comment, as an alternative to repeatedly using `dnl'. This
2270 special usage is recognized by GNU `m4', so that in this case, the
2271 warning about missing arguments is never triggered.
2273 ifelse(`some comments')
2275 ifelse(`foo', `bar')
2276 error-->m4:stdin:2: Warning: too few arguments to builtin `ifelse'
2279 Using three or four arguments provides decision points.
2281 ifelse(`foo', `bar', `true')
2283 ifelse(`foo', `foo', `true')
2285 define(`foo', `bar')
2287 ifelse(foo, `bar', `true', `false')
2289 ifelse(foo, `foo', `true', `false')
2292 Notice how the first argument was used unquoted; it is common to
2293 compare the expansion of a macro with a string. With this macro, you
2294 can now reproduce the behavior of blind builtins, where the macro is
2295 recognized only with arguments.
2297 define(`foo', `ifelse(`$#', `0', ``$0'', `arguments:$#')')
2306 For an example of a way to make defining blind macros easier, see
2307 *note Composition::.
2309 The macro `ifelse' can take more than four arguments. If given more
2310 than four arguments, `ifelse' works like a `case' or `switch' statement
2311 in traditional programming languages. If STRING-1 and STRING-2 are
2312 equal, `ifelse' expands into EQUAL-1, otherwise the procedure is
2313 repeated with the first three arguments discarded. This calls for an
2316 ifelse(`foo', `bar', `third', `gnu', `gnats')
2317 error-->m4:stdin:1: Warning: excess arguments to builtin `ifelse' ignored
2319 ifelse(`foo', `bar', `third', `gnu', `gnats', `sixth')
2321 ifelse(`foo', `bar', `third', `gnu', `gnats', `sixth', `seventh')
2323 ifelse(`foo', `bar', `3', `gnu', `gnats', `6', `7', `8')
2324 error-->m4:stdin:4: Warning: excess arguments to builtin `ifelse' ignored
2327 Naturally, the normal case will be slightly more advanced than these
2328 examples. A common use of `ifelse' is in macros implementing loops of
2332 File: m4.info, Node: Shift, Next: Forloop, Prev: Ifelse, Up: Conditionals
2334 6.3 Recursion in `m4'
2335 =====================
2337 There is no direct support for loops in `m4', but macros can be
2338 recursive. There is no limit on the number of recursion levels, other
2339 than those enforced by your hardware and operating system.
2341 Loops can be programmed using recursion and the conditionals
2342 described previously.
2344 There is a builtin macro, `shift', which can, among other things, be
2345 used for iterating through the actual arguments to a macro:
2347 -- Builtin: shift (ARG1, ...)
2348 Takes any number of arguments, and expands to all its arguments
2349 except ARG1, separated by commas, with each argument quoted.
2351 The macro `shift' is recognized only with parameters.
2357 shift(`foo', `bar', `baz')
2360 An example of the use of `shift' is this macro:
2362 -- Composite: reverse (...)
2363 Takes any number of arguments, and reverses their order.
2365 It is implemented as:
2367 define(`reverse', `ifelse(`$#', `0', , `$#', `1', ``$1'',
2368 `reverse(shift($@)), `$1'')')
2374 reverse(`foo', `bar', `gnats', `and gnus')
2375 =>and gnus, gnats, bar, foo
2377 While not a very interesting macro, it does show how simple loops
2378 can be made with `shift', `ifelse' and recursion. It also shows that
2379 `shift' is usually used with `$@'. Another example of this is an
2380 implementation of a short-circuiting conditional operator.
2382 -- Composite: cond (TEST-1, STRING-1, EQUAL-1, [TEST-2], [STRING-2],
2383 [EQUAL-2], ..., [NOT-EQUAL])
2384 Similar to `ifelse', where an equal comparison between the first
2385 two strings results in the third, otherwise the first three
2386 arguments are discarded and the process repeats. The difference
2387 is that each TEST-<N> is expanded only when it is encountered.
2388 This means that every third argument to `cond' is normally given
2389 one more level of quoting than the corresponding argument to
2392 Here is the implementation of `cond', along with a demonstration of
2393 how it can short-circuit the side effects in `side'. Notice how all
2394 the unquoted side effects happen regardless of how many comparisons are
2395 made with `ifelse', compared with only the relevant effects with `cond'.
2398 `ifelse(`$#', `1', `$1',
2399 `ifelse($1, `$2', `$3',
2400 `$0(shift(shift(shift($@))))')')')dnl
2401 define(`side', `define(`counter', incr(counter))$1')dnl
2403 `define(`counter', `0')dnl
2404 ifelse(side(`$1'), `yes', `one comparison: ',
2405 side(`$1'), `no', `two comparisons: ',
2406 side(`$1'), `maybe', `three comparisons: ',
2407 `side(`default answer: ')')counter')dnl
2409 `define(`counter', `0')dnl
2410 cond(`side(`$1')', `yes', `one comparison: ',
2411 `side(`$1')', `no', `two comparisons: ',
2412 `side(`$1')', `maybe', `three comparisons: ',
2413 `side(`default answer: ')')counter')dnl
2417 =>two comparisons: 3
2419 =>three comparisons: 3
2420 example1(`feeling rather indecisive today')
2425 =>two comparisons: 2
2427 =>three comparisons: 3
2428 example2(`feeling rather indecisive today')
2431 Another common task that requires iteration is joining a list of
2432 arguments into a single string.
2434 -- Composite: join ([SEPARATOR], [ARGS...])
2435 -- Composite: joinall ([SEPARATOR], [ARGS...])
2436 Generate a single-quoted string, consisting of each ARG separated
2437 by SEPARATOR. While `joinall' always outputs a SEPARATOR between
2438 arguments, `join' avoids the SEPARATOR for an empty ARG.
2440 Here are some examples of its usage, based on the implementation
2441 `m4-1.4.16/examples/join.m4' distributed in this package:
2446 join,join(`-'),join(`-', `'),join(`-', `', `')
2448 joinall,joinall(`-'),joinall(`-', `'),joinall(`-', `', `')
2452 join(`-', `1', `2', `3')
2454 join(`', `1', `2', `3')
2456 join(`-', `', `1', `', `', `2', `')
2458 joinall(`-', `', `1', `', `', `2', `')
2460 join(`,', `1', `2', `3')
2462 define(`nargs', `$#')dnl
2463 nargs(join(`,', `1', `2', `3'))
2466 Examining the implementation shows some interesting points about
2467 several m4 programming idioms.
2470 undivert(`join.m4')dnl
2472 =># join(sep, args) - join each non-empty ARG into a single
2473 =># string, with each element separated by SEP
2475 =>`ifelse(`$#', `2', ``$2'',
2476 => `ifelse(`$2', `', `', ``$2'_')$0(`$1', shift(shift($@)))')')
2478 =>`ifelse(`$#$2', `2', `',
2479 => `ifelse(`$2', `', `', ``$1$2'')$0(`$1', shift(shift($@)))')')
2480 =># joinall(sep, args) - join each ARG, including empty ones,
2481 =># into a single string, with each element separated by SEP
2482 =>define(`joinall', ``$2'_$0(`$1', shift($@))')
2483 =>define(`_joinall',
2484 =>`ifelse(`$#', `2', `', ``$1$3'$0(`$1', shift(shift($@)))')')
2487 First, notice that this implementation creates helper macros `_join'
2488 and `_joinall'. This division of labor makes it easier to output the
2489 correct number of SEPARATOR instances: `join' and `joinall' are
2490 responsible for the first argument, without a separator, while `_join'
2491 and `_joinall' are responsible for all remaining arguments, always
2492 outputting a separator when outputting an argument.
2494 Next, observe how `join' decides to iterate to itself, because the
2495 first ARG was empty, or to output the argument and swap over to
2496 `_join'. If the argument is non-empty, then the nested `ifelse'
2497 results in an unquoted `_', which is concatenated with the `$0' to form
2498 the next macro name to invoke. The `joinall' implementation is simpler
2499 since it does not have to suppress empty ARG; it always executes once
2500 then defers to `_joinall'.
2502 Another important idiom is the idea that SEPARATOR is reused for
2503 each iteration. Each iteration has one less argument, but rather than
2504 discarding `$1' by iterating with `$0(shift($@))', the macro discards
2505 `$2' by using `$0(`$1', shift(shift($@)))'.
2507 Next, notice that it is possible to compare more than one condition
2508 in a single `ifelse' test. The test of `$#$2' against `2' allows
2509 `_join' to iterate for two separate reasons--either there are still
2510 more than two arguments, or there are exactly two arguments but the
2511 last argument is not empty.
2513 Finally, notice that these macros require exactly two arguments to
2514 terminate recursion, but that they still correctly result in empty
2515 output when given no ARGS (i.e., zero or one macro argument). On the
2516 first pass when there are too few arguments, the `shift' results in no
2517 output, but leaves an empty string to serve as the required second
2518 argument for the second pass. Put another way, ``$1', shift($@)' is
2519 not the same as `$@', since only the former guarantees at least two
2522 Sometimes, a recursive algorithm requires adding quotes to each
2523 element, or treating multiple arguments as a single element:
2525 -- Composite: quote (...)
2526 -- Composite: dquote (...)
2527 -- Composite: dquote_elt (...)
2528 Takes any number of arguments, and adds quoting. With `quote',
2529 only one level of quoting is added, effectively removing whitespace
2530 after commas and turning multiple arguments into a single string.
2531 With `dquote', two levels of quoting are added, one around each
2532 element, and one around the list. And with `dquote_elt', two
2533 levels of quoting are added around each element.
2535 An actual implementation of these three macros is distributed as
2536 `m4-1.4.16/examples/quote.m4' in this package. First, let's examine
2542 -quote-dquote-dquote_elt-
2544 -quote()-dquote()-dquote_elt()-
2546 -quote(`1')-dquote(`1')-dquote_elt(`1')-
2548 -quote(`1', `2')-dquote(`1', `2')-dquote_elt(`1', `2')-
2549 =>-1,2-`1',`2'-`1',`2'-
2550 define(`n', `$#')dnl
2551 -n(quote(`1', `2'))-n(dquote(`1', `2'))-n(dquote_elt(`1', `2'))-
2553 dquote(dquote_elt(`1', `2'))
2555 dquote_elt(dquote(`1', `2'))
2558 The last two lines show that when given two arguments, `dquote'
2559 results in one string, while `dquote_elt' results in two. Now, examine
2560 the implementation. Note that `quote' and `dquote_elt' make decisions
2561 based on their number of arguments, so that when called without
2562 arguments, they result in nothing instead of a quoted empty string;
2563 this is so that it is possible to distinguish between no arguments and
2564 an empty first argument. `dquote', on the other hand, results in a
2565 string no matter what, since it is still possible to tell whether it
2566 was invoked without arguments based on the resulting string.
2569 undivert(`quote.m4')dnl
2571 =># quote(args) - convert args to single-quoted string
2572 =>define(`quote', `ifelse(`$#', `0', `', ``$*'')')
2573 =># dquote(args) - convert args to quoted list of quoted strings
2574 =>define(`dquote', ``$@'')
2575 =># dquote_elt(args) - convert args to list of double-quoted strings
2576 =>define(`dquote_elt', `ifelse(`$#', `0', `', `$#', `1', ```$1''',
2577 => ```$1'',$0(shift($@))')')
2580 It is worth pointing out that `quote(ARGS)' is more efficient than
2581 `joinall(`,', ARGS)' for producing the same output.
2583 One more useful macro based on `shift' allows portably selecting an
2584 arbitrary argument (usually greater than the ninth argument), without
2585 relying on the GNU extension of multi-digit arguments (*note
2588 -- Composite: argn (N, ...)
2589 Expands to argument N out of the remaining arguments. N must be a
2590 positive number. Usually invoked as `argn(`N',$@)'.
2592 It is implemented as:
2594 define(`argn', `ifelse(`$1', 1, ``$2'',
2595 `argn(decr(`$1'), shift(shift($@)))')')
2599 define(`foo', `argn(`11', $@)')
2601 foo(`a', `b', `c', `d', `e', `f', `g', `h', `i', `j', `k', `l')
2605 File: m4.info, Node: Forloop, Next: Foreach, Prev: Shift, Up: Conditionals
2607 6.4 Iteration by counting
2608 =========================
2610 Here is an example of a loop macro that implements a simple for loop.
2612 -- Composite: forloop (ITERATOR, START, END, TEXT)
2613 Takes the name in ITERATOR, which must be a valid macro name, and
2614 successively assign it each integer value from START to END,
2615 inclusive. For each assignment to ITERATOR, append TEXT to the
2616 expansion of the `forloop'. TEXT may refer to ITERATOR. Any
2617 definition of ITERATOR prior to this invocation is restored.
2619 It can, for example, be used for simple counting:
2622 include(`forloop.m4')
2624 forloop(`i', `1', `8', `i ')
2627 For-loops can be nested, like:
2630 include(`forloop.m4')
2632 forloop(`i', `1', `4', `forloop(`j', `1', `8', ` (i, j)')
2634 => (1, 1) (1, 2) (1, 3) (1, 4) (1, 5) (1, 6) (1, 7) (1, 8)
2635 => (2, 1) (2, 2) (2, 3) (2, 4) (2, 5) (2, 6) (2, 7) (2, 8)
2636 => (3, 1) (3, 2) (3, 3) (3, 4) (3, 5) (3, 6) (3, 7) (3, 8)
2637 => (4, 1) (4, 2) (4, 3) (4, 4) (4, 5) (4, 6) (4, 7) (4, 8)
2640 The implementation of the `forloop' macro is fairly straightforward.
2641 The `forloop' macro itself is simply a wrapper, which saves the
2642 previous definition of the first argument, calls the internal macro
2643 `_forloop', and re-establishes the saved definition of the first
2646 The macro `_forloop' expands the fourth argument once, and tests to
2647 see if the iterator has reached the final value. If it has not
2648 finished, it increments the iterator (using the predefined macro
2649 `incr', *note Incr::), and recurses.
2651 Here is an actual implementation of `forloop', distributed as
2652 `m4-1.4.16/examples/forloop.m4' in this package:
2655 undivert(`forloop.m4')dnl
2657 =># forloop(var, from, to, stmt) - simple version
2658 =>define(`forloop', `pushdef(`$1', `$2')_forloop($@)popdef(`$1')')
2659 =>define(`_forloop',
2660 => `$4`'ifelse($1, `$3', `', `define(`$1', incr($1))$0($@)')')
2663 Notice the careful use of quotes. Certain macro arguments are left
2664 unquoted, each for its own reason. Try to find out _why_ these
2665 arguments are left unquoted, and see what happens if they are quoted.
2666 (As presented, these two macros are useful but not very robust for
2667 general use. They lack even basic error handling for cases like START
2668 less than END, END not numeric, or ITERATOR not being a macro name.
2669 See if you can improve these macros; or *note Answers: Improved
2673 File: m4.info, Node: Foreach, Next: Stacks, Prev: Forloop, Up: Conditionals
2675 6.5 Iteration by list contents
2676 ==============================
2678 Here is an example of a loop macro that implements list iteration.
2680 -- Composite: foreach (ITERATOR, PAREN-LIST, TEXT)
2681 -- Composite: foreachq (ITERATOR, QUOTE-LIST, TEXT)
2682 Takes the name in ITERATOR, which must be a valid macro name, and
2683 successively assign it each value from PAREN-LIST or QUOTE-LIST.
2684 In `foreach', PAREN-LIST is a comma-separated list of elements
2685 contained in parentheses. In `foreachq', QUOTE-LIST is a
2686 comma-separated list of elements contained in a quoted string.
2687 For each assignment to ITERATOR, append TEXT to the overall
2688 expansion. TEXT may refer to ITERATOR. Any definition of
2689 ITERATOR prior to this invocation is restored.
2691 As an example, this displays each word in a list inside of a
2692 sentence, using an implementation of `foreach' distributed as
2693 `m4-1.4.16/examples/foreach.m4', and `foreachq' in
2694 `m4-1.4.16/examples/foreachq.m4'.
2697 include(`foreach.m4')
2699 foreach(`x', (foo, bar, foobar), `Word was: x
2704 include(`foreachq.m4')
2706 foreachq(`x', `foo, bar, foobar', `Word was: x
2712 It is possible to be more complex; each element of the PAREN-LIST or
2713 QUOTE-LIST can itself be a list, to pass as further arguments to a
2714 helper macro. This example generates a shell case statement:
2717 include(`foreach.m4')
2719 define(`_case', ` $1)
2722 define(`_cat', `$1$2')dnl
2725 foreach(`x', `(`(`a', `vara')', `(`b', `varb')', `(`c', `varc')')',
2726 `_cat(`_case', x)')dnl
2736 The implementation of the `foreach' macro is a bit more involved; it
2737 is a wrapper around two helper macros. First, `_arg1' is needed to
2738 grab the first element of a list. Second, `_foreach' implements the
2739 recursion, successively walking through the original list. Here is a
2740 simple implementation of `foreach':
2743 undivert(`foreach.m4')dnl
2745 =># foreach(x, (item_1, item_2, ..., item_n), stmt)
2746 =># parenthesized list, simple version
2747 =>define(`foreach', `pushdef(`$1')_foreach($@)popdef(`$1')')
2748 =>define(`_arg1', `$1')
2749 =>define(`_foreach', `ifelse(`$2', `()', `',
2750 => `define(`$1', _arg1$2)$3`'$0(`$1', (shift$2), `$3')')')
2753 Unfortunately, that implementation is not robust to macro names as
2754 list elements. Each iteration of `_foreach' is stripping another layer
2755 of quotes, leading to erratic results if list elements are not already
2756 fully expanded. The first cut at implementing `foreachq' takes this
2757 into account. Also, when using quoted elements in a PAREN-LIST, the
2758 overall list must be quoted. A QUOTE-LIST has the nice property of
2759 requiring fewer characters to create a list containing the same quoted
2760 elements. To see the difference between the two macros, we attempt to
2761 pass double-quoted macro names in a list, expecting the macro name on
2762 output after one layer of quotes is removed during list iteration and
2763 the final layer removed during the final rescan:
2766 define(`a', `1')define(`b', `2')define(`c', `3')
2768 include(`foreach.m4')
2770 include(`foreachq.m4')
2772 foreach(`x', `(``a'', ``(b'', ``c)'')', `x
2779 foreachq(`x', ```a'', ``(b'', ``c)''', `x
2785 Obviously, `foreachq' did a better job; here is its implementation:
2788 undivert(`foreachq.m4')dnl
2789 =>include(`quote.m4')dnl
2791 =># foreachq(x, `item_1, item_2, ..., item_n', stmt)
2792 =># quoted list, simple version
2793 =>define(`foreachq', `pushdef(`$1')_foreachq($@)popdef(`$1')')
2794 =>define(`_arg1', `$1')
2795 =>define(`_foreachq', `ifelse(quote($2), `', `',
2796 => `define(`$1', `_arg1($2)')$3`'$0(`$1', `shift($2)', `$3')')')
2799 Notice that `_foreachq' had to use the helper macro `quote' defined
2800 earlier (*note Shift::), to ensure that the embedded `ifelse' call does
2801 not go haywire if a list element contains a comma. Unfortunately, this
2802 implementation of `foreachq' has its own severe flaw. Whereas the
2803 `foreach' implementation was linear, this macro is quadratic in the
2804 number of list elements, and is much more likely to trip up the limit
2805 set by the command line option `--nesting-limit' (or `-L', *note
2806 Invoking m4: Limits control.). Additionally, this implementation does
2807 not expand `defn(`ITERATOR')' very well, when compared with `foreach'.
2810 include(`foreach.m4')include(`foreachq.m4')
2812 foreach(`name', `(`a', `b')', ` defn(`name')')
2814 foreachq(`name', ``a', `b'', ` defn(`name')')
2815 => _arg1(`a', `b') _arg1(shift(`a', `b'))
2817 It is possible to have robust iteration with linear behavior and sane
2818 ITERATOR contents for either list style. See if you can learn from the
2819 best elements of both of these implementations to create robust macros
2820 (or *note Answers: Improved foreach.).
2823 File: m4.info, Node: Stacks, Next: Composition, Prev: Foreach, Up: Conditionals
2825 6.6 Working with definition stacks
2826 ==================================
2828 Thanks to `pushdef', manipulation of a stack is an intrinsic operation
2829 in `m4'. Normally, only the topmost definition in a stack is
2830 important, but sometimes, it is desirable to manipulate the entire
2833 -- Composite: stack_foreach (MACRO, ACTION)
2834 -- Composite: stack_foreach_lifo (MACRO, ACTION)
2835 For each of the `pushdef' definitions associated with MACRO,
2836 invoke the macro ACTION with a single argument of that definition.
2837 `stack_foreach' visits the oldest definition first, while
2838 `stack_foreach_lifo' visits the current definition first. ACTION
2839 should not modify or dereference MACRO. There are a few special
2840 macros, such as `defn', which cannot be used as the MACRO
2843 A sample implementation of these macros is distributed in the file
2844 `m4-1.4.16/examples/stack.m4'.
2849 pushdef(`a', `1')pushdef(`a', `2')pushdef(`a', `3')
2851 define(`show', ``$1'
2854 stack_foreach(`a', `show')dnl
2858 stack_foreach_lifo(`a', `show')dnl
2863 Now for the implementation. Note the definition of a helper macro,
2864 `_stack_reverse', which destructively swaps the contents of one stack
2865 of definitions into the reverse order in the temporary macro `tmp-$1'.
2866 By calling the helper twice, the original order is restored back into
2867 the macro `$1'; since the operation is destructive, this explains why
2868 `$1' must not be modified or dereferenced during the traversal. The
2869 caller can then inject additional code to pass the definition currently
2870 being visited to `$2'. The choice of helper names is intentional;
2871 since `-' is not valid as part of a macro name, there is no risk of
2872 conflict with a valid macro name, and the code is guaranteed to use
2873 `defn' where necessary. Finally, note that any macro used in the
2874 traversal of a `pushdef' stack, such as `pushdef' or `defn', cannot be
2875 handled by `stack_foreach', since the macro would temporarily be
2876 undefined during the algorithm.
2879 undivert(`stack.m4')dnl
2881 =># stack_foreach(macro, action)
2882 =># Invoke ACTION with a single argument of each definition
2883 =># from the definition stack of MACRO, starting with the oldest.
2884 =>define(`stack_foreach',
2885 =>`_stack_reverse(`$1', `tmp-$1')'dnl
2886 =>`_stack_reverse(`tmp-$1', `$1', `$2(defn(`$1'))')')
2887 =># stack_foreach_lifo(macro, action)
2888 =># Invoke ACTION with a single argument of each definition
2889 =># from the definition stack of MACRO, starting with the newest.
2890 =>define(`stack_foreach_lifo',
2891 =>`_stack_reverse(`$1', `tmp-$1', `$2(defn(`$1'))')'dnl
2892 =>`_stack_reverse(`tmp-$1', `$1')')
2893 =>define(`_stack_reverse',
2894 =>`ifdef(`$1', `pushdef(`$2', defn(`$1'))$3`'popdef(`$1')$0($@)')')
2898 File: m4.info, Node: Composition, Prev: Stacks, Up: Conditionals
2900 6.7 Building macros with macros
2901 ===============================
2903 Since m4 is a macro language, it is possible to write macros that can
2904 build other macros. First on the list is a way to automate the
2905 creation of blind macros.
2907 -- Composite: define_blind (NAME, [VALUE])
2908 Defines NAME as a blind macro, such that NAME will expand to VALUE
2909 only when given explicit arguments. VALUE should not be the
2910 result of `defn' (*note Defn::). This macro is only recognized
2911 with parameters, and results in an empty string.
2913 Defining a macro to define another macro can be a bit tricky. We
2914 want to use a literal `$#' in the argument to the nested `define'.
2915 However, if `$' and `#' are adjacent in the definition of
2916 `define_blind', then it would be expanded as the number of arguments to
2917 `define_blind' rather than the intended number of arguments to NAME.
2918 The solution is to pass the difficult characters through extra
2919 arguments to a helper macro `_define_blind'. When composing macros, it
2920 is a common idiom to need a helper macro to concatenate text that forms
2921 parameters in the composed macro, rather than interpreting the text as
2922 a parameter of the composing macro.
2924 As for the limitation against using `defn', there are two reasons.
2925 If a macro was previously defined with `define_blind', then it can
2926 safely be renamed to a new blind macro using plain `define'; using
2927 `define_blind' to rename it just adds another layer of `ifelse',
2928 occupying memory and slowing down execution. And if a macro is a
2929 builtin, then it would result in an attempt to define a macro
2930 consisting of both text and a builtin token; this is not supported, and
2931 the builtin token is flattened to an empty string.
2933 With that explanation, here's the definition, and some sample usage.
2934 Notice that `define_blind' is itself a blind macro.
2937 define(`define_blind', `ifelse(`$#', `0', ``$0'',
2938 `_$0(`$1', `$2', `$'`#', `$'`0')')')
2940 define(`_define_blind', `define(`$1',
2941 `ifelse(`$3', `0', ``$4'', `$2')')')
2945 define_blind(`foo', `arguments were $*')
2950 =>arguments were bar
2951 define(`blah', defn(`foo'))
2956 =>arguments were a,b
2958 =>ifelse(`$#', `0', ``$0'', `arguments were $*')
2960 Another interesting composition tactic is argument "currying", or
2961 factoring a macro that takes multiple arguments for use in a context
2962 that provides exactly one argument.
2964 -- Composite: curry (MACRO, ...)
2965 Expand to a macro call that takes exactly one argument, then
2966 appends that argument to the original arguments and invokes MACRO
2967 with the resulting list of arguments.
2969 A demonstration of currying makes the intent of this macro a little
2970 more obvious. The macro `stack_foreach' mentioned earlier is an example
2971 of a context that provides exactly one argument to a macro name. But
2972 coupled with currying, we can invoke `reverse' with two arguments for
2973 each definition of a macro stack. This example uses the file
2974 `m4-1.4.16/examples/curry.m4' included in the distribution.
2977 include(`curry.m4')include(`stack.m4')
2979 define(`reverse', `ifelse(`$#', `0', , `$#', `1', ``$1'',
2980 `reverse(shift($@)), `$1'')')
2982 pushdef(`a', `1')pushdef(`a', `2')pushdef(`a', `3')
2984 stack_foreach(`a', `:curry(`reverse', `4')')
2986 curry(`curry', `reverse', `1')(`2')(`3')
2989 Now for the implementation. Notice how `curry' leaves off with a
2990 macro name but no open parenthesis, while still in the middle of
2991 collecting arguments for `$1'. The macro `_curry' is the helper macro
2992 that takes one argument, then adds it to the list and finally supplies
2993 the closing parenthesis. The use of a comma inside the `shift' call
2994 allows currying to also work for a macro that takes one argument,
2995 although it often makes more sense to invoke that macro directly rather
2996 than going through `curry'.
2999 undivert(`curry.m4')dnl
3001 =># curry(macro, args)
3002 =># Expand to a macro call that takes one argument, then invoke
3003 =># macro(args, extra).
3004 =>define(`curry', `$1(shift($@,)_$0')
3005 =>define(`_curry', ``$1')')
3008 Unfortunately, with M4 1.4.x, `curry' is unable to handle builtin
3009 tokens, which are silently flattened to the empty string when passed
3010 through another text macro. This limitation will be lifted in a future
3013 Putting the last few concepts together, it is possible to copy or
3014 rename an entire stack of macro definitions.
3016 -- Composite: copy (SOURCE, DEST)
3017 -- Composite: rename (SOURCE, DEST)
3018 Ensure that DEST is undefined, then define it to the same stack of
3019 definitions currently in SOURCE. `copy' leaves SOURCE unchanged,
3020 while `rename' undefines SOURCE. There are only a few macros,
3021 such as `copy' or `defn', which cannot be copied via this macro.
3023 The implementation is relatively straightforward (although since it
3024 uses `curry', it is unable to copy builtin macros, such as the second
3025 definition of `a' as a synonym for `divnum'. See if you can design a
3026 version that works around this limitation, or *note Answers: Improved
3030 include(`curry.m4')include(`stack.m4')
3032 define(`rename', `copy($@)undefine(`$1')')dnl
3033 define(`copy', `ifdef(`$2', `errprint(`$2 already defined
3035 `stack_foreach(`$1', `curry(`pushdef', `$2')')')')dnl
3036 pushdef(`a', `1')pushdef(`a', defn(`divnum'))pushdef(`a', `2')
3050 File: m4.info, Node: Debugging, Next: Input Control, Prev: Conditionals, Up: Top
3052 7 How to debug macros and input
3053 *******************************
3055 When writing macros for `m4', they often do not work as intended on the
3056 first try (as is the case with most programming languages).
3057 Fortunately, there is support for macro debugging in `m4'.
3061 * Dumpdef:: Displaying macro definitions
3062 * Trace:: Tracing macro calls
3063 * Debug Levels:: Controlling debugging output
3064 * Debug Output:: Saving debugging output
3067 File: m4.info, Node: Dumpdef, Next: Trace, Up: Debugging
3069 7.1 Displaying macro definitions
3070 ================================
3072 If you want to see what a name expands into, you can use the builtin
3075 -- Builtin: dumpdef ([NAMES...])
3076 Accepts any number of arguments. If called without any arguments,
3077 it displays the definitions of all known names, otherwise it
3078 displays the definitions of the NAMES given. The output is
3079 printed to the current debug file (usually standard error), and is
3080 sorted by name. If an unknown name is encountered, a warning is
3083 The expansion of `dumpdef' is void.
3086 define(`foo', `Hello world.')
3089 error-->foo: `Hello world.'
3092 error-->define: <define>
3095 The last example shows how builtin macros definitions are displayed.
3096 The definition that is dumped corresponds to what would occur if the
3097 macro were to be called at that point, even if other definitions are
3098 still live due to redefining a macro during argument collection.
3101 pushdef(`f', ``$0'1')pushdef(`f', ``$0'2')
3103 f(popdef(`f')dumpdef(`f'))
3106 f(popdef(`f')dumpdef(`f'))
3107 error-->m4:stdin:3: undefined macro `f'
3110 *Note Debug Levels::, for information on controlling the details of
3114 File: m4.info, Node: Trace, Next: Debug Levels, Prev: Dumpdef, Up: Debugging
3116 7.2 Tracing macro calls
3117 =======================
3119 It is possible to trace macro calls and expansions through the builtins
3120 `traceon' and `traceoff':
3122 -- Builtin: traceon ([NAMES...])
3123 -- Builtin: traceoff ([NAMES...])
3124 When called without any arguments, `traceon' and `traceoff' will
3125 turn tracing on and off, respectively, for all currently defined
3128 When called with arguments, only the macros listed in NAMES are
3129 affected, whether or not they are currently defined.
3131 The expansion of `traceon' and `traceoff' is void.
3133 Whenever a traced macro is called and the arguments have been
3134 collected, the call is displayed. If the expansion of the macro call
3135 is not void, the expansion can be displayed after the call. The output
3136 is printed to the current debug file (defaulting to standard error,
3137 *note Debug Output::).
3140 define(`foo', `Hello World.')
3142 define(`echo', `$@')
3144 traceon(`foo', `echo')
3147 error-->m4trace: -1- foo -> `Hello World.'
3149 echo(`gnus', `and gnats')
3150 error-->m4trace: -1- echo(`gnus', `and gnats') -> ``gnus',`and gnats''
3153 The number between dashes is the depth of the expansion. It is one
3154 most of the time, signifying an expansion at the outermost level, but it
3155 increases when macro arguments contain unquoted macro calls. The
3156 maximum number that will appear between dashes is controlled by the
3157 option `--nesting-limit' (or `-L', *note Invoking m4: Limits control.).
3158 Additionally, the option `--trace' (or `-t') can be used to invoke
3159 `traceon(NAME)' before parsing input.
3163 error-->m4trace: -1- ifelse
3165 ifelse(ifelse(ifelse(`three levels')))
3166 error-->m4trace: -3- ifelse
3167 error-->m4trace: -2- ifelse
3168 error-->m4trace: -1- ifelse
3170 ifelse(ifelse(ifelse(ifelse(`four levels'))))
3171 error-->m4:stdin:3: recursion limit of 3 exceeded, use -L<N> to change it
3173 Tracing by name is an attribute that is preserved whether the macro
3174 is defined or not. This allows the selection of macros to trace before
3175 those macros are defined.
3186 define(`foo', `bar')
3189 error-->m4trace: -1- foo -> `bar'
3193 ifdef(`foo', `yes', `no')
3196 error-->m4:stdin:9: undefined macro `foo'
3198 define(`foo', `blah')
3201 error-->m4trace: -1- foo -> `blah'
3208 Tracing even works on builtins. However, `defn' (*note Defn::) does
3209 not transfer tracing status.
3215 error-->m4trace: -1- traceon(`traceoff')
3217 traceoff(`traceoff')
3218 error-->m4trace: -1- traceoff(`traceoff')
3222 traceon(`eval', `m4_divnum')
3224 define(`m4_eval', defn(`eval'))
3226 define(`m4_divnum', defn(`divnum'))
3229 error-->m4trace: -1- eval(`0') -> `0'
3232 error-->m4trace: -2- m4_divnum -> `0'
3235 *Note Debug Levels::, for information on controlling the details of
3236 the display. The format of the trace output is not specified by POSIX,
3237 and varies between implementations of `m4'.
3240 File: m4.info, Node: Debug Levels, Next: Debug Output, Prev: Trace, Up: Debugging
3242 7.3 Controlling debugging output
3243 ================================
3245 The `-d' option to `m4' (or `--debug', *note Invoking m4: Debugging
3246 options.) controls the amount of details presented in three categories
3247 of output. Trace output is requested by `traceon' (*note Trace::), and
3248 each line is prefixed by `m4trace:' in relation to a macro invocation.
3249 Debug output tracks useful events not associated with a macro
3250 invocation, and each line is prefixed by `m4debug:'. Finally,
3251 `dumpdef' (*note Dumpdef::) output is affected, with no prefix added to
3254 The FLAGS following the option can be one or more of the following:
3257 In trace output, show the actual arguments that were collected
3258 before invoking the macro. This applies to all macro calls if the
3259 `t' flag is used, otherwise only the macros covered by calls of
3260 `traceon'. Arguments are subject to length truncation specified by
3261 the command line option `--arglength' (or `-l').
3264 In trace output, show several trace lines for each macro call. A
3265 line is shown when the macro is seen, but before the arguments are
3266 collected; a second line when the arguments have been collected
3267 and a third line after the call has completed.
3270 In trace output, show the expansion of each macro call, if it is
3271 not void. This applies to all macro calls if the `t' flag is used,
3272 otherwise only the macros covered by calls of `traceon'. The
3273 expansion is subject to length truncation specified by the command
3274 line option `--arglength' (or `-l').
3277 In debug and trace output, include the name of the current input
3278 file in the output line.
3281 In debug output, print a message each time the current input file
3285 In debug and trace output, include the current input line number
3289 In debug output, print a message when a named file is found
3290 through the path search mechanism (*note Search Path::), giving
3291 the actual file name used.
3294 In trace and dumpdef output, quote actual arguments and macro
3295 expansions in the display with the current quotes. This is useful
3296 in connection with the `a' and `e' flags above.
3299 In trace output, trace all macro calls made in this invocation of
3300 `m4', regardless of the settings of `traceon'.
3303 In trace output, add a unique `macro call id' to each line of the
3304 trace output. This is useful in connection with the `c' flag
3308 A shorthand for all of the above flags.
3310 If no flags are specified with the `-d' option, the default is
3311 `aeq'. The examples throughout this manual assume the default flags.
3313 There is a builtin macro `debugmode', which allows on-the-fly
3314 control of the debugging output format:
3316 -- Builtin: debugmode ([FLAGS])
3317 The argument FLAGS should be a subset of the letters listed above.
3318 As special cases, if the argument starts with a `+', the flags are
3319 added to the current debug flags, and if it starts with a `-', they
3320 are removed. If no argument is present, all debugging flags are
3321 cleared (as if no `-d' was given), and with an empty argument the
3322 flags are reset to the default of `aeq'.
3324 The expansion of `debugmode' is void.
3327 define(`foo', `FOO')
3334 error-->m4trace: -1- foo -> `FOO'
3339 error-->m4trace: -1- foo
3344 error-->m4trace:8: -1- foo
3347 The following example demonstrates the behavior of length truncation,
3348 when specified on the command line. Note that each argument and the
3349 final result are individually truncated. Also, the special tokens for
3350 builtin functions are not truncated.
3353 define(`echo', `$@')debugmode(`+t')
3355 echo(`1', `long string')
3356 error-->m4trace: -1- echo(`1', `long s...') -> ``1',`l...'
3358 indir(`echo', defn(`changequote'))
3359 error-->m4trace: -2- defn(`change...')
3360 error-->m4trace: -1- indir(`echo', <changequote>) -> ``''
3363 This example shows the effects of the debug flags that are not
3364 related to macro tracing.
3366 $ m4 -dip -I examples
3367 error-->m4debug: input read from stdin
3369 error-->m4debug: path search for `foo' found `examples/foo'
3370 error-->m4debug: input read from examples/foo
3372 error-->m4debug: input reverted to stdin, line 1
3374 error-->m4debug: input exhausted
3377 File: m4.info, Node: Debug Output, Prev: Debug Levels, Up: Debugging
3379 7.4 Saving debugging output
3380 ===========================
3382 Debug and tracing output can be redirected to files using either the
3383 `--debugfile' option to `m4' (*note Invoking m4: Debugging options.),
3384 or with the builtin macro `debugfile':
3386 -- Builtin: debugfile ([FILE])
3387 Sends all further debug and trace output to FILE, opened in append
3388 mode. If FILE is the empty string, debug and trace output are
3389 discarded. If `debugfile' is called without any arguments, debug
3390 and trace output are sent to standard error. This does not affect
3391 warnings, error messages, or `errprint' output, which are always
3392 sent to standard error. If FILE cannot be opened, the current
3393 debug file is unchanged, and an error is issued.
3395 The expansion of `debugfile' is void.
3401 error-->m4:stdin:2: Warning: excess arguments to builtin `divnum' ignored
3402 error-->m4trace: -1- divnum(`extra') -> `0'
3407 error-->m4:stdin:4: Warning: excess arguments to builtin `divnum' ignored
3412 error-->m4trace: -1- divnum -> `0'
3416 File: m4.info, Node: Input Control, Next: File Inclusion, Prev: Debugging, Up: Top
3421 This chapter describes various builtin macros for controlling the input
3426 * Dnl:: Deleting whitespace in input
3427 * Changequote:: Changing the quote characters
3428 * Changecom:: Changing the comment delimiters
3429 * Changeword:: Changing the lexical structure of words
3430 * M4wrap:: Saving text until end of input
3433 File: m4.info, Node: Dnl, Next: Changequote, Up: Input Control
3435 8.1 Deleting whitespace in input
3436 ================================
3438 The builtin `dnl' stands for "Discard to Next Line":
3441 All characters, up to and including the next newline, are discarded
3442 without performing any macro expansion. A warning is issued if
3443 the end of the file is encountered without a newline.
3445 The expansion of `dnl' is void.
3447 It is often used in connection with `define', to remove the newline
3448 that follows the call to `define'. Thus
3450 define(`foo', `Macro `foo'.')dnl A very simple macro, indeed.
3454 The input up to and including the next newline is discarded, as
3455 opposed to the way comments are treated (*note Comments::).
3457 Usually, `dnl' is immediately followed by an end of line or some
3458 other whitespace. GNU `m4' will produce a warning diagnostic if `dnl'
3459 is followed by an open parenthesis. In this case, `dnl' will collect
3460 and process all arguments, looking for a matching close parenthesis.
3461 All predictable side effects resulting from this collection will take
3462 place. `dnl' will return no output. The input following the matching
3463 close parenthesis up to and including the next newline, on whatever
3464 line containing it, will still be discarded.
3466 dnl(`args are ignored, but side effects occur',
3467 define(`foo', `like this')) while this text is ignored: undefine(`foo')
3468 error-->m4:stdin:1: Warning: excess arguments to builtin `dnl' ignored
3469 See how `foo' was defined, foo?
3470 =>See how foo was defined, like this?
3472 If the end of file is encountered without a newline character, a
3473 warning is issued and dnl stops consuming input.
3475 m4wrap(`m4wrap(`2 hi
3481 error-->m4:stdin:1: Warning: end of file treated as newline
3485 File: m4.info, Node: Changequote, Next: Changecom, Prev: Dnl, Up: Input Control
3487 8.2 Changing the quote characters
3488 =================================
3490 The default quote delimiters can be changed with the builtin
3493 -- Builtin: changequote ([START = ``'], [END = `''])
3494 This sets START as the new begin-quote delimiter and END as the
3495 new end-quote delimiter. If both arguments are missing, the
3496 default quotes (``' and `'') are used. If START is void, then
3497 quoting is disabled. Otherwise, if END is missing or void, the
3498 default end-quote delimiter (`'') is used. The quote delimiters
3499 can be of any length.
3501 The expansion of `changequote' is void.
3503 changequote(`[', `]')
3505 define([foo], [Macro [foo].])
3510 The quotation strings can safely contain eight-bit characters. If
3511 no single character is appropriate, START and END can be of any length.
3512 Other implementations cap the delimiter length to five characters, but
3513 GNU has no inherent limit.
3515 changequote(`[[[', `]]]')
3517 define([[[foo]]], [[[Macro [[[[[foo]]]]].]]])
3522 Calling `changequote' with START as the empty string will
3523 effectively disable the quoting mechanism, leaving no way to quote text.
3524 However, using an empty string is not portable, as some other
3525 implementations of `m4' revert to the default quoting, while others
3526 preserve the prior non-empty delimiter. If START is not empty, then an
3527 empty END will use the default end-quote delimiter of `'', as
3528 otherwise, it would be impossible to end a quoted string. Again, this
3529 is not portable, as some other `m4' implementations reuse START as the
3530 end-quote delimiter, while others preserve the previous non-empty
3531 value. Omitting both arguments restores the default begin-quote and
3532 end-quote delimiters; fortunately this behavior is portable to all
3533 implementations of `m4'.
3535 define(`foo', `Macro `FOO'.')
3548 There is no way in `m4' to quote a string containing an unmatched
3549 begin-quote, except using `changequote' to change the current quotes.
3551 If the quotes should be changed from, say, `[' to `[[', temporary
3552 quote characters have to be defined. To achieve this, two calls of
3553 `changequote' must be made, one for the temporary quotes and one for
3556 Macros are recognized in preference to the begin-quote string, so if
3557 a prefix of START can be recognized as part of a potential macro name,
3558 the quoting mechanism is effectively disabled. Unless you use
3559 `changeword' (*note Changeword::), this means that START should not
3560 begin with a letter, digit, or `_' (underscore). However, even though
3561 quoted strings are not recognized, the quote characters can still be
3562 discerned in macro expansion and in trace output.
3564 define(`echo', `$@')
3568 changequote(`q', `Q')
3576 changequote(`-', `EOF')
3582 changequote(`1', `2')
3589 Quotes are recognized in preference to argument collection. In
3590 particular, if START is a single `(', then argument collection is
3591 effectively disabled. For portability with other implementations, it
3592 is a good idea to avoid `(', `,', and `)' as the first character in
3595 define(`echo', `$#:$@:')
3599 changequote(`(',`)')
3605 changequote(`((', `))')
3613 changequote(`,', `)')
3618 However, if you are not worried about portability, using `(' and `)'
3619 as quoting characters has an interesting property--you can use it to
3620 compute a quoted string containing the expansion of any quoted text, as
3621 long as the expansion results in both balanced quotes and balanced
3622 parentheses. The trick is realizing `expand' uses `$1' unquoted, to
3623 trigger its expansion using the normal quoting characters, but uses
3624 extra parentheses to group unquoted commas that occur in the expansion
3625 without consuming whitespace following those commas. Then `_expand'
3626 uses `changequote' to convert the extra parentheses back into quoting
3627 characters. Note that it takes two more `changequote' invocations to
3628 restore the original quotes. Contrast the behavior on whitespace when
3629 using `$*', via `quote', to attempt the same task.
3631 changequote(`[', `]')dnl
3632 define([a], [1, (b)])dnl
3634 define([quote], [[$*]])dnl
3635 define([expand], [_$0(($1))])dnl
3637 [changequote([(], [)])$1changequote`'changequote(`[', `]')])dnl
3638 expand([a, a, [a, a], [[a, a]]])
3639 =>1, (2), 1, (2), a, a, [a, a]
3640 quote(a, a, [a, a], [[a, a]])
3641 =>1,(2),1,(2),a, a,[a, a]
3643 If END is a prefix of START, the end-quote will be recognized in
3644 preference to a nested begin-quote. In particular, changing the quotes
3645 to have the same string for START and END disables nesting of quotes.
3646 When quote nesting is disabled, it is impossible to double-quote
3647 strings across macro expansions, so using the same string is not done
3652 changequote(`""', `"')
3664 changequote(`"', `"')
3669 It is an error if the end of file occurs within a quoted string.
3675 error-->m4:stdin:2: ERROR: end of file in string
3677 ifelse(`dangling quote
3679 error-->m4:stdin:1: ERROR: end of file in string
3682 File: m4.info, Node: Changecom, Next: Changeword, Prev: Changequote, Up: Input Control
3684 8.3 Changing the comment delimiters
3685 ===================================
3687 The default comment delimiters can be changed with the builtin macro
3690 -- Builtin: changecom ([START], [END = `<NL>'])
3691 This sets START as the new begin-comment delimiter and END as the
3692 new end-comment delimiter. If both arguments are missing, or
3693 START is void, then comments are disabled. Otherwise, if END is
3694 missing or void, the default end-comment delimiter of newline is
3695 used. The comment delimiters can be of any length.
3697 The expansion of `changecom' is void.
3699 define(`comment', `COMMENT')
3702 =># A normal comment
3703 changecom(`/*', `*/')
3705 # Not a comment anymore
3706 =># Not a COMMENT anymore
3707 But: /* this is a comment now */ while this is not a comment
3708 =>But: /* this is a comment now */ while this is not a COMMENT
3710 Note how comments are copied to the output, much as if they were
3711 quoted strings. If you want the text inside a comment expanded, quote
3712 the begin-comment delimiter.
3714 Calling `changecom' without any arguments, or with START as the
3715 empty string, will effectively disable the commenting mechanism. To
3716 restore the original comment start of `#', you must explicitly ask for
3717 it. If START is not empty, then an empty END will use the default
3718 end-comment delimiter of newline, as otherwise, it would be impossible
3719 to end a comment. However, this is not portable, as some other `m4'
3720 implementations preserve the previous non-empty delimiters instead.
3722 define(`comment', `COMMENT')
3726 # Not a comment anymore
3727 =># Not a COMMENT anymore
3733 The comment strings can safely contain eight-bit characters. If no
3734 single character is appropriate, START and END can be of any length.
3735 Other implementations cap the delimiter length to five characters, but
3736 GNU has no inherent limit.
3738 Comments are recognized in preference to macros. However, this is
3739 not compatible with other implementations, where macros and even quoting
3740 takes precedence over comments, so it may change in a future release.
3741 For portability, this means that START should not begin with a letter,
3742 digit, or `_' (underscore), and that neither the start-quote nor the
3743 start-comment string should be a prefix of the other.
3747 define(`hi1hi2', `hello')
3760 Comments are recognized in preference to argument collection. In
3761 particular, if START is a single `(', then argument collection is
3762 effectively disabled. For portability with other implementations, it
3763 is a good idea to avoid `(', `,', and `)' as the first character in
3766 define(`echo', `$#:$*:$@:')
3776 changecom(`((', `))')
3785 =>1:HI,hi)bye:HI,hi)bye:
3789 =>3:HI,,HI,HI:HI,,`'hi,HI:
3790 echo(hi,`,`'hi',hi`'changecom(`,,', `hi'))
3791 =>3:HI,,`'hi,HI:HI,,`'hi,HI:
3793 It is an error if the end of file occurs within a comment.
3795 changecom(`/*', `*/')
3799 error-->m4:stdin:2: ERROR: end of file in comment
3802 File: m4.info, Node: Changeword, Next: M4wrap, Prev: Changecom, Up: Input Control
3804 8.4 Changing the lexical structure of words
3805 ===========================================
3807 The macro `changeword' and all associated functionality is
3808 experimental. It is only available if the `--enable-changeword'
3809 option was given to `configure', at GNU `m4' installation time.
3810 The functionality will go away in the future, to be replaced by
3811 other new features that are more efficient at providing the same
3812 capabilities. _Do not rely on it_. Please direct your comments
3813 about it the same way you would do for bugs.
3815 A file being processed by `m4' is split into quoted strings, words
3816 (potential macro names) and simple tokens (any other single character).
3817 Initially a word is defined by the following regular expression:
3819 [_a-zA-Z][_a-zA-Z0-9]*
3821 Using `changeword', you can change this regular expression:
3823 -- Optional builtin: changeword (REGEX)
3824 Changes the regular expression for recognizing macro names to be
3825 REGEX. If REGEX is empty, use `[_a-zA-Z][_a-zA-Z0-9]*'. REGEX
3826 must obey the constraint that every prefix of the desired final
3827 pattern is also accepted by the regular expression. If REGEX
3828 contains grouping parentheses, the macro invoked is the portion
3829 that matched the first group, rather than the entire matching
3832 The expansion of `changeword' is void. The macro `changeword' is
3833 recognized only with parameters.
3835 Relaxing the lexical rules of `m4' might be useful (for example) if
3836 you wanted to apply translations to a file of numbers:
3838 ifdef(`changeword', `', `errprint(` skipping: no changeword support
3840 changeword(`[_a-zA-Z0-9]+')
3845 Tightening the lexical rules is less useful, because it will
3846 generally make some of the builtins unavailable. You could use it to
3847 prevent accidental call of builtins, for example:
3849 ifdef(`changeword', `', `errprint(` skipping: no changeword support
3851 define(`_indir', defn(`indir'))
3853 changeword(`_[_a-zA-Z0-9]*')
3857 _indir(`esyscmd', `echo hi')
3861 Because `m4' constructs its words a character at a time, there is a
3862 restriction on the regular expressions that may be passed to
3863 `changeword'. This is that if your regular expression accepts `foo',
3864 it must also accept `f' and `fo'.
3866 ifdef(`changeword', `', `errprint(` skipping: no changeword support
3872 dnl This example wants to recognize changeword, dnl, and `foo\n'.
3873 dnl First, we check that our regexp will match.
3874 regexp(`changeword', `[cd][a-z]*\|foo[
3878 ', `[cd][a-z]*\|foo[
3881 regexp(`f', `[cd][a-z]*\|foo[
3886 changeword(`[cd][a-z]*\|foo[
3889 dnl Even though `foo\n' matches, we forgot to allow `f'.
3892 changeword(`[cd][a-z]*\|fo*[
3895 dnl Now we can call `foo\n'.
3899 `changeword' has another function. If the regular expression
3900 supplied contains any grouped subexpressions, then text outside the
3901 first of these is discarded before symbol lookup. So:
3903 ifdef(`changeword', `', `errprint(` skipping: no changeword support
3906 `errprint(` skipping: syscmd does not have unix semantics
3908 changecom(`/*', `*/')dnl
3909 define(`foo', `bar')dnl
3910 changeword(`#\([_a-zA-Z0-9]*\)')
3912 #esyscmd(`echo foo \#foo')
3916 `m4' now requires a `#' mark at the beginning of every macro
3917 invocation, so one can use `m4' to preprocess plain text without losing
3918 various words like `divert'.
3920 In `m4', macro substitution is based on text, while in TeX, it is
3921 based on tokens. `changeword' can throw this difference into relief.
3922 For example, here is the same idea represented in TeX and `m4'. First,
3925 \def\a{\message{Hello}}
3932 Then, the `m4' version:
3934 ifdef(`changeword', `', `errprint(` skipping: no changeword support
3936 define(`a', `errprint(`Hello')')dnl
3937 changeword(`@\([_a-zA-Z0-9]*\)')
3942 In the TeX example, the first line defines a macro `a' to print the
3943 message `Hello'. The second line defines <@> to be usable instead of
3944 <\> as an escape character. The third line defines <\> to be a normal
3945 printing character, not an escape. The fourth line invokes the macro
3946 `a'. So, when TeX is run on this file, it displays the message `Hello'.
3948 When the `m4' example is passed through `m4', it outputs
3949 `errprint(Hello)'. The reason for this is that TeX does lexical
3950 analysis of macro definition when the macro is _defined_. `m4' just
3951 stores the text, postponing the lexical analysis until the macro is
3954 You should note that using `changeword' will slow `m4' down by a
3955 factor of about seven, once it is changed to something other than the
3956 default regular expression. You can invoke `changeword' with the empty
3957 string to restore the default word definition, and regain the parsing
3961 File: m4.info, Node: M4wrap, Prev: Changeword, Up: Input Control
3963 8.5 Saving text until end of input
3964 ==================================
3966 It is possible to `save' some text until the end of the normal input has
3967 been seen. Text can be saved, to be read again by `m4' when the normal
3968 input has been exhausted. This feature is normally used to initiate
3969 cleanup actions before normal exit, e.g., deleting temporary files.
3971 To save input text, use the builtin `m4wrap':
3973 -- Builtin: m4wrap (STRING, ...)
3974 Stores STRING in a safe place, to be reread when end of input is
3975 reached. As a GNU extension, additional arguments are
3976 concatenated with a space to the STRING.
3978 The expansion of `m4wrap' is void. The macro `m4wrap' is
3979 recognized only with parameters.
3981 define(`cleanup', `This is the `cleanup' action.
3986 This is the first and last normal input line.
3987 =>This is the first and last normal input line.
3989 =>This is the cleanup action.
3991 The saved input is only reread when the end of normal input is seen,
3992 and not if `m4exit' is used to exit `m4'.
3994 It is safe to call `m4wrap' from saved text, but then the order in
3995 which the saved text is reread is undefined. If `m4wrap' is not used
3996 recursively, the saved pieces of text are reread in the opposite order
3997 in which they were saved (LIFO--last in, first out). However, this
3998 behavior is likely to change in a future release, to match POSIX, so
3999 you should not depend on this order.
4001 It is possible to emulate POSIX behavior even with older versions of
4002 GNU M4 by including the file `m4-1.4.16/examples/wrapfifo.m4' from the
4006 undivert(`wrapfifo.m4')dnl
4007 =>dnl Redefine m4wrap to have FIFO semantics.
4008 =>define(`_m4wrap_level', `0')dnl
4010 =>`ifdef(`m4wrap'_m4wrap_level,
4011 => `define(`m4wrap'_m4wrap_level,
4012 => defn(`m4wrap'_m4wrap_level)`$1')',
4013 => `builtin(`m4wrap', `define(`_m4wrap_level',
4014 => incr(_m4wrap_level))dnl
4015 =>m4wrap'_m4wrap_level)dnl
4016 =>define(`m4wrap'_m4wrap_level, `$1')')')dnl
4017 include(`wrapfifo.m4')
4019 m4wrap(`a`'m4wrap(`c
4020 ', `d')')m4wrap(`b')
4025 It is likewise possible to emulate LIFO behavior without resorting to
4026 the GNU M4 extension of `builtin', by including the file
4027 `m4-1.4.16/examples/wraplifo.m4' from the distribution.
4028 (Unfortunately, both examples shown here share some subtle bugs. See
4029 if you can find and correct them; or *note Answers: Improved m4wrap.).
4032 undivert(`wraplifo.m4')dnl
4033 =>dnl Redefine m4wrap to have LIFO semantics.
4034 =>define(`_m4wrap_level', `0')dnl
4035 =>define(`_m4wrap', defn(`m4wrap'))dnl
4037 =>`ifdef(`m4wrap'_m4wrap_level,
4038 => `define(`m4wrap'_m4wrap_level,
4039 => `$1'defn(`m4wrap'_m4wrap_level))',
4040 => `_m4wrap(`define(`_m4wrap_level', incr(_m4wrap_level))dnl
4041 =>m4wrap'_m4wrap_level)dnl
4042 =>define(`m4wrap'_m4wrap_level, `$1')')')dnl
4043 include(`wraplifo.m4')
4045 m4wrap(`a`'m4wrap(`c
4046 ', `d')')m4wrap(`b')
4051 Here is an example of implementing a factorial function using
4054 define(`f', `ifelse(`$1', `0', `Answer: 0!=1
4055 ', eval(`$1>1'), `0', `Answer: $2$1=eval(`$2$1')
4056 ', `m4wrap(`f(decr(`$1'), `$2$1*')')')')
4061 =>Answer: 10*9*8*7*6*5*4*3*2*1=3628800
4063 Invocations of `m4wrap' at the same recursion level are concatenated
4064 and rescanned as usual:
4069 m4wrap(`a')m4wrap(`a')
4074 however, the transition between recursion levels behaves like an end of
4075 file condition between two input files.
4077 m4wrap(`m4wrap(`)')len(abc')
4080 error-->m4:stdin:1: ERROR: end of file in argument list
4083 File: m4.info, Node: File Inclusion, Next: Diversions, Prev: Input Control, Up: Top
4088 `m4' allows you to include named files at any point in the input.
4092 * Include:: Including named files
4093 * Search Path:: Searching for include files
4096 File: m4.info, Node: Include, Next: Search Path, Up: File Inclusion
4098 9.1 Including named files
4099 =========================
4101 There are two builtin macros in `m4' for including files:
4103 -- Builtin: include (FILE)
4104 -- Builtin: sinclude (FILE)
4105 Both macros cause the file named FILE to be read by `m4'. When
4106 the end of the file is reached, input is resumed from the previous
4109 The expansion of `include' and `sinclude' is therefore the
4112 If FILE does not exist, is a directory, or cannot otherwise be
4113 read, the expansion is void, and `include' will fail with an error
4114 while `sinclude' is silent. The empty string counts as a file
4115 that does not exist.
4117 The macros `include' and `sinclude' are recognized only with
4121 error-->m4:stdin:1: cannot open `none': No such file or directory
4124 error-->m4:stdin:2: cannot open `': No such file or directory
4131 The rest of this section assumes that `m4' is invoked with the `-I'
4132 option (*note Invoking m4: Preprocessor features.) pointing to the
4133 `m4-1.4.16/examples' directory shipped as part of the GNU `m4' package.
4134 The file `m4-1.4.16/examples/incl.m4' in the distribution contains the
4137 $ cat examples/incl.m4
4138 =>Include file start
4142 Normally file inclusion is used to insert the contents of a file
4143 into the input stream. The contents of the file will be read by `m4'
4144 and macro calls in the file will be expanded:
4147 define(`foo', `FOO')
4150 =>Include file start
4155 The fact that `include' and `sinclude' expand to the contents of the
4156 file can be used to define macros that operate on entire files. Here
4157 is an example, which defines `bar' to expand to the contents of
4161 define(`bar', include(`incl.m4'))
4163 This is `bar': >>bar<<
4164 =>This is bar: >>Include file start
4169 This use of `include' is not trivial, though, as files can contain
4170 quotes, commas, and parentheses, which can interfere with the way the
4171 `m4' parser works. GNU `m4' seamlessly concatenates the file contents
4172 with the next character, even if the included file ended in the middle
4173 of a comment, string, or macro call. These conditions are only treated
4174 as end of file errors if specified as input files on the command line.
4176 In GNU `m4', an alternative method of reading files is using
4177 `undivert' (*note Undivert::) on a named file.
4180 File: m4.info, Node: Search Path, Prev: Include, Up: File Inclusion
4182 9.2 Searching for include files
4183 ===============================
4185 GNU `m4' allows included files to be found in other directories than
4186 the current working directory.
4188 If the `--prepend-include' or `-B' command-line option was provided
4189 (*note Invoking m4: Preprocessor features.), those directories are
4190 searched first, in reverse order that those options were listed on the
4191 command line. Then `m4' looks in the current working directory. Next
4192 comes the directories specified with the `--include' or `-I' option, in
4193 the order found on the command line. Finally, if the `M4PATH'
4194 environment variable is set, it is expected to contain a
4195 colon-separated list of directories, which will be searched in order.
4197 If the automatic search for include-files causes trouble, the `p'
4198 debug flag (*note Debug Levels::) can help isolate the problem.
4201 File: m4.info, Node: Diversions, Next: Text handling, Prev: File Inclusion, Up: Top
4203 10 Diverting and undiverting output
4204 ***********************************
4206 Diversions are a way of temporarily saving output. The output of `m4'
4207 can at any time be diverted to a temporary file, and be reinserted into
4208 the output stream, "undiverted", again at a later time.
4210 Numbered diversions are counted from 0 upwards, diversion number 0
4211 being the normal output stream. GNU `m4' tries to keep diversions in
4212 memory. However, there is a limit to the overall memory usable by all
4213 diversions taken together (512K, currently). When this maximum is
4214 about to be exceeded, a temporary file is opened to receive the
4215 contents of the biggest diversion still in memory, freeing this memory
4216 for other diversions. When creating the temporary file, `m4' honors
4217 the value of the environment variable `TMPDIR', and falls back to
4218 `/tmp'. Thus, the amount of available disk space provides the only
4219 real limit on the number and aggregate size of diversions.
4221 Diversions make it possible to generate output in a different order
4222 than the input was read. It is possible to implement topological
4223 sorting dependencies. For example, GNU Autoconf makes use of
4224 diversions under the hood to ensure that the expansion of a prerequisite
4225 macro appears in the output prior to the expansion of a dependent macro,
4226 regardless of which order the two macros were invoked in the user's
4231 * Divert:: Diverting output
4232 * Undivert:: Undiverting output
4233 * Divnum:: Diversion numbers
4234 * Cleardivert:: Discarding diverted text
4237 File: m4.info, Node: Divert, Next: Undivert, Up: Diversions
4239 10.1 Diverting output
4240 =====================
4242 Output is diverted using `divert':
4244 -- Builtin: divert ([NUMBER = `0'])
4245 The current diversion is changed to NUMBER. If NUMBER is left out
4246 or empty, it is assumed to be zero. If NUMBER cannot be parsed,
4247 the diversion is unchanged.
4249 The expansion of `divert' is void.
4251 When all the `m4' input will have been processed, all existing
4252 diversions are automatically undiverted, in numerical order.
4255 This text is diverted.
4258 This text is not diverted.
4259 =>This text is not diverted.
4262 =>This text is diverted.
4264 Several calls of `divert' with the same argument do not overwrite
4265 the previous diverted text, but append to it. Diversions are printed
4266 after any wrapped text is expanded.
4268 define(`text', `TEXT')
4270 divert(`1')`diverted text.'
4273 m4wrap(`Wrapped text precedes ')
4276 =>Wrapped TEXT precedes diverted text.
4278 If output is diverted to a negative diversion, it is simply
4279 discarded. This can be used to suppress unwanted output. A common
4280 example of unwanted output is the trailing newlines after macro
4281 definitions. Here is a common programming idiom in `m4' for avoiding
4285 define(`foo', `Macro `foo'.')
4286 define(`bar', `Macro `bar'.')
4290 Traditional implementations only supported ten diversions. But as a
4291 GNU extension, diversion numbers can be as large as positive integers
4292 will allow, rather than treating a multi-digit diversion number as a
4293 request to discard text.
4295 divert(eval(`1<<28'))world
4301 Note that `divert' is an English word, but also an active macro
4302 without arguments. When processing plain text, the word might appear in
4303 normal text and be unintentionally swallowed as a macro invocation. One
4304 way to avoid this is to use the `-P' option to rename all builtins
4305 (*note Invoking m4: Operation modes.). Another is to write a wrapper
4306 that requires a parameter to be recognized.
4308 We decided to divert the stream for irrigation.
4309 =>We decided to the stream for irrigation.
4310 define(`divert', `ifelse(`$#', `0', ``$0'', `builtin(`$0', $@)')')
4316 We decided to divert the stream for irrigation.
4317 =>We decided to divert the stream for irrigation.
4320 File: m4.info, Node: Undivert, Next: Divnum, Prev: Divert, Up: Diversions
4322 10.2 Undiverting output
4323 =======================
4325 Diverted text can be undiverted explicitly using the builtin `undivert':
4327 -- Builtin: undivert ([DIVERSIONS...])
4328 Undiverts the numeric DIVERSIONS given by the arguments, in the
4329 order given. If no arguments are supplied, all diversions are
4330 undiverted, in numerical order.
4332 As a GNU extension, DIVERSIONS may contain non-numeric strings,
4333 which are treated as the names of files to copy into the output
4334 without expansion. A warning is issued if a file could not be
4337 The expansion of `undivert' is void.
4340 This text is diverted.
4343 This text is not diverted.
4344 =>This text is not diverted.
4347 =>This text is diverted.
4350 Notice the last two blank lines. One of them comes from the newline
4351 following `undivert', the other from the newline that followed the
4352 `divert'! A diversion often starts with a blank line like this.
4354 When diverted text is undiverted, it is _not_ reread by `m4', but
4355 rather copied directly to the current output, and it is therefore not
4356 an error to undivert into a diversion. Undiverting the empty string is
4357 the same as specifying diversion 0; in either case nothing happens
4358 since the output has already been flushed.
4360 divert(`1')diverted text
4371 divert(`2')undivert(`1')diverted text`'divert
4379 When a diversion has been undiverted, the diverted text is discarded,
4380 and it is not possible to bring back diverted text more than once.
4383 This text is diverted first.
4384 divert(`0')undivert(`1')dnl
4386 =>This text is diverted first.
4390 This text is also diverted but not appended.
4391 divert(`0')undivert(`1')dnl
4393 =>This text is also diverted but not appended.
4395 Attempts to undivert the current diversion are silently ignored.
4396 Thus, when the current diversion is not 0, the current diversion does
4397 not get rearranged among the other diversions.
4402 divert(`2')undivert`'dnl
4403 divert`'undivert`'dnl
4408 GNU `m4' allows named files to be undiverted. Given a non-numeric
4409 argument, the contents of the file named will be copied, uninterpreted,
4410 to the current output. This complements the builtin `include' (*note
4411 Include::). To illustrate the difference, assume the file `foo'
4419 define(`bar', `BAR')
4428 If the file is not found (or cannot be read), an error message is
4429 issued, and the expansion is void. It is possible to intermix files
4430 and diversion numbers.
4432 divert(`1')diversion one
4433 divert(`2')undivert(`foo')dnl
4434 divert(`3')diversion three
4436 undivert(`1', `2', `foo', `3')dnl
4443 File: m4.info, Node: Divnum, Next: Cleardivert, Prev: Undivert, Up: Diversions
4445 10.3 Diversion numbers
4446 ======================
4448 The current diversion is tracked by the builtin `divnum':
4451 Expands to the number of the current diversion.
4456 Diversion one: divnum
4458 Diversion two: divnum
4466 File: m4.info, Node: Cleardivert, Prev: Divnum, Up: Diversions
4468 10.4 Discarding diverted text
4469 =============================
4471 Often it is not known, when output is diverted, whether the diverted
4472 text is actually needed. Since all non-empty diversion are brought back
4473 on the main output stream when the end of input is seen, a method of
4474 discarding a diversion is needed. If all diversions should be
4475 discarded, the easiest is to end the input to `m4' with `divert(`-1')'
4476 followed by an explicit `undivert':
4479 Diversion one: divnum
4481 Diversion two: divnum
4486 No output is produced at all.
4488 Clearing selected diversions can be done with the following macro:
4490 -- Composite: cleardivert ([DIVERSIONS...])
4491 Discard the contents of each of the listed numeric DIVERSIONS.
4493 define(`cleardivert',
4494 `pushdef(`_n', divnum)divert(`-1')undivert($@)divert(_n)popdef(`_n')')
4497 It is called just like `undivert', but the effect is to clear the
4498 diversions, given by the arguments. (This macro has a nasty bug! You
4499 should try to see if you can find it and correct it; or *note Answers:
4500 Improved cleardivert.).
4503 File: m4.info, Node: Text handling, Next: Arithmetic, Prev: Diversions, Up: Top
4505 11 Macros for text handling
4506 ***************************
4508 There are a number of builtins in `m4' for manipulating text in various
4509 ways, extracting substrings, searching, substituting, and so on.
4513 * Len:: Calculating length of strings
4514 * Index macro:: Searching for substrings
4515 * Regexp:: Searching for regular expressions
4516 * Substr:: Extracting substrings
4517 * Translit:: Translating characters
4518 * Patsubst:: Substituting text by regular expression
4519 * Format:: Formatting strings (printf-like)
4522 File: m4.info, Node: Len, Next: Index macro, Up: Text handling
4524 11.1 Calculating length of strings
4525 ==================================
4527 The length of a string can be calculated by `len':
4529 -- Builtin: len (STRING)
4530 Expands to the length of STRING, as a decimal number.
4532 The macro `len' is recognized only with parameters.
4540 File: m4.info, Node: Index macro, Next: Regexp, Prev: Len, Up: Text handling
4542 11.2 Searching for substrings
4543 =============================
4545 Searching for substrings is done with `index':
4547 -- Builtin: index (STRING, SUBSTRING)
4548 Expands to the index of the first occurrence of SUBSTRING in
4549 STRING. The first character in STRING has index 0. If SUBSTRING
4550 does not occur in STRING, `index' expands to `-1'.
4552 The macro `index' is recognized only with parameters.
4554 index(`gnus, gnats, and armadillos', `nat')
4556 index(`gnus, gnats, and armadillos', `dag')
4559 Omitting SUBSTRING evokes a warning, but still produces output;
4560 contrast this with an empty SUBSTRING.
4563 error-->m4:stdin:1: Warning: too few arguments to builtin `index'
4571 File: m4.info, Node: Regexp, Next: Substr, Prev: Index macro, Up: Text handling
4573 11.3 Searching for regular expressions
4574 ======================================
4576 Searching for regular expressions is done with the builtin `regexp':
4578 -- Builtin: regexp (STRING, REGEXP, [REPLACEMENT])
4579 Searches for REGEXP in STRING. The syntax for regular expressions
4580 is the same as in GNU Emacs, which is similar to BRE, Basic
4581 Regular Expressions in POSIX. *Note Syntax of Regular
4582 Expressions: (emacs)Regexps. Support for ERE, Extended Regular
4583 Expressions is not available, but will be added in GNU M4 2.0.
4585 If REPLACEMENT is omitted, `regexp' expands to the index of the
4586 first match of REGEXP in STRING. If REGEXP does not match
4587 anywhere in STRING, it expands to -1.
4589 If REPLACEMENT is supplied, and there was a match, `regexp'
4590 changes the expansion to this argument, with `\N' substituted by
4591 the text matched by the Nth parenthesized sub-expression of
4592 REGEXP, up to nine sub-expressions. The escape `\&' is replaced
4593 by the text of the entire regular expression matched. For all
4594 other characters, `\' treats the next character literally. A
4595 warning is issued if there were fewer sub-expressions than the
4596 `\N' requested, or if there is a trailing `\'. If there was no
4597 match, `regexp' expands to the empty string.
4599 The macro `regexp' is recognized only with parameters.
4601 regexp(`GNUs not Unix', `\<[a-z]\w+')
4603 regexp(`GNUs not Unix', `\<Q\w*')
4605 regexp(`GNUs not Unix', `\w\(\w+\)$', `*** \& *** \1 ***')
4606 =>*** Unix *** nix ***
4607 regexp(`GNUs not Unix', `\<Q\w*', `*** \& *** \1 ***')
4610 Here are some more examples on the handling of backslash:
4612 regexp(`abc', `\(b\)', `\\\10\a')
4614 regexp(`abc', `b', `\1\')
4615 error-->m4:stdin:2: Warning: sub-expression 1 not present
4616 error-->m4:stdin:2: Warning: trailing \ ignored in replacement
4618 regexp(`abc', `\(\(d\)?\)\(c\)', `\1\2\3\4\5\6')
4619 error-->m4:stdin:3: Warning: sub-expression 4 not present
4620 error-->m4:stdin:3: Warning: sub-expression 5 not present
4621 error-->m4:stdin:3: Warning: sub-expression 6 not present
4624 Omitting REGEXP evokes a warning, but still produces output;
4625 contrast this with an empty REGEXP argument.
4628 error-->m4:stdin:1: Warning: too few arguments to builtin `regexp'
4632 regexp(`abc', `', `\\def')
4636 File: m4.info, Node: Substr, Next: Translit, Prev: Regexp, Up: Text handling
4638 11.4 Extracting substrings
4639 ==========================
4641 Substrings are extracted with `substr':
4643 -- Builtin: substr (STRING, FROM, [LENGTH])
4644 Expands to the substring of STRING, which starts at index FROM,
4645 and extends for LENGTH characters, or to the end of STRING, if
4646 LENGTH is omitted. The starting index of a string is always 0.
4647 The expansion is empty if there is an error parsing FROM or
4648 LENGTH, if FROM is beyond the end of STRING, or if LENGTH is
4651 The macro `substr' is recognized only with parameters.
4653 substr(`gnus, gnats, and armadillos', `6')
4654 =>gnats, and armadillos
4655 substr(`gnus, gnats, and armadillos', `6', `5')
4658 Omitting FROM evokes a warning, but still produces output.
4661 error-->m4:stdin:1: Warning: too few arguments to builtin `substr'
4664 error-->m4:stdin:2: empty string treated as 0 in builtin `substr'
4668 File: m4.info, Node: Translit, Next: Patsubst, Prev: Substr, Up: Text handling
4670 11.5 Translating characters
4671 ===========================
4673 Character translation is done with `translit':
4675 -- Builtin: translit (STRING, CHARS, [REPLACEMENT])
4676 Expands to STRING, with each character that occurs in CHARS
4677 translated into the character from REPLACEMENT with the same index.
4679 If REPLACEMENT is shorter than CHARS, the excess characters of
4680 CHARS are deleted from the expansion; if CHARS is shorter, the
4681 excess characters in REPLACEMENT are silently ignored. If
4682 REPLACEMENT is omitted, all characters in STRING that are present
4683 in CHARS are deleted from the expansion. If a character appears
4684 more than once in CHARS, only the first instance is used in making
4685 the translation. Only a single translation pass is made, even if
4686 characters in REPLACEMENT also appear in CHARS.
4688 As a GNU extension, both CHARS and REPLACEMENT can contain
4689 character-ranges, e.g., `a-z' (meaning all lowercase letters) or
4690 `0-9' (meaning all digits). To include a dash `-' in CHARS or
4691 REPLACEMENT, place it first or last in the entire string, or as
4692 the last character of a range. Back-to-back ranges can share a
4693 common endpoint. It is not an error for the last character in the
4694 range to be `larger' than the first. In that case, the range runs
4695 backwards, i.e., `9-0' means the string `9876543210'. The
4696 expansion of a range is dependent on the underlying encoding of
4697 characters, so using ranges is not always portable between
4700 The macro `translit' is recognized only with parameters.
4702 translit(`GNUs not Unix', `A-Z')
4704 translit(`GNUs not Unix', `a-z', `A-Z')
4706 translit(`GNUs not Unix', `A-Z', `z-a')
4708 translit(`+,-12345', `+--1-5', `<;>a-c-a')
4710 translit(`abcdef', `aabdef', `bcged')
4713 In the ASCII encoding, the first example deletes all uppercase
4714 letters, the second converts lowercase to uppercase, and the third
4715 `mirrors' all uppercase letters, while converting them to lowercase.
4716 The two first cases are by far the most common, even though they are not
4717 portable to EBCDIC or other encodings. The fourth example shows a
4718 range ending in `-', as well as back-to-back ranges. The final example
4719 shows that `a' is mapped to `b', not `c'; the resulting `b' is not
4720 further remapped to `g'; the `d' and `e' are swapped, and the `f' is
4723 Omitting CHARS evokes a warning, but still produces output.
4726 error-->m4:stdin:1: Warning: too few arguments to builtin `translit'
4730 File: m4.info, Node: Patsubst, Next: Format, Prev: Translit, Up: Text handling
4732 11.6 Substituting text by regular expression
4733 ============================================
4735 Global substitution in a string is done by `patsubst':
4737 -- Builtin: patsubst (STRING, REGEXP, [REPLACEMENT])
4738 Searches STRING for matches of REGEXP, and substitutes REPLACEMENT
4739 for each match. The syntax for regular expressions is the same as
4740 in GNU Emacs (*note Regexp::).
4742 The parts of STRING that are not covered by any match of REGEXP
4743 are copied to the expansion. Whenever a match is found, the
4744 search proceeds from the end of the match, so a character from
4745 STRING will never be substituted twice. If REGEXP matches a
4746 string of zero length, the start position for the search is
4747 incremented, to avoid infinite loops.
4749 When a replacement is to be made, REPLACEMENT is inserted into the
4750 expansion, with `\N' substituted by the text matched by the Nth
4751 parenthesized sub-expression of PATSUBST, for up to nine
4752 sub-expressions. The escape `\&' is replaced by the text of the
4753 entire regular expression matched. For all other characters, `\'
4754 treats the next character literally. A warning is issued if there
4755 were fewer sub-expressions than the `\N' requested, or if there is
4758 The REPLACEMENT argument can be omitted, in which case the text
4759 matched by REGEXP is deleted.
4761 The macro `patsubst' is recognized only with parameters.
4763 patsubst(`GNUs not Unix', `^', `OBS: ')
4764 =>OBS: GNUs not Unix
4765 patsubst(`GNUs not Unix', `\<', `OBS: ')
4766 =>OBS: GNUs OBS: not OBS: Unix
4767 patsubst(`GNUs not Unix', `\w*', `(\&)')
4768 =>(GNUs)() (not)() (Unix)()
4769 patsubst(`GNUs not Unix', `\w+', `(\&)')
4770 =>(GNUs) (not) (Unix)
4771 patsubst(`GNUs not Unix', `[A-Z][a-z]+')
4773 patsubst(`GNUs not Unix', `not', `NOT\')
4774 error-->m4:stdin:6: Warning: trailing \ ignored in replacement
4777 Here is a slightly more realistic example, which capitalizes
4778 individual words or whole sentences, by substituting calls of the macros
4779 `upcase' and `downcase' into the strings.
4781 -- Composite: upcase (TEXT)
4782 -- Composite: downcase (TEXT)
4783 -- Composite: capitalize (TEXT)
4784 Expand to TEXT, but with capitalization changed: `upcase' changes
4785 all letters to upper case, `downcase' changes all letters to lower
4786 case, and `capitalize' changes the first character of each word to
4787 upper case and the remaining characters to lower case.
4789 First, an example of their usage, using implementations distributed
4790 in `m4-1.4.16/examples/capitalize.m4'.
4793 include(`capitalize.m4')
4795 upcase(`GNUs not Unix')
4797 downcase(`GNUs not Unix')
4799 capitalize(`GNUs not Unix')
4802 Now for the implementation. There is a helper macro `_capitalize'
4803 which puts only its first word in mixed case. Then `capitalize' merely
4804 parses out the words, and replaces them with an invocation of
4805 `_capitalize'. (As presented here, the `capitalize' macro has some
4806 subtle flaws. You should try to see if you can find and correct them;
4807 or *note Answers: Improved capitalize.).
4810 undivert(`capitalize.m4')dnl
4814 =># capitalize(text)
4815 =># change case of text, simple version
4816 =>define(`upcase', `translit(`$*', `a-z', `A-Z')')
4817 =>define(`downcase', `translit(`$*', `A-Z', `a-z')')
4818 =>define(`_capitalize',
4819 => `regexp(`$1', `^\(\w\)\(\w*\)',
4820 => `upcase(`\1')`'downcase(`\2')')')
4821 =>define(`capitalize', `patsubst(`$1', `\w+', `_$0(`\&')')')
4824 While `regexp' replaces the whole input with the replacement as soon
4825 as there is a match, `patsubst' replaces each _occurrence_ of a match
4826 and preserves non-matching pieces:
4831 patreg(`bar foo baz Foo', `foo\|Foo', `FOO')
4834 patreg(`aba abb 121', `\(.\)\(.\)\1', `\2\1\2')
4838 Omitting REGEXP evokes a warning, but still produces output;
4839 contrast this with an empty REGEXP argument.
4842 error-->m4:stdin:1: Warning: too few arguments to builtin `patsubst'
4846 patsubst(`abc', `', `\\-')
4850 File: m4.info, Node: Format, Prev: Patsubst, Up: Text handling
4852 11.7 Formatting strings (printf-like)
4853 =====================================
4855 Formatted output can be made with `format':
4857 -- Builtin: format (FORMAT-STRING, ...)
4858 Works much like the C function `printf'. The first argument
4859 FORMAT-STRING can contain `%' specifications which are satisfied
4860 by additional arguments, and the expansion of `format' is the
4863 The macro `format' is recognized only with parameters.
4865 Its use is best described by a few examples:
4867 define(`foo', `The brown fox jumped over the lazy dog')
4869 format(`The string "%s" uses %d characters', foo, len(foo))
4870 =>The string "The brown fox jumped over the lazy dog" uses 38 characters
4871 format(`%*.*d', `-1', `-1', `1')
4873 format(`%.0f', `56789.9876')
4875 len(format(`%-*X', `5000', `1'))
4877 ifelse(format(`%010F', `infinity'), ` INF', `success',
4878 format(`%010F', `infinity'), ` INFINITY', `success',
4879 format(`%010F', `infinity'))
4881 ifelse(format(`%.1A', `1.999'), `0X1.0P+1', `success',
4882 format(`%.1A', `1.999'), `0X2.0P+0', `success',
4883 format(`%.1A', `1.999'))
4885 format(`%g', `0xa.P+1')
4888 Using the `forloop' macro defined earlier (*note Forloop::), this
4889 example shows how `format' can be used to produce tabular output.
4892 include(`forloop.m4')
4894 forloop(`i', `1', `10', `format(`%6d squared is %10d
4905 => 10 squared is 100
4908 The builtin `format' is modeled after the ANSI C `printf' function,
4909 and supports these `%' specifiers: `c', `s', `d', `o', `x', `X', `u',
4910 `a', `A', `e', `E', `f', `F', `g', `G', and `%'; it supports field
4911 widths and precisions, and the flags `+', `-', ` ', `0', `#', and `''.
4912 For integer specifiers, the width modifiers `hh', `h', and `l' are
4913 recognized, and for floating point specifiers, the width modifier `l'
4914 is recognized. Items not yet supported include positional arguments,
4915 the `n', `p', `S', and `C' specifiers, the `z', `t', `j', `L' and `ll'
4916 modifiers, and any platform extensions available in the native
4917 `printf'. For more details on the functioning of `printf', see the C
4918 Library Manual, or the POSIX specification (for example, `%a' is
4919 supported even on platforms that haven't yet implemented C99
4920 hexadecimal floating point output natively).
4922 Unrecognized specifiers result in a warning. It is anticipated that
4923 a future release of GNU `m4' will support more specifiers, and give
4924 better warnings when various problems such as overflow are encountered.
4925 Likewise, escape sequences are not yet recognized.
4928 error-->m4:stdin:1: Warning: unrecognized specifier in `%p'
4932 File: m4.info, Node: Arithmetic, Next: Shell commands, Prev: Text handling, Up: Top
4934 12 Macros for doing arithmetic
4935 ******************************
4937 Integer arithmetic is included in `m4', with a C-like syntax. As
4938 convenient shorthands, there are builtins for simple increment and
4939 decrement operations.
4943 * Incr:: Decrement and increment operators
4944 * Eval:: Evaluating integer expressions
4947 File: m4.info, Node: Incr, Next: Eval, Up: Arithmetic
4949 12.1 Decrement and increment operators
4950 ======================================
4952 Increment and decrement of integers are supported using the builtins
4955 -- Builtin: incr (NUMBER)
4956 -- Builtin: decr (NUMBER)
4957 Expand to the numerical value of NUMBER, incremented or
4958 decremented, respectively, by one. Except for the empty string,
4959 the expansion is empty if NUMBER could not be parsed.
4961 The macros `incr' and `decr' are recognized only with parameters.
4968 error-->m4:stdin:3: empty string treated as 0 in builtin `incr'
4971 error-->m4:stdin:4: empty string treated as 0 in builtin `decr'
4975 File: m4.info, Node: Eval, Prev: Incr, Up: Arithmetic
4977 12.2 Evaluating integer expressions
4978 ===================================
4980 Integer expressions are evaluated with `eval':
4982 -- Builtin: eval (EXPRESSION, [RADIX = `10'], [WIDTH])
4983 Expands to the value of EXPRESSION. The expansion is empty if a
4984 problem is encountered while parsing the arguments. If specified,
4985 RADIX and WIDTH control the format of the output.
4987 Calculations are done with 32-bit signed numbers. Overflow
4988 silently results in wraparound. A warning is issued if division
4989 by zero is attempted, or if EXPRESSION could not be parsed.
4991 Expressions can contain the following operators, listed in order of
4992 decreasing precedence.
4998 Unary plus and minus, and bitwise and logical negation
5004 Multiplication, division, and modulo
5007 Addition and subtraction
5013 Relational operators
5022 Bitwise exclusive-or
5033 The macro `eval' is recognized only with parameters.
5035 All binary operators, except exponentiation, are left associative. C
5036 operators that perform variable assignment, such as `+=' or `--', are
5037 not implemented, since `eval' only operates on constants, not
5038 variables. Attempting to use them results in an error. However, since
5039 traditional implementations treated `=' as an undocumented alias for
5040 `==' as opposed to an assignment operator, this usage is supported as a
5041 special case. Be aware that a future version of GNU M4 may support
5042 assignment semantics as an extension when POSIX mode is not requested,
5043 and that using `=' to check equality is not portable.
5046 error-->m4:stdin:1: Warning: recommend ==, not =, for equality operator
5049 error-->m4:stdin:2: invalid operator in eval: ++0
5052 error-->m4:stdin:3: invalid operator in eval: 0 |= 1
5055 Note that some older `m4' implementations use `^' as an alternate
5056 operator for the exponentiation, although POSIX requires the C behavior
5057 of bitwise exclusive-or. The precedence of the negation operators, `~'
5058 and `!', was traditionally lower than equality. The unary operators
5059 could not be used reliably more than once on the same term without
5060 intervening parentheses. The traditional precedence of the equality
5061 operators `==' and `!=' was identical instead of lower than the
5062 relational operators such as `<', even through GNU M4 1.4.8. Starting
5063 with version 1.4.9, GNU M4 correctly follows POSIX precedence rules.
5064 M4 scripts designed to be portable between releases must be aware that
5065 parentheses may be required to enforce C precedence rules. Likewise,
5066 division by zero, even in the unused branch of a short-circuiting
5067 operator, is not always well-defined in other implementations.
5069 Following are some examples where the current version of M4 follows C
5070 precedence rules, but where older versions and some other
5071 implementations of `m4' require explicit parentheses to get the correct
5076 eval(`(1 == 2) > 0')
5086 eval(`+ + - ~ ! ~ 0')
5091 error-->m4:stdin:9: divide by zero in eval: 0 || 1 / 0
5096 error-->m4:stdin:11: modulo by zero in eval: 2 && 1 % 0
5099 As a GNU extension, the operator `**' performs integral
5100 exponentiation. The operator is right-associative, and if evaluated,
5101 the exponent must be non-negative, and at least one of the arguments
5102 must be non-zero, or a warning is issued.
5106 eval(`(2 ** 3) ** 2')
5114 error-->m4:stdin:5: divide by zero in eval: 0 ** 0
5116 error-->m4:stdin:6: negative exponent in eval: 4 ** -2
5119 Within EXPRESSION, (but not RADIX or WIDTH), numbers without a
5120 special prefix are decimal. A simple `0' prefix introduces an octal
5121 number. `0x' introduces a hexadecimal number. As GNU extensions, `0b'
5122 introduces a binary number. `0r' introduces a number expressed in any
5123 radix between 1 and 36: the prefix should be immediately followed by
5124 the decimal expression of the radix, a colon, then the digits making
5125 the number. For radix 1, leading zeros are ignored, and all remaining
5126 digits must be `1'; for all other radices, the digits are `0', `1', `2',
5127 .... Beyond `9', the digits are `a', `b' ... up to `z'. Lower and
5128 upper case letters can be used interchangeably in numbers prefixes and
5131 Parentheses may be used to group subexpressions whenever needed.
5132 For the relational operators, a true relation returns `1', and a false
5133 relation return `0'.
5135 Here are a few examples of use of `eval'.
5145 eval(index(`Hello world', `llo') >= 0)
5147 eval(`0r1:0111 + 0b100 + 0r3:12')
5149 define(`square', `eval(`($1) ** 2')')
5153 square(square(`5')` + 1')
5155 define(`foo', `666')
5158 error-->m4:stdin:11: bad expression in eval: foo / 6
5163 As the last two lines show, `eval' does not handle macro names, even
5164 if they expand to a valid expression (or part of a valid expression).
5165 Therefore all macros must be expanded before they are passed to `eval'.
5167 Some calculations are not portable to other implementations, since
5168 they have undefined semantics in C, but GNU `m4' has well-defined
5169 behavior on overflow. When shifting, an out-of-range shift amount is
5170 implicitly brought into the range of 32-bit signed integers using an
5171 implicit bit-wise and with 0x1f).
5173 define(`max_int', eval(`0x7fffffff'))
5175 define(`min_int', incr(max_int))
5181 ifelse(eval(min_int` / -1'), min_int, `overflow occurred')
5185 eval(`0x80000000 % -1')
5192 If RADIX is specified, it specifies the radix to be used in the
5193 expansion. The default radix is 10; this is also the case if RADIX is
5194 the empty string. A warning results if the radix is outside the range
5195 of 1 through 36, inclusive. The result of `eval' is always taken to be
5196 signed. No radix prefix is output, and for radices greater than 10,
5197 the digits are lower case. The WIDTH argument specifies the minimum
5198 output width, excluding any negative sign. The result is zero-padded
5199 to extend the expansion to the requested width. A warning results if
5200 the width is negative. If RADIX or WIDTH is out of bounds, the
5201 expansion of `eval' is empty.
5209 eval(`666', `6', `10')
5211 eval(`-666', `6', `10')
5215 `0r1:'eval(`10', `1', `11')
5220 error-->m4:stdin:9: radix 37 in builtin `eval' out of range
5223 error-->m4:stdin:10: negative width to builtin `eval'
5226 error-->m4:stdin:11: empty string treated as 0 in builtin `eval'
5230 File: m4.info, Node: Shell commands, Next: Miscellaneous, Prev: Arithmetic, Up: Top
5232 13 Macros for running shell commands
5233 ************************************
5235 There are a few builtin macros in `m4' that allow you to run shell
5236 commands from within `m4'.
5238 Note that the definition of a valid shell command is system
5239 dependent. On UNIX systems, this is the typical `/bin/sh'. But on
5240 other systems, such as native Windows, the shell has a different syntax
5241 of commands that it understands. Some examples in this chapter assume
5242 `/bin/sh', and also demonstrate how to quit early with a known exit
5243 value if this is not the case.
5247 * Platform macros:: Determining the platform
5248 * Syscmd:: Executing simple commands
5249 * Esyscmd:: Reading the output of commands
5250 * Sysval:: Exit status
5251 * Mkstemp:: Making temporary files
5254 File: m4.info, Node: Platform macros, Next: Syscmd, Up: Shell commands
5256 13.1 Determining the platform
5257 =============================
5259 Sometimes it is desirable for an input file to know which platform `m4'
5260 is running on. GNU `m4' provides several macros that are predefined to
5261 expand to the empty string; checking for their existence will confirm
5264 -- Optional builtin: __gnu__
5265 -- Optional builtin: __os2__
5266 -- Optional builtin: os2
5267 -- Optional builtin: __unix__
5268 -- Optional builtin: unix
5269 -- Optional builtin: __windows__
5270 -- Optional builtin: windows
5271 Each of these macros is conditionally defined as needed to
5272 describe the environment of `m4'. If defined, each macro expands
5273 to the empty string. For now, these macros silently ignore all
5274 arguments, but in a future release of M4, they might warn if
5275 arguments are present.
5277 When GNU extensions are in effect (that is, when you did not use the
5278 `-G' option, *note Invoking m4: Limits control.), GNU `m4' will define
5279 the macro `__gnu__' to expand to the empty string.
5286 Extensions are ifdef(`__gnu__', `active', `inactive')
5287 =>Extensions are active
5294 Extensions are ifdef(`__gnu__', `active', `inactive')
5295 =>Extensions are inactive
5297 On UNIX systems, GNU `m4' will define `__unix__' by default, or
5298 `unix' when the `-G' option is specified.
5300 On native Windows systems, GNU `m4' will define `__windows__' by
5301 default, or `windows' when the `-G' option is specified.
5303 On OS/2 systems, GNU `m4' will define `__os2__' by default, or `os2'
5304 when the `-G' option is specified.
5306 If GNU `m4' does not provide a platform macro for your system,
5307 please report that as a bug.
5309 define(`provided', `0')
5311 ifdef(`__unix__', `define(`provided', incr(provided))')
5313 ifdef(`__windows__', `define(`provided', incr(provided))')
5315 ifdef(`__os2__', `define(`provided', incr(provided))')
5321 File: m4.info, Node: Syscmd, Next: Esyscmd, Prev: Platform macros, Up: Shell commands
5323 13.2 Executing simple commands
5324 ==============================
5326 Any shell command can be executed, using `syscmd':
5328 -- Builtin: syscmd (SHELL-COMMAND)
5329 Executes SHELL-COMMAND as a shell command.
5331 The expansion of `syscmd' is void, _not_ the output from
5332 SHELL-COMMAND! Output or error messages from SHELL-COMMAND are
5333 not read by `m4'. *Note Esyscmd::, if you need to process the
5336 Prior to executing the command, `m4' flushes its buffers. The
5337 default standard input, output and error of SHELL-COMMAND are the
5338 same as those of `m4'.
5340 By default, the SHELL-COMMAND will be used as the argument to the
5341 `-c' option of the `/bin/sh' shell (or the version of `sh'
5342 specified by `command -p getconf PATH', if your system supports
5343 that). If you prefer a different shell, the `configure' script
5344 can be given the option `--with-syscmd-shell=LOCATION' to set the
5345 location of an alternative shell at GNU `m4' installation; the
5346 alternative shell must still support `-c'.
5348 The macro `syscmd' is recognized only with parameters.
5350 define(`foo', `FOO')
5356 Note how the expansion of `syscmd' keeps the trailing newline of the
5357 command, as well as using the newline that appeared after the macro.
5359 The following is an example of SHELL-COMMAND using the same standard
5362 $ echo "m4wrap(\`syscmd(\`cat')')" | m4
5365 It tells `m4' to read all of its input before executing the wrapped
5366 text, then hand a valid (albeit emptied) pipe as standard input for the
5367 `cat' subcommand. Therefore, you should be careful when using standard
5368 input (either by specifying no files, or by passing `-' as a file name
5369 on the command line, *note Invoking m4: Command line files.), and also
5370 invoking subcommands via `syscmd' or `esyscmd' that consume data from
5371 standard input. When standard input is a seekable file, the subprocess
5372 will pick up with the next character not yet processed by `m4'; when it
5373 is a pipe or other non-seekable file, there is no guarantee how much
5374 data will already be buffered by `m4' and thus unavailable to the child.
5377 File: m4.info, Node: Esyscmd, Next: Sysval, Prev: Syscmd, Up: Shell commands
5379 13.3 Reading the output of commands
5380 ===================================
5382 If you want `m4' to read the output of a shell command, use `esyscmd':
5384 -- Builtin: esyscmd (SHELL-COMMAND)
5385 Expands to the standard output of the shell command SHELL-COMMAND.
5387 Prior to executing the command, `m4' flushes its buffers. The
5388 default standard input and standard error of SHELL-COMMAND are the
5389 same as those of `m4'. The error output of SHELL-COMMAND is not a
5390 part of the expansion: it will appear along with the error output
5393 By default, the SHELL-COMMAND will be used as the argument to the
5394 `-c' option of the `/bin/sh' shell (or the version of `sh'
5395 specified by `command -p getconf PATH', if your system supports
5396 that). If you prefer a different shell, the `configure' script
5397 can be given the option `--with-syscmd-shell=LOCATION' to set the
5398 location of an alternative shell at GNU `m4' installation; the
5399 alternative shell must still support `-c'.
5401 The macro `esyscmd' is recognized only with parameters.
5403 define(`foo', `FOO')
5409 Note how the expansion of `esyscmd' keeps the trailing newline of
5410 the command, as well as using the newline that appeared after the macro.
5412 Just as with `syscmd', care must be exercised when sharing standard
5413 input between `m4' and the child process of `esyscmd'.
5416 File: m4.info, Node: Sysval, Next: Mkstemp, Prev: Esyscmd, Up: Shell commands
5421 To see whether a shell command succeeded, use `sysval':
5424 Expands to the exit status of the last shell command run with
5425 `syscmd' or `esyscmd'. Expands to 0 if no command has been run
5432 ifelse(sysval, `0', `zero', `non-zero')
5444 ifelse(sysval, `0', `zero', `non-zero')
5446 esyscmd(`echo dnl && exit 127')
5455 `sysval' results in 127 if there was a problem executing the
5456 command, for example, if the system-imposed argument length is exceeded,
5457 or if there were not enough resources to fork. It is not possible to
5458 distinguish between failed execution and successful execution that had
5459 an exit status of 127, unless there was output from the child process.
5461 On UNIX platforms, where it is possible to detect when command
5462 execution is terminated by a signal, rather than a normal exit, the
5463 result is the signal number shifted left by eight bits.
5465 dnl This test assumes kill is a shell builtin, and that signals are
5468 `errprint(` skipping: syscmd does not have unix semantics
5470 syscmd(`kill -9 $$')
5478 esyscmd(`kill -9 $$')
5484 File: m4.info, Node: Mkstemp, Prev: Sysval, Up: Shell commands
5486 13.5 Making temporary files
5487 ===========================
5489 Commands specified to `syscmd' or `esyscmd' might need a temporary
5490 file, for output or for some other purpose. There is a builtin macro,
5491 `mkstemp', for making a temporary file:
5493 -- Builtin: mkstemp (TEMPLATE)
5494 -- Builtin: maketemp (TEMPLATE)
5495 Expands to the quoted name of a new, empty file, made from the
5496 string TEMPLATE, which should end with the string `XXXXXX'. The
5497 six `X' characters are then replaced with random characters
5498 matching the regular expression `[a-zA-Z0-9._-]', in order to make
5499 the file name unique. If fewer than six `X' characters are found
5500 at the end of `template', the result will be longer than the
5501 template. The created file will have access permissions as if by
5502 `chmod =rw,go=', meaning that the current umask of the `m4'
5503 process is taken into account, and at most only the current user
5504 can read and write the file.
5506 The traditional behavior, standardized by POSIX, is that
5507 `maketemp' merely replaces the trailing `X' with the process id,
5508 without creating a file or quoting the expansion, and without
5509 ensuring that the resulting string is a unique file name. In
5510 part, this means that using the same TEMPLATE twice in the same
5511 input file will result in the same expansion. This behavior is a
5512 security hole, as it is very easy for another process to guess the
5513 name that will be generated, and thus interfere with a subsequent
5514 use of `syscmd' trying to manipulate that file name. Hence, POSIX
5515 has recommended that all new implementations of `m4' provide the
5516 secure `mkstemp' builtin, and that users of `m4' check for its
5519 The expansion is void and an error issued if a temporary file could
5522 The macros `mkstemp' and `maketemp' are recognized only with
5525 If you try this next example, you will most likely get different
5526 output for the two file names, since the replacement characters are
5530 define(`tmp', `oops')
5532 maketemp(`/tmp/fooXXXXXX')
5534 ifdef(`mkstemp', `define(`maketemp', defn(`mkstemp'))',
5535 `define(`mkstemp', defn(`maketemp'))dnl
5536 errprint(`warning: potentially insecure maketemp implementation
5542 Unless you use the `--traditional' command line option (or `-G',
5543 *note Invoking m4: Limits control.), the GNU version of `maketemp' is
5544 secure. This means that using the same template to multiple calls will
5545 generate multiple files. However, we recommend that you use the new
5546 `mkstemp' macro, introduced in GNU M4 1.4.8, which is secure even in
5547 traditional mode. Also, as of M4 1.4.11, the secure implementation
5548 quotes the resulting file name, so that you are guaranteed to know what
5549 file was created even if the random file name happens to match an
5550 existing macro. Notice that this example is careful to use `defn' to
5551 avoid unintended expansion of `foo'.
5554 define(`foo', `errprint(`oops')')
5556 syscmd(`rm -f foo-??????')sysval
5558 define(`file1', maketemp(`foo-XXXXXX'))dnl
5559 ifelse(esyscmd(`echo \` foo-?????? \''), ` foo-?????? ',
5560 `no file', `created')
5562 define(`file2', maketemp(`foo-XX'))dnl
5563 define(`file3', mkstemp(`foo-XXXXXX'))dnl
5564 ifelse(len(defn(`file1')), len(defn(`file2')),
5565 `same length', `different')
5567 ifelse(defn(`file1'), defn(`file2'), `same', `different file')
5569 ifelse(defn(`file2'), defn(`file3'), `same', `different file')
5571 ifelse(defn(`file1'), defn(`file3'), `same', `different file')
5573 syscmd(`rm 'defn(`file1') defn(`file2') defn(`file3'))
5579 File: m4.info, Node: Miscellaneous, Next: Frozen files, Prev: Shell commands, Up: Top
5581 14 Miscellaneous builtin macros
5582 *******************************
5584 This chapter describes various builtins, that do not really belong in
5585 any of the previous chapters.
5589 * Errprint:: Printing error messages
5590 * Location:: Printing current location
5591 * M4exit:: Exiting from `m4'
5594 File: m4.info, Node: Errprint, Next: Location, Up: Miscellaneous
5596 14.1 Printing error messages
5597 ============================
5599 You can print error messages using `errprint':
5601 -- Builtin: errprint (MESSAGE, ...)
5602 Prints MESSAGE and the rest of the arguments to standard error,
5603 separated by spaces. Standard error is used, regardless of the
5604 `--debugfile' option (*note Invoking m4: Debugging options.).
5606 The expansion of `errprint' is void. The macro `errprint' is
5607 recognized only with parameters.
5609 errprint(`Invalid arguments to forloop
5611 error-->Invalid arguments to forloop
5613 errprint(`1')errprint(`2',`3
5618 A trailing newline is _not_ printed automatically, so it should be
5619 supplied as part of the argument, as in the example. Unfortunately, the
5620 exact output of `errprint' is not very portable to other `m4'
5621 implementations: POSIX requires that all arguments be printed, but some
5622 implementations of `m4' only print the first. Furthermore, some BSD
5623 implementations always append a newline for each `errprint' call,
5624 regardless of whether the last argument already had one, and POSIX is
5625 silent on whether this is acceptable.
5628 File: m4.info, Node: Location, Next: M4exit, Prev: Errprint, Up: Miscellaneous
5630 14.2 Printing current location
5631 ==============================
5633 To make it possible to specify the location of an error, three utility
5636 -- Builtin: __file__
5637 -- Builtin: __line__
5638 -- Builtin: __program__
5639 Expand to the quoted name of the current input file, the current
5640 input line number in that file, and the quoted name of the current
5643 errprint(__program__:__file__:__line__: `input error
5645 error-->m4:stdin:1: input error
5648 Line numbers start at 1 for each file. If the file was found due to
5649 the `-I' option or `M4PATH' environment variable, that is reflected in
5650 the file name. The syncline option (`-s', *note Invoking m4:
5651 Preprocessor features.), and the `f' and `l' flags of `debugmode'
5652 (*note Debug Levels::), also use this notion of current file and line.
5653 Redefining the three location macros has no effect on syncline, debug,
5654 warning, or error message output.
5656 This example reuses the file `incl.m4' mentioned earlier (*note
5660 define(`foo', ``$0' called at __file__:__line__')
5663 =>foo called at stdin:2
5665 =>Include file start
5666 =>foo called at examples/incl.m4:2
5670 The location of macros invoked during the rescanning of macro
5671 expansion text corresponds to the location in the file where the
5672 expansion was triggered, regardless of how many newline characters the
5673 expansion text contains. As of GNU M4 1.4.8, the location of text
5674 wrapped with `m4wrap' (*note M4wrap::) is the point at which the
5675 `m4wrap' was invoked. Previous versions, however, behaved as though
5676 wrapped text came from line 0 of the file "".
5678 define(`echo', `$@')
5680 define(`foo', `echo(__line__
5690 foo(errprint(__line__
5707 The `__program__' macro behaves like `$0' in shell terminology. If
5708 you invoke `m4' through an absolute path or a link with a different
5709 spelling, rather than by relying on a `PATH' search for plain `m4', it
5710 will affect how `__program__' expands. The intent is that you can use
5711 it to produce error messages with the same formatting that `m4'
5712 produces internally. It can also be used within `syscmd' (*note
5713 Syscmd::) to pick the same version of `m4' that is currently running,
5714 rather than whatever version of `m4' happens to be first in `PATH'. It
5715 was first introduced in GNU M4 1.4.6.
5718 File: m4.info, Node: M4exit, Prev: Location, Up: Miscellaneous
5720 14.3 Exiting from `m4'
5721 ======================
5723 If you need to exit from `m4' before the entire input has been read,
5724 you can use `m4exit':
5726 -- Builtin: m4exit ([CODE = `0'])
5727 Causes `m4' to exit, with exit status CODE. If CODE is left out,
5728 the exit status is zero. If CODE cannot be parsed, or is outside
5729 the range of 0 to 255, the exit status is one. No further input
5730 is read, and all wrapped and diverted text is discarded.
5732 m4wrap(`This text is lost due to `m4exit'.')
5734 divert(`1') So is this.
5737 m4exit And this is never read.
5739 A common use of this is to abort processing:
5741 -- Composite: fatal_error (MESSAGE)
5742 Abort processing with an error message and non-zero status. Prefix
5743 MESSAGE with details about where the error occurred, and print the
5744 resulting string to standard error.
5746 define(`fatal_error',
5747 `errprint(__program__:__file__:__line__`: fatal error: $*
5750 fatal_error(`this is a BAD one, buster')
5751 error-->m4:stdin:4: fatal error: this is a BAD one, buster
5753 After this macro call, `m4' will exit with exit status 1. This macro
5754 is only intended for error exits, since the normal exit procedures are
5755 not followed, i.e., diverted text is not undiverted, and saved text
5756 (*note M4wrap::) is not reread. (This macro could be made more robust
5757 to earlier versions of `m4'. You should try to see if you can find
5758 weaknesses and correct them; or *note Answers: Improved fatal_error.).
5760 Note that it is still possible for the exit status to be different
5761 than what was requested by `m4exit'. If `m4' detects some other error,
5762 such as a write error on standard output, the exit status will be
5763 non-zero even if `m4exit' requested zero.
5765 If standard input is seekable, then the file will be positioned at
5766 the next unread character. If it is a pipe or other non-seekable file,
5767 then there are no guarantees how much data `m4' might have read into
5768 buffers, and thus discarded.
5771 File: m4.info, Node: Frozen files, Next: Compatibility, Prev: Miscellaneous, Up: Top
5773 15 Fast loading of frozen state
5774 *******************************
5776 Some bigger `m4' applications may be built over a common base
5777 containing hundreds of definitions and other costly initializations.
5778 Usually, the common base is kept in one or more declarative files,
5779 which files are listed on each `m4' invocation prior to the user's
5780 input file, or else each input file uses `include'.
5782 Reading the common base of a big application, over and over again,
5783 may be time consuming. GNU `m4' offers some machinery to speed up the
5784 start of an application using lengthy common bases.
5788 * Using frozen files:: Using frozen files
5789 * Frozen file format:: Frozen file format
5792 File: m4.info, Node: Using frozen files, Next: Frozen file format, Up: Frozen files
5794 15.1 Using frozen files
5795 =======================
5797 Suppose a user has a library of `m4' initializations in `base.m4',
5798 which is then used with multiple input files:
5800 $ m4 base.m4 input1.m4
5801 $ m4 base.m4 input2.m4
5802 $ m4 base.m4 input3.m4
5804 Rather than spending time parsing the fixed contents of `base.m4'
5805 every time, the user might rather execute:
5807 $ m4 -F base.m4f base.m4
5809 once, and further execute, as often as needed:
5811 $ m4 -R base.m4f input1.m4
5812 $ m4 -R base.m4f input2.m4
5813 $ m4 -R base.m4f input3.m4
5815 with the varying input. The first call, containing the `-F' option,
5816 only reads and executes file `base.m4', defining various application
5817 macros and computing other initializations. Once the input file
5818 `base.m4' has been completely processed, GNU `m4' produces in
5819 `base.m4f' a "frozen" file, that is, a file which contains a kind of
5820 snapshot of the `m4' internal state.
5822 Later calls, containing the `-R' option, are able to reload the
5823 internal state of `m4', from `base.m4f', _prior_ to reading any other
5824 input files. This means instead of starting with a virgin copy of
5825 `m4', input will be read after having effectively recovered the effect
5826 of a prior run. In our example, the effect is the same as if file
5827 `base.m4' has been read anew. However, this effect is achieved a lot
5830 Only one frozen file may be created or read in any one `m4'
5831 invocation. It is not possible to recover two frozen files at once.
5832 However, frozen files may be updated incrementally, through using `-R'
5833 and `-F' options simultaneously. For example, if some care is taken,
5836 $ m4 file1.m4 file2.m4 file3.m4 file4.m4
5838 could be broken down in the following sequence, accumulating the same
5841 $ m4 -F file1.m4f file1.m4
5842 $ m4 -R file1.m4f -F file2.m4f file2.m4
5843 $ m4 -R file2.m4f -F file3.m4f file3.m4
5844 $ m4 -R file3.m4f file4.m4
5846 Some care is necessary because not every effort has been made for
5847 this to work in all cases. In particular, the trace attribute of
5848 macros is not handled, nor the current setting of `changeword'.
5849 Currently, `m4wrap' and `sysval' also have problems. Also,
5850 interactions for some options of `m4', being used in one call and not
5851 in the next, have not been fully analyzed yet. On the other end, you
5852 may be confident that stacks of `pushdef' definitions are handled
5853 correctly, as well as undefined or renamed builtins, and changed
5854 strings for quotes or comments. And future releases of GNU M4 will
5855 improve on the utility of frozen files.
5857 When an `m4' run is to be frozen, the automatic undiversion which
5858 takes place at end of execution is inhibited. Instead, all positively
5859 numbered diversions are saved into the frozen file. The active
5860 diversion number is also transmitted.
5862 A frozen file to be reloaded need not reside in the current
5863 directory. It is looked up the same way as an `include' file (*note
5866 If the frozen file was generated with a newer version of `m4', and
5867 contains directives that an older `m4' cannot parse, attempting to load
5868 the frozen file with option `-R' will cause `m4' to exit with status 63
5869 to indicate version mismatch.
5872 File: m4.info, Node: Frozen file format, Prev: Using frozen files, Up: Frozen files
5874 15.2 Frozen file format
5875 =======================
5877 Frozen files are sharable across architectures. It is safe to write a
5878 frozen file on one machine and read it on another, given that the
5879 second machine uses the same or newer version of GNU `m4'. It is
5880 conventional, but not required, to give a frozen file the suffix of
5883 These are simple (editable) text files, made up of directives, each
5884 starting with a capital letter and ending with a newline (<NL>).
5885 Wherever a directive is expected, the character `#' introduces a
5886 comment line; empty lines are also ignored if they are not part of an
5887 embedded string. In the following descriptions, each LEN refers to the
5888 length of the corresponding strings STR in the next line of input.
5889 Numbers are always expressed in decimal. There are no escape
5890 characters. The directives are:
5892 `C LEN1 , LEN2 <NL> STR1 STR2 <NL>'
5893 Uses STR1 and STR2 as the begin-comment and end-comment strings.
5894 If omitted, then `#' and <NL> are the comment delimiters.
5896 `D NUMBER, LEN <NL> STR <NL>'
5897 Selects diversion NUMBER, making it current, then copy STR in the
5898 current diversion. NUMBER may be a negative number for a
5899 non-existing diversion. To merely specify an active selection,
5900 use this command with an empty STR. With 0 as the diversion
5901 NUMBER, STR will be issued on standard output at reload time. GNU
5902 `m4' will not produce the `D' directive with non-zero length for
5903 diversion 0, but this can be done with manual edits. This
5904 directive may appear more than once for the same diversion, in
5905 which case the diversion is the concatenation of the various uses.
5906 If omitted, then diversion 0 is current.
5908 `F LEN1 , LEN2 <NL> STR1 STR2 <NL>'
5909 Defines, through `pushdef', a definition for STR1 expanding to the
5910 function whose builtin name is STR2. If the builtin does not
5911 exist (for example, if the frozen file was produced by a copy of
5912 `m4' compiled with changeword support, but the version of `m4'
5913 reloading was compiled without it), the reload is silent, but any
5914 subsequent use of the definition of STR1 will result in a warning.
5915 This directive may appear more than once for the same name, and
5916 its order, along with `T', is important. If omitted, you will
5917 have no access to any builtins.
5919 `Q LEN1 , LEN2 <NL> STR1 STR2 <NL>'
5920 Uses STR1 and STR2 as the begin-quote and end-quote strings. If
5921 omitted, then ``' and `'' are the quote delimiters.
5923 `T LEN1 , LEN2 <NL> STR1 STR2 <NL>'
5924 Defines, though `pushdef', a definition for STR1 expanding to the
5925 text given by STR2. This directive may appear more than once for
5926 the same name, and its order, along with `F', is important.
5929 Confirms the format of the file. `m4' 1.4.16 only creates and
5930 understands frozen files where NUMBER is 1. This directive must
5931 be the first non-comment in the file, and may not appear more than
5935 File: m4.info, Node: Compatibility, Next: Answers, Prev: Frozen files, Up: Top
5937 16 Compatibility with other versions of `m4'
5938 ********************************************
5940 This chapter describes the many of the differences between this
5941 implementation of `m4', and of other implementations found under UNIX,
5942 such as System V Release 3, Solaris, and BSD flavors. In particular,
5943 it lists the known differences and extensions to POSIX. However, the
5944 list is not necessarily comprehensive.
5946 At the time of this writing, POSIX 2001 (also known as IEEE Std
5947 1003.1-2001) is the latest standard, although a new version of POSIX is
5948 under development and includes several proposals for modifying what
5949 `m4' is required to do. The requirements for `m4' are shared between
5950 SUSv3 and POSIX, and can be viewed at
5951 `http://www.opengroup.org/onlinepubs/000095399/utilities/m4.html'.
5955 * Extensions:: Extensions in GNU M4
5956 * Incompatibilities:: Facilities in System V m4 not in GNU M4
5957 * Other Incompatibilities:: Other incompatibilities
5960 File: m4.info, Node: Extensions, Next: Incompatibilities, Up: Compatibility
5962 16.1 Extensions in GNU M4
5963 =========================
5965 This version of `m4' contains a few facilities that do not exist in
5966 System V `m4'. These extra facilities are all suppressed by using the
5967 `-G' command line option (*note Invoking m4: Limits control.), unless
5968 overridden by other command line options.
5970 * In the `$N' notation for macro arguments, N can contain several
5971 digits, while the System V `m4' only accepts one digit. This
5972 allows macros in GNU `m4' to take any number of arguments, and not
5973 only nine (*note Arguments::).
5975 This means that `define(`foo', `$11')' is ambiguous between
5976 implementations. To portably choose between grabbing the first
5977 parameter and appending 1 to the expansion, or grabbing the
5978 eleventh parameter, you can do the following:
5982 dnl First argument, concatenated with 1
5983 define(`_1', `$1')define(`first1', `_1($@)1')
5985 dnl Eleventh argument, portable
5986 define(`_9', `$9')define(`eleventh', `_9(shift(shift($@)))')
5988 dnl Eleventh argument, GNU style
5989 define(`Eleventh', `$11')
5991 first1(`a', `b', `c', `d', `e', `f', `g', `h', `i', `j', `k')
5993 eleventh(`a', `b', `c', `d', `e', `f', `g', `h', `i', `j', `k')
5995 Eleventh(`a', `b', `c', `d', `e', `f', `g', `h', `i', `j', `k')
5998 Also see the `argn' macro (*note Shift::).
6000 * The `divert' (*note Divert::) macro can manage more than 9
6001 diversions. GNU `m4' treats all positive numbers as valid
6002 diversions, rather than discarding diversions greater than 9.
6004 * Files included with `include' and `sinclude' are sought in a user
6005 specified search path, if they are not found in the working
6006 directory. The search path is specified by the `-I' option and the
6007 `M4PATH' environment variable (*note Search Path::).
6009 * Arguments to `undivert' can be non-numeric, in which case the named
6010 file will be included uninterpreted in the output (*note
6013 * Formatted output is supported through the `format' builtin, which
6014 is modeled after the C library function `printf' (*note Format::).
6016 * Searches and text substitution through basic regular expressions
6017 are supported by the `regexp' (*note Regexp::) and `patsubst'
6018 (*note Patsubst::) builtins. Some BSD implementations use
6019 extended regular expressions instead.
6021 * The output of shell commands can be read into `m4' with `esyscmd'
6024 * There is indirect access to any builtin macro with `builtin'
6027 * Macros can be called indirectly through `indir' (*note Indir::).
6029 * The name of the program, the current input file, and the current
6030 input line number are accessible through the builtins
6031 `__program__', `__file__', and `__line__' (*note Location::).
6033 * The format of the output from `dumpdef' and macro tracing can be
6034 controlled with `debugmode' (*note Debug Levels::).
6036 * The destination of trace and debug output can be controlled with
6037 `debugfile' (*note Debug Output::).
6039 * The `maketemp' (*note Mkstemp::) macro behaves like `mkstemp',
6040 creating a new file with a unique name on every invocation, rather
6041 than following the insecure behavior of replacing the trailing `X'
6042 characters with the `m4' process id.
6044 * POSIX only requires support for the command line options `-s',
6045 `-D', and `-U', so all other options accepted by GNU M4 are
6046 extensions. *Note Invoking m4::, for a description of these
6049 The debugging and tracing facilities in GNU `m4' are much more
6050 extensive than in most other versions of `m4'.
6053 File: m4.info, Node: Incompatibilities, Next: Other Incompatibilities, Prev: Extensions, Up: Compatibility
6055 16.2 Facilities in System V `m4' not in GNU `m4'
6056 ================================================
6058 The version of `m4' from System V contains a few facilities that have
6059 not been implemented in GNU `m4' yet. Additionally, POSIX requires
6060 some behaviors that GNU `m4' has not implemented yet. Relying on these
6061 behaviors is non-portable, as a future release of GNU `m4' may change.
6063 * POSIX requires support for multiple arguments to `defn', without
6064 any clarification on how `defn' behaves when one of the multiple
6065 arguments names a builtin. System V `m4' and some other
6066 implementations allow mixing builtins and text macros into a single
6067 macro. GNU `m4' only supports joining multiple text arguments,
6068 although a future implementation may lift this restriction to
6069 behave more like System V. The only portable way to join text
6070 macros with builtins is via helper macros and implicit
6071 concatenation of macro results.
6073 * POSIX requires an application to exit with non-zero status if it
6074 wrote an error message to stderr. This has not yet been
6075 consistently implemented for the various builtins that are
6076 required to issue an error (such as `eval' (*note Eval::) when an
6077 argument cannot be parsed).
6079 * Some traditional implementations only allow reading standard input
6080 once, but GNU `m4' correctly handles multiple instances of `-' on
6083 * POSIX requires `m4wrap' (*note M4wrap::) to act in FIFO (first-in,
6084 first-out) order, but GNU `m4' currently uses LIFO order.
6085 Furthermore, POSIX states that only the first argument to `m4wrap'
6086 is saved for later evaluation, but GNU `m4' saves and processes
6087 all arguments, with output separated by spaces.
6089 * POSIX states that builtins that require arguments, but are called
6090 without arguments, have undefined behavior. Traditional
6091 implementations simply behave as though empty strings had been
6092 passed. For example, `a`'define`'b' would expand to `ab'. But
6093 GNU `m4' ignores certain builtins if they have missing arguments,
6094 giving `adefineb' for the above example.
6096 * Traditional implementations handle `define(`f',`1')' (*note
6097 Define::) by undefining the entire stack of previous definitions,
6098 and if doing `undefine(`f')' first. GNU `m4' replaces just the top
6099 definition on the stack, as if doing `popdef(`f')' followed by
6100 `pushdef(`f',`1')'. POSIX allows either behavior.
6102 * POSIX 2001 requires `syscmd' (*note Syscmd::) to evaluate command
6103 output for macro expansion, but this was a mistake that is
6104 anticipated to be corrected in the next version of POSIX. GNU
6105 `m4' follows traditional behavior in `syscmd' where output is not
6106 rescanned, and provides the extension `esyscmd' that does scan the
6109 * At one point, POSIX required `changequote(ARG)' (*note
6110 Changequote::) to use newline as the close quote, but this was a
6111 bug, and the next version of POSIX is anticipated to state that
6112 using empty strings or just one argument is unspecified.
6113 Meanwhile, the GNU `m4' behavior of treating an empty end-quote
6114 delimiter as `'' is not portable, as Solaris treats it as
6115 repeating the start-quote delimiter, and BSD treats it as leaving
6116 the previous end-quote delimiter unchanged. For predictable
6117 results, never call changequote with just one argument, or with
6118 empty strings for arguments.
6120 * At one point, POSIX required `changecom(ARG,)' (*note Changecom::)
6121 to make it impossible to end a comment, but this is a bug, and the
6122 next version of POSIX is anticipated to state that using empty
6123 strings is unspecified. Meanwhile, the GNU `m4' behavior of
6124 treating an empty end-comment delimiter as newline is not
6125 portable, as BSD treats it as leaving the previous end-comment
6126 delimiter unchanged. It is also impossible in BSD implementations
6127 to disable comments, even though that is required by POSIX. For
6128 predictable results, never call changecom with empty strings for
6131 * Most implementations of `m4' give macros a higher precedence than
6132 comments when parsing, meaning that if the start delimiter given to
6133 `changecom' (*note Changecom::) starts with a macro name, comments
6134 are effectively disabled. POSIX does not specify what the
6135 precedence is, so this version of GNU `m4' parser recognizes
6136 comments, then macros, then quoted strings.
6138 * Traditional implementations allow argument collection, but not
6139 string and comment processing, to span file boundaries. Thus, if
6140 `a.m4' contains `len(', and `b.m4' contains `abc)', `m4 a.m4 b.m4'
6141 outputs `3' with traditional `m4', but gives an error message that
6142 the end of file was encountered inside a macro with GNU `m4'. On
6143 the other hand, traditional implementations do end of file
6144 processing for files included with `include' or `sinclude' (*note
6145 Include::), while GNU `m4' seamlessly integrates the content of
6146 those files. Thus `include(`a.m4')include(`b.m4')' will output
6147 `3' instead of giving an error.
6149 * Traditional `m4' treats `traceon' (*note Trace::) without
6150 arguments as a global variable, independent of named macro tracing.
6151 Also, once a macro is undefined, named tracing of that macro is
6152 lost. On the other hand, when GNU `m4' encounters `traceon'
6153 without arguments, it turns tracing on for all existing
6154 definitions at the time, but does not trace future definitions;
6155 `traceoff' without arguments turns tracing off for all definitions
6156 regardless of whether they were also traced by name; and tracing
6157 by name, such as with `-tfoo' at the command line or
6158 `traceon(`foo')' in the input, is an attribute that is preserved
6159 even if the macro is currently undefined.
6161 Additionally, while POSIX requires trace output, it makes no
6162 demands on the formatting of that output. Parsing trace output is
6163 not guaranteed to be reliable, even between different releases of
6164 GNU M4; however, the intent is that any future changes in trace
6165 output will only occur under the direction of additional
6166 `debugmode' flags (*note Debug Levels::).
6168 * POSIX requires `eval' (*note Eval::) to treat all operators with
6169 the same precedence as C. However, earlier versions of GNU `m4'
6170 followed the traditional behavior of other `m4' implementations,
6171 where bitwise and logical negation (`~' and `!') have lower
6172 precedence than equality operators; and where equality operators
6173 (`==' and `!=') had the same precedence as relational operators
6174 (such as `<'). Use explicit parentheses to ensure proper
6175 precedence. As extensions to POSIX, GNU `m4' gives well-defined
6176 semantics to operations that C leaves undefined, such as when
6177 overflow occurs, when shifting negative numbers, or when
6178 performing division by zero. POSIX also requires `=' to cause an
6179 error, but many traditional implementations allowed it as an alias
6182 * POSIX 2001 requires `translit' (*note Translit::) to treat each
6183 character of the second and third arguments literally. However,
6184 it is anticipated that the next version of POSIX will allow the
6185 GNU `m4' behavior of treating `-' as a range operator.
6187 * POSIX requires `m4' to honor the locale environment variables of
6188 `LANG', `LC_ALL', `LC_CTYPE', `LC_MESSAGES', and `NLSPATH', but
6189 this has not yet been implemented in GNU `m4'.
6191 * POSIX states that only unquoted leading newlines and blanks (that
6192 is, space and tab) are ignored when collecting macro arguments.
6193 However, this appears to be a bug in POSIX, since most traditional
6194 implementations also ignore all whitespace (formfeed, carriage
6195 return, and vertical tab). GNU `m4' follows tradition and ignores
6196 all leading unquoted whitespace.
6198 * A strictly-compliant POSIX client is not allowed to use
6199 command-line arguments not specified by POSIX. However, since
6200 this version of M4 ignores `POSIXLY_CORRECT' and enables the option
6201 `--gnu' by default (*note Invoking m4: Limits control.), a client
6202 desiring to be strictly compliant has no way to disable GNU
6203 extensions that conflict with POSIX when directly invoking the
6204 compiled `m4'. A future version of `GNU' M4 will honor the
6205 environment variable `POSIXLY_CORRECT', implicitly enabling
6206 `--traditional' if it is set, in order to allow a
6207 strictly-compliant client. In the meantime, a client needing
6208 strict POSIX compliance can use the workaround of invoking a shell
6209 script wrapper, where the wrapper then adds `--traditional' to the
6210 arguments passed to the compiled `m4'.
6213 File: m4.info, Node: Other Incompatibilities, Prev: Incompatibilities, Up: Compatibility
6215 16.3 Other incompatibilities
6216 ============================
6218 There are a few other incompatibilities between this implementation of
6219 `m4', and the System V version.
6221 * GNU `m4' implements sync lines differently from System V `m4',
6222 when text is being diverted. GNU `m4' outputs the sync lines when
6223 the text is being diverted, and System V `m4' when the diverted
6224 text is being brought back.
6226 The problem is which lines and file names should be attached to
6227 text that is being, or has been, diverted. System V `m4' regards
6228 all the diverted text as being generated by the source line
6229 containing the `undivert' call, whereas GNU `m4' regards the
6230 diverted text as being generated at the time it is diverted.
6232 The sync line option is used mostly when using `m4' as a front end
6233 to a compiler. If a diverted line causes a compiler error, the
6234 error messages should most probably refer to the place where the
6235 diversion was made, and not where it was inserted again.
6248 The current `m4' implementation has a limitation that the syncline
6249 output at the start of each diversion occurs no matter what, even
6250 if the previous diversion did not end with a newline. This goes
6251 contrary to the claim that synclines appear on a line by
6252 themselves, so this limitation may be corrected in a future
6253 version of `m4'. In the meantime, when using `-s', it is wisest
6254 to make sure all diversions end with newline.
6256 * GNU `m4' makes no attempt at prohibiting self-referential
6264 There is nothing inherently wrong with defining `x' to return `x'.
6265 The wrong thing is to expand `x' unquoted, because that would
6266 cause an infinite rescan loop. In `m4', one might use macros to
6267 hold strings, as we do for variables in other programming
6268 languages, further checking them with:
6270 ifelse(defn(`HOLDER'), `VALUE', ...)
6272 In cases like this one, an interdiction for a macro to hold its
6273 own name would be a useless limitation. Of course, this leaves
6274 more rope for the GNU `m4' user to hang himself! Rescanning hangs
6275 may be avoided through careful programming, a little like for
6276 endless loops in traditional programming languages.
6279 File: m4.info, Node: Answers, Next: Copying This Package, Prev: Compatibility, Up: Top
6281 17 Correct version of some examples
6282 ***********************************
6284 Some of the examples in this manuals are buggy or not very robust, for
6285 demonstration purposes. Improved versions of these composite macros are
6290 * Improved exch:: Solution for `exch'
6291 * Improved forloop:: Solution for `forloop'
6292 * Improved foreach:: Solution for `foreach'
6293 * Improved copy:: Solution for `copy'
6294 * Improved m4wrap:: Solution for `m4wrap'
6295 * Improved cleardivert:: Solution for `cleardivert'
6296 * Improved capitalize:: Solution for `capitalize'
6297 * Improved fatal_error:: Solution for `fatal_error'
6300 File: m4.info, Node: Improved exch, Next: Improved forloop, Up: Answers
6302 17.1 Solution for `exch'
6303 ========================
6305 The `exch' macro (*note Arguments::) as presented requires clients to
6306 double quote their arguments. A nicer definition, which lets clients
6307 follow the rule of thumb of one level of quoting per level of
6308 parentheses, involves adding quotes in the definition of `exch', as
6311 define(`exch', ``$2', `$1'')
6313 define(exch(`expansion text', `macro'))
6319 File: m4.info, Node: Improved forloop, Next: Improved foreach, Prev: Improved exch, Up: Answers
6321 17.2 Solution for `forloop'
6322 ===========================
6324 The `forloop' macro (*note Forloop::) as presented earlier can go into
6325 an infinite loop if given an iterator that is not parsed as a macro
6326 name. It does not do any sanity checking on its numeric bounds, and
6327 only permits decimal numbers for bounds. Here is an improved version,
6328 shipped as `m4-1.4.16/examples/forloop2.m4'; this version also
6329 optimizes overhead by calling four macros instead of six per iteration
6330 (excluding those in TEXT), by not dereferencing the ITERATOR in the
6334 undivert(`forloop2.m4')dnl
6336 =># forloop(var, from, to, stmt) - improved version:
6337 =># works even if VAR is not a strict macro name
6338 =># performs sanity check that FROM is larger than TO
6339 =># allows complex numerical expressions in TO and FROM
6340 =>define(`forloop', `ifelse(eval(`($2) <= ($3)'), `1',
6341 => `pushdef(`$1')_$0(`$1', eval(`$2'),
6342 => eval(`$3'), `$4')popdef(`$1')')')
6343 =>define(`_forloop',
6344 => `define(`$1', `$2')$4`'ifelse(`$2', `$3', `',
6345 => `$0(`$1', incr(`$2'), `$3', `$4')')')
6347 include(`forloop2.m4')
6349 forloop(`i', `2', `1', `no iteration occurs')
6351 forloop(`', `1', `2', ` odd iterator name')
6352 => odd iterator name odd iterator name
6353 forloop(`i', `5 + 5', `0xc', ` 0x`'eval(i, `16')')
6355 forloop(`i', `a', `b', `non-numeric bounds')
6356 error-->m4:stdin:6: bad expression in eval (bad input): (a) <= (b)
6359 One other change to notice is that the improved version used `_$0'
6360 rather than `_foreach' to invoke the helper routine. In general, this
6361 is a good practice to follow, because then the set of macros can be
6362 uniformly transformed. The following example shows a transformation
6363 that doubles the current quoting and appends a suffix `2' to each
6364 transformed macro. If `foreach' refers to the literal `_foreach', then
6365 `foreach2' invokes `_foreach' instead of the intended `_foreach2', and
6366 the mixing of quoting paradigms leads to an infinite recursion loop in
6369 $ m4 -d -L 9 -I examples
6370 define(`arg1', `$1')include(`forloop2.m4')include(`quote.m4')
6372 define(`double', `define(`$1'`2',
6373 arg1(patsubst(dquote(defn(`$1')), `[`']', `\&\&')))')
6375 double(`forloop')double(`_forloop')defn(`forloop2')
6376 =>ifelse(eval(``($2) <= ($3)''), ``1'',
6377 => ``pushdef(``$1'')_$0(``$1'', eval(``$2''),
6378 => eval(``$3''), ``$4'')popdef(``$1'')'')
6379 forloop(i, 1, 5, `ifelse(')forloop(i, 1, 5, `)')
6381 changequote(`[', `]')changequote([``], [''])
6383 forloop2(i, 1, 5, ``ifelse('')forloop2(i, 1, 5, ``)'')
6385 changequote`'include(`forloop.m4')
6387 double(`forloop')double(`_forloop')defn(`forloop2')
6388 =>pushdef(``$1'', ``$2'')_forloop($@)popdef(``$1'')
6389 forloop(i, 1, 5, `ifelse(')forloop(i, 1, 5, `)')
6391 changequote(`[', `]')changequote([``], [''])
6393 forloop2(i, 1, 5, ``ifelse('')forloop2(i, 1, 5, ``)'')
6394 error-->m4:stdin:12: recursion limit of 9 exceeded, use -L<N> to change it
6396 One more optimization is still possible. Instead of repeatedly
6397 assigning a variable then invoking or dereferencing it, it is possible
6398 to pass the current iterator value as a single argument. Coupled with
6399 `curry' if other arguments are needed (*note Composition::), or with
6400 helper macros if the argument is needed in more than one place in the
6401 expansion, the output can be generated with three, rather than four,
6402 macros of overhead per iteration. Notice how the file
6403 `m4-1.4.16/examples/forloop3.m4' rearranges the arguments of the helper
6404 `_forloop' to take two arguments that are placed around the current
6405 value. By splitting a balanced set of parantheses across multiple
6406 arguments, the helper macro can now be shared by `forloop' and the new
6410 include(`forloop3.m4')
6412 undivert(`forloop3.m4')dnl
6414 =># forloop_arg(from, to, macro) - invoke MACRO(value) for
6415 =># each value between FROM and TO, without define overhead
6416 =>define(`forloop_arg', `ifelse(eval(`($1) <= ($2)'), `1',
6417 => `_forloop(`$1', eval(`$2'), `$3(', `)')')')
6418 =># forloop(var, from, to, stmt) - refactored to share code
6419 =>define(`forloop', `ifelse(eval(`($2) <= ($3)'), `1',
6420 => `pushdef(`$1')_forloop(eval(`$2'), eval(`$3'),
6421 => `define(`$1',', `)$4')popdef(`$1')')')
6422 =>define(`_forloop',
6423 => `$3`$1'$4`'ifelse(`$1', `$2', `',
6424 => `$0(incr(`$1'), `$2', `$3', `$4')')')
6426 forloop(`i', `1', `3', ` i')
6428 define(`echo', `$@')
6430 forloop_arg(`1', `3', ` echo')
6434 forloop_arg(`1', `3', `curry(`pushdef', `a')')
6445 Of course, it is possible to make even more improvements, such as
6446 adding an optional step argument, or allowing iteration through
6447 descending sequences. GNU Autoconf provides some of these additional
6448 bells and whistles in its `m4_for' macro.
6451 File: m4.info, Node: Improved foreach, Next: Improved copy, Prev: Improved forloop, Up: Answers
6453 17.3 Solution for `foreach'
6454 ===========================
6456 The `foreach' and `foreachq' macros (*note Foreach::) as presented
6457 earlier each have flaws. First, we will examine and fix the quadratic
6458 behavior of `foreachq':
6461 include(`foreachq.m4')
6463 traceon(`shift')debugmode(`aq')
6465 foreachq(`x', ``1', `2', `3', `4'', `x
6468 error-->m4trace: -3- shift(`1', `2', `3', `4')
6469 error-->m4trace: -2- shift(`1', `2', `3', `4')
6471 error-->m4trace: -4- shift(`1', `2', `3', `4')
6472 error-->m4trace: -3- shift(`2', `3', `4')
6473 error-->m4trace: -3- shift(`1', `2', `3', `4')
6474 error-->m4trace: -2- shift(`2', `3', `4')
6476 error-->m4trace: -5- shift(`1', `2', `3', `4')
6477 error-->m4trace: -4- shift(`2', `3', `4')
6478 error-->m4trace: -3- shift(`3', `4')
6479 error-->m4trace: -4- shift(`1', `2', `3', `4')
6480 error-->m4trace: -3- shift(`2', `3', `4')
6481 error-->m4trace: -2- shift(`3', `4')
6483 error-->m4trace: -6- shift(`1', `2', `3', `4')
6484 error-->m4trace: -5- shift(`2', `3', `4')
6485 error-->m4trace: -4- shift(`3', `4')
6486 error-->m4trace: -3- shift(`4')
6488 Each successive iteration was adding more quoted `shift'
6489 invocations, and the entire list contents were passing through every
6490 iteration. In general, when recursing, it is a good idea to make the
6491 recursion use fewer arguments, rather than adding additional quoted
6492 uses of `shift'. By doing so, `m4' uses less memory, invokes fewer
6493 macros, is less likely to run into machine limits, and most
6494 importantly, performs faster. The fixed version of `foreachq' can be
6495 found in `m4-1.4.16/examples/foreachq2.m4':
6498 include(`foreachq2.m4')
6500 undivert(`foreachq2.m4')dnl
6501 =>include(`quote.m4')dnl
6503 =># foreachq(x, `item_1, item_2, ..., item_n', stmt)
6504 =># quoted list, improved version
6505 =>define(`foreachq', `pushdef(`$1')_$0($@)popdef(`$1')')
6506 =>define(`_arg1q', ``$1'')
6507 =>define(`_rest', `ifelse(`$#', `1', `', `dquote(shift($@))')')
6508 =>define(`_foreachq', `ifelse(`$2', `', `',
6509 => `define(`$1', _arg1q($2))$3`'$0(`$1', _rest($2), `$3')')')
6511 traceon(`shift')debugmode(`aq')
6513 foreachq(`x', ``1', `2', `3', `4'', `x
6516 error-->m4trace: -3- shift(`1', `2', `3', `4')
6518 error-->m4trace: -3- shift(`2', `3', `4')
6520 error-->m4trace: -3- shift(`3', `4')
6523 Note that the fixed version calls unquoted helper macros in
6524 `_foreachq' to trim elements immediately; those helper macros in turn
6525 must re-supply the layer of quotes lost in the macro invocation.
6526 Contrast the use of `_arg1q', which quotes the first list element, with
6527 `_arg1' of the earlier implementation that returned the first list
6528 element directly. Additionally, by calling the helper method
6529 immediately, the `defn(`ITERATOR')' no longer contains unexpanded
6532 The astute m4 programmer might notice that the solution above still
6533 uses more memory and macro invocations, and thus more time, than
6534 strictly necessary. Note that `$2', which contains an arbitrarily long
6535 quoted list, is expanded and rescanned three times per iteration of
6536 `_foreachq'. Furthermore, every iteration of the algorithm effectively
6537 unboxes then reboxes the list, which costs a couple of macro
6538 invocations. It is possible to rewrite the algorithm for a bit more
6539 speed by swapping the order of the arguments to `_foreachq' in order to
6540 operate on an unboxed list in the first place, and by using the
6541 fixed-length `$#' instead of an arbitrary length list as the key to end
6542 recursion. The result is an overhead of six macro invocations per loop
6543 (excluding any macros in TEXT), instead of eight. This alternative
6544 approach is available as `m4-1.4.16/examples/foreach3.m4':
6547 include(`foreachq3.m4')
6549 undivert(`foreachq3.m4')dnl
6551 =># foreachq(x, `item_1, item_2, ..., item_n', stmt)
6552 =># quoted list, alternate improved version
6553 =>define(`foreachq', `ifelse(`$2', `', `',
6554 => `pushdef(`$1')_$0(`$1', `$3', `', $2)popdef(`$1')')')
6555 =>define(`_foreachq', `ifelse(`$#', `3', `',
6556 => `define(`$1', `$4')$2`'$0(`$1', `$2',
6557 => shift(shift(shift($@))))')')
6559 traceon(`shift')debugmode(`aq')
6561 foreachq(`x', ``1', `2', `3', `4'', `x
6564 error-->m4trace: -4- shift(`x', `x
6565 error-->', `', `1', `2', `3', `4')
6566 error-->m4trace: -3- shift(`x
6567 error-->', `', `1', `2', `3', `4')
6568 error-->m4trace: -2- shift(`', `1', `2', `3', `4')
6570 error-->m4trace: -4- shift(`x', `x
6571 error-->', `1', `2', `3', `4')
6572 error-->m4trace: -3- shift(`x
6573 error-->', `1', `2', `3', `4')
6574 error-->m4trace: -2- shift(`1', `2', `3', `4')
6576 error-->m4trace: -4- shift(`x', `x
6577 error-->', `2', `3', `4')
6578 error-->m4trace: -3- shift(`x
6579 error-->', `2', `3', `4')
6580 error-->m4trace: -2- shift(`2', `3', `4')
6582 error-->m4trace: -4- shift(`x', `x
6583 error-->', `3', `4')
6584 error-->m4trace: -3- shift(`x
6585 error-->', `3', `4')
6586 error-->m4trace: -2- shift(`3', `4')
6588 In the current version of M4, every instance of `$@' is rescanned as
6589 it is encountered. Thus, the `foreachq3.m4' alternative uses much less
6590 memory than `foreachq2.m4', and executes as much as 10% faster, since
6591 each iteration encounters fewer `$@'. However, the implementation of
6592 rescanning every byte in `$@' is quadratic in the number of bytes
6593 scanned (for example, making the broken version in `foreachq.m4' cubic,
6594 rather than quadratic, in behavior). A future release of M4 will
6595 improve the underlying implementation by reusing results of previous
6596 scans, so that both styles of `foreachq' can become linear in the
6597 number of bytes scanned. Notice how the implementation injects an
6598 empty argument prior to expanding `$2' within `foreachq'; the helper
6599 macro `_foreachq' then ignores the third argument altogether, and ends
6600 recursion when there are three arguments left because there was nothing
6601 left to pass through `shift'. Thus, each iteration only needs one
6602 `ifelse', rather than the two conditionals used in the version from
6605 So far, all of the implementations of `foreachq' presented have been
6606 quadratic with M4 1.4.x. But `forloop' is linear, because each
6607 iteration parses a constant amount of arguments. So, it is possible to
6608 design a variant that uses `forloop' to do the iteration, then uses
6609 `$@' only once at the end, giving a linear result even with older M4
6610 implementations. This implementation relies on the GNU extension that
6611 `$10' expands to the tenth argument rather than the first argument
6612 concatenated with `0'. The trick is to define an intermediate macro
6613 that repeats the text `m4_define(`$1', `$N')$2`'', with `n' set to
6614 successive integers corresponding to each argument. The helper macro
6615 `_foreachq_' is needed in order to generate the literal sequences such
6616 as `$1' into the intermediate macro, rather than expanding them as the
6617 arguments of `_foreachq'. With this approach, no `shift' calls are
6618 even needed! Even though there are seven macros of overhead per
6619 iteration instead of six in `foreachq3.m4', the linear scaling is
6620 apparent at relatively small list sizes. However, this approach will
6621 need adjustment when a future version of M4 follows POSIX by no longer
6622 treating `$10' as the tenth argument; the anticipation is that `${10}'
6623 can be used instead, although that alternative syntax is not yet
6627 include(`foreachq4.m4')
6629 undivert(`foreachq4.m4')dnl
6630 =>include(`forloop2.m4')dnl
6632 =># foreachq(x, `item_1, item_2, ..., item_n', stmt)
6633 =># quoted list, version based on forloop
6634 =>define(`foreachq',
6635 =>`ifelse(`$2', `', `', `_$0(`$1', `$3', $2)')')
6636 =>define(`_foreachq',
6637 =>`pushdef(`$1', forloop(`$1', `3', `$#',
6638 => `$0_(`1', `2', indir(`$1'))')`popdef(
6639 => `$1')')indir(`$1', $@)')
6640 =>define(`_foreachq_',
6641 =>``define(`$$1', `$$3')$$2`''')
6643 traceon(`shift')debugmode(`aq')
6645 foreachq(`x', ``1', `2', `3', `4'', `x
6652 For yet another approach, the improved version of `foreach',
6653 available in `m4-1.4.16/examples/foreach2.m4', simply overquotes the
6654 arguments to `_foreach' to begin with, using `dquote_elt'. Then
6655 `_foreach' can just use `_arg1' to remove the extra layer of quoting
6656 that was added up front:
6659 include(`foreach2.m4')
6661 undivert(`foreach2.m4')dnl
6662 =>include(`quote.m4')dnl
6664 =># foreach(x, (item_1, item_2, ..., item_n), stmt)
6665 =># parenthesized list, improved version
6666 =>define(`foreach', `pushdef(`$1')_$0(`$1',
6667 => (dquote(dquote_elt$2)), `$3')popdef(`$1')')
6668 =>define(`_arg1', `$1')
6669 =>define(`_foreach', `ifelse(`$2', `(`')', `',
6670 => `define(`$1', _arg1$2)$3`'$0(`$1', (dquote(shift$2)), `$3')')')
6672 traceon(`shift')debugmode(`aq')
6674 foreach(`x', `(`1', `2', `3', `4')', `x
6676 error-->m4trace: -4- shift(`1', `2', `3', `4')
6677 error-->m4trace: -4- shift(`2', `3', `4')
6678 error-->m4trace: -4- shift(`3', `4')
6680 error-->m4trace: -3- shift(``1'', ``2'', ``3'', ``4'')
6682 error-->m4trace: -3- shift(``2'', ``3'', ``4'')
6684 error-->m4trace: -3- shift(``3'', ``4'')
6686 error-->m4trace: -3- shift(``4'')
6688 It is likewise possible to write a variant of `foreach' that
6689 performs in linear time on M4 1.4.x; the easiest method is probably
6690 writing a version of `foreach' that unboxes its list, then invokes
6691 `_foreachq' as previously defined in `foreachq4.m4'.
6693 In summary, recursion over list elements is trickier than it
6694 appeared at first glance, but provides a powerful idiom within `m4'
6695 processing. As a final demonstration, both list styles are now able to
6696 handle several scenarios that would wreak havoc on one or both of the
6697 original implementations. This points out one other difference between
6698 the list styles. `foreach' evaluates unquoted list elements only once,
6699 in preparation for calling `_foreach', similary for `foreachq' as
6700 provided by `foreachq3.m4' or `foreachq4.m4'. But `foreachq', as
6701 provided by `foreachq2.m4', evaluates unquoted list elements twice
6702 while visiting the first list element, once in `_arg1q' and once in
6703 `_rest'. When deciding which list style to use, one must take into
6704 account whether repeating the side effects of unquoted list elements
6705 will have any detrimental effects.
6708 include(`foreach2.m4')
6710 include(`foreachq2.m4')
6713 foreach(`x', `', `<x>') / foreachq(`x', `', `<x>')
6715 dnl 1-element list of empty element
6716 foreach(`x', `()', `<x>') / foreachq(`x', ``'', `<x>')
6718 dnl 2-element list of empty elements
6719 foreach(`x', `(`',`')', `<x>') / foreachq(`x', ``',`'', `<x>')
6721 dnl 1-element list of a comma
6722 foreach(`x', `(`,')', `<x>') / foreachq(`x', ``,'', `<x>')
6724 dnl 2-element list of unbalanced parentheses
6725 foreach(`x', `(`(', `)')', `<x>') / foreachq(`x', ``(', `)'', `<x>')
6727 define(`ab', `oops')dnl using defn(`iterator')
6728 foreach(`x', `(`a', `b')', `defn(`x')') /dnl
6729 foreachq(`x', ``a', `b'', `defn(`x')')
6731 define(`active', `ACT, IVE')
6735 dnl list of unquoted macros; expansion occurs before recursion
6736 foreach(`x', `(active, active)', `<x>
6738 error-->m4trace: -4- active -> `ACT, IVE'
6739 error-->m4trace: -4- active -> `ACT, IVE'
6744 foreachq(`x', `active, active', `<x>
6746 error-->m4trace: -3- active -> `ACT, IVE'
6747 error-->m4trace: -3- active -> `ACT, IVE'
6749 error-->m4trace: -3- active -> `ACT, IVE'
6750 error-->m4trace: -3- active -> `ACT, IVE'
6754 dnl list of quoted macros; expansion occurs during recursion
6755 foreach(`x', `(`active', `active')', `<x>
6757 error-->m4trace: -1- active -> `ACT, IVE'
6759 error-->m4trace: -1- active -> `ACT, IVE'
6761 foreachq(`x', ``active', `active'', `<x>
6763 error-->m4trace: -1- active -> `ACT, IVE'
6765 error-->m4trace: -1- active -> `ACT, IVE'
6767 dnl list of double-quoted macro names; no expansion
6768 foreach(`x', `(``active'', ``active'')', `<x>
6772 foreachq(`x', ```active'', ``active''', `<x>
6778 File: m4.info, Node: Improved copy, Next: Improved m4wrap, Prev: Improved foreach, Up: Answers
6780 17.4 Solution for `copy'
6781 ========================
6783 The macro `copy' presented above is unable to handle builtin tokens
6784 with M4 1.4.x, because it tries to pass the builtin token through the
6785 macro `curry', where it is silently flattened to an empty string (*note
6786 Composition::). Rather than using the problematic `curry' to work
6787 around the limitation that `stack_foreach' expects to invoke a macro
6788 that takes exactly one argument, we can write a new macro that lets us
6789 form the exact two-argument `pushdef' call sequence needed, so that we
6790 are no longer passing a builtin token through a text macro.
6792 -- Composite: stack_foreach_sep (MACRO, PRE, POST, SEP)
6793 -- Composite: stack_foreach_sep_lifo (MACRO, PRE, POST, SEP)
6794 For each of the `pushdef' definitions associated with MACRO,
6795 expand the sequence `PRE`'definition`'POST'. Additionally, expand
6796 SEP between definitions. `stack_foreach_sep' visits the oldest
6797 definition first, while `stack_foreach_sep_lifo' visits the
6798 current definition first. The expansion may dereference MACRO,
6799 but should not modify it. There are a few special macros, such as
6800 `defn', which cannot be used as the MACRO parameter.
6802 Note that `stack_foreach(`MACRO', `ACTION')' is equivalent to
6803 `stack_foreach_sep(`MACRO', `ACTION(', `)')'. By supplying explicit
6804 parentheses, split among the PRE and POST arguments to
6805 `stack_foreach_sep', it is now possible to construct macro calls with
6806 more than one argument, without passing builtin tokens through a macro
6807 call. It is likewise possible to directly reference the stack
6808 definitions without a macro call, by leaving PRE and POST empty. Thus,
6809 in addition to fixing `copy' on builtin tokens, it also executes with
6810 fewer macro invocations.
6812 The new macro also adds a separator that is only output after the
6813 first iteration of the helper `_stack_reverse_sep', implemented by
6814 prepending the original SEP to PRE and omitting a SEP argument in
6815 subsequent iterations. Note that the empty string that separates SEP
6816 from PRE is provided as part of the fourth argument when originally
6817 calling `_stack_reverse_sep', and not by writing `$4`'$3' as the third
6818 argument in the recursive call; while the other approach would give the
6819 same output, it does so at the expense of increasing the argument size
6820 on each iteration of `_stack_reverse_sep', which results in quadratic
6821 instead of linear execution time. The improved stack walking macros
6822 are available in `m4-1.4.16/examples/stack_sep.m4':
6825 include(`stack_sep.m4')
6827 define(`copy', `ifdef(`$2', `errprint(`$2 already defined
6829 `stack_foreach_sep(`$1', `pushdef(`$2',', `)')')')dnl
6830 pushdef(`a', `1')pushdef(`a', defn(`divnum'))
6840 pushdef(`c', `1')pushdef(`c', `2')
6842 stack_foreach_sep_lifo(`c', `', `', `, ')
6844 undivert(`stack_sep.m4')dnl
6846 =># stack_foreach_sep(macro, pre, post, sep)
6847 =># Invoke PRE`'defn`'POST with a single argument of each definition
6848 =># from the definition stack of MACRO, starting with the oldest, and
6849 =># separated by SEP between definitions.
6850 =>define(`stack_foreach_sep',
6851 =>`_stack_reverse_sep(`$1', `tmp-$1')'dnl
6852 =>`_stack_reverse_sep(`tmp-$1', `$1', `$2`'defn(`$1')$3', `$4`'')')
6853 =># stack_foreach_sep_lifo(macro, pre, post, sep)
6854 =># Like stack_foreach_sep, but starting with the newest definition.
6855 =>define(`stack_foreach_sep_lifo',
6856 =>`_stack_reverse_sep(`$1', `tmp-$1', `$2`'defn(`$1')$3', `$4`'')'dnl
6857 =>`_stack_reverse_sep(`tmp-$1', `$1')')
6858 =>define(`_stack_reverse_sep',
6859 =>`ifdef(`$1', `pushdef(`$2', defn(`$1'))$3`'popdef(`$1')$0(
6860 => `$1', `$2', `$4$3')')')
6864 File: m4.info, Node: Improved m4wrap, Next: Improved cleardivert, Prev: Improved copy, Up: Answers
6866 17.5 Solution for `m4wrap'
6867 ==========================
6869 The replacement `m4wrap' versions presented above, designed to
6870 guarantee FIFO or LIFO order regardless of the underlying M4
6871 implementation, share a bug when dealing with wrapped text that looks
6872 like parameter expansion. Note how the invocation of `m4wrapN'
6873 interprets these parameters, while using the builtin preserves them for
6877 include(`wraplifo.m4')
6879 m4wrap(`define(`foo', ``$0:'-$1-$*-$#-')foo(`a', `b')
6882 builtin(`m4wrap', ``'define(`bar', ``$0:'-$1-$*-$#-')bar(`a', `b')
6889 Additionally, the computation of `_m4wrap_level' and creation of
6890 multiple `m4wrapN' placeholders in the original examples is more
6891 expensive in time and memory than strictly necessary. Notice how the
6892 improved version grabs the wrapped text via `defn' to avoid parameter
6893 expansion, then undefines `_m4wrap_text', before stripping a level of
6894 quotes with `_arg1' to expand the text. That way, each level of
6895 wrapping reuses the single placeholder, which starts each nesting level
6896 in an undefined state.
6898 Finally, it is worth emulating the GNU M4 extension of saving all
6899 arguments to `m4wrap', separated by a space, rather than saving just
6900 the first argument. This is done with the `join' macro documented
6901 previously (*note Shift::). The improved LIFO example is shipped as
6902 `m4-1.4.16/examples/wraplifo2.m4', and can easily be converted to a
6903 FIFO solution by swapping the adjacent invocations of `joinall' and
6907 include(`wraplifo2.m4')
6909 undivert(`wraplifo2.m4')dnl
6910 =>dnl Redefine m4wrap to have LIFO semantics, improved example.
6911 =>include(`join.m4')dnl
6912 =>define(`_m4wrap', defn(`m4wrap'))dnl
6913 =>define(`_arg1', `$1')dnl
6915 =>`ifdef(`_$0_text',
6916 => `define(`_$0_text', joinall(` ', $@)defn(`_$0_text'))',
6917 => `_$0(`_arg1(defn(`_$0_text')undefine(`_$0_text'))')dnl
6918 =>define(`_$0_text', joinall(` ', $@))')')dnl
6919 m4wrap(`define(`foo', ``$0:'-$1-$*-$#-')foo(`a', `b')
6923 m4wrap(`nested', `', `$@
6932 File: m4.info, Node: Improved cleardivert, Next: Improved capitalize, Prev: Improved m4wrap, Up: Answers
6934 17.6 Solution for `cleardivert'
6935 ===============================
6937 The `cleardivert' macro (*note Cleardivert::) cannot, as it stands, be
6938 called without arguments to clear all pending diversions. That is
6939 because using undivert with an empty string for an argument is different
6940 than using it with no arguments at all. Compare the earlier definition
6941 with one that takes the number of arguments into account:
6943 define(`cleardivert',
6944 `pushdef(`_n', divnum)divert(`-1')undivert($@)divert(_n)popdef(`_n')')
6954 define(`cleardivert',
6955 `pushdef(`_num', divnum)divert(`-1')ifelse(`$#', `0',
6956 `undivert`'', `undivert($@)')divert(_num)popdef(`_num')')
6967 File: m4.info, Node: Improved capitalize, Next: Improved fatal_error, Prev: Improved cleardivert, Up: Answers
6969 17.7 Solution for `capitalize'
6970 ==============================
6972 The `capitalize' macro (*note Patsubst::) as presented earlier does not
6973 allow clients to follow the quoting rule of thumb. Consider the three
6974 macros `active', `Active', and `ACTIVE', and the difference between
6975 calling `capitalize' with the expansion of a macro, expanding the
6976 result of a case change, and changing the case of a double-quoted
6980 include(`capitalize.m4')dnl
6981 define(`active', `act1, ive')dnl
6982 define(`Active', `Act2, Ive')dnl
6983 define(`ACTIVE', `ACT3, IVE')dnl
6994 downcase(``ACTIVE'')
6998 capitalize(`active')
7000 capitalize(``active'')
7001 =>_capitalize(`active')
7006 capitalize(`active')
7009 First, when `capitalize' is called with more than one argument, it
7010 was throwing away later arguments, whereas `upcase' and `downcase' used
7011 `$*' to collect them all. The fix is simple: use `$*' consistently.
7013 Next, with single-quoting, `capitalize' outputs a single character,
7014 a set of quotes, then the rest of the characters, making it impossible
7015 to invoke `Active' after the fact, and allowing the alternate macro `A'
7016 to interfere. Here, the solution is to use additional quoting in the
7017 helper macros, then pass the final over-quoted output string through
7018 `_arg1' to remove the extra quoting and finally invoke the concatenated
7019 portions as a single string.
7021 Finally, when passed a double-quoted string, the nested macro
7022 `_capitalize' is never invoked because it ended up nested inside
7023 quotes. This one is the toughest to fix. In short, we have no idea how
7024 many levels of quotes are in effect on the substring being altered by
7025 `patsubst'. If the replacement string cannot be expressed entirely in
7026 terms of literal text and backslash substitutions, then we need a
7027 mechanism to guarantee that the helper macros are invoked outside of
7028 quotes. In other words, this sounds like a job for `changequote'
7029 (*note Changequote::). By changing the active quoting characters, we
7030 can guarantee that replacement text injected by `patsubst' always
7031 occurs in the middle of a string that has exactly one level of
7032 over-quoting using alternate quotes; so the replacement text closes the
7033 quoted string, invokes the helper macros, then reopens the quoted
7034 string. In turn, that means the replacement text has unbalanced quotes,
7035 necessitating another round of `changequote'.
7037 In the fixed version below, (also shipped as
7038 `m4-1.4.16/examples/capitalize2.m4'), `capitalize' uses the alternate
7039 quotes of `<<[' and `]>>' (the longer strings are chosen so as to be
7040 less likely to appear in the text being converted). The helpers
7041 `_to_alt' and `_from_alt' merely reduce the number of characters
7042 required to perform a `changequote', since the definition changes
7043 twice. The outermost pair means that `patsubst' and `_capitalize_alt'
7044 are invoked with alternate quoting; the innermost pair is used so that
7045 the third argument to `patsubst' can contain an unbalanced `]>>'/`<<['
7046 pair. Note that `upcase' and `downcase' must be redefined as
7047 `_upcase_alt' and `_downcase_alt', since they contain nested quotes but
7048 are invoked with the alternate quoting scheme in effect.
7051 include(`capitalize2.m4')dnl
7052 define(`active', `act1, ive')dnl
7053 define(`Active', `Act2, Ive')dnl
7054 define(`ACTIVE', `ACT3, IVE')dnl
7055 define(`A', `OOPS')dnl
7056 capitalize(active; `active'; ``active''; ```actIVE''')
7057 =>Act1,Ive; Act2, Ive; Active; `Active'
7058 undivert(`capitalize2.m4')dnl
7062 =># capitalize(text)
7063 =># change case of text, improved version
7064 =>define(`upcase', `translit(`$*', `a-z', `A-Z')')
7065 =>define(`downcase', `translit(`$*', `A-Z', `a-z')')
7066 =>define(`_arg1', `$1')
7067 =>define(`_to_alt', `changequote(`<<[', `]>>')')
7068 =>define(`_from_alt', `changequote(<<[`]>>, <<[']>>)')
7069 =>define(`_upcase_alt', `translit(<<[$*]>>, <<[a-z]>>, <<[A-Z]>>)')
7070 =>define(`_downcase_alt', `translit(<<[$*]>>, <<[A-Z]>>, <<[a-z]>>)')
7071 =>define(`_capitalize_alt',
7072 => `regexp(<<[$1]>>, <<[^\(\w\)\(\w*\)]>>,
7073 => <<[_upcase_alt(<<[<<[\1]>>]>>)_downcase_alt(<<[<<[\2]>>]>>)]>>)')
7074 =>define(`capitalize',
7075 => `_arg1(_to_alt()patsubst(<<[<<[$*]>>]>>, <<[\w+]>>,
7076 => _from_alt()`]>>_$0_alt(<<[\&]>>)<<['_to_alt())_from_alt())')
7080 File: m4.info, Node: Improved fatal_error, Prev: Improved capitalize, Up: Answers
7082 17.8 Solution for `fatal_error'
7083 ===============================
7085 The `fatal_error' macro (*note M4exit::) is not robust to versions of
7086 GNU M4 earlier than 1.4.8, where invoking `__file__' (*note Location::)
7087 inside `m4wrap' would result in an empty string, and `__line__'
7088 resulted in `0' even though all files start at line 1. Furthermore,
7089 versions earlier than 1.4.6 did not support the `__program__' macro.
7090 If you want `fatal_error' to work across the entire 1.4.x release
7091 series, a better implementation would be:
7093 define(`fatal_error',
7094 `errprint(ifdef(`__program__', `__program__', ``m4'')'dnl
7095 `:ifelse(__line__, `0', `',
7096 `__file__:__line__:')` fatal error: $*
7099 m4wrap(`divnum(`demo of internal message')
7100 fatal_error(`inside wrapped text')')
7103 error-->m4:stdin:6: Warning: excess arguments to builtin `divnum' ignored
7105 error-->m4:stdin:6: fatal error: inside wrapped text
7108 File: m4.info, Node: Copying This Package, Next: Copying This Manual, Prev: Answers, Up: Top
7110 Appendix A How to make copies of the overall M4 package
7111 *******************************************************
7113 This appendix covers the license for copying the source code of the
7114 overall M4 package. This manual is under a different set of
7115 restrictions, covered later (*note Copying This Manual::).
7119 * GNU General Public License:: License for copying the M4 package
7122 File: m4.info, Node: GNU General Public License, Up: Copying This Package
7124 A.1 License for copying the M4 package
7125 ======================================
7127 Version 3, 29 June 2007
7129 Copyright (C) 2007 Free Software Foundation, Inc. `http://fsf.org/'
7131 Everyone is permitted to copy and distribute verbatim copies of this
7132 license document, but changing it is not allowed.
7137 The GNU General Public License is a free, copyleft license for software
7138 and other kinds of works.
7140 The licenses for most software and other practical works are designed
7141 to take away your freedom to share and change the works. By contrast,
7142 the GNU General Public License is intended to guarantee your freedom to
7143 share and change all versions of a program--to make sure it remains
7144 free software for all its users. We, the Free Software Foundation, use
7145 the GNU General Public License for most of our software; it applies
7146 also to any other work released this way by its authors. You can apply
7147 it to your programs, too.
7149 When we speak of free software, we are referring to freedom, not
7150 price. Our General Public Licenses are designed to make sure that you
7151 have the freedom to distribute copies of free software (and charge for
7152 them if you wish), that you receive source code or can get it if you
7153 want it, that you can change the software or use pieces of it in new
7154 free programs, and that you know you can do these things.
7156 To protect your rights, we need to prevent others from denying you
7157 these rights or asking you to surrender the rights. Therefore, you
7158 have certain responsibilities if you distribute copies of the software,
7159 or if you modify it: responsibilities to respect the freedom of others.
7161 For example, if you distribute copies of such a program, whether
7162 gratis or for a fee, you must pass on to the recipients the same
7163 freedoms that you received. You must make sure that they, too, receive
7164 or can get the source code. And you must show them these terms so they
7167 Developers that use the GNU GPL protect your rights with two steps:
7168 (1) assert copyright on the software, and (2) offer you this License
7169 giving you legal permission to copy, distribute and/or modify it.
7171 For the developers' and authors' protection, the GPL clearly explains
7172 that there is no warranty for this free software. For both users' and
7173 authors' sake, the GPL requires that modified versions be marked as
7174 changed, so that their problems will not be attributed erroneously to
7175 authors of previous versions.
7177 Some devices are designed to deny users access to install or run
7178 modified versions of the software inside them, although the
7179 manufacturer can do so. This is fundamentally incompatible with the
7180 aim of protecting users' freedom to change the software. The
7181 systematic pattern of such abuse occurs in the area of products for
7182 individuals to use, which is precisely where it is most unacceptable.
7183 Therefore, we have designed this version of the GPL to prohibit the
7184 practice for those products. If such problems arise substantially in
7185 other domains, we stand ready to extend this provision to those domains
7186 in future versions of the GPL, as needed to protect the freedom of
7189 Finally, every program is threatened constantly by software patents.
7190 States should not allow patents to restrict development and use of
7191 software on general-purpose computers, but in those that do, we wish to
7192 avoid the special danger that patents applied to a free program could
7193 make it effectively proprietary. To prevent this, the GPL assures that
7194 patents cannot be used to render the program non-free.
7196 The precise terms and conditions for copying, distribution and
7197 modification follow.
7199 TERMS AND CONDITIONS
7200 ====================
7204 "This License" refers to version 3 of the GNU General Public
7207 "Copyright" also means copyright-like laws that apply to other
7208 kinds of works, such as semiconductor masks.
7210 "The Program" refers to any copyrightable work licensed under this
7211 License. Each licensee is addressed as "you". "Licensees" and
7212 "recipients" may be individuals or organizations.
7214 To "modify" a work means to copy from or adapt all or part of the
7215 work in a fashion requiring copyright permission, other than the
7216 making of an exact copy. The resulting work is called a "modified
7217 version" of the earlier work or a work "based on" the earlier work.
7219 A "covered work" means either the unmodified Program or a work
7220 based on the Program.
7222 To "propagate" a work means to do anything with it that, without
7223 permission, would make you directly or secondarily liable for
7224 infringement under applicable copyright law, except executing it
7225 on a computer or modifying a private copy. Propagation includes
7226 copying, distribution (with or without modification), making
7227 available to the public, and in some countries other activities as
7230 To "convey" a work means any kind of propagation that enables other
7231 parties to make or receive copies. Mere interaction with a user
7232 through a computer network, with no transfer of a copy, is not
7235 An interactive user interface displays "Appropriate Legal Notices"
7236 to the extent that it includes a convenient and prominently visible
7237 feature that (1) displays an appropriate copyright notice, and (2)
7238 tells the user that there is no warranty for the work (except to
7239 the extent that warranties are provided), that licensees may
7240 convey the work under this License, and how to view a copy of this
7241 License. If the interface presents a list of user commands or
7242 options, such as a menu, a prominent item in the list meets this
7247 The "source code" for a work means the preferred form of the work
7248 for making modifications to it. "Object code" means any
7249 non-source form of a work.
7251 A "Standard Interface" means an interface that either is an
7252 official standard defined by a recognized standards body, or, in
7253 the case of interfaces specified for a particular programming
7254 language, one that is widely used among developers working in that
7257 The "System Libraries" of an executable work include anything,
7258 other than the work as a whole, that (a) is included in the normal
7259 form of packaging a Major Component, but which is not part of that
7260 Major Component, and (b) serves only to enable use of the work
7261 with that Major Component, or to implement a Standard Interface
7262 for which an implementation is available to the public in source
7263 code form. A "Major Component", in this context, means a major
7264 essential component (kernel, window system, and so on) of the
7265 specific operating system (if any) on which the executable work
7266 runs, or a compiler used to produce the work, or an object code
7267 interpreter used to run it.
7269 The "Corresponding Source" for a work in object code form means all
7270 the source code needed to generate, install, and (for an executable
7271 work) run the object code and to modify the work, including
7272 scripts to control those activities. However, it does not include
7273 the work's System Libraries, or general-purpose tools or generally
7274 available free programs which are used unmodified in performing
7275 those activities but which are not part of the work. For example,
7276 Corresponding Source includes interface definition files
7277 associated with source files for the work, and the source code for
7278 shared libraries and dynamically linked subprograms that the work
7279 is specifically designed to require, such as by intimate data
7280 communication or control flow between those subprograms and other
7283 The Corresponding Source need not include anything that users can
7284 regenerate automatically from other parts of the Corresponding
7287 The Corresponding Source for a work in source code form is that
7290 2. Basic Permissions.
7292 All rights granted under this License are granted for the term of
7293 copyright on the Program, and are irrevocable provided the stated
7294 conditions are met. This License explicitly affirms your unlimited
7295 permission to run the unmodified Program. The output from running
7296 a covered work is covered by this License only if the output,
7297 given its content, constitutes a covered work. This License
7298 acknowledges your rights of fair use or other equivalent, as
7299 provided by copyright law.
7301 You may make, run and propagate covered works that you do not
7302 convey, without conditions so long as your license otherwise
7303 remains in force. You may convey covered works to others for the
7304 sole purpose of having them make modifications exclusively for
7305 you, or provide you with facilities for running those works,
7306 provided that you comply with the terms of this License in
7307 conveying all material for which you do not control copyright.
7308 Those thus making or running the covered works for you must do so
7309 exclusively on your behalf, under your direction and control, on
7310 terms that prohibit them from making any copies of your
7311 copyrighted material outside their relationship with you.
7313 Conveying under any other circumstances is permitted solely under
7314 the conditions stated below. Sublicensing is not allowed; section
7315 10 makes it unnecessary.
7317 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
7319 No covered work shall be deemed part of an effective technological
7320 measure under any applicable law fulfilling obligations under
7321 article 11 of the WIPO copyright treaty adopted on 20 December
7322 1996, or similar laws prohibiting or restricting circumvention of
7325 When you convey a covered work, you waive any legal power to forbid
7326 circumvention of technological measures to the extent such
7327 circumvention is effected by exercising rights under this License
7328 with respect to the covered work, and you disclaim any intention
7329 to limit operation or modification of the work as a means of
7330 enforcing, against the work's users, your or third parties' legal
7331 rights to forbid circumvention of technological measures.
7333 4. Conveying Verbatim Copies.
7335 You may convey verbatim copies of the Program's source code as you
7336 receive it, in any medium, provided that you conspicuously and
7337 appropriately publish on each copy an appropriate copyright notice;
7338 keep intact all notices stating that this License and any
7339 non-permissive terms added in accord with section 7 apply to the
7340 code; keep intact all notices of the absence of any warranty; and
7341 give all recipients a copy of this License along with the Program.
7343 You may charge any price or no price for each copy that you convey,
7344 and you may offer support or warranty protection for a fee.
7346 5. Conveying Modified Source Versions.
7348 You may convey a work based on the Program, or the modifications to
7349 produce it from the Program, in the form of source code under the
7350 terms of section 4, provided that you also meet all of these
7353 a. The work must carry prominent notices stating that you
7354 modified it, and giving a relevant date.
7356 b. The work must carry prominent notices stating that it is
7357 released under this License and any conditions added under
7358 section 7. This requirement modifies the requirement in
7359 section 4 to "keep intact all notices".
7361 c. You must license the entire work, as a whole, under this
7362 License to anyone who comes into possession of a copy. This
7363 License will therefore apply, along with any applicable
7364 section 7 additional terms, to the whole of the work, and all
7365 its parts, regardless of how they are packaged. This License
7366 gives no permission to license the work in any other way, but
7367 it does not invalidate such permission if you have separately
7370 d. If the work has interactive user interfaces, each must display
7371 Appropriate Legal Notices; however, if the Program has
7372 interactive interfaces that do not display Appropriate Legal
7373 Notices, your work need not make them do so.
7375 A compilation of a covered work with other separate and independent
7376 works, which are not by their nature extensions of the covered
7377 work, and which are not combined with it such as to form a larger
7378 program, in or on a volume of a storage or distribution medium, is
7379 called an "aggregate" if the compilation and its resulting
7380 copyright are not used to limit the access or legal rights of the
7381 compilation's users beyond what the individual works permit.
7382 Inclusion of a covered work in an aggregate does not cause this
7383 License to apply to the other parts of the aggregate.
7385 6. Conveying Non-Source Forms.
7387 You may convey a covered work in object code form under the terms
7388 of sections 4 and 5, provided that you also convey the
7389 machine-readable Corresponding Source under the terms of this
7390 License, in one of these ways:
7392 a. Convey the object code in, or embodied in, a physical product
7393 (including a physical distribution medium), accompanied by the
7394 Corresponding Source fixed on a durable physical medium
7395 customarily used for software interchange.
7397 b. Convey the object code in, or embodied in, a physical product
7398 (including a physical distribution medium), accompanied by a
7399 written offer, valid for at least three years and valid for
7400 as long as you offer spare parts or customer support for that
7401 product model, to give anyone who possesses the object code
7402 either (1) a copy of the Corresponding Source for all the
7403 software in the product that is covered by this License, on a
7404 durable physical medium customarily used for software
7405 interchange, for a price no more than your reasonable cost of
7406 physically performing this conveying of source, or (2) access
7407 to copy the Corresponding Source from a network server at no
7410 c. Convey individual copies of the object code with a copy of
7411 the written offer to provide the Corresponding Source. This
7412 alternative is allowed only occasionally and noncommercially,
7413 and only if you received the object code with such an offer,
7414 in accord with subsection 6b.
7416 d. Convey the object code by offering access from a designated
7417 place (gratis or for a charge), and offer equivalent access
7418 to the Corresponding Source in the same way through the same
7419 place at no further charge. You need not require recipients
7420 to copy the Corresponding Source along with the object code.
7421 If the place to copy the object code is a network server, the
7422 Corresponding Source may be on a different server (operated
7423 by you or a third party) that supports equivalent copying
7424 facilities, provided you maintain clear directions next to
7425 the object code saying where to find the Corresponding Source.
7426 Regardless of what server hosts the Corresponding Source, you
7427 remain obligated to ensure that it is available for as long
7428 as needed to satisfy these requirements.
7430 e. Convey the object code using peer-to-peer transmission,
7431 provided you inform other peers where the object code and
7432 Corresponding Source of the work are being offered to the
7433 general public at no charge under subsection 6d.
7436 A separable portion of the object code, whose source code is
7437 excluded from the Corresponding Source as a System Library, need
7438 not be included in conveying the object code work.
7440 A "User Product" is either (1) a "consumer product", which means
7441 any tangible personal property which is normally used for personal,
7442 family, or household purposes, or (2) anything designed or sold for
7443 incorporation into a dwelling. In determining whether a product
7444 is a consumer product, doubtful cases shall be resolved in favor of
7445 coverage. For a particular product received by a particular user,
7446 "normally used" refers to a typical or common use of that class of
7447 product, regardless of the status of the particular user or of the
7448 way in which the particular user actually uses, or expects or is
7449 expected to use, the product. A product is a consumer product
7450 regardless of whether the product has substantial commercial,
7451 industrial or non-consumer uses, unless such uses represent the
7452 only significant mode of use of the product.
7454 "Installation Information" for a User Product means any methods,
7455 procedures, authorization keys, or other information required to
7456 install and execute modified versions of a covered work in that
7457 User Product from a modified version of its Corresponding Source.
7458 The information must suffice to ensure that the continued
7459 functioning of the modified object code is in no case prevented or
7460 interfered with solely because modification has been made.
7462 If you convey an object code work under this section in, or with,
7463 or specifically for use in, a User Product, and the conveying
7464 occurs as part of a transaction in which the right of possession
7465 and use of the User Product is transferred to the recipient in
7466 perpetuity or for a fixed term (regardless of how the transaction
7467 is characterized), the Corresponding Source conveyed under this
7468 section must be accompanied by the Installation Information. But
7469 this requirement does not apply if neither you nor any third party
7470 retains the ability to install modified object code on the User
7471 Product (for example, the work has been installed in ROM).
7473 The requirement to provide Installation Information does not
7474 include a requirement to continue to provide support service,
7475 warranty, or updates for a work that has been modified or
7476 installed by the recipient, or for the User Product in which it
7477 has been modified or installed. Access to a network may be denied
7478 when the modification itself materially and adversely affects the
7479 operation of the network or violates the rules and protocols for
7480 communication across the network.
7482 Corresponding Source conveyed, and Installation Information
7483 provided, in accord with this section must be in a format that is
7484 publicly documented (and with an implementation available to the
7485 public in source code form), and must require no special password
7486 or key for unpacking, reading or copying.
7488 7. Additional Terms.
7490 "Additional permissions" are terms that supplement the terms of
7491 this License by making exceptions from one or more of its
7492 conditions. Additional permissions that are applicable to the
7493 entire Program shall be treated as though they were included in
7494 this License, to the extent that they are valid under applicable
7495 law. If additional permissions apply only to part of the Program,
7496 that part may be used separately under those permissions, but the
7497 entire Program remains governed by this License without regard to
7498 the additional permissions.
7500 When you convey a copy of a covered work, you may at your option
7501 remove any additional permissions from that copy, or from any part
7502 of it. (Additional permissions may be written to require their own
7503 removal in certain cases when you modify the work.) You may place
7504 additional permissions on material, added by you to a covered work,
7505 for which you have or can give appropriate copyright permission.
7507 Notwithstanding any other provision of this License, for material
7508 you add to a covered work, you may (if authorized by the copyright
7509 holders of that material) supplement the terms of this License
7512 a. Disclaiming warranty or limiting liability differently from
7513 the terms of sections 15 and 16 of this License; or
7515 b. Requiring preservation of specified reasonable legal notices
7516 or author attributions in that material or in the Appropriate
7517 Legal Notices displayed by works containing it; or
7519 c. Prohibiting misrepresentation of the origin of that material,
7520 or requiring that modified versions of such material be
7521 marked in reasonable ways as different from the original
7524 d. Limiting the use for publicity purposes of names of licensors
7525 or authors of the material; or
7527 e. Declining to grant rights under trademark law for use of some
7528 trade names, trademarks, or service marks; or
7530 f. Requiring indemnification of licensors and authors of that
7531 material by anyone who conveys the material (or modified
7532 versions of it) with contractual assumptions of liability to
7533 the recipient, for any liability that these contractual
7534 assumptions directly impose on those licensors and authors.
7536 All other non-permissive additional terms are considered "further
7537 restrictions" within the meaning of section 10. If the Program as
7538 you received it, or any part of it, contains a notice stating that
7539 it is governed by this License along with a term that is a further
7540 restriction, you may remove that term. If a license document
7541 contains a further restriction but permits relicensing or
7542 conveying under this License, you may add to a covered work
7543 material governed by the terms of that license document, provided
7544 that the further restriction does not survive such relicensing or
7547 If you add terms to a covered work in accord with this section, you
7548 must place, in the relevant source files, a statement of the
7549 additional terms that apply to those files, or a notice indicating
7550 where to find the applicable terms.
7552 Additional terms, permissive or non-permissive, may be stated in
7553 the form of a separately written license, or stated as exceptions;
7554 the above requirements apply either way.
7558 You may not propagate or modify a covered work except as expressly
7559 provided under this License. Any attempt otherwise to propagate or
7560 modify it is void, and will automatically terminate your rights
7561 under this License (including any patent licenses granted under
7562 the third paragraph of section 11).
7564 However, if you cease all violation of this License, then your
7565 license from a particular copyright holder is reinstated (a)
7566 provisionally, unless and until the copyright holder explicitly
7567 and finally terminates your license, and (b) permanently, if the
7568 copyright holder fails to notify you of the violation by some
7569 reasonable means prior to 60 days after the cessation.
7571 Moreover, your license from a particular copyright holder is
7572 reinstated permanently if the copyright holder notifies you of the
7573 violation by some reasonable means, this is the first time you have
7574 received notice of violation of this License (for any work) from
7575 that copyright holder, and you cure the violation prior to 30 days
7576 after your receipt of the notice.
7578 Termination of your rights under this section does not terminate
7579 the licenses of parties who have received copies or rights from
7580 you under this License. If your rights have been terminated and
7581 not permanently reinstated, you do not qualify to receive new
7582 licenses for the same material under section 10.
7584 9. Acceptance Not Required for Having Copies.
7586 You are not required to accept this License in order to receive or
7587 run a copy of the Program. Ancillary propagation of a covered work
7588 occurring solely as a consequence of using peer-to-peer
7589 transmission to receive a copy likewise does not require
7590 acceptance. However, nothing other than this License grants you
7591 permission to propagate or modify any covered work. These actions
7592 infringe copyright if you do not accept this License. Therefore,
7593 by modifying or propagating a covered work, you indicate your
7594 acceptance of this License to do so.
7596 10. Automatic Licensing of Downstream Recipients.
7598 Each time you convey a covered work, the recipient automatically
7599 receives a license from the original licensors, to run, modify and
7600 propagate that work, subject to this License. You are not
7601 responsible for enforcing compliance by third parties with this
7604 An "entity transaction" is a transaction transferring control of an
7605 organization, or substantially all assets of one, or subdividing an
7606 organization, or merging organizations. If propagation of a
7607 covered work results from an entity transaction, each party to that
7608 transaction who receives a copy of the work also receives whatever
7609 licenses to the work the party's predecessor in interest had or
7610 could give under the previous paragraph, plus a right to
7611 possession of the Corresponding Source of the work from the
7612 predecessor in interest, if the predecessor has it or can get it
7613 with reasonable efforts.
7615 You may not impose any further restrictions on the exercise of the
7616 rights granted or affirmed under this License. For example, you
7617 may not impose a license fee, royalty, or other charge for
7618 exercise of rights granted under this License, and you may not
7619 initiate litigation (including a cross-claim or counterclaim in a
7620 lawsuit) alleging that any patent claim is infringed by making,
7621 using, selling, offering for sale, or importing the Program or any
7626 A "contributor" is a copyright holder who authorizes use under this
7627 License of the Program or a work on which the Program is based.
7628 The work thus licensed is called the contributor's "contributor
7631 A contributor's "essential patent claims" are all patent claims
7632 owned or controlled by the contributor, whether already acquired or
7633 hereafter acquired, that would be infringed by some manner,
7634 permitted by this License, of making, using, or selling its
7635 contributor version, but do not include claims that would be
7636 infringed only as a consequence of further modification of the
7637 contributor version. For purposes of this definition, "control"
7638 includes the right to grant patent sublicenses in a manner
7639 consistent with the requirements of this License.
7641 Each contributor grants you a non-exclusive, worldwide,
7642 royalty-free patent license under the contributor's essential
7643 patent claims, to make, use, sell, offer for sale, import and
7644 otherwise run, modify and propagate the contents of its
7645 contributor version.
7647 In the following three paragraphs, a "patent license" is any
7648 express agreement or commitment, however denominated, not to
7649 enforce a patent (such as an express permission to practice a
7650 patent or covenant not to sue for patent infringement). To
7651 "grant" such a patent license to a party means to make such an
7652 agreement or commitment not to enforce a patent against the party.
7654 If you convey a covered work, knowingly relying on a patent
7655 license, and the Corresponding Source of the work is not available
7656 for anyone to copy, free of charge and under the terms of this
7657 License, through a publicly available network server or other
7658 readily accessible means, then you must either (1) cause the
7659 Corresponding Source to be so available, or (2) arrange to deprive
7660 yourself of the benefit of the patent license for this particular
7661 work, or (3) arrange, in a manner consistent with the requirements
7662 of this License, to extend the patent license to downstream
7663 recipients. "Knowingly relying" means you have actual knowledge
7664 that, but for the patent license, your conveying the covered work
7665 in a country, or your recipient's use of the covered work in a
7666 country, would infringe one or more identifiable patents in that
7667 country that you have reason to believe are valid.
7669 If, pursuant to or in connection with a single transaction or
7670 arrangement, you convey, or propagate by procuring conveyance of, a
7671 covered work, and grant a patent license to some of the parties
7672 receiving the covered work authorizing them to use, propagate,
7673 modify or convey a specific copy of the covered work, then the
7674 patent license you grant is automatically extended to all
7675 recipients of the covered work and works based on it.
7677 A patent license is "discriminatory" if it does not include within
7678 the scope of its coverage, prohibits the exercise of, or is
7679 conditioned on the non-exercise of one or more of the rights that
7680 are specifically granted under this License. You may not convey a
7681 covered work if you are a party to an arrangement with a third
7682 party that is in the business of distributing software, under
7683 which you make payment to the third party based on the extent of
7684 your activity of conveying the work, and under which the third
7685 party grants, to any of the parties who would receive the covered
7686 work from you, a discriminatory patent license (a) in connection
7687 with copies of the covered work conveyed by you (or copies made
7688 from those copies), or (b) primarily for and in connection with
7689 specific products or compilations that contain the covered work,
7690 unless you entered into that arrangement, or that patent license
7691 was granted, prior to 28 March 2007.
7693 Nothing in this License shall be construed as excluding or limiting
7694 any implied license or other defenses to infringement that may
7695 otherwise be available to you under applicable patent law.
7697 12. No Surrender of Others' Freedom.
7699 If conditions are imposed on you (whether by court order,
7700 agreement or otherwise) that contradict the conditions of this
7701 License, they do not excuse you from the conditions of this
7702 License. If you cannot convey a covered work so as to satisfy
7703 simultaneously your obligations under this License and any other
7704 pertinent obligations, then as a consequence you may not convey it
7705 at all. For example, if you agree to terms that obligate you to
7706 collect a royalty for further conveying from those to whom you
7707 convey the Program, the only way you could satisfy both those
7708 terms and this License would be to refrain entirely from conveying
7711 13. Use with the GNU Affero General Public License.
7713 Notwithstanding any other provision of this License, you have
7714 permission to link or combine any covered work with a work licensed
7715 under version 3 of the GNU Affero General Public License into a
7716 single combined work, and to convey the resulting work. The terms
7717 of this License will continue to apply to the part which is the
7718 covered work, but the special requirements of the GNU Affero
7719 General Public License, section 13, concerning interaction through
7720 a network will apply to the combination as such.
7722 14. Revised Versions of this License.
7724 The Free Software Foundation may publish revised and/or new
7725 versions of the GNU General Public License from time to time.
7726 Such new versions will be similar in spirit to the present
7727 version, but may differ in detail to address new problems or
7730 Each version is given a distinguishing version number. If the
7731 Program specifies that a certain numbered version of the GNU
7732 General Public License "or any later version" applies to it, you
7733 have the option of following the terms and conditions either of
7734 that numbered version or of any later version published by the
7735 Free Software Foundation. If the Program does not specify a
7736 version number of the GNU General Public License, you may choose
7737 any version ever published by the Free Software Foundation.
7739 If the Program specifies that a proxy can decide which future
7740 versions of the GNU General Public License can be used, that
7741 proxy's public statement of acceptance of a version permanently
7742 authorizes you to choose that version for the Program.
7744 Later license versions may give you additional or different
7745 permissions. However, no additional obligations are imposed on any
7746 author or copyright holder as a result of your choosing to follow a
7749 15. Disclaimer of Warranty.
7751 THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
7752 APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE
7753 COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS"
7754 WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED,
7755 INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
7756 MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE
7757 RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.
7758 SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
7759 NECESSARY SERVICING, REPAIR OR CORRECTION.
7761 16. Limitation of Liability.
7763 IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
7764 WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES
7765 AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU
7766 FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
7767 CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE
7768 THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA
7769 BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
7770 PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
7771 PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF
7772 THE POSSIBILITY OF SUCH DAMAGES.
7774 17. Interpretation of Sections 15 and 16.
7776 If the disclaimer of warranty and limitation of liability provided
7777 above cannot be given local legal effect according to their terms,
7778 reviewing courts shall apply local law that most closely
7779 approximates an absolute waiver of all civil liability in
7780 connection with the Program, unless a warranty or assumption of
7781 liability accompanies a copy of the Program in return for a fee.
7784 END OF TERMS AND CONDITIONS
7785 ===========================
7787 How to Apply These Terms to Your New Programs
7788 =============================================
7790 If you develop a new program, and you want it to be of the greatest
7791 possible use to the public, the best way to achieve this is to make it
7792 free software which everyone can redistribute and change under these
7795 To do so, attach the following notices to the program. It is safest
7796 to attach them to the start of each source file to most effectively
7797 state the exclusion of warranty; and each file should have at least the
7798 "copyright" line and a pointer to where the full notice is found.
7800 ONE LINE TO GIVE THE PROGRAM'S NAME AND A BRIEF IDEA OF WHAT IT DOES.
7801 Copyright (C) YEAR NAME OF AUTHOR
7803 This program is free software: you can redistribute it and/or modify
7804 it under the terms of the GNU General Public License as published by
7805 the Free Software Foundation, either version 3 of the License, or (at
7806 your option) any later version.
7808 This program is distributed in the hope that it will be useful, but
7809 WITHOUT ANY WARRANTY; without even the implied warranty of
7810 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
7811 General Public License for more details.
7813 You should have received a copy of the GNU General Public License
7814 along with this program. If not, see `http://www.gnu.org/licenses/'.
7816 Also add information on how to contact you by electronic and paper
7819 If the program does terminal interaction, make it output a short
7820 notice like this when it starts in an interactive mode:
7822 PROGRAM Copyright (C) YEAR NAME OF AUTHOR
7823 This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
7824 This is free software, and you are welcome to redistribute it
7825 under certain conditions; type `show c' for details.
7827 The hypothetical commands `show w' and `show c' should show the
7828 appropriate parts of the General Public License. Of course, your
7829 program's commands might be different; for a GUI interface, you would
7832 You should also get your employer (if you work as a programmer) or
7833 school, if any, to sign a "copyright disclaimer" for the program, if
7834 necessary. For more information on this, and how to apply and follow
7835 the GNU GPL, see `http://www.gnu.org/licenses/'.
7837 The GNU General Public License does not permit incorporating your
7838 program into proprietary programs. If your program is a subroutine
7839 library, you may consider it more useful to permit linking proprietary
7840 applications with the library. If this is what you want to do, use the
7841 GNU Lesser General Public License instead of this License. But first,
7842 please read `http://www.gnu.org/philosophy/why-not-lgpl.html'.
7845 File: m4.info, Node: Copying This Manual, Next: Indices, Prev: Copying This Package, Up: Top
7847 Appendix B How to make copies of this manual
7848 ********************************************
7850 This appendix covers the license for copying this manual. Note that
7851 some of the longer examples in this manual are also distributed in the
7852 directory `m4-1.4.16/examples/', where a more permissive license is in
7853 effect when copying just the examples.
7857 * GNU Free Documentation License:: License for copying this manual