Using previously highlighted text in TextMate snippets

In a previous (and very verbose) post on TextMate snippets, I showed a snippet to easily and simply use a tab trigger to insert a try... catch statement. If you missed it feel free to catch up here. The idea was that you type in try, press tab and TextMate spits out:

try {

} catch(e) {


Now, the cursor is automatically positioned inside the try block, and the next time you press tab it moves to the catch block. Pressing tab again moves you outside the block. This is great, but not hugely useful in the real world. What would be more likely than writing an empty try... catch statement up-front would be to write some code, and choose to surround it in the try block. I promised to tell you how to do that, and it is much simpler than I thought.

The answer is the TextMate variable $TM_SELECTED_TEXT. It does exactly what it says it does, but you can’t use a tab trigger to achieve our goal here. Highlight some text, and start typing and of course, the text is overwritten. In this instance, a tab trigger will not do. You need to use a "Key Equivalent" (or hotkey or shortcut key to the rest of us). In my instance, I have more than enough of those to remember already, thankyouverymuch, and so I highlight the text and do one of the following:

  • Click the Bundle menu item at the top of the screen and drill down to my snippet
  • Press Ctrl+Escape and drill down to my snippet
  • Or, my favourite, press Ctrl+Command+T to bring up a list of all the snippets, type "try" to filter the list, and press return

There is nothing to stop you just typing try and pressing return either.

Here is the final snippet:

try ... catch
Tab trigger:
try {
} catch(e) {

try... catch TextMate Bundle Editor Example

Note that there should be a trailing extra carriage return, to ensure the final tab takes us out on to the line following the block.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>