Sha256: 4b386b018d2fd35c6ecc8747a3b616eefb6deb6b1d8f5670fb5cb182e790e3bd

Contents?: true

Size: 1.44 KB

Versions: 26

Compression:

Stored size: 1.44 KB

Contents

require 'syntax/convertors/abstract'

module Syntax
  module Convertors

    # A simple class for converting a text into HTML.
    class HTML < Abstract

      # Converts the given text to HTML, using spans to represent token groups
      # of any type but <tt>:normal</tt> (which is always unhighlighted). If
      # +pre+ is +true+, the html is automatically wrapped in pre tags.
      def convert( text, pre=true )
        html = ""
        html << "<pre>" if pre
        regions = []
        @tokenizer.tokenize( text ) do |tok|
          value = html_escape(tok)
          case tok.instruction
            when :region_close then
              regions.pop
              html << "</span>"
            when :region_open then
              regions.push tok.group
              html << "<span class=\"#{tok.group}\">#{value}"
            else
              if tok.group == ( regions.last || :normal )
                html << value
              else
                html << "<span class=\"#{tok.group}\">#{value}</span>"
              end
          end
        end
        html << "</span>" while regions.pop
        html << "</pre>" if pre
        html
      end

      private

        # Replaces some characters with their corresponding HTML entities.
        def html_escape( string )
          string.gsub( /&/, "&amp;" ).
                 gsub( /</, "&lt;" ).
                 gsub( />/, "&gt;" ).
                 gsub( /"/, "&quot;" )
        end

    end

  end
end

Version data entries

26 entries across 26 versions & 3 rubygems

Version Path
syntax-1.2.1 lib/syntax/convertors/html.rb
syntax-1.2.0 lib/syntax/convertors/html.rb
syntax-1.1.0 lib/syntax/convertors/html.rb
vanity-1.7.1 vendor/ruby/1.9.1/gems/syntax-1.0.0/lib/syntax/convertors/html.rb
syntax-1.0.0 lib/syntax/convertors/html.rb
syntax-0.7.0 lib/syntax/convertors/html.rb
typo-3.99.0 vendor/syntax/lib/syntax/convertors/html.rb
typo-3.99.3 vendor/syntax/lib/syntax/convertors/html.rb
typo-3.99.2 vendor/syntax/lib/syntax/convertors/html.rb
typo-3.99.1 vendor/syntax/lib/syntax/convertors/html.rb
typo-4.0.1 vendor/syntax/lib/syntax/convertors/html.rb
typo-3.99.4 vendor/syntax/lib/syntax/convertors/html.rb
typo-4.0.0 vendor/syntax/lib/syntax/convertors/html.rb
typo-4.0.2 vendor/syntax/lib/syntax/convertors/html.rb
typo-4.0.3 vendor/syntax/lib/syntax/convertors/html.rb
typo-4.1.1 vendor/syntax/lib/syntax/convertors/html.rb
typo-5.0.1 vendor/syntax/lib/syntax/convertors/html.rb
typo-4.1 vendor/syntax/lib/syntax/convertors/html.rb
typo-5.0.2 vendor/syntax/lib/syntax/convertors/html.rb
typo-5.0.3.98.1 vendor/syntax/lib/syntax/convertors/html.rb