| Module | CodeRay::ForRedCloth |
| In: |
lib/coderay/for_redcloth.rb
|
A little hack to enable CodeRay highlighting in RedCloth.
Usage:
require 'coderay'
require 'coderay/for_redcloth'
RedCloth.new('@[ruby]puts "Hello, World!"@').to_html
Make sure you have RedCloth 4.0.3 activated, for example by calling
require 'rubygems'
before RedCloth is loaded and before calling CodeRay.for_redcloth.
# File lib/coderay/for_redcloth.rb, line 15
15: def self.install
16: gem 'RedCloth', '>= 4.0.3' rescue nil
17: require 'redcloth'
18: raise 'CodeRay.for_redcloth needs RedCloth 4.0.3 or later.' unless RedCloth::VERSION.to_s >= '4.0.3'
19: RedCloth::TextileDoc.send :include, ForRedCloth::TextileDoc
20: RedCloth::Formatters::HTML.module_eval do
21: def unescape(html)
22: replacements = {
23: '&' => '&',
24: '"' => '"',
25: '>' => '>',
26: '<' => '<',
27: }
28: html.gsub(/&(?:amp|quot|[gl]t);/) { |entity| replacements[entity] }
29: end
30: undef_method :code, :bc_open, :bc_close, :escape_pre
31: def code(opts) # :nodoc:
32: opts[:block] = true
33: if opts[:lang] && !filter_coderay
34: require 'coderay'
35: @in_bc ||= nil
36: format = @in_bc ? :div : :span
37: highlighted_code = CodeRay.encode opts[:text], opts[:lang], format, :stream => true
38: highlighted_code.sub!(/\A<(span|div)/) { |m| m + pba(@in_bc || opts) }
39: highlighted_code = unescape(highlighted_code) unless @in_bc
40: highlighted_code
41: else
42: "<code#{pba(opts)}>#{opts[:text]}</code>"
43: end
44: end
45: def bc_open(opts) # :nodoc:
46: opts[:block] = true
47: @in_bc = opts
48: opts[:lang] ? '' : "<pre#{pba(opts)}>"
49: end
50: def bc_close(opts) # :nodoc:
51: opts = @in_bc
52: @in_bc = nil
53: opts[:lang] ? '' : "</pre>\n"
54: end
55: def escape_pre(text)
56: if @in_bc ||= nil
57: text
58: else
59: html_esc(text, :html_escape_preformatted)
60: end
61: end
62: end
63: end
# File lib/coderay/for_redcloth.rb, line 55
55: def escape_pre(text)
56: if @in_bc ||= nil
57: text
58: else
59: html_esc(text, :html_escape_preformatted)
60: end
61: end