Sha256: 224a3af81435aac605df00790a259276872702564fc8123b7da14b44bdb911af

Contents?: true

Size: 1.7 KB

Versions: 6

Compression:

Stored size: 1.7 KB

Contents

require 'coderay'

require 'rabbit/utils'
require 'rabbit/parser/ext/escape'

module Rabbit
  module Parser
    module Ext
      module CodeRay
        include GetText

        module_function
        def highlight(lang, text, logger)
          tokens = ::CodeRay.scan(text.strip, lang.to_sym)
          tokens.encode(RabbitEncoder.new)
        end

        class RabbitEncoder < ::CodeRay::Encoders::Encoder
          include Element

          def setup(options)
            super
            @out = SyntaxHighlightingBlock.new
            @elements = [@out]
          end

          def text_token(text, type=:plain)
            p [:text, type, text] if Utils.syntax_highlighting_debug?
            escaped_text = Escape.escape_meta_character(text)
            text_element = SyntaxHighlightingText.new(Text.new(escaped_text))
            tag_name = type.to_s.gsub(/_/, '-')
            CustomTag.new("syntax-#{tag_name}", text_element)
          end

          def open_token(kind)
            p [:open, kind] if Utils.syntax_highlighting_debug?
            @out = TextContainer.new
            @elements << @out
            CustomTag.new("syntax-#{kind}")
          end

          def begin_line(kind)
            p [:begin_line, kind] if Utils.syntax_highlighting_debug?
            nil
          end

          def end_line(kind)
            p [:end_line, kind] if Utils.syntax_highlighting_debug?
            nil
          end

          def close_token(kind)
            p [:close, kind] if Utils.syntax_highlighting_debug?
            block = @elements.pop
            @out = @elements.last
            block
          end

          def finish(options)
            super
          end
        end
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
rabbit-1.0.5 lib/rabbit/parser/ext/coderay.rb
rabbit-1.0.4 lib/rabbit/parser/ext/coderay.rb
rabbit-1.0.3 lib/rabbit/parser/ext/coderay.rb
rabbit-1.0.2 lib/rabbit/parser/ext/coderay.rb
rabbit-1.0.1 lib/rabbit/parser/ext/coderay.rb
rabbit-1.0.0 lib/rabbit/parser/ext/coderay.rb