Skip to content

Yasnippets Custom Snippetsλ︎

Yasnippets are written in plain text, so are easy to write. They support tab stops $1, placeholders ${1:defaultvalue} and ensure indentation rules are applied $<

How to write a snippetλ︎

The content can be anything, simple text or more usefully a code structure with placeholders

The basic structure of a snippet template is:

# key : short-form-name    (text that expands to snippet body)
# name : FullNameOfSnippet (shows in autocompletion menu after key )
# contributor: Practicalli
# --
;; ${1:Title placeholder text}
;; License: ${2:name of licence} Copyright Practicalli
$0

Example: Simple text replacementλ︎

As Practicalli develops the book content its useful to highlight sections which are still work in progress. Rather than type the same message over again, a simple snippet called wip is created.

# key : wip
# name : Work In Progress
# contributor: Practicalli <info@practical.li>
# --
> **Fixme** work in progress

When you expand this snippet with Meta / then the snippet name is replaced by the content.

Example: Using tab stopsλ︎

Yasnippets official snippets repository contains a snippet called form in the html-mode. This expands into a html form and jumps from method, id, action and content.

# key : form
# contributor : Practicalli <info@practical.li>
# name :<form method="..." id="..." action="..."></form>
# --
<form method="$1" id="$2" action="$3">
  $0
</form>

When the snippet is expanded, the snippet name is replaced by the content as usual but the cursor is placed at the first tab stop $1. Each time you press TAB you move to the next tab stop.

$0 is our exit point from the snippet, so pressing TAB reverts to the usual behaviour outside of YASnippet.

Further examples are covered in the Emacs YASnippet video tutorial or Adding YASnippets snippets & Snippet expansion with YASnippet

Testing snippetsλ︎

M-x yas-tryout-snippet opens a new empty buffer in the appropriate major mode and inserts the snippet so you can then test it with M-/.

M-x yas-load-snippet-buffer to load the new snippet into the correct major mode.

M-x yas-load-snippet-buffer-and-close also loads the new snippet into the correct major mode and kills the snippet buffer (prompting to save first if necessary).