5 .. _Organizing Snippets: snippet-organization.html
6 .. _Expanding Snippets: snippet-expansion.html
7 .. _Writing Snippets: snippet-development.html
8 .. _The YASnippet Menu: snippet-menu.html
15 Quickly finding snippets
16 ------------------------
18 There are some ways you can quickly find a snippet file:
20 * ``M-x yas/new-snippet``
22 Prompts you for a snippet name, then tries to guess a suitable
23 directory to store it, prompting you for creation if it does not
24 exist. Finally, places you in a new buffer set to ``snippet-mode``
25 so you can write your snippet.
27 * ``M-x yas/find-snippets``
29 Lets you find the snippet file in the directory the snippet was
30 loaded from (if it exists) like ``find-file-other-window``. The
31 directory searching logic is similar to ``M-x yas/new-snippet``.
33 * ``M-x yas/visit-snippet-file``
35 Prompts you for possible snippet expansions like
36 ``yas/insert-snippet``, but instead of expanding it, takes you
37 directly to the snippet definition's file, if it exists.
39 Once you find this file it will be set to ``snippet-mode`` (see ahead)
40 and you can start editing your snippet.
43 Using the ``snippet-mode`` major mode
44 -------------------------------------
46 There is a major mode ``snippet-mode`` to edit snippets. You can set
47 the buffer to this mode with ``M-x snippet-mode``. It provides
48 reasonably useful syntax highlighting.
50 Two commands are defined in this mode:
52 * ``M-x yas/load-snippet-buffer``
54 When editing a snippet, this loads the snippet into the correct
55 mode and menu. Bound to ``C-c C-c`` by default while in
58 * ``M-x yas/tryout-snippet``
60 When editing a snippet, this opens a new empty buffer, sets it to
61 the appropriate major mode and inserts the snippet there, so you
62 can see what it looks like. This is bound to ``C-c C-t`` while in
65 There are also *snippets for writing snippets*: ``vars``, ``$f`` and
71 A file defining a snippet generally contains the template to be
74 Optionally, if the file contains a line of ``# --``, the lines above
75 it count as comments, some of which can be *directives* (or meta
76 data). Snippet directives look like ``# property: value`` and tweak
77 certain snippets properties described below. If no ``# --`` is found,
78 the whole file is considered the snippet template.
80 Here's a typical example:
84 #contributor : pluskid <pluskid@gmail.com>
89 Here's a list of currently supported directives:
91 ``# key:`` snippet abbrev
92 --------------------------
94 This is the probably the most important directive, it's the
95 abbreviation you type to expand a snippet just before hitting
98 If you don't specify this it will default to the name of the file the
99 snippet is being loaded from, unless YASnippet is ignoring file names
100 as triggers (see ``yas/ignore-filenames-as-triggers`` in `Organizing
101 snippets`_), in which case this snippet
102 will not be expandable through the key mechanism.
104 Sometimes the key of a snippet is non-ASCII or not valid filename
105 (e.g. contains ``/``). One can then define the ``key`` property which
106 will overwrite the filename as the key to expand the snippet.
108 ``# name:`` snippet name
109 ------------------------
111 This is a one-line description of the snippet. It will be displayed in
112 the menu. It's a good idea to select a descriptive name for a
113 snippet -- especially distinguishable among similar snippets.
115 If you omit this name it will default to the file name the snippet was
118 ``# condition:`` snippet condition
119 ----------------------------------
120 This is a piece of Emacs-lisp code. If a snippet has a condition, then it
121 will only be expanded when the condition code evaluate to some non-nil
124 See also ``yas/buffer-local-condition`` in `Expanding snippets`_
127 ``# group:`` snippet menu grouping
128 ----------------------------------
130 When expanding/visiting snippets from the menu-bar menu, snippets for a
131 given mode can be grouped into sub-menus . This is useful if one has
132 too many snippets for a mode which will make the menu too
135 The ``# group:`` property only affect menu construction (See `the
136 YASnippet menu`_) and the same effect can be achieved by grouping
137 snippets into sub-directories and using the ``.yas-make-groups``
138 special file (for this see `Organizing Snippets`_
141 Refer to the bundled snippets for ``ruby-mode`` for examples on the
142 ``# group:`` directive. Group can also be nested, e.g. ``control
143 structure.loops`` tells that the snippet is under the ``loops`` group
144 which is under the ``control structure`` group.
146 ``# expand-env:`` expand environment
147 ------------------------------------
149 This is another piece of Emacs-lisp code in the form of a ``let``
150 *varlist form*, i.e. a list of lists assigning values to variables. It
151 can be used to override variable values while the snippet is being
154 Interesting variables to override are ``yas/wrap-around-region`` and
155 ``yas/indent-line`` (see `Expanding Snippets`_).
157 As an example, you might normally have ``yas/indent-line`` set to
158 ``'auto`` and ``yas/wrap-around-region`` set to ``t``, but for this
159 particularly brilliant piece of ASCII art these values would mess up
160 your hard work. You can then use:
165 # expand-env: ((yas/indent-line 'fixed) (yas/wrap-around-region 'nil))
178 ``# binding:`` direct keybinding
179 ---------------------------------
181 You can use this directive to expand a snippet directly from a normal
182 Emacs keybinding. The keybinding will be registered in the Emacs
183 keymap named after the major mode the snippet is active
186 Additionally a variable ``yas/prefix`` is set to to the prefix
187 argument you normally use for a command. This allows for small
188 variations on the same snippet, for example in this "html-mode"
194 #binding: "C-c C-c C-m"
196 <p>`(when yas/prefix "\n")`$0`(when yas/prefix "\n")`</p>
198 This binding will be recorded in the keymap ``html-mode-map``. To
199 expand a paragraph tag newlines, just press "C-u C-c C-c
200 C-m". Omitting the "C-u" will expand the paragraph tag without
203 To override the keymap choice based on the major mode name. Use a cons
204 cell where the first element specifies the name of the keymap where
205 you want to record the keybinding.
210 #binding: (rinari-minor-mode-map . "C-c C-c C-m")
212 <p>`(when yas/prefix "\n")`$0`(when yas/prefix "\n")`</p>
214 **Note**: this feature is still **experimental**, it might go away, be
215 changed in future release, and should be used with caution: It is easy
216 to override important keybindings for many basic modes and it is hard
217 to undefine them. For the moment, the variable
218 ``yas/active-keybindings`` can tell you what snippet keybindings are
219 active and the function ``yas/kill-snippet-keybindings`` will attempt
220 to undefine all the keybindings.
222 ``# contributor:`` snippet author
223 ---------------------------------------------------
225 This is optional and has no effect whatsoever on snippet
226 functionality, but it looks nice.
232 The syntax of the snippet template is simple but powerful, very
233 similar to TextMate's.
238 Arbitrary text can be included as the content of a template. They are
239 usually interpreted as plain text, except ``$`` and `````. You need to
240 use ``\`` to escape them: ``\$`` and ``\```. The ``\`` itself may also
241 needed to be escaped as ``\\`` sometimes.
243 Embedded Emacs-lisp code
244 ------------------------
246 Emacs-Lisp code can be embedded inside the template, written inside
247 back-quotes (`````). The lisp forms are evaluated when the snippet is
248 being expanded. The evaluation is done in the same buffer as the
249 snippet being expanded.
251 Here's an example for ``c-mode`` to calculate the header file guard
256 #ifndef ${1:_`(upcase (file-name-nondirectory (file-name-sans-extension (buffer-file-name))))`_H_}
263 From version 0.6, snippets expansions are run with some special
264 Emacs-lisp variables bound. One of this is ``yas/selected-text``. You
265 can therefore define a snippet like:
270 `yas/selected-text`$0
273 to "wrap" the selected region inside your recently inserted
274 snippet. Alternatively, you can also customize the variable
275 ``yas/wrap-around-region`` to ``t`` which will do this automatically.
280 Tab stops are fields that you can navigate back and forth by ``TAB``
281 and ``S-TAB``. They are written by ``$`` followed with a
282 number. ``$0`` has the special meaning of the *exit point* of a
283 snippet. That is the last place to go when you've traveled all the
284 fields. Here's a typical example:
295 Tab stops can have default values -- a.k.a placeholders. The syntax is
302 They acts as the default value for a tab stop. But when you firstly
303 type at a tab stop, the default value will be replaced by your
304 typing. The number can be omitted if you don't want to create
305 `mirrors`_ or `transformations`_ for this field.
312 We refer the tab stops with placeholders as a *field*. A field can have
313 mirrors. Its mirrors will get updated when you change the text of a
314 field. Here's an example:
318 \begin{${1:enumerate}}
322 When you type ``"document"`` at ``${1:enumerate}``, the word
323 ``"document"`` will also be inserted at ``\end{$1}``. The best
324 explanation is to see the screencast(`YouTube
325 <http://www.youtube.com/watch?v=vOj7btx3ATg>`_ or `avi video
326 <http://yasnippet.googlecode.com/files/yasnippet.avi>`_).
328 The tab stops with the same number to the field act as its mirrors. If
329 none of the tab stops has an initial value, the first one is selected
330 as the field and others mirrors.
334 Mirrors with transformations
335 ----------------------------
337 If the value of an ``${n:``-construct starts with and contains ``$(``,
338 then it is interpreted as a mirror for field ``n`` with a
339 transformation. The mirror's text content is calculated according to
340 this transformation, which is Emacs-lisp code that gets evaluated in
341 an environment where the variable ``text`` (or ``yas/text``) is bound
342 to the text content (string) contained in the field ``n``.Here's an
343 example for Objective-C:
352 - (void)set${2:$(capitalize text)}:($1)aValue
355 $2 = [aValue retain];
359 Look at ``${2:$(capitalize text)}``, it is a mirror with
360 transformation instead of a field. The actual field is at the first
361 line: ``${2:foo}``. When you type text in ``${2:foo}``, the
362 transformation will be evaluated and the result will be placed there
363 as the transformed text. So in this example, if you type "baz" in the
364 field, the transformed text will be "Baz". This example is also
365 available in the screencast.
367 Another example is for ``rst-mode``. In reStructuredText, the document
368 title can be some text surrounded by "===" below and above. The "==="
369 should be at least as long as the text. So
385 is not. Here's an snippet for rst title:
389 ${1:$(make-string (string-width text) ?\=)}
391 ${1:$(make-string (string-width text) ?\=)}
395 Fields with transformations
396 ---------------------------
398 From version 0.6 on, you can also have lisp transformation inside
399 fields. These work mostly mirror transformations but are evaluated
400 when you first enter the field, after each change you make to the
401 field and also just before you exit the field.
403 The syntax is also a tiny bit different, so that the parser can
404 distinguish between fields and mirrors. In the following example
408 #define "${1:mydefine$(upcase yas/text)}"
410 ``mydefine`` gets automatically upcased to ``MYDEFINE`` once you enter
411 the field. As you type text, it gets filtered through the
412 transformation every time.
414 Note that to tell this kind of expression from a mirror with a
415 transformation, YASnippet needs extra text between the ``:`` and the
416 transformation's ``$``. If you don't want this extra-text, you can use
421 #define "${1:$$(upcase yas/text)}"
423 Please note that as soon as a transformation takes place, it changes
424 the value of the field and sets it its internal modification state to
425 ``true``. As a consequence, the auto-deletion behaviour of normal
426 fields does not take place. This is by design.
428 Choosing fields value from a list and other tricks
429 --------------------------------------------------
431 As mentioned, the field transformation is invoked just after you enter
432 the field, and with some useful variables bound, notably
433 ``yas/field-modified-p`` and ``yas/moving-away-p``. Because of this
434 feature you can place a transformation in the primary field that lets
435 you select default values for it.
437 The ``yas/choose-value`` does this work for you. For example:
441 <div align="${2:$$(yas/choose-value '("right" "center" "left"))}">
445 See the definition of ``yas/choose-value`` to see how it was written
446 using the two variables.
448 Here's another use, for LaTeX-mode, which calls reftex-label just as
449 you enter snippet field 2. This one makes use of ``yas/modified-p``
454 \section{${1:"Titel der Tour"}}%
456 \label{{2:"waiting for reftex-label call..."$(unless yas/modified-p (reftex-label nil 'dont-
459 The function ``yas/verify-value`` has another neat trick, and makes
460 use of ``yas/moving-away-p``. Try it and see! Also, check out this
462 <http://groups.google.com/group/smart-snippet/browse_thread/thread/282a90a118e1b662>`_
464 Nested placeholder fields
465 -------------------------
467 From version 0.6 on, you can also have nested placeholders of the type:
471 <div${1: id="${2:some_id}"}>$0</div>
473 This allows you to choose if you want to give this ``div`` an ``id``
474 attribute. If you tab forward after expanding it will let you change
475 "some_id" to whatever you like. Alternatively, you can just press
476 ``C-d`` (which executes ``yas/skip-and-clear-or-delete-char``) and go
477 straight to the exit marker.
479 By the way, ``C-d`` will only clear the field if you cursor is at the
480 beginning of the field *and* it hasn't been changed yet. Otherwise, it
481 performs the normal Emacs ``delete-char`` command.
483 Customizable variables
484 ======================
489 The key bound to ``yas/expand`` when function ``yas/minor-mode`` is
492 Value is a string that is converted to the internal Emacs key
493 representation using ``read-kbd-macro``.
495 Default value is ``"TAB"``.
497 ``yas/next-field-key``
498 ----------------------
500 The key to navigate to next field when a snippet is active.
502 Value is a string that is converted to the internal Emacs key
503 representation using ``read-kbd-macro``.
505 Can also be a list of keys.
507 Default value is ``"TAB"``.
509 ``yas/prev-field-key``
510 ----------------------
512 The key to navigate to previous field when a snippet is active.
514 Value is a string that is converted to the internal Emacs key
515 representation using ``read-kbd-macro``.
517 Can also be a list of keys.
519 Default value is ``("<backtab>" "<S-tab>)"``.
521 ``yas/skip-and-clear-key``
522 --------------------------
524 The key to clear the currently active field.
526 Value is a string that is converted to the internal Emacs key
527 representation using ``read-kbd-macro``.
529 Can also be a list of keys.
531 Default value is ``"C-d"``.
536 If non-nil, don't raise errors in inline Emacs-lisp evaluation inside
537 snippet definitions. An error string "[yas] error" is returned instead.
542 The variable ``yas/indent-line`` controls the indenting. It is bound
543 to ``'auto`` by default, which causes your snippet to be indented
544 according to the mode of the buffer it was inserted in.
546 Another variable ``yas/also-auto-indent-first-line``, when non-nil
547 does exactly that :-).
549 To use the hard-coded indentation in your snippet template, set this
550 variable to ``fixed``.
552 To control indentation on a per-snippet basis, see also the directive
553 ``# expand-env:`` in `Writing Snippets`_.
555 For backward compatibility with earlier versions of YASnippet, you can
556 also place a ``$>`` in your snippet, an ``(indent-according-to-mode)``
557 will be executed there to indent the line. This only takes effect when
558 ``yas/indent-line`` is set to something other than ``'auto``.
562 for (${int i = 0}; ${i < 10}; ${++i})
567 ``yas/wrap-around-region``
568 --------------------------
570 If non-nil, YASnippet will try to expand the snippet's exit marker
571 around the currently selected region. When this variable is set to t,
572 this has the same effect has using the ```yas/selected-text``` inline
575 Because on most systems starting to type deletes the currently
576 selected region, this works mostly for snippets with direct
577 keybindings or with the ``yas/insert-snippet`` command.
579 However, when the value is of this variable is ``cua`` YASnippet will
580 additionally look-up any recently selected that you deleted by starting
581 typing. This allows you select a region, type a snippet key (deleting
582 the region), then press ``yas/trigger-key`` to see the deleted region
583 spring back to life inside your new snippet.
585 ``yas/triggers-in-field``
586 --------------------------
588 If non-nil, ``yas/next-field-key`` can trigger stacked expansions,
589 that is a snippet expansion inside another snippet
590 expansion. Otherwise, ``yas/next-field-key`` just tries to move on to
593 ``yas/snippet-revival``
594 -----------------------
596 Non-nil means re-activate snippet fields after undo/redo.
598 ``yas/after-exit-snippet-hook`` and ``yas/before-expand-snippet-hook``
599 ----------------------------------------------------------------------
601 These hooks are called, respectively, before the insertion of a
602 snippet and after exiting the snippet. If you find any strange but
603 functional use for them, that's probably a design flaw in YASnippet,
606 Importing TextMate snippets
607 ===========================
609 There are a couple of tools that take TextMate's ".tmSnippet" xml
610 files and create YASnippet definitions:
612 * `a python script by Jeff Wheeler
613 <http://code.nokrev.com/?p=snippet-copier.git;a=blob_plain;f=snippet_copier.py>`_
616 <http://yasnippet.googlecode.com/svn/trunk/extras/textmate_import.rb>`_
617 , ``textmate_import.rb`` adapted from `Rob Christie's
618 <http://www.neutronflux.net/2009/07/28/shoulda-snippets-for-emacs/>`_,
619 which I have uploaded to the repository.
621 In this section, i'll shortly cover the **second** option.
623 Download the ``textmate_import.rb`` tool and the TextMate
624 bundle you're interested in.
628 $ curl -O http://yasnippet.googlecode.com/svn/trunk/extras/textmate_import.rb
629 $ svn export http://svn.textmate.org/trunk/Bundles/HTML.tmbundle/
632 Then invoke ``textmate_import.rb`` like this:
636 $ ./textmate_import.rb -d HTML.tmbundle/Snippets/ -o html-mode -g HTML.tmbundle/info.plist
638 You should end up with a ``html-mode`` subdir containing snippets
639 exported from textmate.
643 $ tree html-mode # to view dir contents, if you have 'tree' installed
645 The ``-g`` is optional but helps the tool figure out the grouping.
646 According to `Organizing Snippets`_, don't forget to touch
647 ``.yas-make-groups`` and ``.yas-ignore-filename-triggers`` inside the
650 Also try ``textmate_import.rb --help`` for a list of options.
652 Please note that snippet importation is not yet perfect. You'll
653 probably have some adjustments to some/many snippets. Please
654 contribute these adjustments to the google group or, better yet, patch
655 the ``textmate_import.rb`` to automatically perform them and submit
658 .. LocalWords: html YASnippet yas sourcecode pluskid init filenames filename
659 .. LocalWords: env varlist keybinding keymap rinari ifndef upcase endif
660 .. LocalWords: nondirectory autorelease aValue inline