YASnippet - Snippets for Emacs

I added another package back to my emacs configuration: yasnippet. Yasnippet is supposed to be based off of TextMate’s snippet system, which I have never used but have heard it is quite good. Yasnippet allows you to define your own ’snippets’ which are inserted into your file when you type a certain phrase and hit the trigger key, which is defaulted to tab. For example, in c, if you type ‘if‘, this gets expanded to

if (__)
{
 
}

Where your point is on the _. Once you finish inserting the condition, you can press TAB again to rotate to the next spot defined in the snippet - in this case, the body of the if statement.

These snippets are all kept in a directory as text files, in a folder heirarchy of modes. For example, to modify that if snippet, you would modify the “snippets/text-mode/cc-mode/if” file in your snippets folder. If you just open it up, you will see:

#name : if (...) { ... }
# --
if (${1:condition})
{
    $0
}

The #’s are just comments, and the rest of the snippet will be inserted, with the $’s being the location where the TAB goes to, with it going from $1 to $2 to … to $0. This snippet will be called by the trigger of ‘if’, which is the file name. For more information on editing snippets, see this.

To add yasnippet to your emacs startup, add the following to your init file:

(require 'yasnippet)
(yas/initialize)
(yas/load-directory "~/.emacs.d/yasnippet-0.5.10/snippets")

Where in the call to yas/load-directory you put the location of your snippets folder.

Tags:

4 Responses to “YASnippet - Snippets for Emacs”

  1. Robert says:

    Here’s something that I’m finding difficult to figure out: it seems like there are multiple different templating engines for Emacs. How do we choose? I have a bunch of old templates built using tempo templates. Should I give them up and change to a different scheme? If so, how do I choose which to use?

  2. [...] this was a motivation to finally take the plunge. [...]

  3. awhan says:

    thanks for this post … i have been meaning to redefine the “for” snippet for some time .. .thanks to this post i finally took the plunge
    http://awhan.wordpress.com/2009/07/20/redefining-for-snippet-in-yasnippet/

  4. joao says:

    You might want to try the new 0.6.0 beta, with some new features
    http://yasnippet.googlecode.com/svn/trunk/doc/changelog.html

Leave a Reply