Register now and start sharing your code snippets.
-->

Generate a TOC for a textile file

Ruby posted about 1 year ago by marko

Takes a textile document as input (reads from a file) and generates a TOC (Table Of Contents) for it. The resulting output is a complete HTML document with the TOC and your document integrated. Requires Redcloth. Usage:

   1  ruby ./textile_to_html_with_toc.rb my_textile_document.tex > my_textile_document.html

NOTE : Does not work with direct copy & paste because of a problem of correctly displaying the escaping quotes of the here document.

   1  #!/usr/bin/env ruby
   2  # author: marko dot haapala at aktagon dot com
   3  # idea taken from here: http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/134005
   4  require "rubygems"
   5  require "redcloth"
   6  
   7  def generate_toc (file_name, headreg)
   8  	document = IO.read(file_name)
   9  	toc = "" 
  10  	document.gsub(headreg) do |match|
  11  		number = $1
  12  		name = $2
  13  		header = name.gsub(/\s/,"+")
  14  		toc << '#' * number.to_i + ' "' + name + '":#' + header + "\n"
  15  	end
  16  	RedCloth.new(toc).to_html
  17  end
  18  
  19  def manipulate_body(file_name, headreg)
  20  	document = IO.read(file_name)
  21  	document.gsub!(headreg) do |match|
  22  		number = $1
  23  		name = $2
  24  		header = name.gsub(/\s/,"+")
  25  		"\nh" + number + '. <a name="' + header + '">' + name + '</a>'
  26  	end
  27  	RedCloth.new(document).to_html
  28  end
  29  
  30  if ARGV[0] == nil 
  31  	puts "Oh no! You didn't give me a filename :(" 
  32  	exit 1
  33  end
  34  
  35  file_name = ARGV[0]
  36  headreg = /^\s*h([1-6])\.\s+(.*)/
  37  toc = generate_toc(file_name, headreg)
  38  body = manipulate_body(file_name, headreg)
  39  template = <<-'EOF'
  40  <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
  41  <html xml:lang=\"en\" lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\">
  42  	<head>
  43  		<title>#{file_name}</title>
  44  		<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=ISO-8859-1\">
  45  		<link rel=stylesheet href=\"style.css\" type=\"text/css\">
  46  	</head>
  47  	<body>
  48  		#{toc}
  49  		#{body}
  50  	</body>
  51  </html>
  52  EOF
  53  puts eval("\"" + template + "\"")

Tagged ruby, redcloth, textile, toc generation