One such package I recently discovered that is extremely helpful is something called SnipMate. If you’re coming from TextMate, you’ve probably heard of snippets and know how much of a lifesaver it can be. SnipMate is the exact same thing for Vim. I’m going to show you how you can use Vim SnipMate to code faster.

Ctrl/Cmd-V on Steroids

Typically when coding in Javascript, I use logging to make sure the logic works and the callbacks are fired appropriately. I would type console.log(somethingToLog);. Doesn’t seem like much to type, but what if I suddenly wanted to sprinkle a few loggings into my code, and perhaps I needed to add them in multiple files? I could type out console.log(somethingToLog); each time, or just copy and paste them and change the parameter accordingly.

Or I could just use SnipMate and type log then hit <TAB>, and it immediately changes to console.log(somethingToLog). If I hit <TAB> again, the cursor jumps to somethingToLog where I can replace with whatever parameter I want. Done. No ctrl/cmd-c then ctrl/cmd-v. And no more typing out console.log.

Boilerplate Built-In

What SnipMate essentially does is it has recipes that stores shortcut text, or commands if you will, to code snippets inside snippet files. log in the above example would be the command, while console.log(somethingToLog); would be the code snippet. By hitting <TAB> right after typing the command, SnipMate replaces the entire command with the resulting snippet. Nifty, isn’t it?

So then I could type fun and the resulting code becomes

function function_name (argument) { 
  // body... 
}

As I hit <TAB>, I can jump to function_name, argument and then // body... respectively. Now those boring old boilerplate code becomes, well, more boring. But it only requires just a few keystrokes to type it out! I can do this for if, for, switch, prototype, etc. Anything really. Since snippets are user definable, you can add any custom command to produce any custom snippet you want.

Code Library

If you’re thinking what I’m thinking, then you must be smiling with fascination. You can create your own library of codes that you use repeatedly in your projects.

Let’s say for some reason you need to create a box in Canvas for every project with the code like this:

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');

context.beginPath();
context.rect(100, 50, 200, 200);
context.fillStyle = 'pink';
context.fill();
context.lineWidth = 10;
context.strokeStyle = 'gray';
context.stroke();

How about creating those lines of code with just a quick command of box? You can most definitely do that!

Ok, a little more serious example. Let’s say most of the time when you create a Submit button, you want to always validate the input field to make sure it’s not empty. So you would probably do something like this:

$('.submit').click(function (evt) {
  evt.preventDefault();

  if ($('.name').val() === '') {
    console.log('Field Empty!');
    return;
  }
  // Proceed
});

Now whenever you need to implement a submit button with a validation check, you can just type btnsubmit, and voila, your validation code right away all typed out for you. Much faster than typing it all out. DRY FTW!

Show Me the Magic!

You bet! But first you’ll have to grab your copy of SnipMate from https://github.com/garbas/vim-snipmate or you can just clone it (SnipMate depends on tlib and vim-addon-mw-utils).

% git clone https://github.com/tomtom/tlib_vim.git
% git clone https://github.com/MarcWeber/vim-addon-mw-utils.git
% git clone https://github.com/garbas/vim-snipmate.git

If you haven’t used Pathogen, I suggest you do so since it makes managing scripts so much easier and saves a lot of headaches when loading them.

Now for some reason, SnipMate doesn’t come with preinstalled snippets, so you’ll have to grab them from https://github.com/honza/vim-snippets.

Before explaining further, I should note that SnipMate supports various programming languages and is very smart at determining the files you’re working on. The code examples I gave above are all Javascript, but you can be working in Python, or Ruby, or HTML or Java, or anything, and SnipMate will recognize that and will only activate those commands that are defined specifically for the language.

For instance, I could have similar command fun to create functions in Javascript and Ruby. But depending on the file I’m working on, if it’s Javascript it’ll be replaced with function... () {}, while in Ruby it’ll become def...end.

You’ll notice that namespace wise, SnipMate uses either a snippet file with language-name.snippet or a folder named after the language with multiple snippets.

To add your own custom snippet, you can either create a new snippet file in a folder with the name of the language you want to use, or add it to an existing snippet file provided by vim-snippets. I recommend creating a folder called snippets in your ~/.vim folder to store your custom snippet files.

To create a code snippet is basically just typing snippet followed by the command name, and then the code you want as the snippet in the following line.

Referring back to the submit button validation example, the code snippet will look like this:

snippet btnsubmit
  # Submit button validation (This is a comment)
  $('.submit').click(function (evt) {
    evt.preventDefault();
   
    if ($('.name').val() === '') {
      console.log('Field Empty!');
      return;
    }
    // Proceed
  });

Most of the time though, you’d probably want to customize the button and input field selectors, and the functions to call after validation. Therefore your code snippet would look like this:

snippet btnsubmit
  # Submit button validation
  $('${1:.submit}').click(function (evt) {
    evt.preventDefault();

    if ($('${2:.name}').val() === '') {
      ${3:console.log('Field Empty!');}
      return;
    }
    ${4:// Proceed}
});

What I added were these funny little numbers ${1:.submit} ${2:.name} ${3:.console.log('Field Empty!')} ${4:// Proceed} that allow you to jump through the different areas of the code that you can change by simply hitting <TAB>.

The number “1” corresponds to the tabstop and the text right after the colon is just a placeholder you want to show if it’s not changed. So for instance the .submit CSS class selector will remain the same if you decide to skip it.

That’s pretty much the gist of SnipMate. Very easy to use, but so powerful that I’m not sure if there’s any reason at all to not use it. It actually makes the entire coding experience more enjoyable.

If you haven’t downloaded it yet, go get it now!