4
votes

I'm trying to add line numbers to fenced code blocks in markdown with Jekyll.

I have tried using both kramdown and redcarpet and adding line_numbers: true to the _config.yml file (under the proper renderer config-block) but I can't seem to get line numbers on code blocks.

Solution: It turned out all I had to do was to switch back to kramdown (default markdown renderer) and start the code blocks with {% highlight <language> linenos %} and the code blocks gets line numbers.

3

3 Answers

3
votes

I used this great post. It worked for me. As for the line numbers use,

{% highlight <language> linenos %}
     <code>
 {% endhighlight %}

Check an example on my blog and see if this is what you want.

1
votes

As I'm in love with pandoc I would recommend you to use the pandoc markdown compiler:

Add Pandoc

Install the pandoc compiler, e.g. on debian via sudo apt install pandoc.

Add this to your _config.yaml:

markdown: Pandoc
gems:
  - jekyll-pandoc

Then add the jekyll-pandoc gem to your Gemfile:

group :jekyll_plugins do
    # here are your other gems
    gem "jekyll-pandoc"
end

If you're having trouble refer to the official resources that I included at the end.

Use Pandoc linenumbers

When you have successfully set up jekyll-pandoc you can use it as easy as:

~~~~ {.java .numberLines startFrom="1"}
class MyClassPresentedWithLineNumbersViaPandoc {
  void lineNumberedFunction() {};
}
~~~~

This would enable java code highlighting and linenumbers that start counting at 1.

For an example of the default appearance have a look at this listing in my blog.

Official resources

jekyll-pandoc

pandoc

0
votes

I prefrer code fence ``` or ~~~ over {% highlight %} because markdown previewer can handle it, and also I am used to write it more natural.

The code fence can use the language as well. E.g. ```java will start a java code block.

I use jekyll v4.2 and kramdown with the highlighter rouge.

My config file _config.yml

kramdown:
  syntax_highlighter: rouge
  syntax_highlighter_opts:
    block:
      line_numbers: true

The magic was syntax_highlighter_opts -> block -> line_numbers: true.

There is also an option for <span> elements, but I have never tried it.

kramdown:
  syntax_highlighter: rouge
  syntax_highlighter_opts:
    block:
      line_numbers: true
    span:
      line_numbers: true