New and improved TextMate and Markdown links

As a followup to this post about making reference-style links for Markdown documents in TextMate, I’ve made an improvement to the command so that the reference numbers increment as you add links to the document.

The new command was “inspired” (i.e., stolen from) Fred B. of the TextMate mailing list. He rewrote my original command in Ruby and added the incrementing reference number. I, in turn, have retranslated back to Perl and made one small change: Fred’s command uses the number of the last reference-style link in the document as the number to increment; mine uses the highest-numbered reference-style link. In most cases, the two commands will work the same way, but mine is more forgiving of people like me who go back and make additions and deletions that get the reference numbers out of sequence.

To make the distinction a bit more concrete, suppose a series of cuts and pastes left you with a reference section that looked like this:

[1]: http://www.leancrew.com/all-this
[3]: http://www.macromates.com
[2]: http://www.daringfireball.net/markdown

My command will create a reference-style link with a default reference number of 4 rather than another 3. (I’m pretty sure Fred’s would give you a 3, although my Ruby interpretation may be faulty.)

So how do you create and use this spectacular piece of code? Basically, you follow all the steps given in my previous post on this topic, but you use the following command instead of the one given there.

#!/usr/bin/perl
use List::Util qw(max);

$text = $ENV{'TM_SELECTED_TEXT'};

# Get the highest-numbered reference.
@nums = $text =~ /^\[(\d+)\]: /mg;
$n = max(@nums) + 1;

# Escape special characters.
$text =~ s/([\$\\`])/\\$1/g;

# Insert the snippet.
print '[${1:description}][${2:' . $n . '}]$0'.
       $text . '[$2]: ${3:http://}' . "\n";

Happy linking!

Update (March 7): I cleaned up the code a bit and used the List::Utils max function instead of my own.

I’d like to make it so selected text could be turned into a reference-style link, but I’m worried about how much that will complicate the code. At present, we have a macro calling a command that inserts a snippet; adding the functionality I want will probably add at least two more levels of indirection.