Class: Prawn::ManualBuilder::SyntaxHighlight

Inherits:
Object
  • Object
show all
Defined in:
lib/prawn/manual_builder/syntax_highlight.rb

Constant Summary collapse

DEFAULT_STYLE =
{ color: 'FFFFFF' }.freeze
STRING_STYLE =
{ color: '56D65E' }.freeze
COMMENT_STYPE =
{ color: 'AEAEAE' }.freeze
CONSTANT_STYLE =
{ color: '88A5D2' }.freeze
IVAR_STYLE =
{ color: 'E8ED97' }.freeze
NUMBER_STYLE =
{ color: 'C8FF0E' }.freeze
EMBEXPR_STYLE =
{ color: 'EF804F' }.freeze
KEYWORD_STYLE =
{ color: 'FEE100' }.freeze
SYMBOL_STYLE =
{ color: 'C8FF0E' }.freeze
METHOD_STYLE =
{ color: 'FF5C00' }.freeze

Instance Method Summary collapse

Constructor Details

#initialize(code) ⇒ SyntaxHighlight

Returns a new instance of SyntaxHighlight.



17
18
19
# File 'lib/prawn/manual_builder/syntax_highlight.rb', line 17

def initialize(code)
  @code = code
end

Instance Method Details

#to_prawnObject



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/prawn/manual_builder/syntax_highlight.rb', line 21

def to_prawn
  tokens.each_with_index.map do |token, index|
    style =
      case token.type
      when :STRING_BEGIN, :STRING_CONTENT, :STRING_END, :HEREDOC_START, :HEREDOC_END
        STRING_STYLE
      when :COMMENT
        COMMENT_STYPE
      when :CONSTANT
        CONSTANT_STYLE
      when :INSTANCE_VARIABLE
        IVAR_STYLE
      when :INTEGER, :FLOAT, :INTEGER_RATIONAL, :INTEGER_IMAGINARY
        NUMBER_STYLE
      when :EMBEXPR_BEGIN, :EMBEXPR_END
        EMBEXPR_STYLE
      when /\AKEYWORD_/
        KEYWORD_STYLE
      when :SYMBOL_BEGIN, :LABEL
        SYMBOL_STYLE
      when :IDENTIFIER
        case tokens[index - 1].type
        when :SYMBOL_BEGIN
          SYMBOL_STYLE
        when :DOT
          METHOD_STYLE
        else
          DEFAULT_STYLE
        end
      else
        DEFAULT_STYLE
      end
    { text: token.value.gsub(' ', Prawn::Text::NBSP) }.merge(style)
  end
  .compact
  .each_with_object([]) do |fragment, fragments|
    if fragments.empty?
      fragments << fragment
    elsif fragments.last.reject { |k, _| k == :text} == fragment.reject { |k, _| k == :text } || fragment[:text].match?(/\A[#{Prawn::Text::NBSP}\s\t\r\n]*\z/)
      fragments.last[:text] << fragment[:text]
    else
      fragments << fragment
    end
  end
end