Tuesday, February 3, 2009


Here's the code for formatting using my new script.

# == Synopsis
# Modifies a file to put it into a Maraku format for
# syntax highlighting
# == Usage
# ruby blogfmt.rb file1 file2 ... filen
# == Author
# Scott LaBounty
# == Copyright
# Copyright(c) 2009 Scott LaBounty

require 'getoptlong'
require 'rdoc/usage'
require 'maruku'

# Main Program

if __FILE__ == $0

# Set up the command line options
opts = GetoptLong.new(
["--verbose", "-v", GetoptLong::NO_ARGUMENT],
["--help", "-h", GetoptLong::NO_ARGUMENT]

# Set the default values for the options
verbose = false

# Parse the command line options. If we find one we don't recognize
# an exception will be thrown and we'll rescue with a RDoc::usage
opts.each do | opt, arg|
case opt
when "--help"
when "--verbose"
verbose = true

s = ""
ARGV.each do | fileName |
puts "fileName = #{fileName}" if verbose

# Make sure the file exists
if (File.exist?(fileName)) then

# Open the file
File.open(fileName) do | file |

# For each line in the file
file.each_line do | line |
s += " #{line}"

puts "Could not find #{fileName}"
# Add in the Maraku format for ruby syntax
s += '{:lang=ruby html_use_syntax=true}'

# Convert the file we read in to HTML.
h = Maruku.new(s).to_html_document

# Remove everything up to and including the <body> tag.
h.sub!(/^.*<body>/m, "")

# Remove the closing <body> tag and everything past.
h.sub!(/<\/body>.*$/m, "")

# Print the string which should be everything between the <pre> ... </pre>
puts h

Blogger magically started highlighting everything this morning, so I'm going to assume that it's good, although it's only been tested on our hello.rb example and itself. If anyone uses this, let me know how it works for you.

The code itself is based on a simplistic cat program that I wrote a while back. I tend to use it regularly as a base for programs that loop through files, do something to each line, and then print the (possibly) modified line back out.

No comments:

Post a Comment