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
- 7/1/15: I’ve changed syntax highlighters to Rouge, which is currently in use on this page, so see the following version to see line numbers with highlightjs.
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);
}
}
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:
Otherwise, if I do want line numbering, I just add a “lineNumbers” class:
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:
- Make sure you have Python3 installed so you can run “python3 tools/build.py.” Initially I encountered errors building with Python2.
- By default, the build creates a highlight.js that supports lots of languages, which makes it somewhat heavy at 122KB+. I personally just used “python3 tools/build.py :common” to support the most popular languages.
- The highlight.js is produced in the build directory.
- Run “python3 tools/build.py -h” if you need further help and of course visit the highlight.js site for official documentation.
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.