September 16, 2016

Awesome Asciidoctor: Use Counters in Markup

In Asciidoctor we can create a document attribute as a counter attribute. The attribute is automatically incremented each time we use it in our markup. We can choose to use numbers or characters. Only latin characters from 'a' to 'z' or 'A' to 'Z' are allowed. By default the counter will start at 1, but we can define another start value when we use the counter attribute for the first time.

To define a counter attribute we must prefix the attribute name with counter:. Each time we use this syntax with the counter: prefix the value is incremented and displayed. To only display the current value, without incrementing, we simply refer to the document attribute without the counter: prefix. For example if we want to add a counter attribute with the name steps we would use the following markup in Asciidoctor: {counter:steps}.

To increment the counter without display it we must replace counter: with counter2:. The value of the attribute is incremented but not displayed. So to increment our steps attribute we would use the syntax: {counter2:steps}. To get the current value without incrementing we simply use {steps}.

To start with a different value than 1 we can suffix the attribute name with :<:start-value>. Let's look at how we would create the steps counter attribute starting from 100: {counter:steps:100}. To have a counter with letters we define the start value as a letter from which we want to count: {counter:steps:A}.

In the following example markup we see different usages of the counter support in Asciidoctor:

== Counters

In Asciidoctor we can use counters. To use them
we ({counter:usage}) use a document attribute
prefixed with `counter:` and ({counter:usage}) use it again
to increment the counter.

Instead of numbers we can use characters. To use them
we ({counter:usageChar:A}) use a document attribute
prefixed with `counter:` and suffix `:A` and ({counter:usageChar}) use it again
to increment the counter.

=== Current value

Current value for a counter can be obtained by just referring to document attribute name. 
Value counter is *{usage}*.

=== Increment

{counter2:usage} We can also increment the counter without displaying the value. 
On the next increment the value is *{counter:usage}*.

=== Start at

To start at another number than 1 we can specify the starting counter value as 
a suffix to the counter attribute as `:<start>`.

{counter:sample:10}. do something followed by {counter:sample}. something else.

When we transform this to HTML with Asciidoctor we get the following result:

Written with Asciidoctor 1.5.4.