]> code.delx.au - gnu-emacs-elpa/blob - doc/snippet-development.rst
* Fix the multi-line substitution problem
[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
95 abbreviation you type to expand a snippet just before hitting
96 ``yas/trigger-key``.
97
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.
103
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.
107
108 ``# name:`` snippet name
109 ------------------------
110
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.
114
115 If you omit this name it will default to the file name the snippet was
116 loaded from.
117
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
122 value.
123
124 See also ``yas/buffer-local-condition`` in `Expanding snippets`_
125
126
127 ``# group:`` snippet menu grouping
128 ----------------------------------
129
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
133 long.
134
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`_
139
140
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.
145
146 ``# expand-env:`` expand environment
147 ------------------------------------
148
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
152 expanded.
153
154 Interesting variables to override are ``yas/wrap-around-region`` and
155 ``yas/indent-line`` (see `Expanding Snippets`_).
156
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:
161
162 .. sourcecode:: text
163
164 # name : ASCII home
165 # expand-env: ((yas/indent-line 'fixed) (yas/wrap-around-region 'nil))
166 # --
167 welcome to my
168 X humble
169 / \ home,
170 / \ $0
171 / \
172 /-------\
173 | |
174 | +-+ |
175 | | | |
176 +--+-+--+
177
178 ``# binding:`` direct keybinding
179 ---------------------------------
180
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
184 for.
185
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"
189 snippet.
190
191 .. sourcecode:: text
192
193 #name : <p>...</p>
194 #binding: "C-c C-c C-m"
195 # --
196 <p>`(when yas/prefix "\n")`$0`(when yas/prefix "\n")`</p>
197
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
201 newlines.
202
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.
206
207 .. sourcecode:: text
208
209 #name : <p>...</p>
210 #binding: (rinari-minor-mode-map . "C-c C-c C-m")
211 # --
212 <p>`(when yas/prefix "\n")`$0`(when yas/prefix "\n")`</p>
213
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.
221
222 ``# contributor:`` snippet author
223 ---------------------------------------------------
224
225 This is optional and has no effect whatsoever on snippet
226 functionality, but it looks nice.
227
228
229 Template syntax
230 ===============
231
232 The syntax of the snippet template is simple but powerful, very
233 similar to TextMate's.
234
235 Plain Text
236 ----------
237
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.
242
243 Embedded Emacs-lisp code
244 ------------------------
245
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.
250
251 Here's an example for ``c-mode`` to calculate the header file guard
252 dynamically:
253
254 .. sourcecode:: text
255
256 #ifndef ${1:_`(upcase (file-name-nondirectory (file-name-sans-extension (buffer-file-name))))`_H_}
257 #define $1
258
259 $0
260
261 #endif /* $1 */
262
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:
266
267 .. sourcecode:: text
268
269 for ($1;$2;$3) {
270 `yas/selected-text`$0
271 }
272
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.
276
277 Tab stop fields
278 ---------------
279
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:
285
286 .. sourcecode:: text
287
288 <div$1>
289 $0
290 </div>
291
292 Placeholder fields
293 ------------------
294
295 Tab stops can have default values -- a.k.a placeholders. The syntax is
296 like this:
297
298 .. sourcecode:: text
299
300 ${N:default value}
301
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.
306
307 .. _mirrors:
308
309 Mirrors
310 -------
311
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:
315
316 .. sourcecode:: text
317
318 \begin{${1:enumerate}}
319 $0
320 \end{$1}
321
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>`_).
327
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.
331
332 .. _transformations:
333
334 Mirrors with transformations
335 ----------------------------
336
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:
344
345 .. sourcecode:: text
346
347 - (${1:id})${2:foo}
348 {
349 return $2;
350 }
351
352 - (void)set${2:$(capitalize text)}:($1)aValue
353 {
354 [$2 autorelease];
355 $2 = [aValue retain];
356 }
357 $0
358
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.
366
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
370
371 .. sourcecode:: text
372
373 =====
374 Title
375 =====
376
377 is a valid title but
378
379 .. sourcecode:: text
380
381 ===
382 Title
383 ===
384
385 is not. Here's an snippet for rst title:
386
387 .. sourcecode:: text
388
389 ${1:$(make-string (string-width text) ?\=)}
390 ${1:Title}
391 ${1:$(make-string (string-width text) ?\=)}
392
393 $0
394
395 Fields with transformations
396 ---------------------------
397
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.
402
403 The syntax is also a tiny bit different, so that the parser can
404 distinguish between fields and mirrors. In the following example
405
406 .. sourcecode:: text
407
408 #define "${1:mydefine$(upcase yas/text)}"
409
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.
413
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
417 two ``$``'s instead.
418
419 .. sourcecode:: text
420
421 #define "${1:$$(upcase yas/text)}"
422
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.
427
428 Choosing fields value from a list and other tricks
429 --------------------------------------------------
430
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.
436
437 The ``yas/choose-value`` does this work for you. For example:
438
439 .. sourcecode:: text
440
441 <div align="${2:$$(yas/choose-value '("right" "center" "left"))}">
442 $0
443 </div>
444
445 See the definition of ``yas/choose-value`` to see how it was written
446 using the two variables.
447
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``
450 directly.
451
452 .. sourcecode:: text
453
454 \section{${1:"Titel der Tour"}}%
455 \index{$1}%
456 \label{{2:"waiting for reftex-label call..."$(unless yas/modified-p (reftex-label nil 'dont-
457 insert))}}%
458
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
461 `thread
462 <http://groups.google.com/group/smart-snippet/browse_thread/thread/282a90a118e1b662>`_
463
464 Nested placeholder fields
465 -------------------------
466
467 From version 0.6 on, you can also have nested placeholders of the type:
468
469 .. sourcecode:: text
470
471 <div${1: id="${2:some_id}"}>$0</div>
472
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.
478
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.
482
483 Customizable variables
484 ======================
485
486 ``yas/trigger-key``
487 -------------------
488
489 The key bound to ``yas/expand`` when function ``yas/minor-mode`` is
490 active.
491
492 Value is a string that is converted to the internal Emacs key
493 representation using ``read-kbd-macro``.
494
495 Default value is ``"TAB"``.
496
497 ``yas/next-field-key``
498 ----------------------
499
500 The key to navigate to next field when a snippet is active.
501
502 Value is a string that is converted to the internal Emacs key
503 representation using ``read-kbd-macro``.
504
505 Can also be a list of keys.
506
507 Default value is ``"TAB"``.
508
509 ``yas/prev-field-key``
510 ----------------------
511
512 The key to navigate to previous field when a snippet is active.
513
514 Value is a string that is converted to the internal Emacs key
515 representation using ``read-kbd-macro``.
516
517 Can also be a list of keys.
518
519 Default value is ``("<backtab>" "<S-tab>)"``.
520
521 ``yas/skip-and-clear-key``
522 --------------------------
523
524 The key to clear the currently active field.
525
526 Value is a string that is converted to the internal Emacs key
527 representation using ``read-kbd-macro``.
528
529 Can also be a list of keys.
530
531 Default value is ``"C-d"``.
532
533 ``yas/good-grace``
534 ------------------
535
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.
538
539 ``yas/indent-line``
540 -------------------
541
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.
545
546 Another variable ``yas/also-auto-indent-first-line``, when non-nil
547 does exactly that :-).
548
549 To use the hard-coded indentation in your snippet template, set this
550 variable to ``fixed``.
551
552 To control indentation on a per-snippet basis, see also the directive
553 ``# expand-env:`` in `Writing Snippets`_.
554
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``.
559
560 .. sourcecode:: text
561
562 for (${int i = 0}; ${i < 10}; ${++i})
563 {$>
564 $0$>
565 }$>
566
567 ``yas/wrap-around-region``
568 --------------------------
569
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
573 evaluation.
574
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.
578
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.
584
585 ``yas/triggers-in-field``
586 --------------------------
587
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
591 the next field.
592
593 ``yas/snippet-revival``
594 -----------------------
595
596 Non-nil means re-activate snippet fields after undo/redo.
597
598 ``yas/after-exit-snippet-hook`` and ``yas/before-expand-snippet-hook``
599 ----------------------------------------------------------------------
600
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,
604 so let us know.
605
606 Importing TextMate snippets
607 ===========================
608
609 There are a couple of tools that take TextMate's ".tmSnippet" xml
610 files and create YASnippet definitions:
611
612 * `a python script by Jeff Wheeler
613 <http://code.nokrev.com/?p=snippet-copier.git;a=blob_plain;f=snippet_copier.py>`_
614
615 * a `ruby tool
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.
620
621 In this section, i'll shortly cover the **second** option.
622
623 Download the ``textmate_import.rb`` tool and the TextMate
624 bundle you're interested in.
625
626 .. sourcecode:: text
627
628 $ curl -O http://yasnippet.googlecode.com/svn/trunk/extras/textmate_import.rb
629 $ svn export http://svn.textmate.org/trunk/Bundles/HTML.tmbundle/
630
631
632 Then invoke ``textmate_import.rb`` like this:
633
634 .. sourcecode:: text
635
636 $ ./textmate_import.rb -d HTML.tmbundle/Snippets/ -o html-mode -g HTML.tmbundle/info.plist
637
638 You should end up with a ``html-mode`` subdir containing snippets
639 exported from textmate.
640
641 .. sourcecode:: text
642
643 $ tree html-mode # to view dir contents, if you have 'tree' installed
644
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
648 ``html-mode`` dir.
649
650 Also try ``textmate_import.rb --help`` for a list of options.
651
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
656 that.
657
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