Awesome Asciidoctor: Highlight Lines In Source Code Listings

In Asciidoctor we can configure syntax highlighting for our source code listings. We can choose from the built-in support for Coderay, Pygments, highlight.js and prettify. The syntax highlighter libraries Coderay and Pygments support extra highlighting of lines, so we can add extra attention to those lines. In this post we see how to use the line highlighting feature in Asciidoctor.

First we must add the document attribute source-highlighter and use the value coderay or pygments. When we use Coderay we must also enable the line numbers for the source code listing, because Coderay will highlight the line numbers in the output. Pygments highlight the whole line, with or without line numbers in the output. Therefore we choose Pygments in our example. To highlight certain lines in the source code output we use the highlight attribute for the source code block. We can specify single line numbers separated by a comma (,) or semi colon (;). If we use a comma we must enclose the value of the highlight attribute in quotes. To define a range of line numbers we can define the start and end line numbers with a hyphen in between (eg. 5-10 to highlight lines 5 to 10). To unhighlight a line we must prefix it with a exclamation mark (!). For example the following value for the highlight attribute highlights the lines 2, 3 to 7 and not 5: [source,highlight=1;3-7;!5].

In the following example markup we have a source code block where we highlight the lines 7 to 9. We use Pygments as syntax highlighter:

If we look at the generated HTML we can see lines 7, 8 and 9 are differently styled:

Written with Asciidoctor 1.5.4.

Original blog post

This entry was posted in Asciidoctor, Coding and tagged by mrhaki. Bookmark the permalink.

About mrhaki

My name is Hubert A. Klein Ikkink also known as mrhaki. I work at the great IT company JDriven. Here I work on projects with Groovy & Grails, Gradle and Spring. At JDriven we focus on SpringSource technologies. All colleagues want to learn new technologies, support craftmanship and are very eager to learn. This is truly a great environment to work in. You can contact me via Google+ or @mrhaki.

Leave a Reply

Your email address will not be published. Required fields are marked *