Rubyのソースをhtmlへ
急遽,Rubyのソースをhtml表示できるようなコンバートが必要になりました…
取り急ぎこんな感じで,
#!/usr/bin/ruby =begin The work of this program is to convert from a source file to a html code in display. Converting rule: * TAB A tab is converted to <span style="margin-left:20px;">. * RESERVED WORDS Reserved words which are if, class and so on is coloring blue. =end def convertKeyWords(arg) if(arg =~ /\".*(<).*\"/ ) then arg.gsub!($1, "<") end if(arg =~ /\".*(>).*\"/ ) then arg.gsub!($1, ">") end if( arg =~ /(if)/ ) then arg.gsub!($1, "<span style=\"color:blue;\"><b>" + $1 + "</b></span>") end if(arg =~ /(then)/ ) then arg.gsub!($1, "<span style=\"color:blue;\"><b>" + $1 + "</b></span>") end if(arg =~ /(class)/ ) then arg.gsub!($1, "<span style=\"color:blue;\"><b>" + $1 + "</b></span>") end if(arg =~ /(end)$/ ) then arg.gsub!($1, "<span style=\"color:blue;\"><b>" + $1 + "</b></span>") end if(arg =~ /(while)/ ) then arg.gsub!($1, "<span style=\"color:blue;\"><b>" + $1 + "</b></span>") end if(arg =~ /(def)/ ) then arg.gsub!($1, "<span style=\"color:blue;\"><b>" + $1 + "</b></span>") end if(arg =~ /^(begin)/ ) then arg.gsub!($1, "<span style=\"color:blue;\"><b>" + $1 + "</b></span>") end if(arg =~ /(unless)/ ) then arg.gsub!($1, "<span style=\"color:blue;\"><b>" + $1 + "</b></span>") end if(arg =~ /(#.*)/ ) then arg.gsub!($1, "<span style=\"color:green;\"><b>" + $1 + "</b></span>") end arg end =begin Main thiread =end begin if( ARGV[0] == nil ) then puts " Usage: src2html.rb sourcefile" puts " Sourcefile must be ruby program." exit(1); end puts "<HTML>\n<HEAD>\n<TITLE>\n" + ARGV[0]+ "\n</TITLE>\n</HEAD>\n" unless FileTest::file?(ARGV[0]) then puts "not file" end sourcefile = File.new(ARGV[0]); comment_count = 0 indent_count = 0; while line = sourcefile.gets() if (/^=begin/ =~ line) then comment_count = 1; next end if (/^=end/ =~ line) then comment_count = 0; next end next if (comment_count == 1 ) line = line.chop next if( line.empty? ) # count indent # Following code is error! ToDo indent_count -= 1 if ( /end\s*$/ =~ line ) # convert from tab to style tmp = "" for i in 0...indent_count tmp += "<span style=\"margin-left:20px;\">" end # count indent indent_count += 1 if ( /^begin/ =~ line ) indent_count += 1 if ( /\sthen/ =~ line ) indent_count += 1 if ( /while\s/ =~ line ) indent_count += 1 if ( /def\s/ =~ line ) indent_count += 1 if ( /for\s/ =~ line ) # converting # check key wards line = convertKeyWords(line) line.gsub!(/^\s+/, tmp) line += "<br>\n" puts line end puts "</HTML>" end
近いうちにしっかり作り直す気がする。