Adding Elm Support to Rouge
Rouge is a code highlighter. It is used by Jekyll to highlight code blocks in posts. I found out that there was no support for Elm in Rouge.
Here’s how I’ve added the Elm language support to Rouge.
Adding Elm Lexer
Code highlighting in Rouge is done using lexers. Supported languages have got corresponding lexers. A lexer is responsible for parsing the code and assigning its parts some meaning. For example, saying that some part of a code is a comment, some is a function or a variable name, some is a constant, etc.
The process of adding a new lexer is described in the git repository of the project. Rouge is written in Ruby, but the knowledge of Ruby language is not required. You need to know regular expressions though. I’ve followed the guide to produce the following four files:
-
lib/rouge/lexers/elm.rb
is the code for the lexer. This is the logic that Rouge will use for processing the Elm code. -
spec/visual/samples/elm
is an extended example of the code in Elm. I’ve used the following sources for this file: description of the Basics Elm package for basic operators and syntax, elm-compiler test cases for some edge-case scenarios, and examples from the Elm syntax guide. -
lib/rouge/demos/elm
is a “Hello, world!” version of the Elm program. -
spec/lexers/elm_spec.rb
is a short description of the lexer.
After a review, the commit with the Elm support has been merged and is now a part of the Rouge.
Here’s how the code highlight works:
Without highlight
-- Strings and Lists
"hello" ++ "world" == "helloworld"
[1,1,2] ++ [3,5,8] == [1,1,2,3,5,8]
-- Higher-Order Helpers
leftAligned <| monospace <| fromString "code"
With Rouge highlight
-- Strings and Lists
"hello" ++ "world" == "helloworld"
[1,1,2] ++ [3,5,8] == [1,1,2,3,5,8]
-- Higher-Order Helpers
leftAligned <| monospace <| fromString "code"
Elm Highlight in GitHub Pages
If you are using GitHub Pages to generate your Jekyll site, elm highlight currently (April 9th, 2018) won’t work for you.
Rouge supports Elm starting from version 3.1.0. Jekyll GitHub Pages currently uses Rouge v2.2.1. This will highly likely change in the future. The version of the Rouge used by GitHub Pages is updated with a delay to ensure that there will be no errors related to a code highlighting.
As a workaround, you can use Haskell highlighting instead of Elm. To use Haskell highlight you need to specify haskell
as a parameter for the highlight
tag:
{% highlight haskell %}
-- Strings and Lists
"hello" ++ "world" == "helloworld"
[1,1,2] ++ [3,5,8] == [1,1,2,3,5,8]
-- Higher-Order Helpers
leftAligned <| monospace <| fromString "code"
{% endhighlight %}
The syntaxis of Haskell is similar to Elm and the most of the code highlighting will work fine.