Textile to XHTML converter

A while back, I needed to quickly write some documentation that needed to be in XHTML format. Writing in plain XHTML is a pain, so I decided to write the documentation in Textile and then convert it to XHTML before publishing.

The problem I found was that all Textile converters were made for use in blogs and other online tools. What I needed was a good old-fashioned command line program to convert a given textile file into XHTML.

Fortunately, using Ruby and the excellent RedCloth gem, I could write a small script to accomplish this in a few minutes.

If you have any similar needs, copy the source into a file named textile2html, make it executable (chmod +x) and place it somewhere in your path. Then all you have to do is call textile2html with the textile file as an argument:

$ textile2html documentation.textile
#!/usr/bin/env ruby -wKU
require "rubygems"
require "RedCloth"

if ARGV.size != 1
puts "Usage: textile2html file.textile"
exit
end

# Read input file
textile_string = ""
begin
  input_file = File.new(ARGV[0], "r")
  input_file.each do |line|
    textile_string+=line
  end
  input_file.close
rescue
  puts "Could not read input file."
  exit
end

# Create output file
filename = ARGV[0].gsub(/\.\w+$/, "")
begin
  output_file = File.new("#{filename}.html", "w")
rescue
  puts "Could not create output file."
  exit
end

html_header = <<DOC
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>
DOC

html_header += filename;
html_header += <<DOC
</title>
</head>
<body>
DOC

html_footer = <<DOC
</body>
</html>
DOC

html_output = RedCloth.new(textile_string).to_html
output_file.puts(html_header)
output_file.puts(html_output)
output_file.puts(html_footer)
output_file.close

puts "Done."

Questions? Comments? Post them below.



Tags: ,
This entry was posted on Friday, January 22nd, 2010 at 13:42 and is filed under Programming, Software. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Reply

Your comment

Powered by WP Hashcash