A command line syntax highlighter written in Ruby

Here is the syntax highlighting cat, which I shall call cax.

#!/usr/bin/env ruby
require 'syntax/convertors/html'
require 'rainbow'

filename = ARGV[0]
puts ARGV[0]

line_num=0

tokenizer = Syntax.load "ruby"

file = File.new(filename,"r")
while (line = file.gets)

c_line = ""

tokenizer.tokenize( line ) do |token|
case token.group.to_s
when "string" then c_line = c_line + token.color(:green)
when "ident" then c_line = c_line + token.color(:magenta)
when "normal" then c_line = c_line + token.color(:cyan)
when "keyword" then c_line = c_line + token.color(:red)
when "punct" then c_line = c_line + token.color(:white)
when "symbol" then c_line = c_line + token.color(:white)
when "number" then c_line = c_line + token.color(:white)
when "expr" then c_line = c_line + token.color(:white)
when "comment" then c_line = c_line + token.color(:yellow)
when "constant" then c_line = c_line + token.color(85,85,85) # only named colors show on win32
else c_line = c_line + "  group: #{token.group}"
end
end

line_num = line_num + 1

print (line_num.to_s.rjust(4) + ":").color(:white) + c_line

end

And this is what the output looks like:

It’s obviously missing the theming of the coloured output which I could add in another version.

It requires the rainbow and syntax gems to get working. and on windows you’ll need the win32console gem to see the colours.

This entry was posted in Uncategorized by admin. Bookmark the permalink.

Comments are closed.