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