A TextMate Command for fast abbr tags

[Tweet : ADN : nvALT]

I’m on a roll with stupid scripts today, but it’s Saturday… so, whatever. This is a quick command for creating semantic <abbr> tags in TextMate. It’s short, but pretty smart: if your text is a mix of upper and lowercase letters, it will take the uppercase letters, in order, and create an acronym from them and insert an <abbr> tag, using the original input as the title attribute. If it’s one of a couple other scenarios, it will give you the <abbr> tag setup with your cursor in a logical place to fill in the blanks.

In case you’re wondering why I’m using the wrong tag for my acronyms, the HTML5 spec pretty much does away with the <acronym> tag, and <abbr> appears to be the new, all-purpose solution. It’s not perfectly semantic, but there doesn’t seem to be an ideal solution for acronyms in the spec. This command is really geared toward using the <abbr> for acronyms, but you could easily alter it to insert an <acronym> tag (especially if your doctype is anything other than ‘html’), and it works pretty well for just quickly creating an actual abbreviation, too. It just doesn’t try to guess how to abbreviate anything other than apparent acronyms, but it gives you Snippet tab stops for quick manual editing. If you run it with no selection, it will create a blank <abbr> tag you can tab through and fill in.

To use the command, just create a new TextMate Command in the Bundle Editor, preferably in your own personal bundle (create a new bundle with your name, if you need to). Set the Input to “Selected Text” or “Word”, and the output to Insert as Snippet. Assign a key equivalent if you like. Since it’s outputting HTML, it probably makes sense to set the Scope Selector field to “text.html”, but who knows, you may prefer to use it outside of normal HTML source documents. Once it’s set up, add the code below.

#!/usr/bin/env ruby -rjcode -Ku

input = STDIN.read

if input =~ /^[A-Z]+$/
  print %Q{<abbr title="$1">#{input}</abbr>$0}
  acronym = input.scan(/[A-Z]/).join()
  if acronym.length < 2
    print %Q{<abbr title="${1:#{input}}">$2</abbr>$0}
    print %Q{<abbr title="#{input}">${1:#{acronym}}</abbr>$0}

It’s probably not useful on a frequent enough basis be memorable in cases where you’d actually need it, but there it is. It’s actually a small part of a larger experiment I played with today. I’ll probably post about it this weekend, as it’s useful not just with <abbr> tags, but with any tag with a descriptive attribute. Just a few lines of jQuery which can make the PTWW be more immediately useful, accessible and, well, look cooler.

And yes, I did just make that acronym markup with the above TextMate Command. I feel like a salesman who sells people things which seem perfect for situations they’ll never find themselves in.