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