0

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:

  1. 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?

  2. 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> &amp;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
Community
  • 1
  • 1
DannyB
  • 12,810
  • 5
  • 55
  • 65
  • Is the problem caused by rdiscount or coderay? Is the value between the two OK? Try narrowing the scope of your question, or separate the question in two. – Mladen Jablanović Jun 12 '16 at 14:10
  • It is CodeRay that does the extra encoding. RDiscount encodes, but it should. CodeRay should have the ability to disable escaping I think. The reason I posted it in a single question, is that I am hopeful there is a better way to get markdown with syntax highlighting. – DannyB Jun 12 '16 at 15:19

0 Answers0