Yet another snippet mode for Emacs

Posted: - Modified: | emacs

While reading, I came across yasnippet (yet another snippet extension for Emacs). It provides interactive templates for text or code entry. It’s similar to SkeletonMode, but with TextMate-type syntax, simpler prompting for information, and more focus on expanding mode-sensitive text in the buffer.

Here’s what I did to get started with it on my system:

  1. Download and unpack it as ~/elisp/snippets.
  2. Download and unpack it as ~/elisp/yasnippet-bundle.el .
  3. Symlink lisp-interaction-mode to emacs-lisp-mode with the command
    ln -s ~/elisp/snippets/emacs-lisp-mode ~/elisp/snippets/lisp-interaction-mode
  4. Add the following lines to ~/.emacs
    (require 'yasnippet-bundle)
    (yas/load-directory "~/elisp/snippets")
    ;; I don't like using partial words for completion
    (setq yas/key-syntaxes '("w_" "w_." "^ "))

So far, so good. M-x yas/minor-mode lets me use TAB as the completion key, and I can use TAB and S-TAB to navigate between the fields of a snippet as well. I think it’s a decent snippets mode if you don’t need the complexity of skeleton.el.

After some experimentation, I see how this might make me even happier working on Drupal. I’ve put together this first try at a template for Drupal modules. Drupal code has a lot of repetitive typing and/or search-and-replacing because all the hook functions need to start with the module name. With yasnippet, I can type in the module name once, and all the other functions will be updated. I often find myself looking up the argument lists for the hook functions, too, and the template includes the hooks I tend to use. I think this snippet will save me a lot of start-up time.

You know what would be even cooler? If I could create snippets that dynamically calculate values using Emacs Lisp. Then I could create, for example, a hook_user abbreviation that automatically picked up the module name from the filename or from the other functions. Wouldn’t that be cool?

UPDATE: Putting Emacs Lisp in templates is awesome. With this function in my ~/.emacs:

(defun sacha/drupal-module-name ()
  "Return the Drupal module name for .module and .install files."
  (file-name-sans-extension (file-name-nondirectory (buffer-file-name))))

I can make templates like this one for hook_user. Sweet!

You can comment with Disqus or you can e-mail me at