1/28/2009

CPP File To HTML

Recently, I written converter program with ruby, It is enable to convert a source file of c plus plus to html format.

The converter program can change tab space to span tag of html, and color keywords.
Color of keywords is blue.

Next code is converter program.

#!/usr/bin/ruby

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 =~ /(typedef)/ ) 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 =~ /(using namespace)/ ) 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 =~ /(for)/ ) then

arg.gsub!($1, "<span style=\"color:blue;\"><b>" + $1 + "</b></span>")

end

if(arg =~ /(void)/ ) then

arg.gsub!($1, "<span style=\"color:blue;\"><b>" + $1 + "</b></span>")

end

if(arg =~ /(int)/ ) then

arg.gsub!($1, "<span style=\"color:blue;\"><b>" + $1 + "</b></span>")

end

if(arg =~ /(double)/ ) then

arg.gsub!($1, "<span style=\"color:blue;\"><b>" + $1 + "</b></span>")

end

if(arg =~ /(char)/ ) then

arg.gsub!($1, "<span style=\"color:blue;\"><b>" + $1 + "</b></span>")

end

if(arg =~ /(#include)/ ) 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

if( ARGV[0] == nil ) then

puts " Usage: cpp2html.rb sourcefile"

puts " Sourcefile must be cplusplus source file."

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 ( /\}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 ( /\s*\{/ =~ line )



# converting

# check key wards

line = convertKeyWords(line)

line.gsub!(/^\s+/, tmp)

line += "<br>\n"

puts line

end

puts "</HTML>"

end

No comments: