Following most of the same patterns as TextMate snippets, Sublime Text snippets can be a great timesaver. One of the things I’ve been doing recently is assigning keyboard shortcuts to snippets instead of tab expansions, allowing me to apply them to selected text with the $SELECTION placeholder. That, combined with some text mutation offers some serious timesaving options. To illustrate, I thought I’d share a couple of very handy logging snippets.

These are added to the default user keybindings file located in your Sublime application support folder, in the file Packages/User/Default (OSX).sublime-keymap (substitute your OS as needed).

The first thing to note is that you can add a language scope to the keybindings, so that the same keybinding inserts different snippets depending on what language you’re currently working in.

Here are the two logging snippets I use most commonly, one for JavaScript, and one for Objective-C:

{
  // Logging snippets
  // JavaScript
  { "keys": ["alt+shift+l"],
    "command": "insert_snippet",
    "args": {
      "contents": "console.${1:log}(${2:}${SELECTION/;//g});${0}"
    }, 
    "context": [
      { "key": "selector", "operator": "equal", "operand": "source.js", "match_all": true }
    ]
  },

  // Objective-C
  { "keys": ["alt+shift+l"],
    "command": "insert_snippet",
    "args": {
      "contents": "NSLog(@\"${1:%@}\"${1/.*(%\\S+).*|(.+)/(?1:, )/}${2:${SELECTION/;//g}});\n${0}"
    }, 
    "context": [
      { "key": "selector", "operator": "equal", "operand": "source.objc", "match_all": true } 
    ]
  }
}

These add an ⌥⇧L (Option-Shift-L) keybinding. When you trigger it in a JS file, it will insert a console.log() statement. If there is a selection when it’s triggered, the selection will be moved into the arguments for the command. Initially the log keyword is selected, so that you can change it to debug, dir, or any of the available methods in the console API. Hitting TAB from there jumps into the arguments for the command, where you can add a string or object to log. One more TAB jumps the cursor to after the closing semicolon.

In the Objective-C snippet, ⌥⇧L will produce NSLog(@"%@", );. Any current selection will be added to the format string arguments, and you can use placeholders to reference the arguments. The %@ is automatically selected for editing. If you delete the %@ from the format string, the trailing comma will automatically be removed. If you add back any %_ placeholder, the comma will return and TAB will place the cursor into the format arguments.

Between the two of these examples, you should have enough to come up with snippets for debug logging in any language. If you have some awesome snippets to share, please gist them and shoot me a link here or on Twitter!