May the source be with you, but remember the KISS principle ;-)

Contents Bulletin Scripting in shell and Perl Network troubleshooting History Humor

m4 Macroprocessor

News Recommended Links Recommended Articles An Introduction to m4 Sun documentation
 Building text files with m4 macros Using m4 to write HTML Tips Humor Etc

M4 is a very old text file macro processor, almost as old as C-Preprocessor (which was in turn modeled after PL/1 preprocessor).

It was was developed in 1977, based on ideas of Christopher Strachey. The distinguishing features of this style of macro preprocessing include the fact that it is free form, not line based (as typical for macro preprocessors designed for assembly language processing) and the high degree of re-expansion (e.g., a macro's arguments are expanded twice, once during scanning and once when they are interpolated). It was the original macro engine used to implement Ratfor (Rational Fortran), and is shipped with most Unix variants. One of the most widespread uses is in GNU autoconf. It is also used in the configuration process of the widespread MTA sendmail. In general, it can be useful for code generation purposes. Like in any macroprocessor complex macros are hard to debug.

Gnu m4 has no man page and Solaris man page refers to a different slightly incompatible implementation.  The best manual for GNU M4 I have seen is  GNU macro processor  by Ren'e Seindal

Many operation that are in the past performed by M4 can be done using Perl, PHP or other scripting language.

Top updates

Softpanorama Switchboard
Softpanorama Search


Old News ;-)

M4 + RATFOR Influences

M4 is a macro processor designed by D.M.Ritchie as a front end for RATFOR and C. As a macro processor M4 assisted in expansion of macros for code translation. This helped to enhance program languages making them easier to read and help tailor them to an application.

M4 has roots in GPM (General Purpose Macro-generator). GPM was developed in the 1960Хs and provided important string handling facilities. GPM's most important role was in developing the more powerful M4.

... ... ...

What influenced RATFOR?

RATional FORTRAN (RATFOR) was developed by B. W. Kerninghan in 1975. It was implemented as a pre-processor for FORTRAN and was designed to improve upon FORTRAN by adding C control structures and definition which could be understood by the C pre-processor. This was due to the popularity of C as a general programming language and so RATFORs syntax was heavily influenced by C's.

What did RATFOR influence?

RATFIV is an extension of RATOR, designed by Bill Wood at the Institute of Cancer Research in Philidelphia. The name RATFIV is a pun based on RATFOR (RATFOR => "RAT FOUR" => "RAT FIVE"). As RATFIV is a structured FORTRAN preprocessor it provides such flow control as statements as: IF statements, FOR, WHILE and DO loops. Some of the extensions that RATFIV provides are:

RATFIV has had some rewrite by David Hanson at the University of Arizona and Joe Sventek and Debbie Scherrer at the Lawrence Berkely Laboratory.

The language elf was developed as an extension of FORTRAN and its control structure were based on RATFORs.

Both RATFOR and M4 were used to give an implementation language for the development of the statistical programming language S to allow the developer to keep modern control structures and data types.

Comp.compilers Re C preprocessor vs Macro processor

From: (Richard A. O'Keefe)
Newsgroups: comp.compilers
Date: 13 Nov 1997 23:45:18 -0500
Organization: Comp Sci, RMIT University, Melbourne, Australia.
References: 97-11-021 97-11-033
Keywords: macros

I'm going to release a new version of pdm4 next week, so I thought I'd

Greg Badros <> writes:

>Also, M4 has many many more builtin functions (including regular
>expression matching, and much more) and permits recursive macros; Ansi
>C's cpp disallows recursion in macros.

*GNU* M4 has regular expression stuff, but V7 M4, BSD M4, System V M4,
and PD M4 do *not*. It's worth noting that according to Sun's 'Shade'
toolkit, GNU m4 executes more than 3 times as many instructions as pd

The main thing about m4 is that it is a complete programming language,
while cpp isn't, and that cpp is very closely tied to C lexical
structure, while m4 isn't.

Next weeks' pdm4 release will include case-insensitive macro names as
a run-time option, making it even more useful with Fortran, Pascal,
and Ada than it already is.

>> Does the C preprocessor hold any advantage over M4 ?

>It's easier to learn, is not stuck with complicated quoting rules, and
>more constrained in its capabilities; reasoning about source code
>preprocessed by cpp is hard enough -- reasoning about source code
>processed by m4 would be nearly impossible.

On the other hand, it must be said that cpp has some weirdness (like
pp-numbers) that m4 is free of. m4 has very simple rules that allow
very complex programs, cpp has very complex rules that allow only very
simple "programs". For what it's worth, pdm4 and SVr4 m4 are about
the same size as the cpp distributed with lcc, which is the smallest
cpp I've ssen.

Here's an example of using m4 with C.
Suppose we want to have a two-dimensional array where the
[i][j] element is "fred(i,j)".

define(NROWS, 4)
define(NCOLS, 5)
include(forloop.m4) dnl comes with GNU M4 and pdm4.
char *demo[NROWS][NCOLS] = {
forloop(i, 0, NROWS-1,
`{forloop(j, 0, NCOLS-1,

John Æneas Byron O'Keefe; 1921/02/04-1997/09/27; TLG,TLTA,BBTNOTL.
Richard A. O'Keefe; RMIT Comp.Sci;

Chapter 15. m4 Macro Processor Overview from AIX Version 4.3 General Programming Concepts: Writing and Debugging Programs applies

m4 The m4 Macro Package by D. Robert Adams

Recommended Articles

[20th July 2005] An Introduction to m4


m4 is one of the unsung heroes of Linux and Unix. For instance, in that great book Unix Power Tools, not a single mention is made of it, though m4 has been a standard part of Unix since V7. So, what is it about m4 that makes it so useful, and yet so over-looked?

m4 is a "macro processor": a dry name that disguises a great facility. A macro-processor is basically a program that scans text looking for defined symbols, which it replaces by other text — or other symbols. Thus, it is a powerful general-purpose utility that can be used to automate many tasks people often end up doing in sed, awk, perl, or even their favourite text editor. However, this power and its general-purpose nature is not at all obvious in the bare name, "macro processor". Also, Unix developers already have a built-in macro processor, in the form of the C pre-processor, built into their compiler. Perhaps it is this that accounts for m4's relative neglect. Whatever, this article hopes to show all Unix users the power and usefulness of this software tool.

What Is m4?

So, what is macro processing, and what it is good for? Kernighan and Plauger, in their seminal work Software Tools have a succinct definition:

"Macros are used to extend some underlying language — to perform a translation from one language to another."

Thus, symbolic constants may be defined so that subsequent occurrences of the name are replaced by the defining string of characters, regardless of the contents of the definition or its context. such a definition is called a macro, the replacement process is called macro expansion, and the the program for doing it is called a macro processor. So, the basic facility provided by any macro processor is the replacement of text by other text. A macro is either defined by the m4 program (a "built-in") or by the user. As well as doing macro expansion, m4 has functions that include other files, do integer arithmetic, manipulate text, and so forth. It is, that is to say, a perfect example of the power of the Unix filter concept.

The contemporary implementation of m4 on a Linux system is GNU m4, which follows System V Release 3 m4, with extensions. I am aware of no other version of m4 that has been ported to Linux. m4 implementations on BSD may differ slightly; but by and large, m4 is m4, and this article should be useful for other Unix users too. The latest version is 1.4, which was released in October 1994.

Overview The Scanning Process

As m4 reads its input, it separates it into "tokens". A token is either a previously-defined name, a string, or any single character that is not a part of either a name or a string. The input is then scanned for recognised macros. This scanning process is recursive: scanning continues until no more macros are recognised. The input thus transformed is written to the output. Macros can be built-in, or user-defined. A list of built-in macro follows later.

Defining Macros

The most important of the built-in macros is define , which allows the user to define his own macros. For example, define(author, Paul Dunne) defines a macro "author", any occurrence of which will be expanded to the string "Paul Dunne". m4 expands macro names into their defining text as soon as it possibly can. define is matched by undefine, which removes a macro definition.


The m4 quote characters are ` and '. For example, `this is quoted'. It is often best to quote both macro name and substitution text in a definition. This avoids any unwanted side-effects, such as too early expansion of another macro name. Also, since m4 uses commas as argument separators, any definition with commas in must be quoted.


As we have said, arguments to macros are delimited by commas. They are also, as we've seen, enclosed in parentheses. A macro may also be called with no arguments. This is common where we simply wish to replace one string with another, as in the "author" example above.

Built-in Functions

m4 provides a small set of useful built-in functions. We may group them under the following headings:

Flow Control Functions

m4 provides the classic "if-then" programming construct, in two related forms. ifdef(a,b) defines b if a is defined, and ifelse(a,b,c,d) compares the strings a and b. If they match, string c is returned as the function value; if not, string d. Actually, ifelse is not limited to four arguments; it can take any greater number, and thus provides a limited multi-way decision capability. For example, ifelse(a,b,c,d,e,f,g) means that if a matches b, then return c; else if d matches e, then return f; else return g.

Arithmetic Functions

There are three arithmetic built-ins: incr , which increments its numeric argument by one. decr , which decrements its numeric argument by one. eval , which performs arbitrary integer arithmetic. Its operators are:

unary + and -
** or ^			exponentiation
+ -
== != < <= > >=		equal, not equal, less than, less than or equal to,
			greater than, greater than or equal to
!			not
& or &&			logical and
| or ||			logical or


String Functions

len(a) Returns the length of the string "a".

substr(s, m, n) Returns a substring from the string "s", starting at position m, and continuing for n characters.

As a more complicated example than those we've had so far, consider this combination of ifelse, expr and substr.


Well now, what does that do? It is an implementation of the m4 built-in len in terms of other m4 built-ins! Note the two layers of quotes. The outer layer prevents all initial evaluation. We want "len" defined as exactly what's in the second argument. The inner layer protects the eval built-in from being evaluated while the arguments for the ifelse are collected.

translit(s, f, t) Returns the string "s" with all occurrences of the character(s) listed in "f" replaced by those listed in "t". It functions as a simpler version of the Linux command tr. For example, translit(s,abcdefghijklmnopqrstuvwxyz, nopqrstuvwxyzabcdefghijklm) is the well-known rot13 or Caeser cipher.

File Functions

include(filename) includes the contents of "filename" at the point in the input stream at which it occurs. Useful if we have a central collection of standard m4 macros, which we can then use in another file simply with an appropriate include macro.

divert(n) This is used to divert text from the input stream to an internal file number. File number -1 is equivalent to discarding the text, file number 0 is the normal output stream, and fields number 2 to 9 are usually used for temporary storage. divert(-1) is most commonly used to get rid of the extraneous white space that is often generated by m4. For example,


ensures that no output is performed while the various definitions between the ellipses are performed (the ellipses are not part of m4 syntax!). Otherwise, we would end up with a pack of newlines in our output.

There is a matching function, undivert , which "brings back" all diversions in numeric order.

divnum returns the number of the currently active diversion.

dnl Hard to categorise this one, so I've put it here. dnl is "delete to newline". Used as a comment character in the original m4: as the name suggests, all characters up to the next newline are deleted from the output stream. GNU m4 also allows use of # as a comment character, with the different that such comments *are* passed to the output stream. Any macro calls or definitions after the # are however ignored — the input is passed to the output exactly as is.

System Functions

esyscmd Passes a command to the system interpreter (usually the unix shell) for execution. For example, esyscmd(date) returns today's date.


A full summary of m4 usage is available through typing m4 —help. This gives:

Usage: m4 [OPTION]... [FILE]...
Mandatory or optional arguments to long options are mandatory or optional
for short options too.

Operation modes:
      —help                   display this help and exit
      —version                output version information and exit
  -e, —interactive            unbuffer output, ignore interrupts
  -E, —fatal-warnings         stop execution after first warning
  -Q, —quiet, --silent        suppress some warnings for builtins
  -P, —prefix-builtins        force a `m4_' prefix to all builtins

Preprocessor features:
  -I, —include=DIRECTORY      search this directory second for includes
  -D, —define=NAME[=VALUE]    enter NAME has having VALUE, or empty
  -U, —undefine=NAME          delete builtin NAME
  -s, —synclines              generate `#line NO "FILE"' lines

Limits control:
  -G, —traditional            suppress all GNU extensions
  -H, —hashsize=PRIME         set symbol lookup hash table size
  -L, —nesting-limit=NUMBER   change artificial nesting limit

Frozen state files:
  -F, —freeze-state=FILE      produce a frozen state on FILE at end
  -R, —reload-state=FILE      reload a frozen state from FILE at start

  -d, —debug=[FLAGS]          set debug level (no FLAGS implies `aeq')
  -t, —trace=NAME             trace NAME when it will be defined
  -l, —arglength=NUM          restrict macro tracing size
  -o, —error-output=FILE      redirect debug and trace output

FLAGS is any of:
  t   trace for all macro calls, not only traceon'ed
  a   show actual arguments
  e   show expansion
  q   quote values as necessary, with a or e flag
  c   show before collect, after collect and after call
  x   add a unique macro call id, useful with c flag
  f   say current input file name
  l   say current input line number
  p   show results of path searches
  i   show changes in input files
  V   shorthand for all of the above flags

If no FILE or if FILE is `-', standard input is read.

Well, that's a formidable list of options. But we need only use a few. In fact, most often m4 is run as just 'm4', with perhaps the -P flag to specify that built-ins are preceded by 'm4_', e.g. m4_include rather than include. For example, here's a line I use in a makefile to generate my HTML pages:

htmlize < $*.m4 | m4 -P -D _local luehtml.m4 - | fixhtml > $*.html
In Use Example: a Linux key-map

An interesting use of m4 is for the maintenance of Linux keymap files. I don't do this myself, since hacking an existing file was simplest for me, but it is a good example of the imaginative uses that m4 can be put to. We don't have the space to examine the file in any depth here; take a look at /usr/lib/kbd/keymaps/i386/qwerty/hypermap.m4 on your Linux system.

Example: sendmail config

Perhaps the most well-known of m4 applications is its use to tame the fearsome complexity of sendmail configuration files. The sendmail source distribution comes with a set of m4 macro definition files which are sufficient to generate a for practically any site; at most, a little tweaking of the resulting file (whose syntax has been memorably and justly compared to line noise) may be required. For anyone who has tried to write a sendmail config file from scratch, in the days before the m4 macros, this is a God-send.

Example: generating HTML

I use m4, among other Linux software tools, to maintain my web pages. Rather than mark each page up in HTML, a tiresome chore, I have written a set of definitions that translates m4 macros into HTML. As well as being easier on the eye and easier to write than HTML, this has other advantages. For example, we can define our email address in the master file. Then, if that changes, there is no need to do a global search-and-replace through all the files that constitute the site: a simple "make" updates everything.

But this is the subject of another article. Two, in fact: think of this article as the first of three, with two more coming that will examine first the generation of HTML using m4 macros, and then how I generate this particular website with m4, sed, /bin/sh, and various other standard Unix tools.

Using in the Shell

Piping through m4 provides any shell script with use of all the m4 functions e.g.

# Strings
echo "len($string)" | m4                       # 7
echo "substr($string,4)" | m4                  # A01
echo "regexp($string,0-10-1,&Z)" | m4     # 01Z

# Arithmetic
echo "incr(22)" | m4                           # 23
echo "eval(99 / 3)" | m4                       # 33

Differences Between m4 Versions

Inevitably, there are different versions of m4. This is not an issue for the Linux user, as they will invariably be using GNU m4.

The main difference is that SysV m4 supports multiple arguments to defn. Since the usefulness of this is unclear to GNU m4's maintainer (and indeed to me), this feature is not in GNU m4.

There are several other incompatibilities (which shouldn't surprise anyone who's tried to use GNU make and then BSD's pmake, or vice versa). None are important, so those interested can read the relevant info page (alas, no man page provided). Again, since this article is about m4 rather than GNU m4, so I won't mention the various extensions implemented in the GNU version.


Sadly, there is no man page. There is an info page, however.

One thing to watch for is that the names of m4 builtins occurring in your text will be taken for calls to the function, and expanding. This can be avoided by quoting, but that is inconvenient. Fortunately, GNU m4 offers us a better way. The -P command-line switch allows us to preface all builtins by the string m4_, rather as in the C pre-processor the # character is used.

Quoting can be cantankerous on occasion. Quoting problems can usually be solved by changequote. For example, if we want to include one of the quote characters in a macro definition, we can use changequote([[,]]) and then

define([[`a quoted macro']]) 

will keep the quote characters in the macro definition — note that ` and ' can't be escaped, so we have to do it this way. (Exercise for the reader: how did I mark up that example in m4?)

However, what m4 really needs is an escape character, and it has none. This is the most serious deficiency, leading to baroque layers of quoting, and obscure errors as the layers of quotes are stripped off .

More generally, m4 is a useful tool, but it can be overstretched. Although it can be made to do most things with ingenuity, m4 is at its best when used for straightforward text substitution, as with our HTML example. Kernighan and Plauger sum it up nicely in Software Tools :

"The main thing is to ensure that any operation — macro call, definition, other built-in — can occur in the middle of any other one. If this is possible, then in principle the macro processor is capable of doing any computation, although it may well be hard to express."


"In principle, macro [i.e. m4] is capable of performing any computing task, but it is all too easy to write incomprehensible macros."


Building text files with m4 macros This tutorial describes how to ease the maintenance of text or HTML files,using the m4 macro processor.


A macro command language is often needed when using a text editor. Most of them already have such languages among their features. Even the C compiler provides such a facility for programmers throught the C preprocessor CPP. When it is used to maintain configuration files or a small web site, the GNU/m4 macro processor can efficiently reduce work load. The GNU/m4 macro processor is part of all linux distributions and is a standard among Unix users.

In the following, we show how to use the GNU/m4 macro processor to maintain a set of HTML pages for a small web site. This system will help to keep the whole site coherent. Of course, there are dozens of ways to obtain the same result with Unix tools; that's the beauty of Unix.

This technique is used for the construction of the well known There is an m4 macro kit available from Berkley university and designed by Eric Allman.

The GNU/m4 macro processor is not limited to text and HTML editing. It can prove very useful for programmers wishing to extend the features of CPP or to those wishing to have features equivalent to CPP with other languages.


A macro processor is a program which interprets commands (named macros) defined by the user. Macros are often embedded into the text to process. For instance, the following definition:

define(AUTHOR,`Agatha Christie<>')

allow to use the word "AUTHOR" anywhere in the text. It will be replaced with "Agatha Christie<>" after processing it with m4. There are, of course, more useful functions, as will be shown next.

An example

Let's suppose we have to maintain a web site that has the same pages but within different languages. Moreover, each page has the same header and footer in order to give the site a coherent look. In order to keep things simple and thus avoid the use of a browser to see the result, our example will only deal with text. This will also allow people using lynx to easily browse our site. Here is the HTML code for one page:

HTML Version

<!-- Start of header -->
<TITLE>Lynx homepage</TITLE>
<META name="description" content="Site lynx et m4"> 
<BODY BGCOLOR="#FFFFFF" LINK="#008000" VLINK="#808080" ALINK="#8080FF">
  <TR><TD align=middle colspan="2">
      <H1>Lynx a fully-featured World Wide Web client for character-cell
  <TR><TD align="left" valign="top" width="15%">
      <a href="./index-en.html">English</A><BR>
      <a href="./index-fr.html">French</A><BR>
      <a href="./index-es.html">Italian</A><BR>
      <a href="./index-it.html">Spanish</A><BR>
      <a href="./index-de.html">German</A><BR>
      <TD align=left>
<!-- End of header -->

      <P>Links to the current sources and support materials for Lynx are
   maintained at <A HREF="">Lynx
      <P> and at the Lynx homepage
      <A HREF="">Lynx
      <P>View these pages for information about Lynx, including new

      <P>Lynx is distributed under the GNU General Public License (GPL) without
   restrictions on usage or redistribution.  The Lynx copyright statement,
   "COPYHEADER", and GNU GPL, "COPYING", are included in the top-level
   directory of the distribution.  Lynx is supported by the Lynx user
   community, an entirely volunteer (and unofficial) organization.</P>

<!-- Start of footer -->
<HR size="0" noshadow>
<EM>Page maintained by John Perr.<BR>
Page updated on 25/07/99
- © <A HREF=""></A>1999
<!-- End of footer -->

All pages will have the same header or footer style, only the language and the body of the page will differ. We are now going to design m4 macros that are going to be inserted into the HTML text of our pages in order to replace all the repetitive data.
Before going into the detail of the macros, let us have a look at the above example written with such macros:

  Macro Version

LYNX_TITRE(Lynx a fully-featured World Wide Web
            client for character-cell displays)
LYNX_ENTETE(Lynx homepage)

      <P>Links to the current sources and support materials
      for Lynx are maintained at
      <A HREF="">
      Lynx links</A></P>
      <P> and at the Lynx homepage
      <A HREF="">
      Lynx Information.</A></P>
      <P>View these pages for information about Lynx,
      including new updates.</P>

      <P>Lynx is distributed under the
      GNU General Public License (GPL) without
   restrictions on usage or redistribution.
   The Lynx copyright statement, "COPYHEADER",
   and GNU GPL, "COPYING", are included in the top-level
   directory of the distribution.
   Lynx is supported by the Lynx user community,
   an entirely volunteer (and unofficial) organization.</P>

As such, writing HTML pages is simpler and the text is not lost among HTML tags. To write pages with others languages, translations of this file will have to be built. The french version would be:

LYNX_TITRE(Lynx un navigateur en mode console)
LYNX_ENTETE(Un site pour les utilisateurs de lynx)

   <P>Visitez le
   <A HREF="">
   site officiel de lynx</A>
   pour plus d'informations sur Lynx,
   y compris les nouvelles mises à jour.</P>
   <P>Les liens vers les sources de la version
   courante et divers supports pour Lynx sont
   tenus à jour sur le site
   <A HREF="">
   liens Lynx</A>.</P>

   <P>Lynx est distribue dans le cadre de la lisence GNU
   (General Public License - GPL)
   sans restriction sur son utilisation ni sa distribution.
   Les mentions des droits de reproduction de Lynx, "COPYHEADER",
   et GNU GPL, "COPYING", sont inclus dans la racine de
   l'arborescence de la distribution. Lynx est supporte par
   la communaute des utilisateurs de Lynx, une communaute
   entièrement benevole (et non-officielle).</P>

For each language, the same macros LYNX_TITRE, LYNX_ENTETE and LYNX_PIED are used but with different arguments. These 3 macros allow an efficient replacement for the HTML codes of the header and footer. This is the main advantage of this system: the definition of header and footer is consistent for all the site. If the style of the header and footer has to be changed, only the macro definition file will have to be modified instead of editing each page by hand.

Macro Definitions

Above, 3 macros have been defined in order to achieve most of the formatting. Here is the file defining those macros. Comments follow:

# File mac.css
# Version 1.0 M4 macros for Lynx
# A file trans-LANG.m4 is defined for each
# language, based on the french one.
# If no translation file exist,
# french is the default.
changequote({,})dnl # change quotes to curly braces
ifdef({LANG},,{define({LANG},{fr})})dnl # Default= french
include({trans-}LANG{.m4})dnl	  # call translation file
undefine({format})dnl		  # Suppress the format definition
define({_ANNEE_},esyscmd(date +%Y))dnl 	  #Current year
define({LYNX_TITRE},{define(_TITLE_,$1)})dnl # First macro
dnl # Second macro
define({LYNX_ENTETE},{<!-- Header start -->
<META name="description" content="Site lynx and m4"> 
<META name="keywords" content="m4, lynx, GPL">
<BODY BGCOLOR="#FFFFFF" LINK="#008000" VLINK="#808080" ALINK="#8080FF">
  <TR><TD align=middle colspan="2">
  <TR><TD align="left" valign="top" width="15%">
      <a href="./index-en.html">_ANGLAIS_</A><BR>
      <a href="./index-fr.html">_FRANCAIS_</A><BR>
      <a href="./index-es.html">_ESPAGNOL_</A><BR>
      <a href="./index-it.html">_ITALIEN_</A><BR>
      <a href="./index-de.html">_ALLEMAND_</A><BR>
      <TD align=left>
<!-- end of header -->})dnl
dnl # Third macro
define({LYNX_PIED},{<!-- Start of footer -->
<HR size="0" noshadow>
esyscmd(date +%d/%m/%y)
- &copy <A HREF=""></A>
<!-- End of footer -->})dnl


Lines between "divert(-1)" and "divert(0)" are comments. "Divert" is one of the builtin macros of the m4 processor. It is designed to divert the output of the processor. Using -1, tells the processor not to write the lines coming next in the final HTML file, which is what we want.

The "changequote" macro redefines the quotes normally used to quote macro arguments. They are replaced here with curly braces because in text files, and especially french ones, quotes are heavily used and would introduce misinterpretation of macros. Curly braces are less often used for text or HTML, so that is why they have been choosen here.

The "ifdef" macro is used to test whether the macro LANG is defined and to default it to "fr" if not. The LANG macro is used to set the language. In the lines below, we shall see how to define it when calling m4, in order to choose the language of the HTML page.

The "include" line has the same meaning as with C and is used to include an external file. We use it to load the language specific macro definitions used in the header and footer. Here are its contents according to language:

# File trans-fr.m4
# Definitions for french
define({_WEBMASTER_},{John Perr})dnl
define({_MAINTENEUR_},{Page maintenue par _WEBMASTER_})dnl 
define({_MAJ_},{Date de mise à jour:})dnl
# File trans-en.m4
# Definitions for english
define({_WEBMASTER_},{John Perr})dnl
define({_MAINTENEUR_},{Page maintained by _WEBMASTER_})dnl
define({_MAJ_},{Page updated on })dnl

If you speak Spanish, Italian or German, you should be able to write similar files for these languages.

The line "undefine" suppresses the default definition of the built-in named "format" because it is not used here. If this line is omitted, each time the word "format" appears within the text will disappear unless it is quoted, i.e., surrounded with curly braces. Such a practice is not advisable when editing a simple web page.

Next comes the definition of the current year. It is obtained from the macro "easyscmd" which calls the unix command "date". This command is also used within the definition of the footer in order to print the date at which the page has been updated.

The following line defines the first of our three main macros: LYNX_TITRE. This macro defines another macro called _TITRE_. This double definition is necessary in order to use the title several times within the header and footer of the page from one definition. Note the use of $1 to refer to the first argument of the macro.

The remaining lines define the two others main macros: LYNX_ENTETE and LYNX_PIED which correspond to the contents of the header and footer of our HTML page except for the variable elements of the page. These are:

The "dnl" which appears at the end of each line is a built-in macro of m4 meaning "Delete to New Line". With "dnl" m4 does not generate an empty line when interpreting a macro.

Creating pages

Now that our system is set, the generation of a web page from the files is done with the following command:

Where "XX" is the code to use for each language. Note that the -D option is used, as with gcc, to define a macro from the command line.


The table below presents the files and their use in this application.

The following files are used to generate HTML pages:


The body of the page, that is text written by the author or the translator. It is different for each page and each language. (the code is XX=en for English, es for Spanish, etc...)


Standard definitions. This file is common to all pages and all languages. it can be seen as a sort of style sheet.


Standard definitions for one language. this file is common to all pages for one language. (the code is XX=en for English, es for Spanish, etc...)


Despite its power, the m4 macro processor cannot be compared to a scripting language like Perl or Tcl. Once its few peculiarities have been acquired, it is a quick and handy tool to help process text files. To learn more, consult the documentation bundled with your distribution. You should find a tutorial to m4, about 30 pages long, that covers all the aspects of the GNU/m4 macro processor. You can also have a look at the site of the Linux User Group of Bordeaux (ABUL) which is maintained with a kit of m4 macros, similar to those presented here.  

[ Sep 18, 1997 ] Using m4 to write HTML. By Bob Hepple

1. Some limitations of HTML

It's amazing how easy it is to write simple HTML pages - and the availability of WYSIWYG HTML editors like NETSCAPE GOLD lulls one into a mood of "don't worry, be happy". However, managing multiple, interrelated pages of HTML rapidly gets very, very difficult. I recently had a slightly complex set of pages to put together and it started me thinking - "there has to be an easier way".

I immediately turned to the WWW and looked up all sorts of tools - but quite honestly I was rather disappointed. Mostly, they were what I would call Typing Aids - instead of having to remember arcane incantations like <a href="link">text</a>, you are given a button or a magic keychord like ALT-CTRL-j which remembers the syntax and does all that nasty typing for you.

Linux to the rescue! HTML is built as ordinary text files and therefore the normal Linux text management tools can be used. This includes the revision control tools such as RCS and the text manipulation tools like awk, perl, etc. These offer significant help in version control and managing development by multiple users as well as in automating the process of extracting from a database and displaying the results (the classic "grep |sort |awk" pipeline).

The use of these tools with HTML is documented elsewhere, e.g. see Jim Weinrich's article in Linux Journal Issue 36, April 1997, "Using Perl to Check Web Links" which I'd highly recommend as yet another way to really flex those Linux muscles when writing HTML.

What I will cover here is a little work I've done recently with using m4 in maintaining HTML. The ideas can probably be extended to the more general SGML case very easily.

2. Using m4

I decided to use m4 after looking at various other pre-processors including cpp, the C front-end. While cpp is perhaps a little too C-specific to be very useful with HTML, m4 is a very generic and clean macro expansion program - and it's available under most Unices including Linux.

Instead of editing *.html files, I create *.m4 files with my favourite text editor. These look something like this:


_HEADER(`This is my header')
<P>This is some plain text<P>
_HEAD1(`This is a main heading')
<P>This is some more plain text<P>

The format is simple - just HTML code but you can now include files and add macros rather like in C. I use a convention that my new macros are in capitals and start with "_" to make them stand out from HTML language and to avoid name-space collisions.

The m4 file is then processed as follows to create an .html file e.g.

m4 -P <file.m4 >file.html

This is especially easy if you create a "makefile" to automate this in the usual way. Something like:


.SUFFIXES: .m4 .html
	m4 -P $*.m4 >$*.html
default: index.html
*.html: stdlib.m4
all: default PROJECT1 PROJECT2
	(cd project2; make all)
	(cd project2; make all)

The most useful commands in m4 include the following which are very similar to the cpp equivalents (shown in brackets):


includes a common file into your HTML (#include)


defines an m4 variable (#define)


a conditional (#ifdef)

Some other commands which are useful are:


change the m4 comment character (normally #)


control error disgnostics


turn tracing on and off



m4_incr, m4_decr:

simple arithmetic


more general arithmetic


execute a Linux command and use the output


This is a little complicated, so skip on first reading. It is a way of storing text for output at the end of normal processing - it will come in useful later, when we get to automatic numbering of headings. It sends output from m4 to a temporary file number i. At the end of processing, any text which was diverted is then output, in the order of the file number i. File number -1 is the bit bucket and can be used to comment out chunks of comments. File number 0 is the normal output stream. Thus, for example, you can `m4_divert' text to file 1 and it will only be output at the end.

3. Examples of m4 macros

3.1 Sharing HTML elements across several page

In many "nests" of HTML pages, each page shares elements such as a button bar like this:

This is fairly easy to create in each page - the trouble is that if you make a change in the "standard" button-bar then you then have the tedious job of finding each occurance of it in every file and then manually make the changes.

With m4 we can more easily do this by putting the shared elements into an m4_include statement, just like C.

While I'm at it, I might as well also automate the naming of pages, perhaps by putting the following into an include file, say "button_bar.m4":


	<a href="homepage.html">[Home]</a>
	<a href="$1">[Next]</a>
	<a href="$2">[Prev]</a>
	<a href="indexpage.html">[Index]</a>)

and then in the document itself:


m4_include button_bar.m4

The $1 and $2 parameters in the macro definition are replaced by the strings in the macro call.

3.2 Managing HTML elements that often change

It is very troublesome to have items change in multiple HTML pages. For example, if your email address changes then you will need to change all references to the new address. Instead, with m4 you can do something like this in your stdlib.m4 file:

m4_define(`_EMAIL_ADDRESS', `')

and then just put _EMAIL_ADDRESS in your m4 files.

A more substantial example comes from building strings up with multiple components, any of which may change as the page is developed. If, like me, you develop on one machine, test out the page and then upload to another machine with a totally different address then you could use the m4_ifdef command in your stdlib.m4 file (just like the #ifdef command in cpp):


	m4_ifdef(`_LOCAL', `//', 

m4_define(`_PLUG', `<A REF="">
	<IMG SRC="_HOMEPAGE/gif/powered.gif" 
	ALT="[Linux Information]"> </A>')

Note the careful use of quotes to prevent the variable _LOCAL from being expanded. _HOMEPAGE takes on different values according to whether the variable _LOCAL is defined or not. This can then ripple through the entire project as you make the pages.

In this example, _PLUG is a macro to advertise Linux. When you are testing your pages, you use the local version of _HOMEPAGE. When you are ready to upload, you can remove or comment out the _LOCAL definition like this:

m4_dnl m4_define(`_LOCAL')

... and then re-make.

3.3 Creating new text styles

Styles built into HTML include things like <EM> for emphasis and <CITE> for citations. With m4 you can define your own, new styles like this:


If, later, you decide you prefer <STRONG> instead of <EM> it is a simple matter to change the definition and then every _MYQUOTE paragraph falls into line with a quick make.

The classic guides to good HTML writing say things like "It is strongly recommended that you employ the logical styles such as <EM>...</EM> rather than the physical styles such as <I>...</I> in your documents." Curiously, the WYSIWYG editors for HTML generate purely physical styles. Using these m4 styles may be a good way to keep on using logical styles.

3.4 Typing and mnemonic aids

I don't depend on WYSIWYG editing (having been brought up on troff) but all the same I'm not averse to using help where it's available. There is a choice (and maybe it's a fine line) to be made between:

<BLOCKQUOTE><PRE><CODE>Some code you want to display.



_CODE(Some code you want to display.)

In this case, you would define _CODE like this:



Which version you prefer is a matter of taste and convenience although the m4 macro certainly saves some typing and ensures that HTML codes are not interleaved. Another example I like to use (I can never remember the syntax for links) is:


m4_define(`_LINK', <a href="$1">$2</a>)


<a href="URL_TO_SOMEWHERE">Click here to get to SOMEWHERE </a>


_LINK(`URL_TO_SOMEWHERE', `Click here to get to SOMEWHERE')

3.5 Automatic numbering

m4 has a simple arithmetic facility with two operators m4_incr and m4_decr which act as you might expect - this can be used to create automatic numbering, perhaps for headings, e.g.:


m4_define(_H, `m4_define(`_CARDINAL',
	m4_incr(_CARDINAL))<H2>_CARDINAL.0 $1</H2>')

_H(First Heading)
_H(Second Heading)

This produces:

<H2>1.0 First Heading</H2>
<H2>2.0 Second Heading</H2>

3.6 Automatic date stamping

For simple, datestamping of HTML pages I use the m4_esyscmd command to maintain an automatic timestamp on every page:


This page was updated on m4_esyscmd(date)

which produces:

This page was last updated on Fri May 9 10:35:03 HKT 1997

Of course, you could also use the date, revision and other facilities of revision control systems like RCS or SCCS, e.g. $Date: 2002/10/09 22:24:22 $.

3.7 Generating Tables of Contents

Using m4 allows you to define commonly repeated phrases and use them consistently - I hate repeating myself because I am lazy and because I make mistakes, so I find this feature absolutely key.

A good example of the power of m4 is in building a table of contents in a big page (like this one). This involves repeating the heading title in the table of contents and then in the text itself. This is tedious and error-prone especially when you change the titles. There are specialised tools for generating tables of contents from HTML pages but the simple facility provided by m4 is irresistable to me.

3.7.1 Simple to understand TOC

The following example is a fairly simple-minded Table of Contents generator. First, create some useful macros in stdlib.m4:


m4_define(`_LINK_TO_LABEL', <A HREF="#$1">$1</A>)
m4_define(`_SECTION_HEADER', <A NAME="$1"><H2>$1</H2></A>)

Then define all the section headings in a table at the start of the page body:


m4_define(`_DIFFICULTIES', `The difficulties of HTML')
m4_define(`_USING_M4', `Using <EM>m4</EM>')
m4_define(`_SHARING', `Sharing HTML Elements Across Several Pages')

Then build the table:



Finally, write the text:



The advantages of this approach are that if you change your headings you only need to change them in one place and the table of contents is automatically regenerated; also the links are guaranteed to work.

Hopefully, that simple version was fairly easy to understand.


3.7.2 Simple to use TOC

The Table of Contents generator that I normally use is a bit more complex and will require a little more study, but is much easier to use. It not only builds the Table, but it also automatically numbers the headings on the fly - up to 4 levels of numbering (e.g. section - although this can be easily extended). It is very simple to use as follows:

  1. Where you want the table to appear, call Start_TOC

  2. at every heading use _H1(`Heading for level 1') or _H2(`Heading for level 2') as appropriate.

  3. After the very last HTML code (probably after </HTML>), call End_TOC

  4. and that's all!

The code for these macros is a little complex, so hold your breath:


m4_define(_H1, `m4_divert(-1)
  m4_define(`_TOC_label',`_H1_num. $1')
  m4_divert(0)<LI><A HREF="#_TOC_label">_TOC_label</A>
  m4_divert(1)<A NAME="_TOC_label">
[definitions for _H2, _H3 and _H4 are similar and are 
in the downloadable version of stdlib.m4]


One restriction is that you should not use diversions within your text, unless you preserve the diversion to file 1 used by this TOC generator.


3.8 Simple tables

Other than Tables of Contents, many browsers support tabular information. Here are some funky macros as a short cut to producing these tables. First, an example of their use:

_Table_Hdr(,Apples, Oranges, Lemons)


























...and now the code. Note that this example utilises m4's ability to recurse:

m4_dnl _Start_Table(Columns,TABLE parameters)
m4_dnl defaults are BORDER=1 CELLPADDING="1" CELLSPACING="1"
m4_dnl WIDTH="n" pixels or "n%" of screen width
m4_define(_Start_Table,`<TABLE $1>')

m4_define(`_Table_Hdr_Item', `<th>$1</th>

m4_define(`_Table_Row_Item', `<td>$1</td>




4. m4 gotchas

Unfortunately, m4 is not unremitting sweetness and light - it needs some taming and a little time spent on familiarisation will pay dividends. Definitive documentation is available (for example in emacs' info documentation system) but, without being a complete tutorial, here are a few tips based on my fiddling about with the thing.

4.1 Gotcha 1 - quotes

m4's quotation characters are the grave accent ` which starts the quote, and the acute accent ' which ends it. It may help to put all arguments to macros in quotes, e.g.

_HEAD1(`This is a heading')

The main reason for this is in case there are commas in an argument to a macro - m4 uses commas to separate macro parameters, e.g. _CODE(foo, bar) would print the foo but not the bar. _CODE(`foo, bar') works properly.

This becomes a little complicated when you nest macro calls as in the m4 source code for the examples in this paper - but that is rather an extreme case and normally you would not have to stoop to that level.


4.2 Gotcha 2 - Word swallowing

The worst problem with m4 is that some versions of it "swallow" key words that it recognises, such as "include", "format", "divert", "file", "gnu", "line", "regexp", "shift", "unix", "builtin" and "define". You can protect these words by putting them in m4 quotes, for example:

Smart people `include' Linux in their list
of computer essentials.

The trouble is, this is a royal pain to do - and you're likely to forget which words need protecting.

Another, safer way to protect keywords (my preference) is to invoke m4 with the -P or --prefix-builtins option. Then, all builtin macro names are modified so they all start with the prefix m4_ and ordinary words are left alone. For example, using this option, one should write m4_define instead of define (as shown in the examples in this article).

The only trouble is that not all versions of m4 support this option - notably some PC versions under M$-DOS. Maybe that's just another reason to steer clear of hack code on M$-DOS and stay with Linux!


4.3 Gotcha 3 - Comments

Comments in m4 are introduced with the # character - everything from the # to the end of the line is ignored by m4 and simply passed unchanged to the output. If you want to use # in the HTML page then you would need to quote it like this - `#'. Another option (my preference) is to change the m4 comment character to something exotic like this: m4_changecom(`[[[[') and not have to worry about `#' symbols in your text.

If you want to use comments in the m4 file which do not appear in the final HTML file, then the macro m4_dnl (dnl = Delete to New Line) is for you. This suppresses everything until the next newline.

m4_define(_NEWMACRO, `foo bar') m4_dnl This is a comment

Yet another way to have source code ignored is the m4_divert command. The main purpose of m4_divert is to save text in a temporary buffer for inclusion in the file later on - for example, in building a table of contents or index. However, if you divert to "-1" it just goes to limbo-land. This is useful for getting rid of the whitespace generated by the m4_define command, e.g.:

m4_divert(-1) diversion on
m4_define(this ...)
m4_define(that ...)
m4_divert	diversion turned off


4.4 Gotcha 4 - Debugging

Another tip for when things go wrong is to increase the amount of error diagnostics that m4 emits. The easiest way to do this is to add the following to your m4 file as debugging commands:


buggy lines



5. Conclusion

"ah ha!", I hear you say. "HTML 3.0 already has an include statement". Yes it has, and it looks like this:

<!--#include file="junk.html" -->

The problem is that:

There are several other features of m4 that I have not yet exploited in my HTML ramblings so far, such as regular expressions and doubtless many others. It might be interesting to create a "standard" stdlib.m4 for general use with nice macros for general text processing and HTML functions. By all means download my version of stdlib.m4 as a base for your own hacking. I would be interested in hearing of useful macros and if there is enough interest, maybe a Mini-HOWTO could evolve from this paper.

There are many additional advantages in using Linux to develop HTML pages, far beyond the simple assistance given by the typical Typing Aids and WYSIWYG tools.

Certainly, this little hacker will go on using m4 until HTML catches up - I will then do my last make and drop back to using pure HTML.

I hope you enjoy these little tricks and encourage you to contribute your own. Happy hacking!

6. Files to download

You can get the HTML and the m4 source code for this article here (for the sake of completeness, they're copylefted under GPL 2):


using_m4.html	:this file
using_m4.m4	:m4 source
stdlib.m4	:Include file

Recommended Links

Softpanorama hot topic of the month

Softpanorama Recommended

M4 (computer language) - Wikipedia, the free encyclopedia

pSeries and AIX Information Center m4 Macro Processor Overview

GNU macro processor  by Ren'e Seindal

[PDF] Exploiting the m4 Macro LanguageFile Format: PDF/Adobe Acrobat - View as HTML

Webdesign Building text files with m4 macros

The M4 Macro Processor Brian W. Kernighan Dennis M. Ritchie Bell ...

The m4 Macro Package Linux Journal

Sun documentation Programming Utilities Guide


Hints and Tips for the M4 macro processor


FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available in our efforts to advance understanding of environmental, political, human rights, economic, democracy, scientific, and social justice issues, etc. We believe this constitutes a 'fair use' of any such copyrighted material as provided for in section 107 of the US Copyright Law. In accordance with Title 17 U.S.C. Section 107, the material on this site is distributed without profit exclusivly for research and educational purposes.   If you wish to use copyrighted material from this site for purposes of your own that go beyond 'fair use', you must obtain permission from the copyright owner. 

ABUSE: IPs or network segments from which we detect a stream of probes might be blocked for no less then 90 days. Multiple types of probes increase this period.  


Groupthink : Two Party System as Polyarchy : Corruption of Regulators : Bureaucracies : Understanding Micromanagers and Control Freaks : Toxic Managers :   Harvard Mafia : Diplomatic Communication : Surviving a Bad Performance Review : Insufficient Retirement Funds as Immanent Problem of Neoliberal Regime : PseudoScience : Who Rules America : Neoliberalism  : The Iron Law of Oligarchy : Libertarian Philosophy


War and Peace : Skeptical Finance : John Kenneth Galbraith :Talleyrand : Oscar Wilde : Otto Von Bismarck : Keynes : George Carlin : Skeptics : Propaganda  : SE quotes : Language Design and Programming Quotes : Random IT-related quotesSomerset Maugham : Marcus Aurelius : Kurt Vonnegut : Eric Hoffer : Winston Churchill : Napoleon Bonaparte : Ambrose BierceBernard Shaw : Mark Twain Quotes


Vol 25, No.12 (December, 2013) Rational Fools vs. Efficient Crooks The efficient markets hypothesis : Political Skeptic Bulletin, 2013 : Unemployment Bulletin, 2010 :  Vol 23, No.10 (October, 2011) An observation about corporate security departments : Slightly Skeptical Euromaydan Chronicles, June 2014 : Greenspan legacy bulletin, 2008 : Vol 25, No.10 (October, 2013) Cryptolocker Trojan (Win32/Crilock.A) : Vol 25, No.08 (August, 2013) Cloud providers as intelligence collection hubs : Financial Humor Bulletin, 2010 : Inequality Bulletin, 2009 : Financial Humor Bulletin, 2008 : Copyleft Problems Bulletin, 2004 : Financial Humor Bulletin, 2011 : Energy Bulletin, 2010 : Malware Protection Bulletin, 2010 : Vol 26, No.1 (January, 2013) Object-Oriented Cult : Political Skeptic Bulletin, 2011 : Vol 23, No.11 (November, 2011) Softpanorama classification of sysadmin horror stories : Vol 25, No.05 (May, 2013) Corporate bullshit as a communication method  : Vol 25, No.06 (June, 2013) A Note on the Relationship of Brooks Law and Conway Law


Fifty glorious years (1950-2000): the triumph of the US computer engineering : Donald Knuth : TAoCP and its Influence of Computer Science : Richard Stallman : Linus Torvalds  : Larry Wall  : John K. Ousterhout : CTSS : Multix OS Unix History : Unix shell history : VI editor : History of pipes concept : Solaris : MS DOSProgramming Languages History : PL/1 : Simula 67 : C : History of GCC developmentScripting Languages : Perl history   : OS History : Mail : DNS : SSH : CPU Instruction Sets : SPARC systems 1987-2006 : Norton Commander : Norton Utilities : Norton Ghost : Frontpage history : Malware Defense History : GNU Screen : OSS early history

Classic books:

The Peter Principle : Parkinson Law : 1984 : The Mythical Man-MonthHow to Solve It by George Polya : The Art of Computer Programming : The Elements of Programming Style : The Unix Hater’s Handbook : The Jargon file : The True Believer : Programming Pearls : The Good Soldier Svejk : The Power Elite

Most popular humor pages:

Manifest of the Softpanorama IT Slacker Society : Ten Commandments of the IT Slackers Society : Computer Humor Collection : BSD Logo Story : The Cuckoo's Egg : IT Slang : C++ Humor : ARE YOU A BBS ADDICT? : The Perl Purity Test : Object oriented programmers of all nations : Financial Humor : Financial Humor Bulletin, 2008 : Financial Humor Bulletin, 2010 : The Most Comprehensive Collection of Editor-related Humor : Programming Language Humor : Goldman Sachs related humor : Greenspan humor : C Humor : Scripting Humor : Real Programmers Humor : Web Humor : GPL-related Humor : OFM Humor : Politically Incorrect Humor : IDS Humor : "Linux Sucks" Humor : Russian Musical Humor : Best Russian Programmer Humor : Microsoft plans to buy Catholic Church : Richard Stallman Related Humor : Admin Humor : Perl-related Humor : Linus Torvalds Related humor : PseudoScience Related Humor : Networking Humor : Shell Humor : Financial Humor Bulletin, 2011 : Financial Humor Bulletin, 2012 : Financial Humor Bulletin, 2013 : Java Humor : Software Engineering Humor : Sun Solaris Related Humor : Education Humor : IBM Humor : Assembler-related Humor : VIM Humor : Computer Viruses Humor : Bright tomorrow is rescheduled to a day after tomorrow : Classic Computer Humor

The Last but not Least

Copyright © 1996-2016 by Dr. Nikolai Bezroukov. was created as a service to the UN Sustainable Development Networking Programme (SDNP) in the author free time. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License.

The site uses AdSense so you need to be aware of Google privacy policy. You you do not want to be tracked by Google please disable Javascript for this site. This site is perfectly usable without Javascript.

Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.

FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available to advance understanding of computer science, IT technology, economic, scientific, and social issues. We believe this constitutes a 'fair use' of any such copyrighted material as provided by section 107 of the US Copyright Law according to which such material can be distributed without profit exclusively for research and educational purposes.

This is a Spartan WHYFF (We Help You For Free) site written by people for whom English is not a native language. Grammar and spelling errors should be expected. The site contain some broken links as it develops like a living tree...

You can use PayPal to make a contribution, supporting development of this site and speed up access. In case is down you can use the at


The statements, views and opinions presented on this web page are those of the author (or referenced source) and are not endorsed by, nor do they necessarily reflect, the opinions of the author present and former employers, SDNP or any other organization the author may be associated with. We do not warrant the correctness of the information provided or its fitness for any purpose.

Last modified: June 04, 2016