]> code.delx.au - gnu-emacs-elpa/blob - doc/snippet-development.org
move top heading to title
[gnu-emacs-elpa] / doc / snippet-development.org
1 #+SETUPFILE: org-setup.inc
2 #+TITLE: Writing snippets
3
4 * Snippet development
5
6 ** Quickly finding snippets
7
8 There are some ways you can quickly find a snippet file:
9
10 - =M-x yas-new-snippet=
11
12 Prompts you for a snippet name, then tries to guess a suitable
13 directory to store it, prompting you for creation if it does not
14 exist. Finally, places you in a new buffer set to =snippet-mode= so
15 you can write your snippet.
16
17 - =M-x yas-find-snippets=
18
19 Lets you find the snippet file in the directory the snippet was
20 loaded from (if it exists) like =find-file-other-window=. The
21 directory searching logic is similar to =M-x yas-new-snippet=.
22
23 - =M-x yas-visit-snippet-file=
24
25 Prompts you for possible snippet expansions like
26 [[sym:yas-insert-snippet][=yas-insert-snippet=]], but instead of expanding it, takes you directly
27 to the snippet definition's file, if it exists.
28
29 Once you find this file it will be set to =snippet-mode= (see ahead) and
30 you can start editing your snippet.
31
32 ** Using the =snippet-mode= major mode
33
34 There is a major mode =snippet-mode= to edit snippets. You can set the
35 buffer to this mode with =M-x snippet-mode=. It provides reasonably
36 useful syntax highlighting.
37
38 Two commands are defined in this mode:
39
40 - =M-x yas-load-snippet-buffer=
41
42 When editing a snippet, this loads the snippet into the correct
43 mode and menu. Bound to =C-c C-c= by default while in
44 =snippet-mode=.
45
46 - =M-x yas-tryout-snippet=
47
48 When editing a snippet, this opens a new empty buffer, sets it to
49 the appropriate major mode and inserts the snippet there, so you
50 can see what it looks like. This is bound to =C-c C-t= while in
51 =snippet-mode=.
52
53 There are also /snippets for writing snippets/: =vars=, =$f= and =$m=
54 :-).
55
56 * File content
57
58 A file defining a snippet generally contains the template to be
59 expanded.
60
61 Optionally, if the file contains a line of =# --=, the lines above it
62 count as comments, some of which can be /directives/ (or meta data).
63 Snippet directives look like =# property: value= and tweak certain
64 snippets properties described below. If no =# --= is found, the whole
65 file is considered the snippet template.
66
67 Here's a typical example:
68
69 #+BEGIN_SRC snippet
70 # contributor: pluskid <pluskid@gmail.com>
71 # name: __...__
72 # --
73 __${init}__
74 #+END_SRC
75
76 Here's a list of currently supported directives:
77
78 ** =# key:= snippet abbrev
79
80 This is the probably the most important directive, it's the abbreviation
81 you type to expand a snippet just before hitting [[sym:yas-trigger-key][=yas-trigger-key=]]. If
82 you don't specify this the snippet will not be expandable through the
83 key mechanism.
84
85 ** =# name:= snippet name
86
87 This is a one-line description of the snippet. It will be displayed in
88 the menu. It's a good idea to select a descriptive name for a snippet --
89 especially distinguishable among similar snippets.
90
91 If you omit this name it will default to the file name the snippet was
92 loaded from.
93
94 ** =# condition:= snippet condition
95
96 This is a piece of Emacs-lisp code. If a snippet has a condition, then
97 it will only be expanded when the condition code evaluate to some
98 non-nil value.
99
100 See also [[sym:yas-buffer-local-condition][=yas-buffer-local-condition=]] in
101 [[./snippet-expansion.org][Expanding snippets]]
102
103 ** =# group:= snippet menu grouping
104
105 When expanding/visiting snippets from the menu-bar menu, snippets for a
106 given mode can be grouped into sub-menus . This is useful if one has too
107 many snippets for a mode which will make the menu too long.
108
109 The =# group:= property only affect menu construction (See
110 [[./snippet-menu.org][the YASnippet menu]]) and the same effect can be
111 achieved by grouping snippets into sub-directories and using the
112 =.yas-make-groups= special file (for this see
113 [[./snippet-organization.org][Organizing Snippets]]
114
115 Refer to the bundled snippets for =ruby-mode= for examples on the
116 =# group:= directive. Group can also be nested, e.g.
117 =control structure.loops= tells that the snippet is under the =loops=
118 group which is under the =control structure= group.
119
120 ** =# expand-env:= expand environment
121
122 This is another piece of Emacs-lisp code in the form of a =let= /varlist
123 form/, i.e. a list of lists assigning values to variables. It can be
124 used to override variable values while the snippet is being expanded.
125
126 Interesting variables to override are [[sym:yas-wrap-around-region][=yas-wrap-around-region=]] and
127 [[sym:yas-indent-line][=yas-indent-line=]] (see [[./snippet-expansion.org][Expanding Snippets]]).
128
129 As an example, you might normally have [[sym:yas-indent-line][=yas-indent-line=]] set to '=auto=
130 and [[sym:yas-wrap-around-region][=yas-wrap-around-region=]] set to =t=, but for this particularly
131 brilliant piece of ASCII art these values would mess up your hard work.
132 You can then use:
133
134 #+BEGIN_SRC snippet
135 # name: ASCII home
136 # expand-env: ((yas-indent-line 'fixed) (yas-wrap-around-region 'nil))
137 # --
138 welcome to my
139 X humble
140 / \ home,
141 / \ $0
142 / \
143 /-------\
144 | |
145 | +-+ |
146 | | | |
147 +--+-+--+
148 #+END_SRC
149
150 ** =# binding:= direct keybinding
151
152 You can use this directive to expand a snippet directly from a normal
153 Emacs keybinding. The keybinding will be registered in the Emacs keymap
154 named after the major mode the snippet is active for.
155
156 Additionally a variable [[sym:yas-prefix][=yas-prefix=]] is set to to the prefix argument
157 you normally use for a command. This allows for small variations on the
158 same snippet, for example in this "html-mode" snippet.
159
160 #+BEGIN_SRC snippet
161 # name: <p>...</p>
162 # binding: C-c C-c C-m
163 # --
164 <p>`(when yas-prefix "\n")`$0`(when yas-prefix "\n")`</p>
165 #+END_SRC
166
167 This binding will be recorded in the keymap =html-mode-map=. To expand a
168 paragraph tag newlines, just press =C-u C-c C-c C-m=. Omitting the =C-u=
169 will expand the paragraph tag without newlines.
170
171 ** =# contributor:= snippet author
172
173 This is optional and has no effect whatsoever on snippet functionality,
174 but it looks nice.
175
176 * Template syntax
177
178 The syntax of the snippet template is simple but powerful, very similar
179 to TextMate's.
180
181 ** Plain Text
182
183 Arbitrary text can be included as the content of a template. They are
184 usually interpreted as plain text, except =$= and ==. You need to
185 use \` to escape them: =\$= and =\=. The \` itself may also needed to be
186 escaped as =\\= sometimes.
187
188 ** Embedded Emacs-lisp code
189
190 Emacs-Lisp code can be embedded inside the template, written inside
191 back-quotes (==). The lisp forms are evaluated when the snippet is
192 being expanded. The evaluation is done in the same buffer as the
193 snippet being expanded.
194
195 Here's an example for c-mode` to calculate the header file guard
196 dynamically:
197
198 #+BEGIN_SRC snippet
199 #ifndef ${1:_`(upcase (file-name-nondirectory (file-name-sans-extension (buffer-file-name))))`_H_}
200 #define $1
201
202 $0
203
204 #endif /* $1 */
205 #+END_SRC
206
207 From version 0.6, snippets expansions are run with some special
208 Emacs-lisp variables bound. One of this is [[sym:yas-selected-text][=yas-selected-text=]]. You can
209 therefore define a snippet like:
210
211 #+BEGIN_SRC snippet
212 for ($1;$2;$3) {
213 `yas-selected-text`$0
214 }
215 #+END_SRC
216
217 to "wrap" the selected region inside your recently inserted snippet.
218 Alternatively, you can also customize the variable
219 [[sym:yas-wrap-around-region][=yas-wrap-around-region=]] to =t= which will do this automatically.
220
221 ** Tab stop fields
222
223 Tab stops are fields that you can navigate back and forth by =TAB= and
224 =S-TAB=. They are written by =$= followed with a number. =$0= has the
225 special meaning of the /exit point/ of a snippet. That is the last place
226 to go when you've traveled all the fields. Here's a typical example:
227
228 #+BEGIN_SRC snippet
229 <div$1>
230 $0
231 </div>
232 #+END_SRC
233 ** Placeholder fields
234
235 Tab stops can have default values -- a.k.a placeholders. The syntax is
236 like this:
237
238 #+BEGIN_SRC snippet
239 ${N:default value}
240 #+END_SRC
241
242 They acts as the default value for a tab stop. But when you firstly
243 type at a tab stop, the default value will be replaced by your typing.
244 The number can be omitted if you don't want to create [[mirrors]] or
245 [[transformations]] for this field.
246
247 ** <<Mirrors>>
248
249 We refer the tab stops with placeholders as a /field/. A field can have
250 mirrors. Its mirrors will get updated when you change the text of a
251 field. Here's an example:
252
253 #+BEGIN_SRC snippet
254 \begin{${1:enumerate}}
255 $0
256 \end{$1}
257 #+END_SRC
258
259 When you type "document" at =${1:enumerate}=, the word "document" will
260 also be inserted at =\end{$1}=. The best explanation is to see the
261 screencast([[http://www.youtube.com/watch?v=vOj7btx3ATg][YouTube]] or [[http://yasnippet.googlecode.com/files/yasnippet.avi][avi video]]).
262
263 The tab stops with the same number to the field act as its mirrors. If
264 none of the tab stops has an initial value, the first one is selected as
265 the field and others mirrors.
266
267 ** Mirrors with <<transformations>>
268
269 If the value of an =${n:=-construct starts with and contains =$(=, then
270 it is interpreted as a mirror for field =n= with a transformation. The
271 mirror's text content is calculated according to this transformation,
272 which is Emacs-lisp code that gets evaluated in an environment where the
273 variable =text= (or [[sym:yas-text][=yas-text=]]) is bound to the text content (string)
274 contained in the field =n=.Here's an example for Objective-C:
275
276 #+BEGIN_SRC snippet
277 - (${1:id})${2:foo}
278 {
279 return $2;
280 }
281
282 - (void)set${2:$(capitalize text)}:($1)aValue
283 {
284 [$2 autorelease];
285 $2 = [aValue retain];
286 }
287 $0
288 #+END_SRC
289
290 Look at =${2:$(capitalize text)}=, it is a mirror with transformation
291 instead of a field. The actual field is at the first line: =${2:foo}=.
292 When you type text in =${2:foo}=, the transformation will be evaluated
293 and the result will be placed there as the transformed text. So in this
294 example, if you type "baz" in the field, the transformed text will be
295 "Baz". This example is also available in the screencast.
296
297 Another example is for =rst-mode=. In reStructuredText, the document
298 title can be some text surrounded by "===" below and above. The "==="
299 should be at least as long as the text. So
300
301 #+BEGIN_SRC rst
302 =====
303 Title
304 =====
305 #+END_SRC
306
307 is a valid title but
308
309 #+BEGIN_SRC rst
310 ===
311 Title
312 ===
313 #+END_SRC
314
315 is not. Here's an snippet for rst title:
316
317 #+BEGIN_SRC snippet
318 ${1:$(make-string (string-width text) ?\=)}
319 ${1:Title}
320 ${1:$(make-string (string-width text) ?\=)}
321
322 $0
323 #+END_SRC
324
325 ** Fields with transformations
326
327 From version 0.6 on, you can also have lisp transformation inside
328 fields. These work mostly mirror transformations but are evaluated when
329 you first enter the field, after each change you make to the field and
330 also just before you exit the field.
331
332 The syntax is also a tiny bit different, so that the parser can
333 distinguish between fields and mirrors. In the following example
334
335 : #define "${1:mydefine$(upcase yas-text)}"
336
337 =mydefine= gets automatically upcased to =MYDEFINE= once you enter the
338 field. As you type text, it gets filtered through the transformation
339 every time.
340
341 Note that to tell this kind of expression from a mirror with a
342 transformation, YASnippet needs extra text between the =:= and the
343 transformation's =$=. If you don't want this extra-text, you can use two
344 =$='s instead.
345
346 : #define "${1:$$(upcase yas-text)}"
347
348 Please note that as soon as a transformation takes place, it changes the
349 value of the field and sets it its internal modification state to
350 =true=. As a consequence, the auto-deletion behaviour of normal fields
351 does not take place. This is by design.
352
353 ** Choosing fields value from a list and other tricks
354
355 As mentioned, the field transformation is invoked just after you enter
356 the field, and with some useful variables bound, notably
357 [[sym:yas-modified-p][=yas-modified-p=]] and [[sym:yas-moving-away-p][=yas-moving-away-p=]]. Because of this feature you
358 can place a transformation in the primary field that lets you select
359 default values for it.
360
361 The [[sym:yas-choose-value][=yas-choose-value=]] does this work for you. For example:
362
363 #+BEGIN_SRC snippet
364 <div align="${2:$$(yas-choose-value '("right" "center" "left"))}">
365 $0
366 </div>
367 #+END_SRC
368
369 See the definition of [[sym:yas-choose-value][=yas-choose-value=]] to see how it was written using
370 the two variables.
371
372 Here's another use, for LaTeX-mode, which calls reftex-label just as you
373 enter snippet field 2. This one makes use of [[sym:yas-modified-p][=yas-modified-p=]] directly.
374
375 #+BEGIN_SRC snippet
376 \section{${1:"Titel der Tour"}}%
377 \index{$1}%
378 \label{{2:"waiting for reftex-label call..."$(unless yas-modified-p (reftex-label nil 'dont-
379 insert))}}%
380 #+END_SRC
381
382 The function [[sym:yas-verify-value][=yas-verify-value=]] has another neat trick, and makes use of
383 [[sym:yas-moving-away-p][=yas-moving-away-p=]]. Try it and see! Also, check out this
384 [[http://groups.google.com/group/smart-snippet/browse_thread/thread/282a90a118e1b662][thread]]
385
386 ** Nested placeholder fields
387
388 From version 0.6 on, you can also have nested placeholders of the type:
389
390 #+BEGIN_SRC snippet
391 <div${1: id="${2:some_id}"}>$0</div>
392 #+END_SRC
393
394 This allows you to choose if you want to give this =div= an =id=
395 attribute. If you tab forward after expanding it will let you change
396 "some\_id" to whatever you like. Alternatively, you can just press =C-d=
397 (which executes [[sym:yas-skip-and-clear-or-delete-char][=yas-skip-and-clear-or-delete-char=]]) and go straight to
398 the exit marker.
399
400 By the way, =C-d= will only clear the field if you cursor is at the
401 beginning of the field /and/ it hasn't been changed yet. Otherwise, it
402 performs the normal Emacs =delete-char= command.
403
404 * Importing TextMate snippets
405
406 There are a couple of tools that take TextMate's ".tmSnippet" xml files
407 and create YASnippet definitions:
408
409
410 - [[http://code.nokrev.com/?p=snippet-copier.git;a=blob_plain;f=snippet_copier.py][a python script by Jeff Wheeler]]
411
412 - a [[http://yasnippet.googlecode.com/svn/trunk/extras/textmate_import.rb][ruby tool]] , =textmate_import.rb= adapted from [[http://www.neutronflux.net/2009/07/28/shoulda-snippets-for-emacs/][Rob Christie's]],
413 which I have uploaded to the repository.
414
415
416 In this section, i'll shortly cover the *second* option.
417
418 Download the =textmate_import.rb= tool and the TextMate bundle you're
419 interested in.
420
421 #+BEGIN_EXAMPLE
422 $ curl -O http://yasnippet.googlecode.com/svn/trunk/extras/textmate_import.rb
423 $ svn export http://svn.textmate.org/trunk/Bundles/HTML.tmbundle/
424 #+END_EXAMPLE
425
426 Then invoke =textmate_import.rb= like this:
427
428 #+BEGIN_EXAMPLE
429 $ ./textmate_import.rb -d HTML.tmbundle/Snippets/ -o html-mode -g HTML.tmbundle/info.plist
430 #+END_EXAMPLE
431
432 You should end up with a =html-mode= subdir containing snippets exported
433 from textmate.
434
435 #+BEGIN_EXAMPLE
436 $ tree html-mode # to view dir contents, if you have 'tree' installed
437 #+END_EXAMPLE
438
439 The =-g= is optional but helps the tool figure out the grouping.
440 According to [[./snippet-organization.org][Organizing Snippets]], don't forget to touch
441 =.yas-make-groups= and =.yas-ignore-filename-triggers= inside the
442 =html-mode= dir.
443
444 Also try =textmate_import.rb --help= for a list of options.
445
446 Please note that snippet importation is not yet perfect. You'll probably
447 have some adjustments to some/many snippets. Please contribute these
448 adjustments to the google group or, better yet, patch the
449 =textmate_import.rb= to automatically perform them and submit that.