Search

Dark theme | Light theme

August 13, 2014

Awesome Asciidoctor: Adding Line Numbers to Source Code Listings

When we write technical documentation with Asciidoctor we can easily include source code listings. When we use the coderay or pygments source code highlighter we can also include line numbers. We must add the attribute linenums to the listing block in our markup. This attribute is used by the source highlighters to create and format the line numbers. We can specify that the line numbers must be generated in table mode or inline mode. When the line numbers are in table mode we can select the source code without the line numbers and copy it to the clipboard. If we use inline mode the line numbers are selectable and are copied together with the selected source code to the clipboard. To specify which mode we want to use for the line numbers we use the document attribute coderay-linenums-mode or pygments-linenums-mode depending on the source highlighter we use. We can use the values table (default) or inline.

= Source code listing

Code listings look cool with Asciidoctor and {source-highlighter}.

[source,groovy,linenums]
----
// File: User.groovy
class User {
    String username
}
----

[source,asciidoc,linenums]
----
# Hello world

Asciidoc(tor) is aweseome!
----

Let's generate HTML output from this markup and use different values for the source-highlighter and ...-linenums-mode attributes. First we use the Coderay source highlighter in table mode:

If we use inline mode (:coderay-linenums-mode: inline), we can see the line numbers are selected as well when we select the source code:

The following screenshots use the Pygments source highlighter with first a table mode for the line numbers and then inline mode:

Written with Asciidoctor 1.5.0.