m4: Divert

1 
1 10.1 Diverting output
1 =====================
1 
1 Output is diverted using 'divert':
1 
1  -- Builtin: divert ([NUMBER = '0'])
1      The current diversion is changed to NUMBER.  If NUMBER is left out
1      or empty, it is assumed to be zero.  If NUMBER cannot be parsed,
1      the diversion is unchanged.
1 
1      The expansion of 'divert' is void.
1 
1    When all the 'm4' input will have been processed, all existing
1 diversions are automatically undiverted, in numerical order.
1 
1      divert(`1')
1      This text is diverted.
1      divert
1      =>
1      This text is not diverted.
1      =>This text is not diverted.
1      ^D
1      =>
1      =>This text is diverted.
1 
1    Several calls of 'divert' with the same argument do not overwrite the
1 previous diverted text, but append to it.  Diversions are printed after
1 any wrapped text is expanded.
1 
1      define(`text', `TEXT')
1      =>
1      divert(`1')`diverted text.'
1      divert
1      =>
1      m4wrap(`Wrapped text precedes ')
1      =>
1      ^D
1      =>Wrapped TEXT precedes diverted text.
1 
1    If output is diverted to a negative diversion, it is simply
1 discarded.  This can be used to suppress unwanted output.  A common
1 example of unwanted output is the trailing newlines after macro
1 definitions.  Here is a common programming idiom in 'm4' for avoiding
1 them.
1 
1      divert(`-1')
1      define(`foo', `Macro `foo'.')
1      define(`bar', `Macro `bar'.')
1      divert
1      =>
1 
1    Traditional implementations only supported ten diversions.  But as a
1 GNU extension, diversion numbers can be as large as positive integers
1 will allow, rather than treating a multi-digit diversion number as a
1 request to discard text.
1 
1      divert(eval(`1<<28'))world
1      divert(`2')hello
1      ^D
1      =>hello
1      =>world
1 
1    Note that 'divert' is an English word, but also an active macro
1 without arguments.  When processing plain text, the word might appear in
1 normal text and be unintentionally swallowed as a macro invocation.  One
1 way to avoid this is to use the '-P' option to rename all builtins
1 (⇒Invoking m4 Operation modes.).  Another is to write a wrapper
1 that requires a parameter to be recognized.
1 
1      We decided to divert the stream for irrigation.
1      =>We decided to  the stream for irrigation.
1      define(`divert', `ifelse(`$#', `0', ``$0'', `builtin(`$0', $@)')')
1      =>
1      divert(`-1')
1      Ignored text.
1      divert(`0')
1      =>
1      We decided to divert the stream for irrigation.
1      =>We decided to divert the stream for irrigation.
1