A blogger workflow Saturday, January 17, 2009

I wanted an easy way to write Blogger entries in my usual editor that gave me the ability to do simple formatting and code syntax highlighting. I've basically ported my old on-line workflow from Wordpress: using Markdown and a syntax highlighter (now Pygments, was previously something else in PHP). It's not perfect but good enough for me.

Step 1: Download Pygments and Markdown

Step 2: add Pygments CSS:

./pygmentize -S borland -f html > style.css

Then copy and paste the contents of style.css into your HTML template.

Step 3: Use Sam's crappy Python script

Here is a little script that that integrates the two tools; reads text from stdin and writes HTML to stdout. Copy and paste the HTML into Blogger.

import sys, re
sys.path.append("pylib")

import markdown2 as markdown
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter

def main():
  NORMAL, IN_PRE = 0, 1
  state = NORMAL

  p_lines = []
  n_lines = []
  lang = "python"

  for line in sys.stdin:
    line = line.rstrip()
    if state == NORMAL:
      m = re.match(r'\s*<pre lang="(.*)">', line)
      if m:
        state = IN_PRE
        lang = m.group(1)
      else:
        n_lines.append(line)
    elif state == IN_PRE:
      m = re.match(r'\s*</pre>', line)
      if m:
        state = NORMAL
        n_lines.append( highlight("\n".join(p_lines), get_lexer_by_name(lang),
            HtmlFormatter()) )
        p_lines = []
      else:
        p_lines.append(line)


  if len(n_lines) > 0:
    print markdown.markdown("\n".join(n_lines))

  if len(p_lines) > 0:
    print "Error in <pre>"

if __name__ == '__main__':
  main()

Step 4: Just go back and use Wordpress

Well, maybe. I like not having to maintain a Wordpress blog though.

0 comments: