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.
November 3rd, 2010 at 01:58
I needed something similar. Thanks for posting this.
I wanted something that would simply output converted output, allowing me to pipe it or write it to disk as needed.
This does the trick:
#!/usr/bin/env ruby
require ‘rubygems’
require ‘RedCloth’
if ARGV.size != 1
puts “Usage: textile2html FILE”
exit
end
print RedCloth.new(IO.read(ARGV[0])).to_html