Syntax highlighting in Jekyll

If you have a coding blog, you will need to show code snippets a lot of the time.

I will explain how to have syntax highlighting in Jekyll using Rouge with the kramdown markdown parser.

Requirements

  • Jekyll version 3.0 or above (check using bundle exec jekyll --version)
  • If your version is less than 3.0 you need to install both kramdown and rouge. gem install kramdown rouge

Jekyll Syntax Highlighting

If you don't have a _.config.yml file then create it and add the following:


markdown: kramdown

kramdown:
  input: GFM
  auto_ids: true
  hard_wrap: false
  syntax_highlighter: rouge

This makes sure you are using kramdown and that everything is working properly. I think the above is just the default settings anyways but I like to make sure.

With Rouge, you have access to the rougify cli tool. To see all available syntax highlighting themes run rougify help style. For example, it shows the following for me:

usage: rougify style [<theme-name>] [<options>]

....
....

available themes:
  base16, base16.dark, base16.light, base16.monokai, base16.monokai.dark, base16.monokai.light, base16.solarized, base16.solarized.dark, base16.solarized.light, bw, colorful, github, gruvbox, gruvbox.dark, gruvbox.light, igorpro, magritte, molokai, monokai, monokai.sublime, pastie, thankful_eyes, tulip

From these themes, choose one you like. You can see a preview of the themes here.

You can view the css by running rougify style colorful. Replace colorful with any of the available themes.

In your assets/css folder (create it if you don't have it), add a file syntax.css. Copy and paste the styles generated by the rougify style command from above. Alternatively, you can do rougify style colorful > assets/css/syntax.css.

Make sure that you are properly linking the stylesheet in the HTML. In my example I would link <link href="/assets/css/syntax.css" rel="stylesheet" >.

Important tip

If the syntax highlighting isn't responsive / wrapping correctly. Then add the following style in the syntax.css stylehsheet

.highlighter-rouge .highlight pre.highlight {
    overflow: auto;
}

How to do syntax highlighting in your blog posts.

In order to have syntax highlighting simply put your code in between 3 backticks on top and 3 backticks on the bottom. Right next to the 3 ticks on top, specify the language of the code you will be highlighting.

For example, pretend I was highlighting php code:

    ```php

    //code here

    ```

Here is a list of all supported languages.

Want to learn how to code and make money online? Check out CodingPhase (referral link)