]> code.delx.au - gnu-emacs-elpa/blob - doc/snippet-development.org
Document $> and fix escaping
[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=
12
13 Creates a new buffer with a template for making a new snippet.
14 The buffer is in =snippet-mode= (see below). When you are done
15 editing the new snippet, use =C-c C-c= to save it. This will
16 prompt for a directory two steps: first, the snippet table
17 (with a default based on the major mode you started in), and then
18 then snippet collection directory (defaults to the first directory
19 in =yas-snippet-dirs=. (See [[file:snippet-organization.org][Organizing Snippets]]
20 for more detail on how snippets are organized.)
21
22 - =M-x yas-find-snippets=
23
24 Lets you find the snippet file in the directory the snippet was
25 loaded from (if it exists) like =find-file-other-window=. The
26 directory searching logic is similar to =M-x yas-new-snippet=.
27
28 - =M-x yas-visit-snippet-file=
29
30 Prompts you for possible snippet expansions like
31 [[sym:yas-insert-snippet][=yas-insert-snippet=]], but instead of expanding it, takes you directly
32 to the snippet definition's file, if it exists.
33
34 Once you find this file it will be set to =snippet-mode= (see ahead) and
35 you can start editing your snippet.
36
37 ** Using the =snippet-mode= major mode
38
39 There is a major mode =snippet-mode= to edit snippets. You can set the
40 buffer to this mode with =M-x snippet-mode=. It provides reasonably
41 useful syntax highlighting.
42
43 Two commands are defined in this mode:
44
45 - =M-x yas-load-snippet-buffer=
46
47 When editing a snippet, this loads the snippet into the correct
48 mode and menu. Bound to =C-c C-c= by default while in
49 =snippet-mode=.
50
51 - =M-x yas-tryout-snippet=
52
53 When editing a snippet, this opens a new empty buffer, sets it to
54 the appropriate major mode and inserts the snippet there, so you
55 can see what it looks like. This is bound to =C-c C-t= while in
56 =snippet-mode=.
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
86 abbreviation you type to expand a snippet just before hitting the key
87 that runs [[sym:yas-expand][=yas-expand=]]. If you don't specify this
88 the snippet will not be expandable through the trigger 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 ** =# type:= =snippet= or =command=
177
178 If the =type= directive is set to =command=, the body of the snippet
179 is interpreted as lisp code to be evaluated when the snippet is
180 triggered.
181
182 If it's =snippet= (the default when there is no =type= directive), the
183 snippet body will be parsed according to the [[Template Syntax]],
184 described below.
185
186 ** =# uuid:= unique identifier
187
188 This provides to a way to identify a snippet, independent of its name.
189 Loading a second snippet file with the same uuid would replace the
190 previous snippet.
191
192 ** =# contributor:= snippet author
193
194 This is optional and has no effect whatsoever on snippet functionality,
195 but it looks nice.
196
197 * Template Syntax
198
199 The syntax of the snippet template is simple but powerful, very similar
200 to TextMate's.
201
202 ** Plain Text
203
204 Arbitrary text can be included as the content of a template. They are
205 usually interpreted as plain text, except =$= and =`=. You need to
206 use =\= to escape them: =\$= and =\`=. The =\= itself may also needed to be
207 escaped as =\\= sometimes.
208
209 ** Embedded Emacs-lisp code
210
211 Emacs-Lisp code can be embedded inside the template, written inside
212 back-quotes (=`=). The lisp forms are evaluated when the snippet is
213 being expanded. The evaluation is done in the same buffer as the
214 snippet being expanded.
215
216 Here's an example for c-mode` to calculate the header file guard
217 dynamically:
218
219 #+BEGIN_SRC snippet
220 #ifndef ${1:_`(upcase (file-name-nondirectory (file-name-sans-extension (buffer-file-name))))`_H_}
221 #define $1
222
223 $0
224
225 #endif /* $1 */
226 #+END_SRC
227
228 From version 0.6, snippets expansions are run with some special
229 Emacs-lisp variables bound. One of this is [[sym:yas-selected-text][=yas-selected-text=]]. You can
230 therefore define a snippet like:
231
232 #+BEGIN_SRC snippet
233 for ($1;$2;$3) {
234 `yas-selected-text`$0
235 }
236 #+END_SRC
237
238 to "wrap" the selected region inside your recently inserted snippet.
239 Alternatively, you can also customize the variable
240 [[sym:yas-wrap-around-region][=yas-wrap-around-region=]] to =t= which will do this automatically.
241
242 ** Tab stop fields
243
244 Tab stops are fields that you can navigate back and forth by =TAB= and
245 =S-TAB=. They are written by =$= followed with a number. =$0= has the
246 special meaning of the /exit point/ of a snippet. That is the last place
247 to go when you've traveled all the fields. Here's a typical example:
248
249 #+BEGIN_SRC snippet
250 <div$1>
251 $0
252 </div>
253 #+END_SRC
254 ** Placeholder fields
255
256 Tab stops can have default values -- a.k.a placeholders. The syntax is
257 like this:
258
259 #+BEGIN_SRC snippet
260 ${N:default value}
261 #+END_SRC
262
263 They acts as the default value for a tab stop. But when you firstly
264 type at a tab stop, the default value will be replaced by your typing.
265 The number can be omitted if you don't want to create [[mirrors-fields][mirrors]] or
266 [[mirror-transformations][transformations]] for this field.
267
268 ** Mirrors <<mirrors-fields>>
269
270 We refer the tab stops with placeholders as a /field/. A field can have
271 mirrors. Its mirrors will get updated when you change the text of a
272 field. Here's an example:
273
274 #+BEGIN_SRC snippet
275 \begin{${1:enumerate}}
276 $0
277 \end{$1}
278 #+END_SRC
279
280 When you type "document" at =${1:enumerate}=, the word "document" will
281 also be inserted at =\end{$1}=. The best explanation is to see the
282 screencast([[http://www.youtube.com/watch?v=vOj7btx3ATg][YouTube]] or [[http://yasnippet.googlecode.com/files/yasnippet.avi][avi video]]).
283
284 The tab stops with the same number to the field act as its mirrors. If
285 none of the tab stops has an initial value, the first one is selected as
286 the field and others mirrors.
287
288 ** Mirrors with transformations <<mirror-transformations>>
289
290 If the value of an =${n:=-construct starts with and contains =$(=,
291 then it is interpreted as a mirror for field =n= with a
292 transformation. The mirror's text content is calculated according to
293 this transformation, which is Emacs-lisp code that gets evaluated in
294 an environment where the variable [[sym:yas-text][=yas-text=]] is bound to the text
295 content (string) contained in the field =n=. Here's an example for
296 Objective-C:
297
298 #+BEGIN_SRC snippet
299 - (${1:id})${2:foo}
300 {
301 return $2;
302 }
303
304 - (void)set${2:$(capitalize yas-text)}:($1)aValue
305 {
306 [$2 autorelease];
307 $2 = [aValue retain];
308 }
309 $0
310 #+END_SRC
311
312 Look at =${2:$(capitalize yas-text)}=, it is a mirror with
313 transformation instead of a field. The actual field is at the first
314 line: =${2:foo}=. When you type text in =${2:foo}=, the transformation
315 will be evaluated and the result will be placed there as the
316 transformed text. So in this example, if you type "baz" in the field,
317 the transformed text will be "Baz". This example is also available in
318 the screencast.
319
320 Another example is for =rst-mode=. In reStructuredText, the document
321 title can be some text surrounded by "===" below and above. The "==="
322 should be at least as long as the text. So
323
324 #+BEGIN_SRC rst
325 =====
326 Title
327 =====
328 #+END_SRC
329
330 is a valid title but
331
332 #+BEGIN_SRC rst
333 ===
334 Title
335 ===
336 #+END_SRC
337
338 is not. Here's an snippet for rst title:
339
340 #+BEGIN_SRC snippet
341 ${1:$(make-string (string-width yas-text) ?\=)}
342 ${1:Title}
343 ${1:$(make-string (string-width yas-text) ?\=)}
344
345 $0
346 #+END_SRC
347
348 ** Fields with transformations
349
350 From version 0.6 on, you can also have lisp transformation inside
351 fields. These work mostly mirror transformations but are evaluated when
352 you first enter the field, after each change you make to the field and
353 also just before you exit the field.
354
355 The syntax is also a tiny bit different, so that the parser can
356 distinguish between fields and mirrors. In the following example
357
358 : #define "${1:mydefine$(upcase yas-text)}"
359
360 =mydefine= gets automatically upcased to =MYDEFINE= once you enter the
361 field. As you type text, it gets filtered through the transformation
362 every time.
363
364 Note that to tell this kind of expression from a mirror with a
365 transformation, YASnippet needs extra text between the =:= and the
366 transformation's =$=. If you don't want this extra-text, you can use two
367 =$='s instead.
368
369 : #define "${1:$$(upcase yas-text)}"
370
371 Please note that as soon as a transformation takes place, it changes the
372 value of the field and sets it its internal modification state to
373 =true=. As a consequence, the auto-deletion behaviour of normal fields
374 does not take place. This is by design.
375
376 ** Choosing fields value from a list and other tricks
377
378 As mentioned, the field transformation is invoked just after you enter
379 the field, and with some useful variables bound, notably
380 [[sym:yas-modified-p][=yas-modified-p=]] and [[sym:yas-moving-away-p][=yas-moving-away-p=]]. Because of this feature you
381 can place a transformation in the primary field that lets you select
382 default values for it.
383
384 The [[sym:yas-choose-value][=yas-choose-value=]] does this work for you. For example:
385
386 #+BEGIN_SRC snippet
387 <div align="${2:$$(yas-choose-value '("right" "center" "left"))}">
388 $0
389 </div>
390 #+END_SRC
391
392 See the definition of [[sym:yas-choose-value][=yas-choose-value=]] to see how it was written using
393 the two variables.
394
395 Here's another use, for LaTeX-mode, which calls reftex-label just as you
396 enter snippet field 2. This one makes use of [[sym:yas-modified-p][=yas-modified-p=]] directly.
397
398 #+BEGIN_SRC snippet
399 \section{${1:"Titel der Tour"}}%
400 \index{$1}%
401 \label{{2:"waiting for reftex-label call..."$(unless yas-modified-p (reftex-label nil 'dont-
402 insert))}}%
403 #+END_SRC
404
405 The function [[sym:yas-verify-value][=yas-verify-value=]] has another neat trick, and makes use
406 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]]
407
408 ** Nested placeholder fields
409
410 From version 0.6 on, you can also have nested placeholders of the type:
411
412 #+BEGIN_SRC snippet
413 <div${1: id="${2:some_id}"}>$0</div>
414 #+END_SRC
415
416 This allows you to choose if you want to give this =div= an =id=
417 attribute. If you tab forward after expanding it will let you change
418 "some\_id" to whatever you like. Alternatively, you can just press =C-d=
419 (which executes [[sym:yas-skip-and-clear-or-delete-char][=yas-skip-and-clear-or-delete-char=]]) and go straight to
420 the exit marker.
421
422 By the way, =C-d= will only clear the field if you cursor is at the
423 beginning of the field /and/ it hasn't been changed yet. Otherwise, it
424 performs the normal Emacs =delete-char= command.
425
426 ** Indentation markers
427
428 If [[sym:yas-indent-line][=yas-indent-line=]] is *not* set to '=auto=, it's still possible to
429 indent specific lines by adding an indentation marker, =$>=, somewhere
430 on the line.