Skip to content

Instantly share code, notes, and snippets.

Created April 30, 2009 07:09
Show Gist options
  • Save anonymous/104317 to your computer and use it in GitHub Desktop.
Save anonymous/104317 to your computer and use it in GitHub Desktop.
Using CodeRay -and- Syntax with RedCloth
#
# Using CodeRay -and- Syntax with RedCloth
#
# Setup both gems in config/environment.rb
# config.gem "syntax", :version => '1.0.0'
# config.gem "coderay", :version => '0.8.312'
#
# Then drop this in config/initializers
#
# Now you can:
#
# For Syntax:
# bc[s_ruby]. => Syntax for Ruby
# @[s_yaml]text@ => Syntax for YAML
#
# For CodeRay:
# Using style= tags w/ the default style
# bc[cs_ruby]. => CodeRay for Ruby
# @[cs_yaml]text@ => CodeRay for YAML
#
# Using class= tags w/ your stylesheet
# bc[cc_ruby]. => CodeRay for Ruby
# @[cc_yaml]text@ => CodeRay for YAML
#
module SyntaxHighlighter
module ForRedCloth
def self.install
RedCloth::Formatters::HTML.module_eval do
def unescape(html)
replacements = {
'&' => '&',
'"' => '"',
'>' => '>',
'&lt;' => '<',
}
html.gsub(/&(?:amp|quot|[gl]t);/) { |entity| replacements[entity] }
end
undef_method :code, :bc_open, :bc_close, :escape_pre
def code(opts)
opts[:block] = true
if opts[:lang] =~ /^(s|cc|cs)_(\w+)/
@in_bc ||= nil
code, lang = $~[1], $~[2]
if code == 's'
syntax_lexer(lang, opts)
else
css = (code == 'cc') ? {:css => :class} : {}
coderay_lexer(lang, css, opts)
end
else
"<code#{pba(opts)}>#{opts[:text]}</code>"
end
end
def syntax_lexer(lang, opts)
single_line = "<span class=\"syntax_inline_#{lang}\">%s</span>"
multi_line = "<div class=\"syntax_multiline_#{lang}\">%s</div>"
wrap_in = @in_bc ? multi_line : single_line
opts[:text] = unescape(opts[:text]) unless @in_bc
highlighted_code = wrap_in % Syntax::Convertors::HTML.for_syntax(lang).convert(opts[:text])
highlighted_code.gsub!(/<pre>|<\/pre>/, '') unless @in_bc
highlighted_code
end
def coderay_lexer(lang, css, opts)
format = @in_bc ? :div : :span
highlighted_code = CodeRay.encode opts[:text], lang, format, {:stream => true}.merge(css)
highlighted_code.sub!(/\A<(span|div)/) { |m| m + pba(@in_bc || opts) }
highlighted_code = unescape(highlighted_code) unless @in_bc
highlighted_code
end
def bc_open(opts)
opts[:block] = true
@in_bc = opts
opts[:lang] ? '' : "<pre#{pba(opts)}>"
end
def bc_close(opts)
opts = @in_bc
@in_bc = nil
opts[:lang] ? '' : "</pre>\n"
end
def escape_pre(text)
if @in_bc ||= nil
text
else
html_esc(text, :html_escape_preformatted)
end
end
end
end
end
end
SyntaxHighlighter::ForRedCloth.install
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment