Firehed's Blog

Handy TextMate snippet for div comments

I like having lots of comments in my HTML for readability, specifically when dealing with divs.  So I'll have

<div id="someid" class="class1 class2">
content
</div><!-- #someid.class1.class2 -->

I'm not exactly the great RegEx expert that's required to figure out how to make that kind of thing come automagically from the standard TextMate snippet for HTML divs, but quite by accident I found that the h1 snippet does something along those lines, in that it converts any spaces to underscores.  Net result?

<div${1: id="${2:someID}"}${3: class="${4:someClass}"}>
    ${0:$TM_SELECTED_TEXT}
</div> <!-- #${2/[[:alpha:]]+|( )/(?1:#:\L$0)/g}.${4/[[:alpha:]]+|( )/(?1:.:\L$0)/g} -->

Yeah, gross.  Just replace the snippet for div with that load of insanity in TextMate's bundle editor and you should be good to go.  It's a tiny bit quirky in that it has to lead with the initial # and . for the id and class respectively, so if you don't have a class set on the div you'll still have a comment looking like <!-- #someid. --> instead of <!-- #someid --> (note the extra period), or vice-versa.  Close enough for government work.

Obviously you could extend that same horrible regex out to other things where you want automatic comments - most block-level elements would be a decent choice.  Note that there's two of them in there - grab the ${someNumber/} bit, and make sure that the number matches the right part of the snippet.

Have fun.