1This is Info file m4.info, produced by Makeinfo-1.47 from the input 2file m4.texinfo. 3 4 This file documents the GNU m4 utility. 5 6 Copyright (C) 1989, 1990, 1991, 1992, 1993 Free Software Foundation, 7Inc. 8 9 Permission is granted to make and distribute verbatim copies of this 10manual provided the copyright notice and this permission notice are 11preserved on all copies. 12 13 Permission is granted to copy and distribute modified versions of 14this manual under the conditions for verbatim copying, provided also 15that the entire resulting derived work is distributed under the terms 16of a permission notice identical to this one. 17 18 Permission is granted to copy and distribute translations of this 19manual into another language, under the above conditions for modified 20versions. 21 22 23File: m4.info, Node: Top, Next: Intro, Prev: (dir), Up: (dir) 24 25 This file documents GNU the `m4' simple macroprocessor, as of 26release 1.1. It has been originally written by Rene Seindal, from 27Denmark. 28 29* Menu: 30 31* Intro:: Introduction to m4 32* Manual:: How to use this manual 33* Bugs:: Reporting bugs in m4 34 35* Invoking m4:: How to run the program 36* Syntax:: Lexical and syntactic conventions 37 38* Macros:: How to invoke macros 39* Definitions:: How to define new macros 40* Conditionals:: Conditionals and loops 41 42* Debugging:: How to debug macros and input 43* Input Control:: Input control 44 45* File Inclusion:: File inclusion 46* Diversions:: Diverting and undiverting output 47 48* Text handling:: Macros for text handling 49* Arithmetic:: Macros for doing arithmetic 50* Unix commands:: Macros for running Unix commands 51* Miscellaneous:: Miscellaneous built-in macros 52 53* Compatibility:: Compatibility with other versions of m4 54 55* Concept index:: Index for many concepts 56* Macro index:: Index for all m4 macros 57 58 -- The Detailed Node Listing -- 59 60Lexical and syntactic conventions 61 62* Names:: Macro names. 63* Quoted strings:: Quoting input to m4. 64* Other tokens:: Other kinds of input tokens. 65* Comments:: Comments in m4 input. 66 67How to invoke macros 68 69* Invocation:: Macro invocation 70* Macro Arguments:: Macro arguments. 71* Quoting Arguments:: On Quoting Arguments to macros. 72* Macro expansion:: Expanding macros. 73 74How to define new macros 75 76* Define:: Defining a new macro 77* Arguments:: Arguments to macros 78* Pseudo Arguments:: Pseudo arguments to macros 79* Undefine:: Deleting a macro 80* Defn:: Renaming macros 81* Pushdef:: Temporarily redefining macros 82 83* Indir:: Indirect call of macros 84* Builtin:: Indirect call of built-ins 85 86Conditionals, loops and recursion 87 88* Ifdef:: Testing if a macro is defined 89* Ifelse:: If-else construct, or multibranch 90* Loops:: Loops and recursion in m4 91 92How to debug macros and input 93 94* Dumpdef:: Displaying macro definitions 95* Trace:: Tracing macro calls 96* Debug Levels:: Controlling debugging output 97* Debug Output:: Saving debugging output 98 99Input control 100 101* Dnl:: Deleting whitespace in input 102* Changequote:: Changing the quote characters 103* Changecom:: Changing the comment delimiters 104* M4wrap:: Saving input until end of input 105 106File inclusion 107 108* Include:: Including named files 109* Search Path:: Searching for include files 110 111Diverting and undiverting output 112 113* Divert:: Diverting output 114* Undivert:: Undiverting output 115* Divnum:: Diversion numbers 116* Cleardiv:: Discarding diverted text 117 118Macros for text handling 119 120* Len:: Calculating length of strings 121* Index:: Searching for substrings 122* Regexp:: Searching for regular expressions 123* Substr:: Extracting substrings 124* Translit:: Translating characters 125* Patsubst:: Substituting text by regular expression 126* Format:: Formatting strings (printf-like) 127 128Macros for doing arithmetic 129 130* Incr:: Decrement and increment operators 131* Eval:: Evaluating integer expressions 132 133Running Unix commands 134 135* Syscmd:: Executing simple commands 136* Esyscmd:: Reading the output of commands 137* Sysval:: Exit codes 138* Maketemp:: Making names for temporary files 139 140Miscellaneous built-in macros 141 142* Errprint:: Printing error messages 143* M4exit:: Exiting from m4 144 145Compatibility with other versions of `m4' 146 147* Extensions:: Extensions in GNU m4 148* Incompatibilities:: Facilities in System V m4 not in GNU m4 149* Other Incompat:: Other incompatibilities 150 151 152File: m4.info, Node: Intro, Next: Manual, Prev: Top, Up: Top 153 154Introduction to `m4' 155******************** 156 157 `m4' is a macro processor, in the sense that in copies its input to 158the output, expanding macros as it goes. Macros are either built-in or 159user-defined, and can take any number of arguments. Besides just doing 160macro expansion, `m4' has built-in functions for including named files, 161running Unix commands, doing integer arithmetic, manipulating text in 162various ways, recursion, etc... 163 164 `m4' can be used either as a front-end to a compiler, or as a macro 165processor in its own right. 166 167 GNU `m4' is mostly compatible with the System V, Release 3 version, 168except for some minor differences. *Note Compatibility:: for more 169details. 170 171 172File: m4.info, Node: Manual, Next: Bugs, Prev: Intro, Up: Top 173 174Using this manual 175***************** 176 177 This manual contains a number of examples of `m4' input and output, 178and a simple notation is used to distinguish input, output and error 179messages from `m4'. Examples are set out from the normal text, and 180shown in a fixed width font, like this 181 182 This is an example of an example! 183 184 To distinguish input from output, all output from `m4' is prefixed 185by the string `=>', and all error messages by the string `error-->'. 186Thus 187 188 Example of input line 189 =>Output line from m4 190 error-->and an error message 191 192 As each of the predefined macros in `m4' is described, a prototype 193call of the macro will be shown, giving descriptive names to the 194arguments, e.g., 195 196 regexp(STRING, REGEXP, opt REPLACEMENT) 197 198 All macro arguments in `m4' are strings, but some are given special 199interpretation, e.g., as numbers, filenames, regular expressions, etc. 200 201 The `opt' before the third argument shows that this argument is 202optional--if it is left out, it is taken to be the empty string. An 203ellipsis (`...') last in the argument list indicates that any number of 204arguments may follow. 205 206 207File: m4.info, Node: Bugs, Next: Invoking m4, Prev: Manual, Up: Top 208 209Problems and bugs 210***************** 211 212 If you have problems with GNU `m4' or think you've found a bug, 213please report it. Before reporting a bug, make sure you've actually 214found a real bug. Carefully reread the documentation and see if it 215really says you can do what you're trying to do. If it's not clear 216whether you should be able to do something or not, report that too; it's 217a bug in the documentation! 218 219 Before reporting a bug or trying to fix it yourself, try to isolate 220it to the smallest possible input file that reproduces the problem. 221Then send us the input file and the exact results `m4' gave you. Also 222say what you expected to occur; this will help us decide whether the 223problem was really in the documentation. 224 225 Once you've got a precise problem, send e-mail to (Internet) 226`bug-gnu-utils@prep.ai.mit.edu' or (UUCP) 227`mit-eddie!prep.ai.mit.edu!bug-gnu-utils'. Please include the version 228number of `m4' you are using. You can get this information with the 229command `m4 -V /dev/null'. 230 231 Non-bug suggestions are always welcome as well. If you have 232questions about things that are unclear in the documentation or are 233just obscure features, please report them too. 234 235 236File: m4.info, Node: Invoking m4, Next: Syntax, Prev: Bugs, Up: Top 237 238Invoking `m4' 239************* 240 241 The format of the `m4' command is: 242 243 `m4' [OPTION...] [MACRO-DEFINITIONS...] [INPUT-FILE...] 244 245 All options begin with `-', or if long option names are used, with a 246`--'. A long option name need not be written completely, and 247unambigous prefix is sufficient. `m4' understands the following 248options: 249 250`--version' 251 Print the version number of the program on standard output, then 252 immediately exit `m4' without reading any INPUT-FILES. 253 254`--help' 255 Print an help summary on standard output, then immediately exit 256 `m4' without reading any INPUT-FILES. 257 258`-G' 259`--traditional' 260 Suppress all the extensions made in this implementation, compared 261 to the System V version. For a list of these, *note 262 Compatibility::.. 263 264`-dFLAGS' 265`--debug=FLAGS' 266 Set the debug-level according to the flags FLAGS. The debug-level 267 controls the format and amount of information presented by the 268 debugging functions. *Note Debug Levels:: for more details on the 269 format and meaning of FLAGS. 270 271`-lNUM' 272`--arglength=NUM' 273 Restrict the size of the output generated by macro tracing. *Note 274 Debug Levels:: for more details. 275 276`-oFILE' 277`--erroroutput=FILE' 278 Redirect debug and trace output to the named file. Error messages 279 are still printed on the standard error output. *Note Debug 280 Output:: for more details. 281 282`-IDIR' 283`--include=DIR' 284 Make `m4' search DIR for included files that are not found in the 285 current working directory. *Note Search Path:: for more details. 286 287`-e' 288`--interactive' 289 Makes this invocation of `m4' interactive. This means that all 290 output will be unbuffered, and interrupts will be ignored. 291 292`-s' 293`--synclines' 294 Generate synchronisation lines, for use by the C preprocessor or 295 other similar tools. This is useful, for example, when `m4' is 296 used as a front end to a compiler. Source file name and line 297 number information is conveyed by directives of the form `#line 298 LINENUM "FILENAME"', which are inserted as needed into the middle 299 of the input. Such directives mean that the following line 300 originated or was expanded from the contents of input file 301 FILENAME at line LINENUM. The `"FILENAME"' part is often omitted 302 when the file name did not change from the previous directive. 303 304 Synchronisation directives are always given on complete lines per 305 themselves. When a synchronisation discrepancy occurs in the 306 middle of an output line, the associated synchronisation directive 307 is delayed until the beginning of the next generated line. 308 309`-P' 310`--prefix_builtins' 311 Internally modify *all* builtin macro names so they all start with 312 the prefix `m4_'. For example, using this option, one should write 313 `m4_define' instead of `define', and `m4___file__' instead of 314 `__file__'. 315 316`-HN' 317`--hashsize=N' 318 Make the internal hash table for symbol lookup be N entries big. 319 The number should be prime. The default is 509 entries. It 320 should not be necessary to increase this value, unless you define 321 an excessive number of macros. 322 323`-NN' 324`--diversions=N' 325 Allow for up to N diversions to be used at the same time. The 326 default is 10 diversions. 327 328`-Q' 329`--quiet' 330`--silent' 331 Suppress warnings about missing or superflous arguments in macro 332 calls. 333 334`-B' 335`-S' 336`-T' 337 These options are present for compatibility with System V `m4', but 338 do nothing in this implementation. 339 340 Macro definitions and deletions can be made on the command line, by 341using the `-D' and `-U' options. They have the following format: 342 343`-DNAME' 344`-DNAME=VALUE' 345`--define=NAME' 346`--define=NAME=VALUE' 347 This enters NAME into the symbol table, before any input files are 348 read. If `=VALUE' is missing, the value is taken to be the empty 349 string. The VALUE can be any string, and the macro can be defined 350 to take arguments, just as if it was defined from within the input. 351 352`-UNAME' 353`--undefine=NAME' 354 This deletes any predefined meaning NAME might have. Obviously, 355 only predefined macros can be deleted in this way. 356 357`-tNAME' 358`--trace=NAME' 359 This enters NAME into the symbol table, as undefined but traced. 360 The macro will consequently be traced from the point it is defined. 361 362 The remaining arguments on the command line are taken to be input 363file names. If no names are present, the standard input is read. A 364file name of `-' is taken to mean the standard input. 365 366 The input files are read in the sequence given. The standard input 367can only be read once, so the filename `-' should only appear once on 368the command line. 369 370 371File: m4.info, Node: Syntax, Next: Macros, Prev: Invoking m4, Up: Top 372 373Lexical and syntactic conventions 374********************************* 375 376 As `m4' reads its input, it separates it into "tokens". A token is 377either a name, a quoted string, or any single character, that is not a 378part of either a name or a string. Input to `m4' can also contain 379comments. 380 381* Menu: 382 383* Names:: Macro names. 384* Quoted strings:: Quoting input to m4. 385* Other tokens:: Other kinds of input tokens. 386* Comments:: Comments in m4 input. 387 388 389File: m4.info, Node: Names, Next: Quoted strings, Prev: Syntax, Up: Syntax 390 391Names 392===== 393 394 A name is any sequence of letters, digits, and the character `_' 395(underscore), where the first character is not a digit. If a name has a 396macro definition, it will be subject to macro expansion (*note 397Macros::. for more details). 398 399 Examples of legal names are: `foo', `_tmp', and `name01'. 400 401 402File: m4.info, Node: Quoted strings, Next: Other tokens, Prev: Names, Up: Syntax 403 404Quoted strings 405============== 406 407 A quoted string is a sequence of characters surrounded by the quotes 408``' and `'', where the number of start and end quotes within the string 409balances. The value of a string token is the text, with one level of 410quotes stripped off. Thus 411 412 `' 413 414 is the empty string, and 415 416 ``quoted'' 417 418 is the string 419 420 `quoted' 421 422 The quote characters can be changed at any time, using the built-in 423macro `changequote'. *Note Changequote:: for more information. 424 425 426File: m4.info, Node: Other tokens, Next: Comments, Prev: Quoted strings, Up: Syntax 427 428Other tokens 429============ 430 431 Any character, that is neither a part of a name, nor of a quoted 432string, is a token by itself. 433 434 435File: m4.info, Node: Comments, Prev: Other tokens, Up: Syntax 436 437Comments 438======== 439 440 Comments in `m4' are normally delimited by the characters `#' and 441newline. All characters between the comment delimiters are ignored, 442but the entire comment (including the delimiters) is passed through to 443the output--comments are *not* discarded by `m4'. 444 445 Comments cannot be nested, so the first newline after a `#' ends the 446comment. The begin comment character can be included in the input by 447quoting it. 448 449 The comment delimiters can be changed to any string at any time, 450using the built-in macro `changecom'. *Note Changecom:: for more 451information. 452 453 454File: m4.info, Node: Macros, Next: Definitions, Prev: Syntax, Up: Top 455 456How to invoke macros 457******************** 458 459 This chapter covers macro invocation, macro arguments and how macro 460expansion is treated. 461 462* Menu: 463 464* Invocation:: Macro invocation 465* Macro Arguments:: Macro arguments. 466* Quoting Arguments:: On Quoting Arguments to macros. 467* Macro expansion:: Expanding macros. 468 469 470File: m4.info, Node: Invocation, Next: Macro Arguments, Prev: Macros, Up: Macros 471 472Macro invocation 473================ 474 475 Macro invocations has one of the forms 476 477 name 478 479which is a macro invocation without any arguments, or 480 481 name(arg1, arg2, ..., argN) 482 483which is a macro invocation with N arguments. Macros can have any 484number of arguments. All arguments are strings, but different macros 485might interpret the arguments in different ways. 486 487 The opening parenthesis *must* follow the NAME directly, with no 488spaces in between. If it does not, the macro is called with no 489arguments at all. 490 491 For a macro call to have no arguments, the parentheses *must* be 492left out. The macro call 493 494 name() 495 496is a macro call with one argument, which is the empty string, not a call 497with no arguments. 498 499 Many builtin macros cannot meaningfully be called without arguments. 500For any of these macros, whenever an opening parenthesis does not 501immediately follow their name, then they are not recognized as builtin 502macros. The sentence "This macro is recognized only when given 503arguments.", later in this document, means exactly that. 504 505 506File: m4.info, Node: Macro Arguments, Next: Quoting Arguments, Prev: Invocation, Up: Macros 507 508Macro arguments 509=============== 510 511 When a name is seen, and it has a macro definition, it will be 512expanded as a macro. 513 514 If the name is followed by an opening parenthesis, the arguments 515will be collected before the macro is called. If too few arguments are 516supplied, the missing arguments are taken to be the empty string. If 517there are too many arguments, the excess arguments are ignored. 518 519 Normally `m4' will issue warnings if a built-in macro is called with 520an inappropriate number of arguments, but it can be suppressed with the 521`-Q' command line option. For user defined macros, there is no check 522of the number of arguments given. 523 524 Macros are expanded normally during argument collection, and whatever 525commas, quotes and parentheses that might show up in the resulting 526expanded text will serve to define the arguments as well. Thus, if FOO 527expands to `,b,c', the macro call 528 529 bar(a foo,d) 530 531 is a macro call with four arguments, which are `a ', `b', `c' and 532`d'. 533 534 535File: m4.info, Node: Quoting Arguments, Next: Macro expansion, Prev: Macro Arguments, Up: Macros 536 537Quoting macro arguments 538======================= 539 540 Each argument has leading unquoted whitespace removed. Within each 541argument, all unquoted parentheses must match. For example, if FOO is 542a macro, 543 544 foo(() (`(') `(') 545 546 is a macro call, with one argument, whose value is `() (() ('. 547 548 It is common practice to quote all arguments to macros, unless you 549are sure you want the arguments expanded. Thus, in the above example 550with the parentheses, the `right' way to do it is like this: 551 552 foo(`() (() (') 553 554 It is, however, in certain cases necessary to leave out quotes for 555some arguments, and there is nothing wrong in doing it. It just makes 556life a bit harder, if you are not careful. 557 558 559File: m4.info, Node: Macro expansion, Prev: Quoting Arguments, Up: Macros 560 561Macro expansion 562=============== 563 564 When the arguments, if any, to a macro call have been collected, the 565macro is expanded, and the expansion text is pushed back onto the input 566(unquoted), and reread. The expansion text from one macro call might 567therefore result in more macros being called, if the calls are included, 568completely or partially, in the first macro calls' expansion. 569 570 Taking a very simple example, if FOO expands to `bar', and BAR 571expands to `Hello world', the input 572 573 foo 574 575will expand first to `bar', and when this is reread and expanded, into 576`Hello world'. 577 578 579File: m4.info, Node: Definitions, Next: Conditionals, Prev: Macros, Up: Top 580 581How to define new macros 582************************ 583 584 Macros can be defined, redefined and deleted in several different 585ways. Also, it is possible to redefine a macro, without losing a 586previous value, which can be brought back at a later time. 587 588* Menu: 589 590* Define:: Defining a new macro 591* Arguments:: Arguments to macros 592* Pseudo Arguments:: Pseudo arguments to macros 593* Undefine:: Deleting a macro 594* Defn:: Renaming macros 595* Pushdef:: Temporarily redefining macros 596 597* Indir:: Indirect call of macros 598* Builtin:: Indirect call of built-ins 599 600 601File: m4.info, Node: Define, Next: Arguments, Prev: Definitions, Up: Definitions 602 603Defining a macro 604================ 605 606 The normal way to define or redefine macros is to use the built-in 607`define': 608 609 define(NAME [, EXPANSION]) 610 611which defines NAME to expand to EXPANSION. If EXPANSION is not given, 612it is taken to be empty. 613 614 The expansion of `define' is void. 615 616 The following example defines the macro FOO to expand to the text 617`Hello World.'. 618 619 define(`foo', `Hello world.') 620 => 621 foo 622 =>Hello world. 623 624 The empty line in the output is there because the newline is not a 625part of the macro definition, and it is consequently copied to the 626output. This can be avoided by use of the macro `dnl' (*note Dnl::. for 627details). 628 629 The macro `define' is recognized only with parameters. 630 631 632File: m4.info, Node: Arguments, Next: Pseudo Arguments, Prev: Define, Up: Definitions 633 634Arguments to macros 635=================== 636 637 Macros can have arguments. The Nth argument is denoted by `$n' in 638the expansion text, and is replaced by the Nth actual argument, when 639the macro is expanded. Here is a example of a macro with two 640arguments. It simply exchanges the order of the two arguments. 641 642 define(`exch', `$2, $1') 643 => 644 exch(arg1, arg2) 645 =>arg2, arg1 646 647 This can be used, for example, if you like the arguments to `define' 648to be reversed. 649 650 define(`exch', `$2, $1') 651 => 652 define(exch(``expansion text'', ``macro'')) 653 => 654 macro 655 =>expansion text 656 657 For an explanation of the double quotes, *note Quoting Arguments::.. 658 659 GNU `m4' allows the number following the `$' to consist of one or 660more digits, allowing macros to have any number of arguments. This is 661not so in Unix implementations of `m4', which only recognize one digit. 662 663 As a special case, the zero'th argument, `$0', is always the name of 664the macro being expanded. 665 666 define(`test', ``Macro name: $0'') 667 => 668 test 669 =>Macro name: test 670 671 If you want quoted text to appear as part of the expansion text, 672remember that quotes can be nested in quoted strings. Thus, in 673 674 define(`foo', `This is macro `foo'.') 675 => 676 foo 677 =>This is macro foo. 678 679The `foo' in the expansion text is *not* expanded, since it is a quoted 680string, and not a name. 681 682 683File: m4.info, Node: Pseudo Arguments, Next: Undefine, Prev: Arguments, Up: Definitions 684 685Special arguments to macros 686=========================== 687 688 There is a special notation for the number of actual arguments 689supplied, and for all the actual arguments. 690 691 The number of actual arguments in a macro call is denoted by `$#' in 692the expansion text. Thus, a macro to display the number of arguments 693given can be 694 695 define(`nargs', `$#') 696 => 697 nargs 698 =>0 699 nargs() 700 =>1 701 nargs(arg1, arg2, arg3) 702 =>3 703 704 The notation `$*' can be used in the expansion text to denote all 705the actual arguments, unquoted, with commas in between. For example 706 707 define(`echo', `$*') 708 => 709 echo(arg1, arg2, arg3 , arg4) 710 =>arg1,arg2,arg3 ,arg4 711 712 Often each argument should be quoted, and the notation `$@' handles 713that. It is just like `$*', except that it quotes each argument. A 714simple example of that is: 715 716 define(`echo', `$@') 717 => 718 echo(arg1, arg2, arg3 , arg4) 719 =>arg1,arg2,arg3 ,arg4 720 721 Where did the quotes go? Of course, they were eaten, when the 722expanded text were reread by `m4'. To show the difference, try 723 724 define(`echo1', `$*') 725 => 726 define(`echo2', `$@') 727 => 728 define(`foo', `This is macro `foo'.') 729 => 730 echo1(foo) 731 =>This is macro This is macro foo.. 732 echo2(foo) 733 =>This is macro foo. 734 735 If you don't understand this, *note Trace::.. 736 737 A `$' sign in the expansion text, that is not followed by anything 738`m4' understands, is simply copied to the macro expansion, as any other 739text is. 740 741 define(`foo', `$$$ hello $$$') 742 => 743 foo 744 =>$$$ hello $$$ 745 746 If you want a macro to expand to something like `$12', put a pair of 747quotes after the `$'. This will prevent `m4' from interpreting the `$' 748sign as a reference to an argument. 749 750 751File: m4.info, Node: Undefine, Next: Defn, Prev: Pseudo Arguments, Up: Definitions 752 753Deleting a macro 754================ 755 756 A macro definition can be removed with `undefine': 757 758 undefine(NAME) 759 760which removes the macro NAME. The macro name must necessarily be 761quoted, since it will be expanded otherwise. 762 763 The expansion of `undefine' is void. 764 765 foo 766 =>foo 767 define(`foo', `expansion text') 768 => 769 foo 770 =>expansion text 771 undefine(`foo') 772 => 773 foo 774 =>foo 775 776 It is not an error for NAME to have no macro definition. In that 777case, `undefine' does nothing. 778 779 The macro `undefine' is recognized only with parameters. 780 781 782File: m4.info, Node: Defn, Next: Pushdef, Prev: Undefine, Up: Definitions 783 784Renaming macros 785=============== 786 787 It is possible to rename an already defined macro. To do this, you 788need the built-in `defn': 789 790 defn(NAME) 791 792which expands to the *quoted definition* of NAME. If the argument is 793not a defined macro, the expansion is void. 794 795 If NAME is a user-defined macro, the quoted definition is simply the 796quoted expansion text. If, instead, NAME is a built-in, the expansion 797is a special token, which points to the built-in's internal definition. 798 This token is only meaningful as the second argument to `define' (and 799`pushdef'), and is ignored in any other context. 800 801 Its normal use is best understood through an example, which shows 802how to rename `undefine' to `zap': 803 804 define(`zap', defn(`undefine')) 805 => 806 zap(`undefine') 807 => 808 undefine(`zap') 809 =>undefine(zap) 810 811 In this way, `defn' can be used to copy macro definitions, and also 812definitions of built-in macros. Even if the original macro is removed, 813the other name can still be used to access the definition. 814 815 The macro `defn' is recognized only with parameters. 816 817 818File: m4.info, Node: Pushdef, Next: Indir, Prev: Defn, Up: Definitions 819 820Temporarily redefining macros 821============================= 822 823 It is possible to redefine a macro temporarily, reverting to the 824previous definition at a later time. This is done with the built-ins 825`pushdef' and `popdef': 826 827 pushdef(NAME [, EXPANSION]) 828 popdef(NAME) 829 830which are quite analogous to `define' and `undefine'. 831 832 These macros work in a stack-like fashion. A macro is temporarily 833redefined with `pushdef', which replaces an existing definition of 834NAME, while saving the previous definition, before the new one is 835installed. If there is no previous definition, `pushdef' behaves 836exactly like `define'. 837 838 If a macro has several definitions (of which only one is accessible), 839the topmost definition can be removed with `popdef'. If there is no 840previous definition, `popdef' behaves like `undefine'. 841 842 define(`foo', `Expansion one.') 843 => 844 foo 845 =>Expansion one. 846 pushdef(`foo', `Expansion two.') 847 => 848 foo 849 =>Expansion two. 850 popdef(`foo') 851 => 852 foo 853 =>Expansion one. 854 popdef(`foo') 855 => 856 foo 857 =>foo 858 859 If a macro with several definitions is redefined with `define', the 860topmost definition is *replaced* with the new definition. If it is 861removed with `undefine', *all* the definitions are removed, and not 862only the topmost one. 863 864 define(`foo', `Expansion one.') 865 => 866 foo 867 =>Expansion one. 868 pushdef(`foo', `Expansion two.') 869 => 870 foo 871 =>Expansion two. 872 define(`foo', `Second expansion two.') 873 => 874 foo 875 =>Second expansion two. 876 undefine(`foo') 877 => 878 foo 879 =>foo 880 881 It is possible to temporarily redefine a built-in with `pushdef' and 882`defn'. 883 884 The macros `pushdef' and `popdef' are recognized only with 885parameters. 886 887 888File: m4.info, Node: Indir, Next: Builtin, Prev: Pushdef, Up: Definitions 889 890Indirect call of macros 891======================= 892 893 Any macro can be called indirectly with `indir': 894 895 indir(NAME, ...) 896 897which results in a call to the macro NAME, which is passed the rest of 898the arguments. This can be used to call macros with "illegal" names 899(`define' allows such names to be defined): 900 901 define(`$$internal$macro', `Internal macro (name `$0')') 902 => 903 $$internal$macro 904 =>$$internal$macro 905 indir(`$$internal$macro') 906 =>Internal macro (name $$internal$macro) 907 908 The point is, here, that larger macro packages can have private 909macros defined, that will not be called by accident. They can *only* be 910called through the built-in `indir'. 911 912 913File: m4.info, Node: Builtin, Prev: Indir, Up: Definitions 914 915Indirect call of built-ins 916========================== 917 918 Built-in macros can be called indirectly with `built-in': 919 920 builtin(NAME, ...) 921 922which results in a call to the built-in NAME, which is passed the rest 923of the arguments. This can be used, if NAME has been given another 924definition that has covered the original. 925 926 The macro `builtin' is recognized only with parameters. 927 928 929File: m4.info, Node: Conditionals, Next: Debugging, Prev: Definitions, Up: Top 930 931Conditionals, loops and recursion 932********************************* 933 934 Macros, expanding to plain text, perhaps with arguments, are not 935quite enough. We would like to have macros expand to different things, 936based on decisions taken at run-time. E.g., we need some kind of 937conditionals. Also, we would like to have some kind of loop construct, 938so we could do something a number of times, or while some condition is 939true. 940 941* Menu: 942 943* Ifdef:: Testing if a macro is defined 944* Ifelse:: If-else construct, or multibranch 945* Loops:: Loops and recursion in m4 946 947 948File: m4.info, Node: Ifdef, Next: Ifelse, Prev: Conditionals, Up: Conditionals 949 950Testing macro definitions 951========================= 952 953 There are two different built-in conditionals in `m4'. The first is 954`ifdef': 955 956 ifdef(NAME, STRING-1, opt STRING-2) 957 958which makes it possible to test whether a macro is defined or not. If 959NAME is defined as a macro, `ifdef' expands to STRING-1, otherwise to 960STRING-2. If STRING-2 is omitted, it is taken to be the empty string 961(according to the normal rules). 962 963 ifdef(`foo', ``foo' is defined', ``foo' is not defined') 964 =>foo is not defined 965 define(`foo', `') 966 => 967 ifdef(`foo', ``foo' is defined', ``foo' is not defined') 968 =>foo is defined 969 970 The macro `ifdef' is recognized only with parameters. 971 972 973File: m4.info, Node: Ifelse, Next: Loops, Prev: Ifdef, Up: Conditionals 974 975Comparing strings 976================= 977 978 The other conditional, `ifelse', is much more powerful. It can be 979used as a way to introduce a long comment, as an if-else construct, or 980as a multibranch, depending on the number of arguments supplied: 981 982 ifelse(COMMENT) 983 ifelse(STRING-1, STRING-2, EQUAL, opt NOT-EQUAL) 984 ifelse(STRING-1, STRING-2, EQUAL, ...) 985 986Used with only one argument, the `ifelse' simply discards it and 987produces no output. This is a common `m4' idiom for introducing a 988block comment, as an alternative to repeatedly using `dnl'. This 989special usage is recognized by GNU `m4', so that in this case, the 990warning about missing arguments is never triggered. 991 992 If called with three or four arguments, `ifelse' expands into EQUAL, 993if STRING-1 and STRING-2 are equal (character for character), otherwise 994it expands to NOT-EQUAL. 995 996 ifelse(foo, bar, `true') 997 => 998 ifelse(foo, foo, `true') 999 =>true 1000 ifelse(foo, bar, `true', `false') 1001 =>false 1002 ifelse(foo, foo, `true', `false') 1003 =>true 1004 1005 However, `ifelse' can take more than four arguments. If given more 1006than four arguments, `ifelse' works like a `case' or `switch' statement 1007in traditional programming languages. If STRING-1 and STRING-2 are 1008equal, `ifelse' expands into EQUAL, otherwise the procedure is repeated 1009with the first three arguments discarded. This calls for an example: 1010 1011 ifelse(foo, bar, `third', gnu, gnats, `sixth', `seventh') 1012 =>seventh 1013 1014 Naturally, the normal case will be slightly more advanced than these 1015examples. A common use of `ifelse' is in macros implementing loops of 1016various kinds. 1017 1018 The macro `ifelse' is recognized only with parameters. 1019 1020 1021File: m4.info, Node: Loops, Prev: Ifelse, Up: Conditionals 1022 1023Loops and recursion 1024=================== 1025 1026 There is no direct support for loops in `m4', but macros can be 1027recursive. There is no limit on the number of recursion levels, other 1028than those enforced by your hardware and operating system. 1029 1030 Loops can be programmed using recursion and the conditionals 1031described previously. 1032 1033 There is a built-in macro, `shift', which can, among other things, 1034be used for iterating through the actual arguments to a macro: 1035 1036 shift(...) 1037 1038It takes any number of arguments, and expands to all but the first 1039argument, separated by commas, with each argument quoted. 1040 1041 shift(bar) 1042 => 1043 shift(foo, bar, baz) 1044 =>bar,baz 1045 1046 An example of the use of `shift' is this macro, which reverses the 1047order of its arguments: 1048 1049 define(`reverse', `ifelse($#, 0, , $#, 1, ``$1'', 1050 `reverse(shift($@)), `$1'')') 1051 => 1052 reverse 1053 => 1054 reverse(foo) 1055 =>foo 1056 reverse(foo, bar, gnats,and gnus) 1057 =>and gnus, gnats, bar, foo 1058 1059 While not a very interesting macro, it does show how simple loops 1060can be made with `shift', `ifelse' and recursion. 1061 1062 Here is an example of a loop macro that implements a simple forloop. 1063 It can, for example, be used for simple counting: 1064 1065 forloop(`i', 1, 8, `i ') 1066 =>1 2 3 4 5 6 7 8 1067 1068 The arguments are a name for the iteration variable, the starting 1069value, the final value, and the text to be expanded for each iteration. 1070 With this macro, the macro `i' is defined only within the loop. After 1071the loop, it retains whatever value it might have had before. 1072 1073 For-loops can be nested, like 1074 1075 forloop(`i', 1, 4, `forloop(`j', 1, 8, `(i, j) ') 1076 ') 1077 =>(1, 1) (1, 2) (1, 3) (1, 4) (1, 5) (1, 6) (1, 7) (1, 8) 1078 =>(2, 1) (2, 2) (2, 3) (2, 4) (2, 5) (2, 6) (2, 7) (2, 8) 1079 =>(3, 1) (3, 2) (3, 3) (3, 4) (3, 5) (3, 6) (3, 7) (3, 8) 1080 =>(4, 1) (4, 2) (4, 3) (4, 4) (4, 5) (4, 6) (4, 7) (4, 8) 1081 => 1082 1083 The implementation of the `forloop' macro is fairly straightforward. 1084 The `forloop' macro itself is simply a wrapper, which saves the 1085previous definition of the first argument, calls the internal macro 1086`_forloop', and re-establishes the saved definition of the first 1087argument. 1088 1089 The macro `_forloop' expands the fourth argument once, and tests to 1090see if it is finished. If it has not finished, it increments the 1091iteration variable (using the predefined macro `incr' (*note Incr::. 1092for details)), and recurses. 1093 1094 Here is the actual implementation of `forloop': 1095 1096 define(`forloop', 1097 `pushdef(`$1', `$2')_forloop(`$1', `$2', `$3', `$4')popdef(`$1')') 1098 define(`_forloop', 1099 `$4`'ifelse($1, `$3', , 1100 `define(`$1', incr($1))_forloop(`$1', `$2', `$3', `$4')')') 1101 1102 Notice the careful use of quotes. Only three macro arguments are 1103unquoted, each for its own reason. Try to find out *why* these three 1104arguments are left unquoted, and see what happens if they are quoted. 1105 1106 Now, even though these two macros are useful, they are still not 1107robust enough for general use. They lack even basic error handling of 1108cases like start value less than final value, and the first argument 1109not being a name. Correcting these errors are left as an exercise to 1110the reader. 1111 1112 1113File: m4.info, Node: Debugging, Next: Input Control, Prev: Conditionals, Up: Top 1114 1115How to debug macros and input 1116***************************** 1117 1118 When writing macros for `m4', most of the time they won't work as 1119intended (as is the case with most programming languages). There is a 1120little support for macro debugging in `m4'. 1121 1122* Menu: 1123 1124* Dumpdef:: Displaying macro definitions 1125* Trace:: Tracing macro calls 1126* Debug Levels:: Controlling debugging output 1127* Debug Output:: Saving debugging output 1128 1129 1130File: m4.info, Node: Dumpdef, Next: Trace, Prev: Debugging, Up: Debugging 1131 1132Displaying macro definitions 1133============================ 1134 1135 If you want to see what a name expands into, you can use the built-in 1136`dumpdef': 1137 1138 dumpdef(...) 1139 1140which accepts any number of arguments. If called without any arguments, 1141it displays the definitions of all known names, otherwise it displays 1142the definitions of the names given. The output is printed directly on 1143the standard error output. 1144 1145 The expansion of `dumpdef' is void. 1146 1147 define(`foo', `Hello world.') 1148 => 1149 dumpdef(`foo') 1150 error-->foo: `Hello world.' 1151 => 1152 dumpdef(`define') 1153 error-->define: <define> 1154 => 1155 1156 The last example shows how built-in macros definitions are displayed. 1157 1158 *Note Debug Levels:: for information on controlling the details of 1159the display. 1160 1161 1162File: m4.info, Node: Trace, Next: Debug Levels, Prev: Dumpdef, Up: Debugging 1163 1164Tracing macro calls 1165=================== 1166 1167 It is possible to trace macro calls and expansions through the 1168built-ins `traceon' and `traceoff': 1169 1170 traceon(...) 1171 traceoff(...) 1172 1173When called without any arguments, `traceon' and `traceoff' will turn 1174tracing on and off, respectively, for all defined macros. When called 1175with arguments, only the named macros are affected. 1176 1177 The expansion of `traceon' and `traceoff' is void. 1178 1179 Whenever a traced macro is called and the arguments have been 1180collected, the call is displayed. If the expansion of the macro call 1181is not void, the expansion can be displayed after the call. The output 1182is printed directly on the standard error output. 1183 1184 define(`foo', `Hello World.') 1185 => 1186 define(`echo', `$@') 1187 => 1188 traceon(`foo', `echo') 1189 => 1190 foo 1191 error-->m4trace: -1- foo -> `Hello World.' 1192 =>Hello World. 1193 echo(gnus, and gnats) 1194 error-->m4trace: -1- echo(`gnus', `and gnats') -> ``gnus',`and gnats'' 1195 =>gnus,and gnats 1196 1197 The number between dashes is the depth of the expansion. It is one 1198most of the time, signifying an expansion at the outermost level, but it 1199increases when macro arguments contain unquoted macro calls. 1200 1201 *Note Debug Levels:: for information on controlling the details of 1202the display. 1203 1204 1205File: m4.info, Node: Debug Levels, Next: Debug Output, Prev: Trace, Up: Debugging 1206 1207Controlling debugging output 1208============================ 1209 1210 The `-d' option to `m4' controls the amount of details presented, 1211when using the macros described in the preceding sections. 1212 1213 The FLAGS following the option can be one or more of the following: 1214 1215`t' 1216 Trace all macro calls made in this invocation of `m4'. 1217 1218`a' 1219 Show the actual arguments in each macro call. This applies to all 1220 macro calls if the `t' flag is used, otherwise only the macros 1221 covered by calls of `traceon'. 1222 1223`e' 1224 Show the expansion of each macro call, if it is not void. This 1225 applies to all macro calls if the `t' flag is used, otherwise only 1226 the macros covered by calls of `traceon'. 1227 1228`q' 1229 Quote actual arguments and macro expansions in the display with the 1230 current quotes. 1231 1232`c' 1233 Show several trace lines for each macro call. A line is shown 1234 when the macro is seen, but before the arguments are collected; a 1235 second line when the arguments have been collected and a third 1236 line after the call has completed. 1237 1238`x' 1239 Add a unique `macro call id' to each line of the trace output. 1240 This is useful in connection with the `c' flag above. 1241 1242`f' 1243 Show the name of the current input file in each trace output line. 1244 1245`l' 1246 Show the the current input line number in each trace output line. 1247 1248`p' 1249 Print a message when a named file is found through the path search 1250 mecanism (*note Search Path::.), giving the actual filename used. 1251 1252`i' 1253 Print a message each time the current input file is changed, 1254 giving file name and input line number. 1255 1256`V' 1257 A shorthand for all of the above flags. 1258 1259 If no flags are specified with the `-d' option, the default is 1260`aeq'. The examples in the previous two sections assumed the default 1261flags. 1262 1263 There is a built-in macro `debugmode', which allows on-the-fly 1264control of the debugging output format: 1265 1266 debugmode(opt FLAGS) 1267 1268The argument FLAGS should be a subset of the letters listed above. As 1269special cases, if the argument starts with a `+', the flags are added 1270to the current debug flags, and if it starts with a `-', they are 1271removed. If no argument is present, the debugging flags are set to 1272zero (as if no `-d' was given), and with an empty argument the flags 1273are reset to the default. 1274 1275 1276File: m4.info, Node: Debug Output, Prev: Debug Levels, Up: Debugging 1277 1278Saving debugging output 1279======================= 1280 1281 Debug and tracing output can be redirected to files using either the 1282`-o' option to `m4', or with the built-in macro `debugfile': 1283 1284 debugfile(opt FILENAME) 1285 1286will send all further debug and trace output to FILENAME. If FILENAME 1287is empty, debug and trace output are discarded and if `debugfile' is 1288called without any arguments, debug and trace output are sent to the 1289standard error output. 1290 1291 1292File: m4.info, Node: Input Control, Next: File Inclusion, Prev: Debugging, Up: Top 1293 1294Input control 1295************* 1296 1297 This chapter describes various built-in macros for controlling the 1298input to `m4'. 1299 1300* Menu: 1301 1302* Dnl:: Deleting whitespace in input 1303* Changequote:: Changing the quote characters 1304* Changecom:: Changing the comment delimiters 1305* M4wrap:: Saving input until end of input 1306 1307 1308File: m4.info, Node: Dnl, Next: Changequote, Prev: Input Control, Up: Input Control 1309 1310Deleting whitespace in input 1311============================ 1312 1313 The built-in `dnl' reads and discards all characters, up to and 1314including the first newline: 1315 1316 dnl 1317 1318and it is often used in connection with `define', to remove the newline 1319that follow the call to `define'. Thus 1320 1321 define(`foo', `Macro `foo'.')dnl A very simple macro, indeed. 1322 foo 1323 =>Macro foo. 1324 1325 The input up to and including the next newline is discarded, as 1326opposed to the way comments are treated (*note Comments::.). 1327 1328 Usually, `dnl' is immediately followed by an end of line or some 1329other whitespace. GNU `m4' will produce a warning diagnostic if `dnl' 1330is followed by an open parenthesis. In this case, `dnl' will collect 1331and process all arguments, looking for a matching close parenthesis. 1332All predictable side effects resulting from this collection will take 1333place. `dnl' will return no output. The input following the matching 1334close parenthesis up to and including the next newline, on whatever 1335line containing it, will still be discarded. 1336 1337 1338File: m4.info, Node: Changequote, Next: Changecom, Prev: Dnl, Up: Input Control 1339 1340Changing the quote characters 1341============================= 1342 1343 The default quote delimiters can be changed with the built-in 1344`changequote': 1345 1346 changequote(opt START, opt END) 1347 1348where START is the new start-quote delimiter and END is the new 1349end-quote delimiter. If any of the arguments are missing, the default 1350quotes (``' and `'') are used instead of the void arguments. 1351 1352 The expansion of `changequote' is void. 1353 1354 changequote([,]) 1355 => 1356 define([foo], [Macro [foo].]) 1357 => 1358 foo 1359 =>Macro foo. 1360 1361 If no single character is appropriate, START and END can be of any 1362length. 1363 1364 changequote([[,]]) 1365 => 1366 define([[foo]], [[Macro [[[foo]]].]]) 1367 => 1368 foo 1369 =>Macro [foo]. 1370 1371 Changing the quotes to the empty strings will effectively disable the 1372quoting mechanism, leaving no way to quote text. 1373 1374 define(`foo', `Macro `FOO'.') 1375 => 1376 changequote(,) 1377 => 1378 foo 1379 =>Macro `FOO'. 1380 `foo' 1381 =>`Macro `FOO'.' 1382 1383 There is no way in `m4' to quote a string containing an unmatched 1384left quote, except using `changequote' to change the current quotes. 1385 1386 Neither quote string should start with a letter or `_' (underscore), 1387as they will be confused with names in the input. Doing so disables 1388the quoting mechanism. 1389 1390 1391File: m4.info, Node: Changecom, Next: M4wrap, Prev: Changequote, Up: Input Control 1392 1393Changing comment delimiters 1394=========================== 1395 1396 The default comment delimiters can be changed with the built-in 1397macro `changecom': 1398 1399 changecom(opt START, opt END) 1400 1401where START is the new start-comment delimiter and END is the new 1402end-comment delimiter. If any of the arguments are void, the default 1403comment delimiters (`#' and newline) are used instead of the void 1404arguments. The comment delimiters can be of any length. 1405 1406 The expansion of `changecom' is void. 1407 1408 define(`comment', `COMMENT') 1409 => 1410 # A normal comment 1411 =># A normal comment 1412 changecom(`/*', `*/') 1413 => 1414 # Not a comment anymore 1415 =># Not a COMMENT anymore 1416 But: /* this is a comment now */ while this is not a comment 1417 =>But: /* this is a comment now */ while this is not a COMMENT 1418 1419 Note how comments are copied to the output, much as if they were 1420quoted strings. If you want the text inside a comment expanded, quote 1421the start comment delimiter. 1422 1423 Calling `changecom' without any arguments disables the commenting 1424mechanism completely. 1425 1426 define(`comment', `COMMENT') 1427 => 1428 changecom 1429 => 1430 # Not a comment anymore 1431 =># Not a COMMENT anymore 1432 1433 1434File: m4.info, Node: M4wrap, Prev: Changecom, Up: Input Control 1435 1436Saving input 1437============ 1438 1439 It is possible to `save' some text until the end of the normal input 1440has been seen. Text can be saved, to be read again by `m4' when the 1441normal input has been exhausted. This feature is normally used to 1442initiate cleanup actions before normal exit, e.g., deleting temporary 1443files. 1444 1445 To save input text, use the built-in `m4wrap': 1446 1447 m4wrap(STRING, ...) 1448 1449which stores STRING and the rest of the arguments in a safe place, to 1450be reread when end of input is reached. 1451 1452 define(`cleanup', `This is the `cleanup' actions. 1453 ') 1454 => 1455 m4wrap(`cleanup') 1456 => 1457 This is the first and last normal input line. 1458 =>This is the first and last normal input line. 1459 ^D 1460 =>This is the cleanup actions. 1461 1462 The saved input is only reread when the end of normal input is seen, 1463and not if `m4exit' is used to exit `m4'. 1464 1465 It is safe to call `m4wrap' from saved text, but then the order in 1466which the saved text is reread is undefined. If `m4wrap' is not used 1467recursively, the saved pieces of text are reread in the opposite order 1468in which they were saved (LIFO--last in, first out). 1469 1470 1471File: m4.info, Node: File Inclusion, Next: Diversions, Prev: Input Control, Up: Top 1472 1473File inclusion 1474************** 1475 1476 `m4' allows you to include named files at any point in the input. 1477 1478* Menu: 1479 1480* Include:: Including named files 1481* Search Path:: Searching for include files 1482 1483 1484File: m4.info, Node: Include, Next: Search Path, Prev: File Inclusion, Up: File Inclusion 1485 1486Including named files 1487===================== 1488 1489 There are two built-in macros in `m4' for including files: 1490 1491 include(FILENAME) 1492 sinclude(FILENAME) 1493 1494both of which cause the file named FILENAME to be read by `m4'. When 1495the end of the file is reached, input is resumed from the previous 1496input file. 1497 1498 The expansion of `include' and `sinclude' is therefore the contents 1499of FILENAME. 1500 1501 It is an error for an `include'd file not to exist. If you don't 1502want error messages about non-existent files, `sinclude' can be used to 1503include a file, if it exists, expanding to nothing if it does not. 1504 1505 include(`no-such-file') 1506 => 1507 error-->m4:30.include:2: can't open no-such-file: No such file or directory 1508 sinclude(`no-such-file') 1509 => 1510 1511 Assume in the following that the file `incl.m4' contains the lines: 1512 Include file start 1513 foo 1514 Include file end 1515 1516Normally file inclusion is used to insert the contents of a file into 1517the input stream. The contents of the file will be read by `m4' and 1518macro calls in the file will be expanded: 1519 1520 define(`foo', `FOO') 1521 => 1522 include(`incl.m4') 1523 =>Include file start 1524 =>FOO 1525 =>Include file end 1526 => 1527 1528 The fact that `include' and `sinclude' expand to the contents of the 1529file can be used to define macros that operate on entire files. Here is 1530an example, which defines `bar' to expand to the contents of `incl.m4': 1531 1532 define(`bar', include(`incl.m4')) 1533 => 1534 This is `bar': >>>bar<<< 1535 =>This is bar: >>>Include file start 1536 =>foo 1537 =>Include file end 1538 =><<< 1539 1540 This use of `include' is not trivial, though, as files can contain 1541quotes, commas and parentheses, which can interfere with the way the 1542`m4' parser works. 1543 1544 The builtin macros `include' and `sinclude' are recognized only when 1545given arguments. 1546 1547 1548File: m4.info, Node: Search Path, Prev: Include, Up: File Inclusion 1549 1550Searching for include files 1551=========================== 1552 1553 GNU `m4' allows included files to be found in other directories than 1554the current working directory. 1555 1556 If a file is not found in the current working directory, and the file 1557name is not absolute, the file will be looked for in a specified search 1558path. First, the directories specified with the `-I' option will be 1559searched, in the order found on the command line. Second, if the 1560`M4PATH' environment variable is set, it is expected to contain a 1561colon-separated list of directories, which will be searched in order. 1562 1563 If the automatic search for include-files causes trouble, the `p' 1564debug flag (*note Debug Levels::.) can help isolate the problem. 1565 1566