Today I'd like to bring your attention to asciidoctor-gradle-plugin. This plugin process Asciidoc sources and creates beautiful documentation. It began life on a cold morning back in February of 2013 during the first JFokus Hackergarten, and has taken a life of its own ever since.
The team just pushed the 1.5.0 release, opening the door for many features, one of which is the topic of today's post: the ability to write custom extensions inside a Gradle build.
So, what exactly do we mean by custom extensions? Recall that Asciidoc has built-in "tags" (or macros) such as include
, image
, source
and more. Well know you can write your own tags
Say for example you'd like to write some content in Pig Latin (a very popular pseudo language in some circles). The rules are simple but given that you have to shuffle letters around it can be tricky to get all the sentences right. It would probably be better if there was an automatic way to convert plain text into its Pig Latin counterpart, wouldn't it? And that's precisely what we'll do. We're aiming to render something similar to the following screenshot
While keeping the source sentence in plain English. The source asciidoc document looks like this
Notice the [pig-latin] tag applied to the second example sentence. We'll begin with a small Gradle build that follows this structure
The bulk of the project is found in the extension itself. We'll begin by defining the build file for the extension
This extension is so simple it only needs the base asciidoctorj dependency to work. Next comes the main course: PigLatinBlock
. This is the code that's capable of handling the pig-latin
block in the asciidoc sources. The implementation is trivial though I can't claim is bug free nor is it capable of dealing with all corner cases.
Basically it breaks an annotated paragraph into lines, then further breaks each line into words and process each one of them. Now comes the part of registering the extension. First we create the handler for the extension
Finally we make sure the extension is registered by writing a metadata file in META-INF/services
We could have used gipsy to keep that file up to date and have it be generated automatically at compile time
And that's al the setup that's needed. Running gradle asciidoctor
on the project results in the asciidoc sources being processed. If for some reason the extension was not correctly registered you'd see a warning on the command line, something along the lines of "WARNING: index.adoc: line 16: invalid style for paragraph: pig-latin".
Keep on Groovying!