I am looking for the most straight forward way to have code syntax highlighting in markdown, using Ruby (without Rails).
I have tried some things with Kramdown and Rouge, and could not make it work, so I am now working with RDiscount and CodeRay.
Most of the things work as I expect, with one small and one big issue:
Small Issue: The only way I found to make CodeRay work with RDiscount, is by applying the highlighting on the HTML rather than on the markdown document. This seems a little off to me and prone to errors. Is there another way?
Big Issue: I am now facing a double HTML escaping issue, and was unable to find any
html_escape: false
option in the CodeRay documentation.
Code
require 'rdiscount'
require 'coderay'
markdown = <<EOF
```ruby
A > B
```
EOF
def coderay(text)
text.gsub(/\<code class="(.+?)"\>(.+?)\<\/code\>/m) do
CodeRay.scan($2, $1).html
end
end
html = RDiscount.new(markdown).to_html
html = coderay(html)
puts html
Output
Notice the double escaping on the greater than sign:
<pre>
<span class="constant">A</span> &gt; <span class="constant">B</span>
</pre>
I have found this related question, but its old and without a solution for this case.
The only way I can come up with, is to unescape the HTML before passing it through CodeRay, but this does not feel right to me. Nevertheless, a working alternative below:
def coderay(text)
text.gsub(/\<code class="(.+?)"\>(.+?)\<\/code\>/m) do
lang, code = $1, $2
code = CGI.unescapeHTML code
CodeRay.scan(code, lang).html
end
end