Tags from keywords in TextMate

I’ve been using TextMate’s blogging bundle for quite a while. I’m sure MarsEdit and Ecto have their advantages, but I’m so used to the TM environment, I like to write everything in it. (It should go without saying that Movable Type’s builtin text entry page is just awful, but I’ll say it anyway: Movable Type’s builtin text entry page is just awful.)

I try to add Technorati-style tags to the bottom of each post, and I wrote a couple of snippets to make that easier. But now I have a better way. I use the Keywords header line at the top of my post and run a TM command to extract the keywords from that line to construct an HTML stanza of Technorati tags. Here’s what the command looks like in the Bundle Editor (you can click on the image to see a full-sized version):

The command is pretty straightforward:

 1:  #!/usr/bin/env python
 2:  
 3:  import sys, re
 4:  
 5:  # Get the list of keywords.
 6:  kwline = re.compile(r'Keywords:')
 7:  for line in sys.stdin:
 8:    if kwline.match(line):
 9:      keywords = line.split(":")[1].strip().split()
10:      break
11:  
12:  # Make a list of tag anchors from the keywords.
13:  tag_template = '<a href="http://technorati.com/tag/%s" rel="tag">%s</a>'
14:  tags = [tag_template % (x, x) for x in keywords]
15:  
16:  # Wrap the tags in a paragraph.
17:  group_template = """<!-- technorati tags start -->
18:  <p class="tags">Tags: %s</p>
19:  <!-- technorati tags end -->"""
20:  
21:  print group_template % "\n".join(tags)

The only complex part is line 9, where I’ve clumped three or four things together: splitting the Keywords line at the colon, stripping the leading and trailing whitespace from the part after the colon, and splitting the resulting string into a list of words.

As you can see in the screenshot, the command’s input is set to Entire Document and its ouput is Insert as Text. I activate it through a Tab Trigger of “kw.” The scope is set to “text.blog” so it can work in either HTML or Markdown blog formats (I have no idea whether the Text or Textile formats accept HTML—if they do, this command will also work with those formats).

As an example, this post (written in Markdown) has a Keywords line of

Keywords: mac textmate blogging movabletype technorati markdown

which leads to a tags stanza of

<!-- technorati tags start -->
<p class="tags">Tags: <a href="http://technorati.com/tag/mac" rel="tag">mac</a>
<a href="http://technorati.com/tag/textmate" rel="tag">textmate</a>
<a href="http://technorati.com/tag/blogging" rel="tag">blogging</a>
<a href="http://technorati.com/tag/movabletype" rel="tag">movabletype</a>
<a href="http://technorati.com/tag/technorati" rel="tag">technorati</a>
<a href="http://technorati.com/tag/markdown" rel="tag">markdown</a></p>
<!-- technorati tags end -->

Tags: