Emacs: Using Templates with YASnippet
2018-08-30 Note, i no longer use yasnippet since ~2014. I use simple emacs abbrev. Emacs: Setup Hundreds of Abbrevs
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, etc}. 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: Setup Hundreds of Abbrevs〕
What is 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:
<div id="▮" class="▯">▯</div>
With your cursor placed in a parameter slot, and pressing Tab will move to next parameter slot.
In Perl, type “for”, press a hotkey, and it becomes:
for (my $var = 0; $var < expression; $var++) { # body… }
In emacs lisp, type “defun”, then it expands to:
(defun myFun () "thisandthat." (interactive) (let (var1) (setq var1 some) ; body… ) )
Installing YASnippet
You can install it with emacs 24's package system. 〔see Emacs: Install Package with ELPA/MELPA〕
Or, go to https://github.com/capitaomorte/yasnippet. (If you are using ErgoEmacs, then YASnippet is already installed.)
Restart emacs.
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.
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 menu [<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.
Define Your Own Template
It is very easy to define your own template. You don't need to know elisp. See: How to Define Templates In YASnippet.