Chris@909: module CodeRay Chris@909: Chris@909: # = Duo Chris@909: # Chris@909: # A Duo is a convenient way to use CodeRay. You just create a Duo, Chris@909: # giving it a lang (language of the input code) and a format (desired Chris@909: # output format), and call Duo#highlight with the code. Chris@909: # Chris@909: # Duo makes it easy to re-use both scanner and encoder for a repetitive Chris@909: # task. It also provides a very easy interface syntax: Chris@909: # Chris@909: # require 'coderay' Chris@909: # CodeRay::Duo[:python, :div].highlight 'import this' Chris@909: # Chris@909: # Until you want to do uncommon things with CodeRay, I recommend to use Chris@909: # this method, since it takes care of everything. Chris@909: class Duo Chris@909: Chris@909: attr_accessor :lang, :format, :options Chris@909: Chris@909: # Create a new Duo, holding a lang and a format to highlight code. Chris@909: # Chris@909: # simple: Chris@909: # CodeRay::Duo[:ruby, :html].highlight 'bla 42' Chris@909: # Chris@909: # with options: Chris@909: # CodeRay::Duo[:ruby, :html, :hint => :debug].highlight '????::??' Chris@909: # Chris@909: # alternative syntax without options: Chris@909: # CodeRay::Duo[:ruby => :statistic].encode 'class << self; end' Chris@909: # Chris@909: # alternative syntax with options: Chris@909: # CodeRay::Duo[{ :ruby => :statistic }, :do => :something].encode 'abc' Chris@909: # Chris@909: # The options are forwarded to scanner and encoder Chris@909: # (see CodeRay.get_scanner_options). Chris@909: def initialize lang = nil, format = nil, options = {} Chris@909: if format.nil? && lang.is_a?(Hash) && lang.size == 1 Chris@909: @lang = lang.keys.first Chris@909: @format = lang[@lang] Chris@909: else Chris@909: @lang = lang Chris@909: @format = format Chris@909: end Chris@909: @options = options Chris@909: end Chris@909: Chris@909: class << self Chris@909: # To allow calls like Duo[:ruby, :html].highlight. Chris@909: alias [] new Chris@909: end Chris@909: Chris@909: # The scanner of the duo. Only created once. Chris@909: def scanner Chris@909: @scanner ||= CodeRay.scanner @lang, CodeRay.get_scanner_options(@options) Chris@909: end Chris@909: Chris@909: # The encoder of the duo. Only created once. Chris@909: def encoder Chris@909: @encoder ||= CodeRay.encoder @format, @options Chris@909: end Chris@909: Chris@909: # Tokenize and highlight the code using +scanner+ and +encoder+. Chris@909: def encode code, options = {} Chris@909: options = @options.merge options Chris@909: encoder.encode(code, @lang, options) Chris@909: end Chris@909: alias highlight encode Chris@909: Chris@909: # Allows to use Duo like a proc object: Chris@909: # Chris@909: # CodeRay::Duo[:python => :yaml].call(code) Chris@909: # Chris@909: # or, in Ruby 1.9 and later: Chris@909: # Chris@909: # CodeRay::Duo[:python => :yaml].(code) Chris@909: alias call encode Chris@909: Chris@909: end Chris@909: Chris@909: end