Chris@909
|
1 module CodeRay
|
Chris@909
|
2
|
Chris@909
|
3 # The result of a scan operation is a TokensProxy, but should act like Tokens.
|
Chris@909
|
4 #
|
Chris@909
|
5 # This proxy makes it possible to use the classic CodeRay.scan.encode API
|
Chris@909
|
6 # while still providing the benefits of direct streaming.
|
Chris@909
|
7 class TokensProxy
|
Chris@909
|
8
|
Chris@909
|
9 attr_accessor :input, :lang, :options, :block
|
Chris@909
|
10
|
Chris@909
|
11 # Create a new TokensProxy with the arguments of CodeRay.scan.
|
Chris@909
|
12 def initialize input, lang, options = {}, block = nil
|
Chris@909
|
13 @input = input
|
Chris@909
|
14 @lang = lang
|
Chris@909
|
15 @options = options
|
Chris@909
|
16 @block = block
|
Chris@909
|
17 end
|
Chris@909
|
18
|
Chris@909
|
19 # Call CodeRay.encode if +encoder+ is a Symbol;
|
Chris@909
|
20 # otherwise, convert the receiver to tokens and call encoder.encode_tokens.
|
Chris@909
|
21 def encode encoder, options = {}
|
Chris@909
|
22 if encoder.respond_to? :to_sym
|
Chris@909
|
23 CodeRay.encode(input, lang, encoder, options)
|
Chris@909
|
24 else
|
Chris@909
|
25 encoder.encode_tokens tokens, options
|
Chris@909
|
26 end
|
Chris@909
|
27 end
|
Chris@909
|
28
|
Chris@909
|
29 # Tries to call encode;
|
Chris@909
|
30 # delegates to tokens otherwise.
|
Chris@909
|
31 def method_missing method, *args, &blk
|
Chris@909
|
32 encode method.to_sym, *args
|
Chris@909
|
33 rescue PluginHost::PluginNotFound
|
Chris@909
|
34 tokens.send(method, *args, &blk)
|
Chris@909
|
35 end
|
Chris@909
|
36
|
Chris@909
|
37 # The (cached) result of the tokenized input; a Tokens instance.
|
Chris@909
|
38 def tokens
|
Chris@909
|
39 @tokens ||= scanner.tokenize(input)
|
Chris@909
|
40 end
|
Chris@909
|
41
|
Chris@909
|
42 # A (cached) scanner instance to use for the scan task.
|
Chris@909
|
43 def scanner
|
Chris@909
|
44 @scanner ||= CodeRay.scanner(lang, options, &block)
|
Chris@909
|
45 end
|
Chris@909
|
46
|
Chris@909
|
47 # Overwrite Struct#each.
|
Chris@909
|
48 def each *args, &blk
|
Chris@909
|
49 tokens.each(*args, &blk)
|
Chris@909
|
50 self
|
Chris@909
|
51 end
|
Chris@909
|
52
|
Chris@909
|
53 end
|
Chris@909
|
54
|
Chris@909
|
55 end
|