How to fence code blocks with line numbers correctly and update the code-block CSS

105 Views Asked by At

I'm trying to add line numbers to fenced code blocks in markdown with Jekyll. Moreover, I am trying to find ways of updating the code CSS style.

Regarding the first question I am trying to follow the instructions in the following thread. Thus, I am trying to do two things, encapsulate the code using the following commands:

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

However, when I do this the code appears right after the line counter:

1
2
3
4
5
import os
import numpy as np
....

And the same behavior is occurring when I am changing in the config.yml the following lines to true:

# Markdown and syntax highlight
markdown: kramdown
highlighter: rouge
kramdown:
  input: GFM
  syntax_highlighter_opts:
    css_class: 'highlight'
    span:
      line_numbers: false #true
    block:
      line_numbers: false #true
      start_line: 1

How can I solve this issue? And in general, how can I change the CSS for only the code blocks?

EDIT:

The results after the inspection of the code:

enter image description here

1

There are 1 best solutions below

4
maikhel On

Your question consists of two issues, let's tackle them one by one.

Adding line numbers

There are two basic different ways of adding code line numbers to code snippets.

  1. Add line numbers for specific code snippet, with
{% highlight python linenos %}
    <code>
{% endhighlight %}
  1. Add line numbers for all code blocks in general:
# _config.yml

markdown: kramdown
highlighter: rouge
kramdown:
  syntax_highlighter_opts:
    css_class: 'highlight'
    block:
      line_numbers: true #true
      start_line: 1

which works for code blocks generated with triple backticks: ```.

If you need line numbers in each code snippet the second approach is more useful.

Styling

To apply a specific style for code snippets you can utilize rouge gem commands.

  1. Install rouge gem locally with gem install rouge command.
  2. Generate the stylesheet for code highlighting style of your choice with
rougify style monokai.sublime > syntax.css

Here you can find a list of supported themes, sometimes there is more than one in a single file (e. g. in base16.rb)

  1. Include syntax CSS file into your layout
  <link rel="stylesheet" href="{{ "/css/syntax.css" | prepend: site.baseurl }}">
  1. Update CSS file if needed, e.g. adjust margins and paddings.