Nanoc Markdown/CodeRay plugin

68 views
Skip to first unread message

Rob Emerson

unread,
May 5, 2008, 5:41:11 AM5/5/08
to nanoc
Hi,

I've written a small Nanoc plugin that filters output via CodeRay.

I write my code segments in Markdown. This filter finds the resulting
<pre><code> blocks generated by Bluecloth and filters them via
CodeRay.

Hope this is useful to someone.

Cheers,

Rob

#
# This is a small filter that searches for <pre><code>...</code></pre>
blocks inside the
# given document and rams the block through CodeRay. This should allow
you to get nice
# syntax highlighted code from straight Markdown (I tested via txt
files through Bluecloth).
#
# Some caveats:
#
# - The <pre><code> block is automatically wrapped in a <div
class="CodeRay"> by this filter.
# - I've defaulted to C below; current this is hardwired.
# - You'll need to add suitable CSS for CodeRay somewhere; this isn't
inlined/generated.
#
# Needs Gems:
#
# - Hpricot
# - CodeRay
#
class CoderayFilter < Nanoc::Filter

identifier :coderay

def run(content)
nanoc_require 'hpricot'
nanoc_require 'coderay'

doc = Hpricot(content)

blocks = doc.search('pre > code').map do |block|

# CodeRay will re-escape, leading to a mess as the content is
already escaped.
# Need to therefore unescape first.
code = codify(html_unescape(block.inner_html), :c)

block.inner_html = code

end

# Crusty; wrap in div.
doc.to_s.gsub('<pre><code>', '<div
class="CodeRay"><pre><code>').gsub('</code></pre>', '<</code></pre></
div>')

end

private

def html_unescape(a_string)
a_string.gsub('&amp;', '&').gsub('&lt;', '<').gsub('&gt;',
'>').gsub('&quot;', '"')
end

def codify(str, lang)
%{#{CodeRay.scan(str, lang).html}}
end

end

Rob Emerson

unread,
May 16, 2008, 4:34:28 PM5/16/08
to nanoc
Wrote this up on my (new! nanoc!) site, if anyone's interested:

http://www.remerson.plus.com/articles/nanoc-coderay/
Reply all
Reply to author
Forward
0 new messages