Next: , Previous: Compatibility, Up: Top


16 Correct version of some examples

Some of the examples in this manuals are buggy, for demonstration purposes. Correctly working macros are presented here.

The exch macro (see Arguments) as presented requires clients to double quote their arguments. A nicer definition, which lets clients follow the rule of thumb of one level of quoting per level of parentheses, involves adding quotes in the definition of exch, as follows:

     define(`exch', ``$2', `$1'')
     =>
     define(exch(`expansion text', `macro'))
     =>
     macro
     =>expansion text

The cleardivert macro (see Cleardiv) cannot, as it stands, be called without arguments to clear all pending diversions. That is because using undivert with an empty string for an argument is different than using it with no arguments at all. Compare the earlier definition with one that takes the number of arguments into account:

     define(`cleardivert',
       `pushdef(`_n', divnum)divert(`-1')undivert($@)divert(_n)popdef(`_n')')
     =>
     divert(`1')one
     divert
     =>
     cleardivert
     =>
     undivert
     =>one
     =>
     define(`cleardivert',
       `pushdef(`_num', divnum)divert(`-1')ifelse(`$#', `0',
         `undivert`'', `undivert($@)')divert(_num)popdef(`_num')')
     =>
     divert(`2')two
     divert
     =>
     cleardivert
     =>
     undivert
     =>

The fatal_error macro (see M4exit) does not quite match the format of internal error messages when invoked inside wrapped text, due to the current limitations of __file__ (see Location) when invoked inside m4wrap. Since m4 omits the file and line number from its warning messages when there is no current file (or equivalently, when the current line is 0, since all files start at line 1), a better implementation would be:

     define(`fatal_error',
       `errprint(__program__:ifelse(__line__, `0', `',
         `__file__:__line__:')` fatal error: $*
     ')m4exit(`1')')
     =>
     m4wrap(`divnum(`demo of internal message')
     fatal_error(`inside wrapped text')')
     =>
     ^D
     error-->m4: Warning: excess arguments to builtin `divnum' ignored
     =>0
     error-->m4: fatal error: inside wrapped text