Skip to content

Instantly share code, notes, and snippets.

@abrochard
Created December 4, 2018 20:42
Show Gist options
  • Save abrochard/e1b903209be30a1df397bfb8b8e4fa0f to your computer and use it in GitHub Desktop.
Save abrochard/e1b903209be30a1df397bfb8b8e4fa0f to your computer and use it in GitHub Desktop.
Notes for the Emacs lightning talk about yasnippet of 12/03/2018

Lightning Talk: Yasnippet

Why

Because writing is hard but also our job. Yasnippet replaces a text key with a defined template.

Basic Usage

Installation

(use-package yasnippet
  :config (yas-global-mode 1))

Simple snippet

Want to create a simple snippet to insert a print statement. The behavior will be:

  • insert `p`
  • press TAB
  • `p` is replaced by `print()` with the cursor between the parenthesis

To create the snippet the steps are:

  • in my python file
  • `M-x yas-new-snippet` OR `C-c & C-n`
  • set the key to be `p`
  • you can use tab to go through the new snippet form
  • here is the content of the snippet
    print($1)
        
  • Press ‘C-c C-c’ when done
  • You can say yes to all following prompts

Your snippet is now ready to test!

Cursor control

If $1 is the first position of the cursor after snippet insertion, $0 is the last position, or where the cursor will be once you are done with inserting the snippet. You can try the following snippet to create a function. Note that you can use TAB to go through the fields.

def $1($2):
    $0

Fancy Usage

Mirroring

If you re-use the same parameter in the snippet, the text you enter will be mirrored in the other locations. Here is an enhancement for the print snippet that will say the name of the variable and the variable content

print('Value of $1: {}'.format($1))

Embedded ELisp

You can include ELisp inside a snippet and the output will be inserted. For example, here is a snippet that will create a new Python class based on the current file name.

class `(s-upper-camel-case (f-no-ext (f-filename (buffer-file-name))))`:
    def __init__(self, $2):
        self.$2 = $2

    $0

If you create a `car.py` file, and insert that snippet, the lisp code will be replaced with `Car` as the class name.

Snippet management

Snippet locations

Snippets are stored under your `emacs.d` folder and separated by major modes.

tree ~/.emacs.d/snippets/

Org-sync-snippet

I like to combine my snippet files into a giant org file and put that under source control. To help with that I created a package that gives to functions:

  • combine the snippets to an org file
  • split an org file to snippet files

You can check it out at https://github.com/abrochard/org-sync-snippets

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment