Thursday, June 19, 2008

Ruby code colorize

ultravioletというライブラリを使って
ソースコードをTextMateのcobaltでHTML化するツールを作成

(使い方)
$ ruby code2html.rb < rubyfile.rb > destination.html

          

   1  #!/usr/bin/env ruby -wKU

   2  # encoding: utf-8

   3  require "rubygems"

   4  require "uv"

   5  

   6  BACKGROUND_COLOR = '#002444'

   7  COLOR = '#e6e1dc'

   8  COLORS = {

   9  #  :punctuation => '#E1EFFF',

  10    :constant => '#FF628C',

  11    :entity => '#FFDD00',

  12    :keyword => '#FF9D00',

  13    :storage => '#FFEE80',

  14    :string => '#3AD900',

  15    :comment => '#0088FF',

  16    :support => '#80FFBB',

  17    :variable => '#CCCCCC',

  18    :symbol => '#6e9cbe',

  19    :JEntityNameType => '#FFDD00',

  20    :attribute => '#d0d0ff',

  21    :StringRegexp => '#80FFC2',

  22    :StringEmbeddedSource => '#FFFFFF',

  23    :exception => '#FF1E00',

  24    :function => '#FFEE80'

  25  }

  26    html = Uv.parse(STDIN.read, "xhtml", "ruby", true, 'cobalt')

  27    

  28    COLORS.each do |token, color|

  29      html.gsub!(/class="#{token}"/i, %Q{style="color:#{color}"})

  30    end

  31    puts %Q(

  32            <pre style="background-color:#{BACKGROUND_COLOR};

  33            color:#{COLOR};

  34            padding:3px 0 3px 0;

  35            overflow:auto;

  36            line-height:15px;

  37            font-size:13px";>

  38            <code>#{html}</code>

  39            </pre>

  40          )


          


参考:Colorize code in your blog posts (with Ruby of course) « Marc-André Cournoyer's blog

No comments: