Emacs: Using Templates with YASnippet

2018-08-30
Note, i no longer use yasnippet since ~2014.
I use simple emacs abbrev.
Emacs: Abbrev Mode

This page shows you a very useful and easy-to-use emacs package for inserting any type of templates for any programing language.

YASnippet is a template system for emacs. It allows you to type a abbreviation
and automatically expand into function templates. Bundled language templates
includes: {C, C++, C#, Perl, Python, Ruby, SQL, LaTeX, HTML, CSS, …}. You
can define your own template set. The template system is simple plain text
based. You do not need to know emacs lisp.

If all you want is a inserting static text, without parameters or moving cursor, then use emacs abbrev. [see Emacs: Abbrev Mode Tutorial]

What's a Template?

A Template is a way to insert text you use often, usually used to expand programing language's function names into parameters and body structure. For example, in HTML, you can type “div”, then press a hotkey, then it expands to:

<divid="▮"class="▯">▯</div>

With your cursor placed in a parameter slot, and pressing Tab will move to next parameter slot.

To test you have installed correctly, open a HTML file. Then, you should see a menu YASnippet. Try it.

How to Use Yasnippet?

You can:

Insert a template by using the menu.

Insert a template by typing the abbreviation, then press Tab.

YASnippet's HTML submenu. The left side are templates, the right side are abbreviations to use.

Find Out What Templates Are Available

For example, let's say you are coding HTML. Go to the menu 〖YASnippet ▸ html-mode〗, then you'll see a submenu. There's a item named 〖<body>…</body>〗. On the right side it shows “body =>”. That means, you can type body, then press Tab, then it'll expand to <body>▮</body>.

The menu gives you a overview of what templates are available for that language.

Another way to know what templates are available is from the folder. For example, for HTML, go to the dir:
~/.emacs.d/plugins/yasnippet-0.8.0/snippets/html-mode/. You'll see a list of files. Those file names, the first part before the dot “.”, is the abbreviation you can use.

Normally, you simply type a keyword or function name of the language then press Tab. If a template is available, it'll be expanded.

Jumping Thru Parameter Slots

After you inserted a template, you can press Tab to go thru the different parameter slots.