Next: , Up: Diversions


10.1 Diverting output

Output is diverted using divert:

— Builtin: divert ([number = ‘0])

The current diversion is changed to number. If number is left out or empty, it is assumed to be zero. If number cannot be parsed, the diversion is unchanged.

The expansion of divert is void.

When all the m4 input will have been processed, all existing diversions are automatically undiverted, in numerical order.

     divert(`1')
     This text is diverted.
     divert
     ⇒
     This text is not diverted.
     ⇒This text is not diverted.
     ^D
     ⇒
     ⇒This text is diverted.

Several calls of divert with the same argument do not overwrite the previous diverted text, but append to it. Diversions are printed after any wrapped text is expanded.

     define(`text', `TEXT')
     ⇒
     divert(`1')`diverted text.'
     divert
     ⇒
     m4wrap(`Wrapped text precedes ')
     ⇒
     ^D
     ⇒Wrapped TEXT precedes diverted text.

If output is diverted to a negative diversion, it is simply discarded. This can be used to suppress unwanted output. A common example of unwanted output is the trailing newlines after macro definitions. Here is a common programming idiom in m4 for avoiding them.

     divert(`-1')
     define(`foo', `Macro `foo'.')
     define(`bar', `Macro `bar'.')
     divert
     ⇒

Traditional implementations only supported ten diversions. But as a GNU extension, diversion numbers can be as large as positive integers will allow, rather than treating a multi-digit diversion number as a request to discard text.

     divert(eval(`1<<28'))world
     divert(`2')hello
     ^D
     ⇒hello
     ⇒world

Note that divert is an English word, but also an active macro without arguments. When processing plain text, the word might appear in normal text and be unintentionally swallowed as a macro invocation. One way to avoid this is to use the -P option to rename all builtins (see Invoking m4). Another is to write a wrapper that requires a parameter to be recognized.

     We decided to divert the stream for irrigation.
     ⇒We decided to  the stream for irrigation.
     define(`divert', `ifelse(`$#', `0', ``$0'', `builtin(`$0', $@)')')
     ⇒
     divert(`-1')
     Ignored text.
     divert(`0')
     ⇒
     We decided to divert the stream for irrigation.
     ⇒We decided to divert the stream for irrigation.