comparison vendor/plugins/coderay-0.9.2/lib/coderay/duo.rb @ 0:513646585e45

* Import Redmine trunk SVN rev 3859
author Chris Cannam
date Fri, 23 Jul 2010 15:52:44 +0100
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:513646585e45
1 module CodeRay
2
3 # = Duo
4 #
5 # A Duo is a convenient way to use CodeRay. You just create a Duo,
6 # giving it a lang (language of the input code) and a format (desired
7 # output format), and call Duo#highlight with the code.
8 #
9 # Duo makes it easy to re-use both scanner and encoder for a repetitive
10 # task. It also provides a very easy interface syntax:
11 #
12 # require 'coderay'
13 # CodeRay::Duo[:python, :div].highlight 'import this'
14 #
15 # Until you want to do uncommon things with CodeRay, I recommend to use
16 # this method, since it takes care of everything.
17 class Duo
18
19 attr_accessor :lang, :format, :options
20
21 # Create a new Duo, holding a lang and a format to highlight code.
22 #
23 # simple:
24 # CodeRay::Duo[:ruby, :page].highlight 'bla 42'
25 #
26 # streaming:
27 # CodeRay::Duo[:ruby, :page].highlight 'bar 23', :stream => true
28 #
29 # with options:
30 # CodeRay::Duo[:ruby, :html, :hint => :debug].highlight '????::??'
31 #
32 # alternative syntax without options:
33 # CodeRay::Duo[:ruby => :statistic].encode 'class << self; end'
34 #
35 # alternative syntax with options:
36 # CodeRay::Duo[{ :ruby => :statistic }, :do => :something].encode 'abc'
37 #
38 # The options are forwarded to scanner and encoder
39 # (see CodeRay.get_scanner_options).
40 def initialize lang = nil, format = nil, options = {}
41 if format == nil and lang.is_a? Hash and lang.size == 1
42 @lang = lang.keys.first
43 @format = lang[@lang]
44 else
45 @lang = lang
46 @format = format
47 end
48 @options = options
49 end
50
51 class << self
52 # To allow calls like Duo[:ruby, :html].highlight.
53 alias [] new
54 end
55
56 # The scanner of the duo. Only created once.
57 def scanner
58 @scanner ||= CodeRay.scanner @lang, CodeRay.get_scanner_options(@options)
59 end
60
61 # The encoder of the duo. Only created once.
62 def encoder
63 @encoder ||= CodeRay.encoder @format, @options
64 end
65
66 # Tokenize and highlight the code using +scanner+ and +encoder+.
67 #
68 # If the :stream option is set, the Duo will go into streaming mode,
69 # saving memory for the cost of time.
70 def encode code, options = { :stream => false }
71 stream = options.delete :stream
72 options = @options.merge options
73 if stream
74 encoder.encode_stream(code, @lang, options)
75 else
76 scanner.code = code
77 encoder.encode_tokens(scanner.tokenize, options)
78 end
79 end
80 alias highlight encode
81
82 end
83
84 end
85