Because writing is hard but also our job. Yasnippet replaces a text key with a defined template.
(use-package yasnippet
:config (yas-global-mode 1))
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!
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
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))
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.
Snippets are stored under your `emacs.d` folder and separated by major modes.
tree ~/.emacs.d/snippets/
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