Smart text templates with yasnippet

We looked before at expanding text with abbreviations which is great for simple things, but you can do a whole lot more using yasnippet. This is a smart template system for emacs, which is best explained with a simple example.

In the animation below I first of all use a snippet to write a fraction in latex by typing frac and hitting TAB which expands to \frac{numerator}{denominator} and places the cursor in the numerator field. I then type 1 and TAB to get to the next field and type 2 and TAB again to exit the snippet.

In the second part of the animation I typed begin and hit TAB to expand the snippet, creating a latex environment. In this example, note how the environment field is mirrored in the begin and end lines so I only type itemize once.

If you use my recommended setup, prelude then you already have yasnippet installed as well as a bunch of useful snippets, so you can get started right away. Otherwise you can install yasnippet from one of the package repositories. In either case you can add

(require 'yasnippet)
(yas-global-mode 1)


to your emacs config file to turn on yasnippet globally so it works in all buffers.

If you install from one of the repositories, you won’t get many snippets, but you can download sets of them from the official git repository and write your own (see below). Snippets are defined in simple text files that you put (by default) in ~/.emacs.d/snippets/ in subdirectories named after the major mode for those snippets. So e.g. ~/.emacs.d/snippets/latex-mode/ contains my snippets that will be active in latex mode.

Writing a snippet is really simple. The fraction snippet I used above looks like this:

# -*- mode: snippet -*-
# name: frac
# key: frac
# --
\frac{${1:numerator}}{${2:denominator}}$0  The name can be whatever you like, but the key is the thing you type and TAB to expand out the snippet. You can see that the ${1:numerator} represents the first field the cursor moves to, with the placeholder text, and similarly for the second field. $0 indicates where the cursor goes when the final TAB exits the snippet. The snippet for the latex environment in the second example is similarly simple: # -*- mode: snippet -*- # name: begin # key: begin # -- \begin{${1:environment}}
$0 \end{$1}


The repeated \$1 mirrors the environment field.

After you have written a snippet, it should also be saved with the key as the file name in the appropriate subdirectory for the major mode you want. You’ll then need to use the commands yas-recompile-all and yas-reload-all to load the new snippets.

These are simple examples and yasnippet can do a lot more, such as include lisp code that is activated when the snippet expands. I’ll show an example of using this to generate email templates in a future post. There are some other sophisticated examples in this video from emacs rocks.

• ozhan fenerci

Thank you. It was really helpful from setting up Prelude to learning inside-out of Emacs.