Note: Information adapted from https://unix.stackexchange.com/questions/280532/m4-macro-implementation-of-global-non-volatile-counter
Markdown does not support auto numbering of sections :-(. However with some M4 magic and some minor changes to your markdown text you can add this handy feature.
The techinique uses the M4 macro processor maintain an auto incrmenting counter and add the correct section numbers to your markdown text. This examples uses a single counter that is never reset, but the technique can be extended for more complex use cases.
More about M4 at https://www.gnu.org/software/m4/manual/m4.html
I run M4 on my markdown as follows (very amenable to automation in a Makefile of course)
m4 -P MyDoc.m4 > MyDoc.md
Note:
-
I use the
-P
option, so all my M4 directives and macro names are prefixed withm4_
. This helps avoid name clashes. -
I don't like the default M4 quote defaults, so I change those to
[
and]
. This is the same convention used by Autoconf
So now I just need to add the following to the start of my markdown files
m4_changequote([, ])m4_dnl
m4_define([m4_counter],[0])m4_dnl
m4_define([m4_ExNumber],[m4_define([m4_counter],m4_eval(m4_counter+1))Activity m4_counter])m4_dnl
Now everywhere the text m4_ExNumber
appears I will get an inrementing integer.
But there is one final twist if you are
using ATX headings
(lines starting with #...
).
M4 ignores anything
after a #
and copies it verbatim to the output. So you need to quote
the #...
section headings. For me that looks like this
[##] m4_ExNumber. Pulling an image from the Docker Hub registry
(because I changed the default quotes)
which becomes
## Activity 1. Pulling an image from the Docker Hub registry