In this post I’ll describe how to add line numbers to a Jekyll 3 site using Rouge. While this should be a simple task, it actually took me a bit of effort to allow code to be copied without line numbers also being copied. Previously I used highlight.js, which was super fast, but I decided to speed things up even more by switching to Rouge and have the syntax highlighting pre-generated as part of the Jekyll static compilation.
Here’s an example with line numbers:
a,b = 1,1
for i in range(n-1):
a,b = b,a+b
Here’s the same example without line numbers:
Notice that selecting and copying the code in both examples does not also copy the line numbers.
Initially I added line number with Pygments but had issues copying code within the generated code blocks because it would also copy the line numbers. Here’s an example of the code I used:
I found some documentation describing how adding linenos=table would separate the code from the line numbers. Alas, I had no luck with this either because it jacked up my layout.
The solution that worked for me was switching to Rouge and doing a bit of CSS.
If you’re using Jekyll 3 then install Rouge and modify your _config.yml to use Rouge:
Similarly to Pygments, you can highlight code like the following example:
This should generate markup similar to the following:
It should hopefully be easier to style the line numbers and code now that they’re separate columns (Pygments kept it as a single pre element with spans intermixed with line numbers and code, which made things tricky.
Specifically for my SCSS/CSS, I used the following code: