Highlight.js Line Numbers

In this post I will show how to add line numbers with syntax highlighting provided through Highlight.js. I decided to give this a whirl after getting a comment from the author Ivan Sagalaev describing how Highlight.js supports line numbers on an experimental code branch (line numbers are actually not included as a feature). Hmm, I thought nobody read my random posts but I guess not :).

Changelog

Examples

So, without further ado, here’s code with line numbers:

1
2
3
4
5
6
7
function fibonacci(n) {
    if(n <= 2) {
        return 1;
    } else {
        return fibonacci(n - 1) + fibonacci(n - 2);
    }
}
function fibonacci(n) {
    if(n <= 2) {
        return 1;
    } else {
        return fibonacci(n - 1) + fibonacci(n - 2);
    }
}

This is just an initial attempt but I’m actually quite happy with how it turned out, especially since I can copy the text and not have it also copy the numbers.

Details

So how does this work? Well, from looking at Ivan’s branch, it appeared that the line numbers were set through a global variable. Instead, I figured that sometimes you may want line numbers and other times you may not, so I rewrote the code to detect for a classname called “lineNumbers” and if it detects that class then it applies line numbering.

For example, if I want code without line numbering I write my HTML like:

<pre>   
    <code class="java">
    System.out.println("hello");
    </code>
</pre>

Otherwise, if I do want line numbering, I just add a “lineNumbers” class:

<pre>
    <code class="java lineNumbers">
    System.out.println("hello");
    </code>
</pre>

Github Fork

If you’re interested in having this for your site, I forked the Highlight.js 7.3 code and added the changes at https://github.com/iominh/highlight.js.

A couple of tips to build the JS library:

You should review the changes described at https://github.com/isagalaev/highlight.js/compare/line-numbers and in particular the CSS that you will need to add.