]> code.delx.au - gnu-emacs-elpa/blob - doc/snippet-development.rst
Fix issue 187
[gnu-emacs-elpa] / doc / snippet-development.rst
1 ================
2 Writing snippets
3 ================
4
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
9
10 .. contents::
11
12 Snippet development
13 ===================
14
15 Quickly finding snippets
16 ------------------------
17
18 There are some ways you can quickly find a snippet file:
19
20 * ``M-x yas/new-snippet``
21
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.
26
27 * ``M-x yas/find-snippets``
28
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``.
32
33 * ``M-x yas/visit-snippet-file``
34
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.
38
39 Once you find this file it will be set to ``snippet-mode`` (see ahead)
40 and you can start editing your snippet.
41
42
43 Using the ``snippet-mode`` major mode
44 -------------------------------------
45
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.
49
50 Two commands are defined in this mode:
51
52 * ``M-x yas/load-snippet-buffer``
53
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
56 ``snippet-mode``.
57
58 * ``M-x yas/tryout-snippet``
59
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
63 ``snippet-mode``.
64
65 There are also *snippets for writing snippets*: ``vars``, ``$f`` and
66 ``$m`` :-).
67
68 File content
69 ============
70
71 A file defining a snippet generally contains the template to be
72 expanded.
73
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.
79
80 Here's a typical example:
81
82 .. sourcecode:: text
83
84 # contributor: pluskid <pluskid@gmail.com>
85 # name: __...__
86 # --
87 __${init}__
88
89 Here's a list of currently supported directives:
90
91 ``# key:`` snippet abbrev
92 --------------------------
93
94 This is the probably the most important directive, it's the abbreviation you
95 type to expand a snippet just before hitting ``yas/trigger-key``. If you don't
96 specify this the snippet will not be expandable through the key mechanism.
97
98 ``# name:`` snippet name
99 ------------------------
100
101 This is a one-line description of the snippet. It will be displayed in
102 the menu. It's a good idea to select a descriptive name for a
103 snippet -- especially distinguishable among similar snippets.
104
105 If you omit this name it will default to the file name the snippet was
106 loaded from.
107
108 ``# condition:`` snippet condition
109 ----------------------------------
110 This is a piece of Emacs-lisp code. If a snippet has a condition, then it
111 will only be expanded when the condition code evaluate to some non-nil
112 value.
113
114 See also ``yas/buffer-local-condition`` in `Expanding snippets`_
115
116
117 ``# group:`` snippet menu grouping
118 ----------------------------------
119
120 When expanding/visiting snippets from the menu-bar menu, snippets for a
121 given mode can be grouped into sub-menus . This is useful if one has
122 too many snippets for a mode which will make the menu too
123 long.
124
125 The ``# group:`` property only affect menu construction (See `the
126 YASnippet menu`_) and the same effect can be achieved by grouping
127 snippets into sub-directories and using the ``.yas-make-groups``
128 special file (for this see `Organizing Snippets`_
129
130
131 Refer to the bundled snippets for ``ruby-mode`` for examples on the
132 ``# group:`` directive. Group can also be nested, e.g. ``control
133 structure.loops`` tells that the snippet is under the ``loops`` group
134 which is under the ``control structure`` group.
135
136 ``# expand-env:`` expand environment
137 ------------------------------------
138
139 This is another piece of Emacs-lisp code in the form of a ``let``
140 *varlist form*, i.e. a list of lists assigning values to variables. It
141 can be used to override variable values while the snippet is being
142 expanded.
143
144 Interesting variables to override are ``yas/wrap-around-region`` and
145 ``yas/indent-line`` (see `Expanding Snippets`_).
146
147 As an example, you might normally have ``yas/indent-line`` set to
148 ``'auto`` and ``yas/wrap-around-region`` set to ``t``, but for this
149 particularly brilliant piece of ASCII art these values would mess up
150 your hard work. You can then use:
151
152 .. sourcecode:: text
153
154 # name: ASCII home
155 # expand-env: ((yas/indent-line 'fixed) (yas/wrap-around-region 'nil))
156 # --
157 welcome to my
158 X humble
159 / \ home,
160 / \ $0
161 / \
162 /-------\
163 | |
164 | +-+ |
165 | | | |
166 +--+-+--+
167
168 ``# binding:`` direct keybinding
169 ---------------------------------
170
171 You can use this directive to expand a snippet directly from a normal
172 Emacs keybinding. The keybinding will be registered in the Emacs
173 keymap named after the major mode the snippet is active
174 for.
175
176 Additionally a variable ``yas/prefix`` is set to to the prefix
177 argument you normally use for a command. This allows for small
178 variations on the same snippet, for example in this "html-mode"
179 snippet.
180
181 .. sourcecode:: text
182
183 # name: <p>...</p>
184 # binding: C-c C-c C-m
185 # --
186 <p>`(when yas/prefix "\n")`$0`(when yas/prefix "\n")`</p>
187
188 This binding will be recorded in the keymap
189 ``html-mode-map``. To expand a paragraph tag newlines, just
190 press ``C-u C-c C-c C-m``. Omitting the ``C-u`` will expand the
191 paragraph tag without newlines.
192
193 ``# contributor:`` snippet author
194 ---------------------------------------------------
195
196 This is optional and has no effect whatsoever on snippet
197 functionality, but it looks nice.
198
199 Template syntax
200 ===============
201
202 The syntax of the snippet template is simple but powerful, very
203 similar to TextMate's.
204
205 Plain Text
206 ----------
207
208 Arbitrary text can be included as the content of a template. They are
209 usually interpreted as plain text, except ``$`` and `````. You need to
210 use ``\`` to escape them: ``\$`` and ``\```. The ``\`` itself may also
211 needed to be escaped as ``\\`` sometimes.
212
213 Embedded Emacs-lisp code
214 ------------------------
215
216 Emacs-Lisp code can be embedded inside the template, written inside
217 back-quotes (`````). The lisp forms are evaluated when the snippet is
218 being expanded. The evaluation is done in the same buffer as the
219 snippet being expanded.
220
221 Here's an example for ``c-mode`` to calculate the header file guard
222 dynamically:
223
224 .. sourcecode:: text
225
226 #ifndef ${1:_`(upcase (file-name-nondirectory (file-name-sans-extension (buffer-file-name))))`_H_}
227 #define $1
228
229 $0
230
231 #endif /* $1 */
232
233 From version 0.6, snippets expansions are run with some special
234 Emacs-lisp variables bound. One of this is ``yas/selected-text``. You
235 can therefore define a snippet like:
236
237 .. sourcecode:: text
238
239 for ($1;$2;$3) {
240 `yas/selected-text`$0
241 }
242
243 to "wrap" the selected region inside your recently inserted
244 snippet. Alternatively, you can also customize the variable
245 ``yas/wrap-around-region`` to ``t`` which will do this automatically.
246
247 Tab stop fields
248 ---------------
249
250 Tab stops are fields that you can navigate back and forth by ``TAB``
251 and ``S-TAB``. They are written by ``$`` followed with a
252 number. ``$0`` has the special meaning of the *exit point* of a
253 snippet. That is the last place to go when you've traveled all the
254 fields. Here's a typical example:
255
256 .. sourcecode:: text
257
258 <div$1>
259 $0
260 </div>
261
262 Placeholder fields
263 ------------------
264
265 Tab stops can have default values -- a.k.a placeholders. The syntax is
266 like this:
267
268 .. sourcecode:: text
269
270 ${N:default value}
271
272 They acts as the default value for a tab stop. But when you firstly
273 type at a tab stop, the default value will be replaced by your
274 typing. The number can be omitted if you don't want to create
275 `mirrors`_ or `transformations`_ for this field.
276
277 .. _mirrors:
278
279 Mirrors
280 -------
281
282 We refer the tab stops with placeholders as a *field*. A field can have
283 mirrors. Its mirrors will get updated when you change the text of a
284 field. Here's an example:
285
286 .. sourcecode:: text
287
288 \begin{${1:enumerate}}
289 $0
290 \end{$1}
291
292 When you type ``"document"`` at ``${1:enumerate}``, the word
293 ``"document"`` will also be inserted at ``\end{$1}``. The best
294 explanation is to see the screencast(`YouTube
295 <http://www.youtube.com/watch?v=vOj7btx3ATg>`_ or `avi video
296 <http://yasnippet.googlecode.com/files/yasnippet.avi>`_).
297
298 The tab stops with the same number to the field act as its mirrors. If
299 none of the tab stops has an initial value, the first one is selected
300 as the field and others mirrors.
301
302 .. _transformations:
303
304 Mirrors with transformations
305 ----------------------------
306
307 If the value of an ``${n:``-construct starts with and contains ``$(``,
308 then it is interpreted as a mirror for field ``n`` with a
309 transformation. The mirror's text content is calculated according to
310 this transformation, which is Emacs-lisp code that gets evaluated in
311 an environment where the variable ``text`` (or ``yas/text``) is bound
312 to the text content (string) contained in the field ``n``.Here's an
313 example for Objective-C:
314
315 .. sourcecode:: text
316
317 - (${1:id})${2:foo}
318 {
319 return $2;
320 }
321
322 - (void)set${2:$(capitalize text)}:($1)aValue
323 {
324 [$2 autorelease];
325 $2 = [aValue retain];
326 }
327 $0
328
329 Look at ``${2:$(capitalize text)}``, it is a mirror with
330 transformation instead of a field. The actual field is at the first
331 line: ``${2:foo}``. When you type text in ``${2:foo}``, the
332 transformation will be evaluated and the result will be placed there
333 as the transformed text. So in this example, if you type "baz" in the
334 field, the transformed text will be "Baz". This example is also
335 available in the screencast.
336
337 Another example is for ``rst-mode``. In reStructuredText, the document
338 title can be some text surrounded by "===" below and above. The "==="
339 should be at least as long as the text. So
340
341 .. sourcecode:: text
342
343 =====
344 Title
345 =====
346
347 is a valid title but
348
349 .. sourcecode:: text
350
351 ===
352 Title
353 ===
354
355 is not. Here's an snippet for rst title:
356
357 .. sourcecode:: text
358
359 ${1:$(make-string (string-width text) ?\=)}
360 ${1:Title}
361 ${1:$(make-string (string-width text) ?\=)}
362
363 $0
364
365 Fields with transformations
366 ---------------------------
367
368 From version 0.6 on, you can also have lisp transformation inside
369 fields. These work mostly mirror transformations but are evaluated
370 when you first enter the field, after each change you make to the
371 field and also just before you exit the field.
372
373 The syntax is also a tiny bit different, so that the parser can
374 distinguish between fields and mirrors. In the following example
375
376 .. sourcecode:: text
377
378 #define "${1:mydefine$(upcase yas/text)}"
379
380 ``mydefine`` gets automatically upcased to ``MYDEFINE`` once you enter
381 the field. As you type text, it gets filtered through the
382 transformation every time.
383
384 Note that to tell this kind of expression from a mirror with a
385 transformation, YASnippet needs extra text between the ``:`` and the
386 transformation's ``$``. If you don't want this extra-text, you can use
387 two ``$``'s instead.
388
389 .. sourcecode:: text
390
391 #define "${1:$$(upcase yas/text)}"
392
393 Please note that as soon as a transformation takes place, it changes
394 the value of the field and sets it its internal modification state to
395 ``true``. As a consequence, the auto-deletion behaviour of normal
396 fields does not take place. This is by design.
397
398 Choosing fields value from a list and other tricks
399 --------------------------------------------------
400
401 As mentioned, the field transformation is invoked just after you enter
402 the field, and with some useful variables bound, notably
403 ``yas/modified-p`` and ``yas/moving-away-p``. Because of this
404 feature you can place a transformation in the primary field that lets
405 you select default values for it.
406
407 The ``yas/choose-value`` does this work for you. For example:
408
409 .. sourcecode:: text
410
411 <div align="${2:$$(yas/choose-value '("right" "center" "left"))}">
412 $0
413 </div>
414
415 See the definition of ``yas/choose-value`` to see how it was written
416 using the two variables.
417
418 Here's another use, for LaTeX-mode, which calls reftex-label just as
419 you enter snippet field 2. This one makes use of ``yas/modified-p``
420 directly.
421
422 .. sourcecode:: text
423
424 \section{${1:"Titel der Tour"}}%
425 \index{$1}%
426 \label{{2:"waiting for reftex-label call..."$(unless yas/modified-p (reftex-label nil 'dont-
427 insert))}}%
428
429 The function ``yas/verify-value`` has another neat trick, and makes
430 use of ``yas/moving-away-p``. Try it and see! Also, check out this
431 `thread
432 <http://groups.google.com/group/smart-snippet/browse_thread/thread/282a90a118e1b662>`_
433
434 Nested placeholder fields
435 -------------------------
436
437 From version 0.6 on, you can also have nested placeholders of the type:
438
439 .. sourcecode:: text
440
441 <div${1: id="${2:some_id}"}>$0</div>
442
443 This allows you to choose if you want to give this ``div`` an ``id``
444 attribute. If you tab forward after expanding it will let you change
445 "some_id" to whatever you like. Alternatively, you can just press
446 ``C-d`` (which executes ``yas/skip-and-clear-or-delete-char``) and go
447 straight to the exit marker.
448
449 By the way, ``C-d`` will only clear the field if you cursor is at the
450 beginning of the field *and* it hasn't been changed yet. Otherwise, it
451 performs the normal Emacs ``delete-char`` command.
452
453 Customizable variables
454 ======================
455
456 ``yas/trigger-key``
457 -------------------
458
459 The key bound to ``yas/expand`` when function ``yas/minor-mode`` is
460 active.
461
462 Value is a string that is converted to the internal Emacs key
463 representation using ``read-kbd-macro``.
464
465 Default value is ``"TAB"``.
466
467 ``yas/next-field-key``
468 ----------------------
469
470 The key to navigate to next field when a snippet is active.
471
472 Value is a string that is converted to the internal Emacs key
473 representation using ``read-kbd-macro``.
474
475 Can also be a list of keys.
476
477 Default value is ``"TAB"``.
478
479 ``yas/prev-field-key``
480 ----------------------
481
482 The key to navigate to previous field when a snippet is active.
483
484 Value is a string that is converted to the internal Emacs key
485 representation using ``read-kbd-macro``.
486
487 Can also be a list of keys.
488
489 Default value is ``("<backtab>" "<S-tab>)"``.
490
491 ``yas/skip-and-clear-key``
492 --------------------------
493
494 The key to clear the currently active field.
495
496 Value is a string that is converted to the internal Emacs key
497 representation using ``read-kbd-macro``.
498
499 Can also be a list of keys.
500
501 Default value is ``"C-d"``.
502
503 ``yas/good-grace``
504 ------------------
505
506 If non-nil, don't raise errors in inline Emacs-lisp evaluation inside
507 snippet definitions. An error string "[yas] error" is returned instead.
508
509 ``yas/indent-line``
510 -------------------
511
512 The variable ``yas/indent-line`` controls the indenting. It is bound
513 to ``'auto`` by default, which causes your snippet to be indented
514 according to the mode of the buffer it was inserted in.
515
516 Another variable ``yas/also-auto-indent-first-line``, when non-nil
517 does exactly that :-).
518
519 To use the hard-coded indentation in your snippet template, set this
520 variable to ``fixed``.
521
522 To control indentation on a per-snippet basis, see also the directive
523 ``# expand-env:`` in `Writing Snippets`_.
524
525 For backward compatibility with earlier versions of YASnippet, you can
526 also place a ``$>`` in your snippet, an ``(indent-according-to-mode)``
527 will be executed there to indent the line. This only takes effect when
528 ``yas/indent-line`` is set to something other than ``'auto``.
529
530 .. sourcecode:: text
531
532 for (${int i = 0}; ${i < 10}; ${++i})
533 {$>
534 $0$>
535 }$>
536
537 ``yas/wrap-around-region``
538 --------------------------
539
540 If non-nil, YASnippet will try to expand the snippet's exit marker
541 around the currently selected region. When this variable is set to t,
542 this has the same effect has using the ```yas/selected-text``` inline
543 evaluation.
544
545 Because on most systems starting to type deletes the currently
546 selected region, this works mostly for snippets with direct
547 keybindings or with the ``yas/insert-snippet`` command.
548
549 However, when the value is of this variable is ``cua`` YASnippet will
550 additionally look-up any recently selected that you deleted by starting
551 typing. This allows you select a region, type a snippet key (deleting
552 the region), then press ``yas/trigger-key`` to see the deleted region
553 spring back to life inside your new snippet.
554
555 ``yas/triggers-in-field``
556 --------------------------
557
558 If non-nil, ``yas/next-field-key`` can trigger stacked expansions,
559 that is a snippet expansion inside another snippet
560 expansion. Otherwise, ``yas/next-field-key`` just tries to move on to
561 the next field.
562
563 ``yas/snippet-revival``
564 -----------------------
565
566 Non-nil means re-activate snippet fields after undo/redo.
567
568 ``yas/after-exit-snippet-hook`` and ``yas/before-expand-snippet-hook``
569 ----------------------------------------------------------------------
570
571 These hooks are called, respectively, before the insertion of a
572 snippet and after exiting the snippet. If you find any strange but
573 functional use for them, that's probably a design flaw in YASnippet,
574 so let us know.
575
576 Importing TextMate snippets
577 ===========================
578
579 There are a couple of tools that take TextMate's ".tmSnippet" xml
580 files and create YASnippet definitions:
581
582 * `a python script by Jeff Wheeler
583 <http://code.nokrev.com/?p=snippet-copier.git;a=blob_plain;f=snippet_copier.py>`_
584
585 * a `ruby tool
586 <http://yasnippet.googlecode.com/svn/trunk/extras/textmate_import.rb>`_
587 , ``textmate_import.rb`` adapted from `Rob Christie's
588 <http://www.neutronflux.net/2009/07/28/shoulda-snippets-for-emacs/>`_,
589 which I have uploaded to the repository.
590
591 In this section, i'll shortly cover the **second** option.
592
593 Download the ``textmate_import.rb`` tool and the TextMate
594 bundle you're interested in.
595
596 .. sourcecode:: text
597
598 $ curl -O http://yasnippet.googlecode.com/svn/trunk/extras/textmate_import.rb
599 $ svn export http://svn.textmate.org/trunk/Bundles/HTML.tmbundle/
600
601
602 Then invoke ``textmate_import.rb`` like this:
603
604 .. sourcecode:: text
605
606 $ ./textmate_import.rb -d HTML.tmbundle/Snippets/ -o html-mode -g HTML.tmbundle/info.plist
607
608 You should end up with a ``html-mode`` subdir containing snippets
609 exported from textmate.
610
611 .. sourcecode:: text
612
613 $ tree html-mode # to view dir contents, if you have 'tree' installed
614
615 The ``-g`` is optional but helps the tool figure out the grouping.
616 According to `Organizing Snippets`_, don't forget to touch
617 ``.yas-make-groups`` and ``.yas-ignore-filename-triggers`` inside the
618 ``html-mode`` dir.
619
620 Also try ``textmate_import.rb --help`` for a list of options.
621
622 Please note that snippet importation is not yet perfect. You'll
623 probably have some adjustments to some/many snippets. Please
624 contribute these adjustments to the google group or, better yet, patch
625 the ``textmate_import.rb`` to automatically perform them and submit
626 that.
627
628 .. LocalWords: html YASnippet yas sourcecode pluskid init filenames filename
629 .. LocalWords: env varlist keybinding keymap rinari ifndef upcase endif
630 .. LocalWords: nondirectory autorelease aValue inline