domingo, 1 de enero de 2012

Using restructuredtext in Blogger

Note

Updated 2012-0109: Added capability to clean_white_spaces.py to accept parameters

When I first blogged about restructuredText [1] I thought I had found a cool way to use TextMate for blogging.

My workflow was:

  1. Type the post in TextMate in restructuredText format.
  2. Run rst2thml.
  3. Open the html file
  4. Copy the tags inside <body> tag to Blogger.
  5. Edit the post in blogger to eliminate the white spaces.

This is not so bad. Until I wanted to update a rather long post I had. I realized that I would have to redo all my steps.

I had read about rst2wp which is a tool to convert to WordPress [2] and found out someone had adapted a script for blogger [3].

Installing rst2bs

These are the step I took to install rst2bs in my Mac with Lion Os X.

  1. Download the script from http://gitorious.org/mles/mles/trees/master by click on Download master as tar.gz
  2. Double click on mles-mles-master.tar.gz.
  3. Open terminal and run the following commands:

    sudo cp ~/Downloads/mles-mles/rst2bs.py /usr/local/bin/

    chmod 755 /usr/local/bin/rst2bs.py

  4. Test it

    rst2bs.py installing_pygments.rst installing_pygments_bs.html

Eliminating White Spaces

For that I wrote a simple Python script. Please bare in mind that my Python skill are almost non existent.

My clean_white_spaces.py reads:


import sys;

fd = open(sys.argv[1])
contents = fd.readlines()
fd.close()
new_contents = []

of = open(sys.argv[2], "w")
print "Eliminanting white spaces from " + sys.argv[1] + " to " + sys.argv[2]
# Get rid of empty lines
pre = False
line_num = 0
for line in contents:
line_num += 1
find_open_pre = "<pre>" in line
find_close_pre = "</pre>" in line
if find_open_pre:
print "PRE FOUND OPEN " + str(line_num)
pre = True
if find_close_pre:
print "PRE FOUND CLOSE " + str(line_num)
pre = False
if not pre:
# Strip whitespace, should leave nothing if empty line was just "\n"
if not line.strip():
continue
# We got something, save it
else:
new_contents.append(line.rstrip('\n'))
else:
new_contents.append(line)
of.writelines(new_contents)
of.close

# Print file sans empty lines
#print "".join(new_contents)
print "Finished"

This script will strip the white spaces if they are not within a <pre> tag.

Run it with the html generated by rst4bs.

python clean_white_spaces.py installing_pygments_bs.html installing_pygments_bs_clean.html

References

[1]Installing restructuredText Bundle for TextMate http://tecnofuenteabierta.blogspot.com/2011/12/installing-restructuredtext-bundle-for.html
[2]Using ReStructured Text with WordPress http://blog.mafr.de/2008/03/22/using-rst-with-wordpress/
[3]Some Twist on the Blog http://grissiom.blogspot.com/2009/12/some-twist-on-blog.html

No hay comentarios:

Publicar un comentario