Chris@0: module CodeRay Chris@0: Chris@0: # = Duo Chris@0: # Chris@0: # A Duo is a convenient way to use CodeRay. You just create a Duo, Chris@0: # giving it a lang (language of the input code) and a format (desired Chris@0: # output format), and call Duo#highlight with the code. Chris@0: # Chris@0: # Duo makes it easy to re-use both scanner and encoder for a repetitive Chris@0: # task. It also provides a very easy interface syntax: Chris@0: # Chris@0: # require 'coderay' Chris@0: # CodeRay::Duo[:python, :div].highlight 'import this' Chris@0: # Chris@0: # Until you want to do uncommon things with CodeRay, I recommend to use Chris@0: # this method, since it takes care of everything. Chris@0: class Duo Chris@0: Chris@0: attr_accessor :lang, :format, :options Chris@0: Chris@0: # Create a new Duo, holding a lang and a format to highlight code. Chris@0: # Chris@0: # simple: Chris@0: # CodeRay::Duo[:ruby, :page].highlight 'bla 42' Chris@0: # Chris@0: # streaming: Chris@0: # CodeRay::Duo[:ruby, :page].highlight 'bar 23', :stream => true Chris@0: # Chris@0: # with options: Chris@0: # CodeRay::Duo[:ruby, :html, :hint => :debug].highlight '????::??' Chris@0: # Chris@0: # alternative syntax without options: Chris@0: # CodeRay::Duo[:ruby => :statistic].encode 'class << self; end' Chris@0: # Chris@0: # alternative syntax with options: Chris@0: # CodeRay::Duo[{ :ruby => :statistic }, :do => :something].encode 'abc' Chris@0: # Chris@0: # The options are forwarded to scanner and encoder Chris@0: # (see CodeRay.get_scanner_options). Chris@0: def initialize lang = nil, format = nil, options = {} Chris@0: if format == nil and lang.is_a? Hash and lang.size == 1 Chris@0: @lang = lang.keys.first Chris@0: @format = lang[@lang] Chris@0: else Chris@0: @lang = lang Chris@0: @format = format Chris@0: end Chris@0: @options = options Chris@0: end Chris@0: Chris@0: class << self Chris@0: # To allow calls like Duo[:ruby, :html].highlight. Chris@0: alias [] new Chris@0: end Chris@0: Chris@0: # The scanner of the duo. Only created once. Chris@0: def scanner Chris@0: @scanner ||= CodeRay.scanner @lang, CodeRay.get_scanner_options(@options) Chris@0: end Chris@0: Chris@0: # The encoder of the duo. Only created once. Chris@0: def encoder Chris@0: @encoder ||= CodeRay.encoder @format, @options Chris@0: end Chris@0: Chris@0: # Tokenize and highlight the code using +scanner+ and +encoder+. Chris@0: # Chris@0: # If the :stream option is set, the Duo will go into streaming mode, Chris@0: # saving memory for the cost of time. Chris@0: def encode code, options = { :stream => false } Chris@0: stream = options.delete :stream Chris@0: options = @options.merge options Chris@0: if stream Chris@0: encoder.encode_stream(code, @lang, options) Chris@0: else Chris@0: scanner.code = code Chris@0: encoder.encode_tokens(scanner.tokenize, options) Chris@0: end Chris@0: end Chris@0: alias highlight encode Chris@0: Chris@0: end Chris@0: Chris@0: end Chris@0: