Next: Undivert, Up: Diversions
Output is diverted using divert
:
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 preceeds ') => ^D =>Wrapped TEXT preceeds diverted text.
If output is diverted to a non-existent 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 how to avoid them.
divert(`-1') define(`foo', `Macro `foo'.') define(`bar', `Macro `bar'.') divert =>
This is a common programming idiom in m4
.
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.