Search

Dark theme | Light theme

June 10, 2014

Awesome Asciidoctor: Change Source Code Indentation

Writing documentation and including source files is made very easy in Asciidoc and Asciidoctor. We can use the include macro to include a source file in our documentation. This way we can write source code, test the code (preferable automated) and the code in our documentation always works and will be up to date. We can use the indent attribute when we include source code to change the indentation. Tab characters are replaced with 4 spaces when we use the indent attribute. We can specify the number of spaces the code needs to be indented with a value of 0 or greater.

The following sample Asciidoc markup will remove all indentation of the original code block which is indented with 4 spaces, because we use the value 0:

[source,groovy,indent=0]
----
    def sample = (1..4).collect { it * 2 }
    assert sample == [2,4,6,8]
----

If we generate HTML we get the following result:

The code still looks indented, but that is done via CSS styling. The padding is set to a value greater than 0, but we can change that of course with our own CSS stylesheet.

In the following sample we set the indent attribute with the value 8:

[source,groovy,indent=8]
----
    def sample = (1..4).collect { it * 2 }
    assert sample == [2,4,6,8]
----

We get the following result:

In the final sample we use the include macro to include source code. We can still use the indent attribute like we did with the inline code samples:

[source,groovy,indent=3]
include::indent.groovy[]

Here is the resulting HTML:

Code written with Asciidoctor 0.1.4.