]> code.delx.au - gnu-emacs-elpa/blob - yasnippet.el
Added a few ert unit tests, mostly for very basic snippet mechanics
[gnu-emacs-elpa] / yasnippet.el
1 ;;; Yasnippet.el --- Yet another snippet extension for Emacs.
2
3 ;; Copyright 2008 pluskid
4 ;; 2009 pluskid, joaotavora
5
6 ;; Authors: pluskid <pluskid@gmail.com>, joaotavora <joaotavora@gmail.com>
7 ;; Version: 0.7.0
8 ;; Package-version: 0.7.0
9 ;; X-URL: http://github.com/capitaomorte/yasnippet
10 ;; Keywords: convenience, emulation
11 ;; URL: http://github.com/capitaomorte/yasnippet
12 ;; EmacsWiki: YaSnippetMode
13
14 ;; This file is free software; you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation; either version 2, or (at your option)
17 ;; any later version.
18
19 ;; This file is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
23
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs; see the file COPYING. If not, write to
26 ;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
27 ;; Boston, MA 02111-1307, USA.
28
29 ;;; Commentary:
30
31 ;; Basic steps to setup:
32 ;;
33 ;; (add-to-list 'load-path
34 ;; "~/.emacs.d/plugins/yasnippet")
35 ;; (require 'yasnippet)
36 ;; (yas/global-mode 1)
37 ;;
38 ;;
39 ;; Interesting variables are:
40 ;;
41 ;; `yas/snippet-dirs'
42 ;;
43 ;; The directory where user-created snippets are to be
44 ;; stored. Can also be a list of directories. In that case,
45 ;; when used for bulk (re)loading of snippets (at startup or
46 ;; via `yas/reload-all'), directories appearing earlier in
47 ;; the list shadow other dir's snippets. Also, the first
48 ;; directory is taken as the default for storing the user's
49 ;; new snippets.
50 ;;
51 ;; The deprecated `yas/root-directory' aliases this variable
52 ;; for backward-compatibility.
53 ;;
54 ;; `yas/extra-modes'
55 ;;
56 ;; A local variable that you can set in a hook to override
57 ;; snippet-lookup based on major mode. It is a a symbol (or
58 ;; list of symbols) that correspond to subdirectories of
59 ;; `yas/snippet-dirs' and is used for deciding which
60 ;; snippets to consider for the active buffer.
61 ;;
62 ;; Deprecated `yas/mode-symbol' aliases this variable for
63 ;; backward-compatibility.
64 ;;
65 ;; Major commands are:
66 ;;
67 ;; M-x yas/expand
68 ;;
69 ;; Try to expand snippets before point. In `yas/minor-mode',
70 ;; this is bound to `yas/trigger-key' which you can customize.
71 ;;
72 ;; M-x yas/load-directory
73 ;;
74 ;; Prompts you for a directory hierarchy of snippets to load.
75 ;;
76 ;; M-x yas/insert-snippet
77 ;;
78 ;; Prompts you for possible snippet expansion if that is
79 ;; possible according to buffer-local and snippet-local
80 ;; expansion conditions. With prefix argument, ignore these
81 ;; conditions.
82 ;;
83 ;; M-x yas/find-snippets
84 ;;
85 ;; Lets you find the snippet files in the correct
86 ;; subdirectory of `yas/snippet-dirs', according to the
87 ;; active major mode (if it exists) like
88 ;; `find-file-other-window'.
89 ;;
90 ;; M-x yas/visit-snippet-file
91 ;;
92 ;; Prompts you for possible snippet expansions like
93 ;; `yas/insert-snippet', but instead of expanding it, takes
94 ;; you directly to the snippet definition's file, if it
95 ;; exists.
96 ;;
97 ;; M-x yas/new-snippet
98 ;;
99 ;; Lets you create a new snippet file in the correct
100 ;; subdirectory of `yas/snippet-dirs', according to the
101 ;; active major mode.
102 ;;
103 ;; M-x yas/load-snippet-buffer
104 ;;
105 ;; When editing a snippet, this loads the snippet. This is
106 ;; bound to "C-c C-c" while in the `snippet-mode' editing
107 ;; mode.
108 ;;
109 ;; M-x yas/tryout-snippet
110 ;;
111 ;; When editing a snippet, this opens a new empty buffer,
112 ;; sets it to the appropriate major mode and inserts the
113 ;; snippet there, so you can see what it looks like. This is
114 ;; bound to "C-c C-t" while in `snippet-mode'.
115 ;;
116 ;; M-x yas/describe-tables
117 ;;
118 ;; Lists known snippets in a separate buffer. User is
119 ;; prompted as to whether only the currently active tables
120 ;; are to be displayed, or all the tables for all major
121 ;; modes.
122 ;;
123 ;; The `dropdown-list.el' extension is bundled with YASnippet, you
124 ;; can optionally use it the preferred "prompting method", puting in
125 ;; your .emacs file, for example:
126 ;;
127 ;; (require 'dropdown-list)
128 ;; (setq yas/prompt-functions '(yas/dropdown-prompt
129 ;; yas/ido-prompt
130 ;; yas/completing-prompt))
131 ;;
132 ;; Also check out the customization group
133 ;;
134 ;; M-x customize-group RET yasnippet RET
135 ;;
136 ;; If you use the customization group to set variables
137 ;; `yas/snippet-dirs' or `yas/global-mode', make sure the path to
138 ;; "yasnippet.el" is present in the `load-path' *before* the
139 ;; `custom-set-variables' is executed in your .emacs file.
140 ;;
141 ;; For more information and detailed usage, refer to the project page:
142 ;; http://github.com/capitaomorte/yasnippet
143
144 ;;; Code:
145
146 (require 'cl)
147 (require 'assoc)
148 (require 'easymenu)
149 (require 'help-mode)
150
151 \f
152 ;;; User customizable variables
153
154 (defgroup yasnippet nil
155 "Yet Another Snippet extension"
156 :group 'editing)
157
158 (defvar yas/load-file-name load-file-name
159 "Store the filename that yasnippet.el was originally loaded from.")
160 (defcustom yas/snippet-dirs (remove nil
161 (list "~/.emacs.d/snippets"
162 (when yas/load-file-name
163 (concat (file-name-directory yas/load-file-name) "snippets"))))
164 "Directory or list of snippet dirs for each major mode.
165
166 The directory where user-created snippets are to be stored. Can
167 also be a list of directories. In that case, when used for
168 bulk (re)loading of snippets (at startup or via
169 `yas/reload-all'), directories appearing earlier in the list
170 shadow other dir's snippets. Also, the first directory is taken
171 as the default for storing the user's new snippets."
172 :type '(choice (string :tag "Single directory (string)")
173 (repeat :args (string) :tag "List of directories (strings)"))
174 :group 'yasnippet
175 :require 'yasnippet
176 :set #'(lambda (symbol new)
177 (let ((old (and (boundp symbol)
178 (symbol-value symbol))))
179 (set-default symbol new)
180 (unless (or (not (fboundp 'yas/reload-all))
181 (equal old new))
182 (yas/reload-all)))))
183 (defun yas/snippet-dirs ()
184 (if (listp yas/snippet-dirs) yas/snippet-dirs (list yas/snippet-dirs)))
185 (defvaralias 'yas/root-directory 'yas/snippet-dirs)
186
187 (defcustom yas/prompt-functions '(yas/x-prompt
188 yas/dropdown-prompt
189 yas/completing-prompt
190 yas/ido-prompt
191 yas/no-prompt)
192 "Functions to prompt for keys, templates, etc interactively.
193
194 These functions are called with the following arguments:
195
196 - PROMPT: A string to prompt the user
197
198 - CHOICES: a list of strings or objects.
199
200 - optional DISPLAY-FN : A function that, when applied to each of
201 the objects in CHOICES will return a string.
202
203 The return value of any function you put here should be one of
204 the objects in CHOICES, properly formatted with DISPLAY-FN (if
205 that is passed).
206
207 - To signal that your particular style of prompting is
208 unavailable at the moment, you can also have the function return
209 nil.
210
211 - To signal that the user quit the prompting process, you can
212 signal `quit' with
213
214 (signal 'quit \"user quit!\")."
215 :type '(repeat function)
216 :group 'yasnippet)
217
218 (defcustom yas/indent-line 'auto
219 "Controls indenting applied to a recent snippet expansion.
220
221 The following values are possible:
222
223 - `fixed' Indent the snippet to the current column;
224
225 - `auto' Indent each line of the snippet with `indent-according-to-mode'
226
227 Every other value means don't apply any snippet-side indendation
228 after expansion (the manual per-line \"$>\" indentation still
229 applies)."
230 :type '(choice (const :tag "Nothing" nothing)
231 (const :tag "Fixed" fixed)
232 (const :tag "Auto" auto))
233 :group 'yasnippet)
234
235 (defcustom yas/also-auto-indent-first-line nil
236 "Non-nil means also auto indent first line according to mode.
237
238 Naturally this is only valid when `yas/indent-line' is `auto'"
239 :type 'boolean
240 :group 'yasnippet)
241
242 (defcustom yas/snippet-revival t
243 "Non-nil means re-activate snippet fields after undo/redo."
244 :type 'boolean
245 :group 'yasnippet)
246
247 (defcustom yas/trigger-key "TAB"
248 "The key bound to `yas/expand' when function `yas/minor-mode' is active.
249
250 Value is a string that is converted to the internal Emacs key
251 representation using `read-kbd-macro'."
252 :type 'string
253 :group 'yasnippet
254 :set #'(lambda (symbol key)
255 (let ((old (and (boundp symbol)
256 (symbol-value symbol))))
257 (set-default symbol key)
258 ;; On very first loading of this defcustom,
259 ;; `yas/trigger-key' is *not* loaded.
260 (if (fboundp 'yas/trigger-key-reload)
261 (yas/trigger-key-reload old)))))
262
263 (defcustom yas/next-field-key '("TAB" "<tab>")
264 "The key to navigate to next field when a snippet is active.
265
266 Value is a string that is converted to the internal Emacs key
267 representation using `read-kbd-macro'.
268
269 Can also be a list of strings."
270 :type '(choice (string :tag "String")
271 (repeat :args (string) :tag "List of strings"))
272 :group 'yasnippet
273 :set #'(lambda (symbol val)
274 (set-default symbol val)
275 (if (fboundp 'yas/init-yas-in-snippet-keymap)
276 (yas/init-yas-in-snippet-keymap))))
277
278
279 (defcustom yas/prev-field-key '("<backtab>" "<S-tab>")
280 "The key to navigate to previous field when a snippet is active.
281
282 Value is a string that is converted to the internal Emacs key
283 representation using `read-kbd-macro'.
284
285 Can also be a list of strings."
286 :type '(choice (string :tag "String")
287 (repeat :args (string) :tag "List of strings"))
288 :group 'yasnippet
289 :set #'(lambda (symbol val)
290 (set-default symbol val)
291 (if (fboundp 'yas/init-yas-in-snippet-keymap)
292 (yas/init-yas-in-snippet-keymap))))
293
294 (defcustom yas/skip-and-clear-key '("C-d" "<delete>" "<deletechar>")
295 "The key to clear the currently active field.
296
297 Value is a string that is converted to the internal Emacs key
298 representation using `read-kbd-macro'.
299
300 Can also be a list of strings."
301 :type '(choice (string :tag "String")
302 (repeat :args (string) :tag "List of strings"))
303 :group 'yasnippet
304 :set #'(lambda (symbol val)
305 (set-default symbol val)
306 (if (fboundp 'yas/init-yas-in-snippet-keymap)
307 (yas/init-yas-in-snippet-keymap))))
308
309 (defcustom yas/triggers-in-field nil
310 "If non-nil, `yas/next-field-key' can trigger stacked expansions.
311
312 Otherwise, `yas/next-field-key' just tries to move on to the next
313 field"
314 :type 'boolean
315 :group 'yasnippet)
316
317 (defcustom yas/fallback-behavior 'call-other-command
318 "How to act when `yas/trigger-key' does *not* expand a snippet.
319
320 - `call-other-command' means try to temporarily disable YASnippet
321 and call the next command bound to `yas/trigger-key'.
322
323 - nil or the symbol `return-nil' mean do nothing. (and
324 `yas/expand-returns' nil)
325
326 - A lisp form (apply COMMAND . ARGS) means interactively call
327 COMMAND, if ARGS is non-nil, call COMMAND non-interactively
328 with ARGS as arguments."
329 :type '(choice (const :tag "Call previous command" call-other-command)
330 (const :tag "Do nothing" return-nil))
331 :group 'yasnippet)
332
333 (defcustom yas/choose-keys-first nil
334 "If non-nil, prompt for snippet key first, then for template.
335
336 Otherwise prompts for all possible snippet names.
337
338 This affects `yas/insert-snippet' and `yas/visit-snippet-file'."
339 :type 'boolean
340 :group 'yasnippet)
341
342 (defcustom yas/choose-tables-first nil
343 "If non-nil, and multiple eligible snippet tables, prompts user for tables first.
344
345 Otherwise, user chooses between the merging together of all
346 eligible tables.
347
348 This affects `yas/insert-snippet', `yas/visit-snippet-file'"
349 :type 'boolean
350 :group 'yasnippet)
351
352 (defcustom yas/use-menu 'abbreviate
353 "Display a YASnippet menu in the menu bar.
354
355 When non-nil, submenus for each snippet table will be listed
356 under the menu \"Yasnippet\".
357
358 - If set to `real-modes' only submenus whose name more or less
359 corresponds to a major mode are listed.
360
361 - If set to `abbreviate', only the current major-mode
362 menu and the modes set in `yas/extra-modes' are listed.
363
364 Any other non-nil value, every submenu is listed."
365 :type '(choice (const :tag "Full" t)
366 (const :tag "Real modes only" real-modes)
367 (const :tag "Abbreviate" abbreviate))
368 :group 'yasnippet)
369
370 (defcustom yas/trigger-symbol " =>"
371 "The text that will be used in menu to represent the trigger."
372 :type 'string
373 :group 'yasnippet)
374
375 (defcustom yas/wrap-around-region nil
376 "If non-nil, snippet expansion wraps around selected region.
377
378 The wrapping occurs just before the snippet's exit marker. This
379 can be overriden on a per-snippet basis."
380 :type 'boolean
381 :group 'yasnippet)
382
383 (defcustom yas/good-grace t
384 "If non-nil, don't raise errors in inline elisp evaluation.
385
386 An error string \"[yas] error\" is returned instead."
387 :type 'boolean
388 :group 'yasnippet)
389
390 (defcustom yas/visit-from-menu nil
391 "If non-nil visit snippets's files from menu, instead of expanding them.
392
393 This cafn only work when snippets are loaded from files."
394 :type 'boolean
395 :group 'yasnippet)
396
397 (defcustom yas/expand-only-for-last-commands nil
398 "List of `last-command' values to restrict tab-triggering to, or nil.
399
400 Leave this set at nil (the default) to be able to trigger an
401 expansion simply by placing the cursor after a valid tab trigger,
402 using whichever commands.
403
404 Optionallly, set this to something like '(self-insert-command) if
405 you to wish restrict expansion to only happen when the last
406 letter of the snippet tab trigger was typed immediately before
407 the trigger key itself."
408 :type '(repeat function)
409 :group 'yasnippet)
410
411 ;; Only two faces, and one of them shouldn't even be used...
412 ;;
413 (defface yas/field-highlight-face
414 '((t (:inherit 'region)))
415 "The face used to highlight the currently active field of a snippet"
416 :group 'yasnippet)
417
418 (defface yas/field-debug-face
419 '()
420 "The face used for debugging some overlays normally hidden"
421 :group 'yasnippet)
422
423 \f
424 ;;; User can also customize the next defvars
425 (defun yas/define-some-keys (keys keymap definition)
426 "Bind KEYS to DEFINITION in KEYMAP, read with `read-kbd-macro'."
427 (let ((keys (or (and (listp keys) keys)
428 (list keys))))
429 (dolist (key keys)
430 (define-key keymap (read-kbd-macro key) definition))))
431
432 (defvar yas/keymap
433 (let ((map (make-sparse-keymap)))
434 (mapc #'(lambda (binding)
435 (yas/define-some-keys (car binding) map (cdr binding)))
436 `((,yas/next-field-key . yas/next-field-or-maybe-expand)
437 (,yas/prev-field-key . yas/prev-field)
438 ("C-g" . yas/abort-snippet)
439 (,yas/skip-and-clear-key . yas/skip-and-clear-or-delete-char)))
440 map)
441 "The keymap active while a snippet expansion is in progress.")
442
443 (defvar yas/key-syntaxes (list "w" "w_" "w_." "w_.()" "^ ")
444 "List of character syntaxes used to find a trigger key before point.
445 The list is tried in the order while scanning characters
446 backwards from point. For example, if the list is '(\"w\" \"w_\")
447 first look for trigger keys which are composed exclusively of
448 \"word\"-syntax characters, and then, if that fails, look for
449 keys which are either of \"word\" or \"symbol\"
450 syntax. Triggering after
451
452 foo-bar
453
454 will, according to the \"w\" element first try \"bar\". If that
455 isn't a trigger key, \"foo-bar\" is tried, respecting a second
456 \"w_\" element.")
457
458 (defvar yas/after-exit-snippet-hook
459 '()
460 "Hooks to run after a snippet exited.
461
462 The hooks will be run in an environment where some variables bound to
463 proper values:
464
465 `yas/snippet-beg' : The beginning of the region of the snippet.
466
467 `yas/snippet-end' : Similar to beg.
468
469 Attention: These hooks are not run when exiting nested/stackd snippet expansion!")
470
471 (defvar yas/before-expand-snippet-hook
472 '()
473 "Hooks to run just before expanding a snippet.")
474
475 (defvar yas/buffer-local-condition
476 '(if (and (or (fourth (syntax-ppss))
477 (fifth (syntax-ppss)))
478 (eq (symbol-function this-command) 'yas/expand-from-trigger-key))
479 '(require-snippet-condition . force-in-comment)
480 t)
481 "Snippet expanding condition.
482
483 This variable is a lisp form which is evaluated everytime a
484 snippet expansion is attemped:
485
486 * If it evaluates to nil, no snippets can be expanded.
487
488 * If it evaluates to the a cons (require-snippet-condition
489 . REQUIREMENT)
490
491 * Snippets bearing no \"# condition:\" directive are not
492 considered
493
494 * Snippets bearing conditions that evaluate to nil (or
495 produce an error) won't be onsidered.
496
497 * If the snippet has a condition that evaluates to non-nil
498 RESULT:
499
500 * If REQUIREMENT is t, the snippet is considered
501
502 * If REQUIREMENT is `eq' RESULT, the snippet is
503 considered
504
505 * Otherwise, the snippet is not considered.
506
507 * If it evaluates to the symbol 'always, all snippets are
508 considered for expansion, regardless of any conditions.
509
510 * If it evaluates to t or some other non-nil value
511
512 * Snippet bearing no conditions, or conditions that
513 evaluate to non-nil, are considered for expansion.
514
515 * Otherwise, the snippet is not considered.
516
517 Here's an example preventing snippets from being expanded from
518 inside comments, in `python-mode' only, with the exception of
519 snippets returning the symbol 'force-in-comment in their
520 conditions.
521
522 (add-hook 'python-mode-hook
523 '(lambda ()
524 (setq yas/buffer-local-condition
525 '(if (python-in-string/comment)
526 '(require-snippet-condition . force-in-comment)
527 t))))
528
529 The default value is similar, it filters out potential snippet
530 expansions inside comments and string literals, unless the
531 snippet itself contains a condition that returns the symbol
532 `force-in-comment'.")
533
534 \f
535 ;;; Internal variables
536
537 (defvar yas/version "0.7.0")
538
539 (defvar yas/menu-table (make-hash-table)
540 "A hash table of MAJOR-MODE symbols to menu keymaps.")
541
542 (defvar yas/known-modes
543 '(ruby-mode rst-mode markdown-mode)
544 "A list of mode which is well known but not part of emacs.")
545
546 (defvar yas/escaped-characters
547 '(?\\ ?` ?\" ?' ?$ ?} ?{ ?\( ?\))
548 "List of characters which *might* need to be escaped.")
549
550 (defconst yas/field-regexp
551 "${\\([0-9]+:\\)?\\([^}]*\\)}"
552 "A regexp to *almost* recognize a field.")
553
554 (defconst yas/multi-dollar-lisp-expression-regexp
555 "$+[ \t\n]*\\(([^)]*)\\)"
556 "A regexp to *almost* recognize a \"$(...)\" expression.")
557
558 (defconst yas/backquote-lisp-expression-regexp
559 "`\\([^`]*\\)`"
560 "A regexp to recognize a \"`lisp-expression`\" expression." )
561
562 (defconst yas/transform-mirror-regexp
563 "${\\(?:\\([0-9]+\\):\\)?$\\([ \t\n]*([^}]*\\)"
564 "A regexp to *almost* recognize a mirror with a transform.")
565
566 (defconst yas/simple-mirror-regexp
567 "$\\([0-9]+\\)"
568 "A regexp to recognize a simple mirror.")
569
570 (defvar yas/snippet-id-seed 0
571 "Contains the next id for a snippet.")
572
573 (defun yas/snippet-next-id ()
574 (let ((id yas/snippet-id-seed))
575 (incf yas/snippet-id-seed)
576 id))
577
578 \f
579 ;;; Minor mode stuff
580
581 ;; XXX: `last-buffer-undo-list' is somehow needed in Carbon Emacs for MacOSX
582 (defvar last-buffer-undo-list nil)
583
584 (defvar yas/minor-mode-menu nil
585 "Holds the YASnippet menu")
586
587 (defun yas/init-minor-keymap ()
588 (let ((map (make-sparse-keymap)))
589 (easy-menu-define yas/minor-mode-menu
590 map
591 "Menu used when YAS/minor-mode is active."
592 '("YASnippet"
593 "----"
594 ["Expand trigger" yas/expand
595 :help "Possibly expand tab trigger before point"]
596 ["Insert at point..." yas/insert-snippet
597 :help "Prompt for an expandable snippet and expand it at point"]
598 ["New snippet..." yas/new-snippet
599 :help "Create a new snippet in an appropriate directory"]
600 ["Visit snippet file..." yas/visit-snippet-file
601 :help "Prompt for an expandable snippet and find its file"]
602 ["Find snippets..." yas/find-snippets
603 :help "Invoke `find-file' in the appropriate snippet directory"]
604 "----"
605 ("Snippet menu behaviour"
606 ["Visit snippets" (setq yas/visit-from-menu t)
607 :help "Visit snippets from the menu"
608 :active t :style radio :selected yas/visit-from-menu]
609 ["Expand snippets" (setq yas/visit-from-menu nil)
610 :help "Expand snippets from the menu"
611 :active t :style radio :selected (not yas/visit-from-menu)]
612 "----"
613 ["Show \"Real\" modes only" (setq yas/use-menu 'real-modes)
614 :help "Show snippet submenus for modes that appear to be real major modes"
615 :active t :style radio :selected (eq yas/use-menu 'real-modes)]
616 ["Show all modes" (setq yas/use-menu 't)
617 :help "Show one snippet submenu for each loaded table"
618 :active t :style radio :selected (eq yas/use-menu 't)]
619 ["Abbreviate according to current mode" (setq yas/use-menu 'abbreviate)
620 :help "Show only snippet submenus for the current active modes"
621 :active t :style radio :selected (eq yas/use-menu 'abbreviate)])
622 ("Indenting"
623 ["Auto" (setq yas/indent-line 'auto)
624 :help "Indent each line of the snippet with `indent-according-to-mode'"
625 :active t :style radio :selected (eq yas/indent-line 'auto)]
626 ["Fixed" (setq yas/indent-line 'fixed)
627 :help "Indent the snippet to the current column"
628 :active t :style radio :selected (eq yas/indent-line 'fixed)]
629 ["None" (setq yas/indent-line 'none)
630 :help "Don't apply any particular snippet indentation after expansion"
631 :active t :style radio :selected (not (member yas/indent-line '(fixed auto)))]
632 "----"
633 ["Also auto indent first line" (setq yas/also-auto-indent-first-line
634 (not yas/also-auto-indent-first-line))
635 :help "When auto-indenting also, auto indent the first line menu"
636 :active (eq yas/indent-line 'auto)
637 :style toggle :selected yas/also-auto-indent-first-line]
638 )
639 ("Prompting method"
640 ["System X-widget" (setq yas/prompt-functions
641 (cons 'yas/x-prompt
642 (remove 'yas/x-prompt
643 yas/prompt-functions)))
644 :help "Use your windowing system's (gtk, mac, windows, etc...) default menu"
645 :active t :style radio :selected (eq (car yas/prompt-functions)
646 'yas/x-prompt)]
647 ["Dropdown-list" (setq yas/prompt-functions
648 (cons 'yas/dropdown-prompt
649 (remove 'yas/dropdown-prompt
650 yas/prompt-functions)))
651 :help "Use a special dropdown list"
652 :active t :style radio :selected (eq (car yas/prompt-functions)
653 'yas/dropdown-prompt)]
654 ["Ido" (setq yas/prompt-functions
655 (cons 'yas/ido-prompt
656 (remove 'yas/ido-prompt
657 yas/prompt-functions)))
658 :help "Use an ido-style minibuffer prompt"
659 :active t :style radio :selected (eq (car yas/prompt-functions)
660 'yas/ido-prompt)]
661 ["Completing read" (setq yas/prompt-functions
662 (cons 'yas/completing-prompt
663 (remove 'yas/completing-prompt-prompt
664 yas/prompt-functions)))
665 :help "Use a normal minibuffer prompt"
666 :active t :style radio :selected (eq (car yas/prompt-functions)
667 'yas/completing-prompt-prompt)]
668 )
669 ("Misc"
670 ["Wrap region in exit marker"
671 (setq yas/wrap-around-region
672 (not yas/wrap-around-region))
673 :help "If non-nil automatically wrap the selected text in the $0 snippet exit"
674 :style toggle :selected yas/wrap-around-region]
675 ["Allow stacked expansions "
676 (setq yas/triggers-in-field
677 (not yas/triggers-in-field))
678 :help "If non-nil allow snippets to be triggered inside other snippet fields"
679 :style toggle :selected yas/triggers-in-field]
680 ["Revive snippets on undo "
681 (setq yas/snippet-revival
682 (not yas/snippet-revival))
683 :help "If non-nil allow snippets to become active again after undo"
684 :style toggle :selected yas/snippet-revival]
685 ["Good grace "
686 (setq yas/good-grace
687 (not yas/good-grace))
688 :help "If non-nil don't raise errors in bad embedded eslip in snippets"
689 :style toggle :selected yas/good-grace]
690 )
691 "----"
692 ["Load snippets..." yas/load-directory
693 :help "Load snippets from a specific directory"]
694 ["Reload everything" yas/reload-all
695 :help "Cleanup stuff, reload snippets, rebuild menus"]
696 ["About" yas/about
697 :help "Display some information about YASsnippet"]))
698 ;; Now for the stuff that has direct keybindings
699 ;;
700 (define-key map "\C-c&\C-s" 'yas/insert-snippet)
701 (define-key map "\C-c&\C-n" 'yas/new-snippet)
702 (define-key map "\C-c&\C-v" 'yas/visit-snippet-file)
703 (define-key map "\C-c&\C-f" 'yas/find-snippets)
704 map))
705
706 (defvar yas/minor-mode-map (yas/init-minor-keymap)
707 "The keymap used when `yas/minor-mode' is active.")
708
709 (defun yas/trigger-key-reload (&optional unbind-key)
710 "Rebind `yas/expand' to the new value of `yas/trigger-key'.
711
712 With optional UNBIND-KEY, try to unbind that key from
713 `yas/minor-mode-map'."
714 (when (and unbind-key
715 (stringp unbind-key)
716 (not (string= unbind-key "")))
717 (define-key yas/minor-mode-map (read-kbd-macro unbind-key) nil))
718 (when (and yas/trigger-key
719 (stringp yas/trigger-key)
720 (not (string= yas/trigger-key "")))
721 (define-key yas/minor-mode-map (read-kbd-macro yas/trigger-key) 'yas/expand)))
722
723 (defvar yas/tables (make-hash-table)
724 "A hash table of MAJOR-MODE symbols to `yas/table' objects.")
725
726 (defvar yas/direct-keymaps (list)
727 "Keymap alist supporting direct snippet keybindings.
728
729 This variable is is placed `emulation-mode-map-alists'.
730
731 Its elements looks like (TABLE-NAME . KEYMAP) and are
732 calculated when loading snippets. TABLE-NAME is a variable
733 set buffer-locally when entering `yas/minor-mode'. KEYMAP binds
734 all defined direct keybindings to the command
735 `yas/expand-from-keymap', which acts similarly to `yas/expand'")
736
737 (defun yas/direct-keymaps-reload ()
738 "Force reload the direct keybinding for active snippet tables."
739 (interactive)
740 (setq yas/direct-keymaps nil)
741 (maphash #'(lambda (name table)
742 (mapc #'(lambda (table)
743 (push (cons (intern (format "yas//direct-%s" name))
744 (yas/table-direct-keymap table))
745 yas/direct-keymaps))
746 (cons table (yas/table-get-all-parents table))))
747 yas/tables))
748
749 (defun yas/direct-keymaps-set-vars ()
750 (let ((modes-to-activate (list major-mode))
751 (mode major-mode))
752 (while (setq mode (get mode 'derived-mode-parent))
753 (push mode modes-to-activate))
754 (dolist (mode (yas/extra-modes))
755 (push mode modes-to-activate))
756 (dolist (mode modes-to-activate)
757 (let ((name (intern (format "yas//direct-%s" mode))))
758 (set-default name nil)
759 (set (make-local-variable name) t)))))
760
761 (defvar yas/minor-mode-hook nil
762 "Hook run when yas/minor-mode is turned on")
763
764 ;;;###autoload
765 (define-minor-mode yas/minor-mode
766 "Toggle YASnippet mode.
767
768 When YASnippet mode is enabled, the `tas/trigger-key' key expands
769 snippets of code depending on the mode.
770
771 With no argument, this command toggles the mode.
772 positive prefix argument turns on the mode.
773 Negative prefix argument turns off the mode.
774
775 You can customize the key through `yas/trigger-key'.
776
777 Key bindings:
778 \\{yas/minor-mode-map}"
779 nil
780 ;; The indicator for the mode line.
781 " yas"
782 :group 'yasnippet
783 (cond (yas/minor-mode
784 ;; Reload the trigger key
785 ;;
786 (yas/trigger-key-reload)
787 ;; Install the direct keymaps in `emulation-mode-map-alists'
788 ;; (we use `add-hook' even though it's not technically a hook,
789 ;; but it works). Then define variables named after modes to
790 ;; index `yas/direct-keymaps'.
791 ;;
792 ;; Also install the post-command-hook.
793 ;;
794 (add-hook 'emulation-mode-map-alists 'yas/direct-keymaps)
795 (add-hook 'post-command-hook 'yas/post-command-handler nil t)
796 (add-hook 'yas/minor-mode-hook 'yas/direct-keymaps-set-vars-runonce 'append))
797 (t
798 ;; Uninstall the direct keymaps and the post-command hook
799 ;;
800 (remove-hook 'post-command-hook 'yas/post-command-handler t)
801 (remove-hook 'emulation-mode-map-alists 'yas/direct-keymaps))))
802
803 (defun yas/direct-keymaps-set-vars-runonce ()
804 (yas/direct-keymaps-set-vars)
805 (remove-hook 'yas/minor-mode-hook 'yas/direct-keymaps-set-vars-runonce))
806
807 (defvar yas/dont-activate nil
808 "If non-nil don't let `yas/minor-mode-on' active yas for this buffer.
809
810 `yas/minor-mode-on' is usually called by `yas/global-mode' so
811 this effectively lets you define exceptions to the \"global\"
812 behaviour. Can also be a function of zero arguments.")
813 (make-variable-buffer-local 'yas/dont-activate)
814
815 (defun yas/minor-mode-on ()
816 "Turn on YASnippet minor mode.
817
818 Do this unless `yas/dont-activate' is truish "
819 (interactive)
820 (unless (or (minibufferp)
821 (if (functionp yas/dont-activate)
822 (funcall yas/dont-activate)
823 yas/dont-activate))
824 ;; Load all snippets definitions unless we still don't have a
825 ;; root-directory or some snippets have already been loaded.
826 ;;
827 (yas/minor-mode 1)))
828
829 ;;;###autoload
830 (define-globalized-minor-mode yas/global-mode yas/minor-mode yas/minor-mode-on
831 :group 'yasnippet
832 :require 'yasnippet)
833
834 (add-hook 'yas/global-mode-hook 'yas/reload-all-maybe)
835 (defun yas/reload-all-maybe ()
836 (if yas/global-mode
837 (yas/reload-all)))
838
839 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
840 ;; Major mode stuff
841 ;;
842 (defvar yas/font-lock-keywords
843 (append '(("^#.*$" . font-lock-comment-face))
844 lisp-font-lock-keywords
845 lisp-font-lock-keywords-1
846 lisp-font-lock-keywords-2
847 '(("$\\([0-9]+\\)"
848 (0 font-lock-keyword-face)
849 (1 font-lock-string-face t))
850 ("${\\([0-9]+\\):?"
851 (0 font-lock-keyword-face)
852 (1 font-lock-warning-face t))
853 ("${" font-lock-keyword-face)
854 ("$[0-9]+?" font-lock-preprocessor-face)
855 ("\\(\\$(\\)" 1 font-lock-preprocessor-face)
856 ("}"
857 (0 font-lock-keyword-face)))))
858
859 (defun yas/init-major-keymap ()
860 (let ((map (make-sparse-keymap)))
861 (easy-menu-define nil
862 map
863 "Menu used when snippet-mode is active."
864 (cons "Snippet"
865 (mapcar #'(lambda (ent)
866 (when (third ent)
867 (define-key map (third ent) (second ent)))
868 (vector (first ent) (second ent) t))
869 (list
870 (list "Load this snippet" 'yas/load-snippet-buffer "\C-c\C-c")
871 (list "Try out this snippet" 'yas/tryout-snippet "\C-c\C-t")))))
872 map))
873
874 (defvar snippet-mode-map
875 (yas/init-major-keymap)
876 "The keymap used when `snippet-mode' is active")
877
878
879 (define-derived-mode snippet-mode text-mode "Snippet"
880 "A mode for editing yasnippets"
881 (setq font-lock-defaults '(yas/font-lock-keywords))
882 (set (make-local-variable 'require-final-newline) nil)
883 (set (make-local-variable 'comment-start) "#")
884 (set (make-local-variable 'comment-start-skip) "#+[\t ]*"))
885
886
887 \f
888 ;;; Internal structs for template management
889
890 (defstruct (yas/template (:constructor yas/make-blank-template))
891 "A template for a snippet."
892 table
893 key
894 content
895 name
896 condition
897 expand-env
898 file
899 keybinding
900 uuid
901 menu-binding-pair
902 group ;; as dictated by the #group: directive or .yas-make-groups
903 perm-group ;; as dictated by `yas/define-menu'
904 )
905
906 (defun yas/populate-template (template &rest args)
907 "Helper function to populate a template with properties"
908 (let (p v)
909 (while args
910 (aset template
911 (position (intern (substring (symbol-name (car args)) 1))
912 (mapcar #'car (get 'yas/template 'cl-struct-slots)))
913 (second args))
914 (setq args (cddr args)))
915 template))
916
917 (defstruct (yas/table (:constructor yas/make-snippet-table (name)))
918 "A table to store snippets for a particular mode.
919
920 Has the following fields:
921
922 `yas/table-name'
923
924 A symbol name normally corresponding to a major mode, but can
925 also be a pseudo major-mode to be referenced in
926 `yas/extra-modes', for example.
927
928 `yas/table-hash'
929
930 A hash table (KEY . NAMEHASH), known as the \"keyhash\". KEY is
931 a string or a vector, where the former is the snippet's trigger
932 and the latter means it's a direct keybinding. NAMEHASH is yet
933 another hash of (NAME . TEMPLATE) where NAME is the snippet's
934 name and TEMPLATE is a `yas/template' object.
935
936 `yas/table-parents'
937
938 A list of tables considered parents of this table: i.e. when
939 searching for expansions they are searched as well.
940
941 `yas/table-direct-keymap'
942
943 A keymap for the snippets in this table that have direct
944 keybindings. This is kept in sync with the keyhash, i.e., all
945 the elements of the keyhash that are vectors appear here as
946 bindings to `yas/expand-from-keymap'.
947
948 `yas/table-uuidhash'
949
950 A hash table mapping snippets uuid's to the same `yas/template'
951 objects. A snippet uuid defaults to the snippet's name.
952 "
953 name
954 (hash (make-hash-table :test 'equal))
955 (uuidhash (make-hash-table :test 'equal))
956 (parents nil)
957 (direct-keymap (make-sparse-keymap)))
958
959 (defun yas/get-template-by-uuid (mode uuid)
960 "Find the snippet template in MODE by its UUID."
961 (let* ((table (gethash mode yas/tables mode)))
962 (when table
963 (gethash uuid (yas/table-uuidhash table)))))
964
965 ;; Apropos storing/updating, this works with two steps:
966 ;;
967 ;; 1. `yas/remove-template-by-uuid' to remove any existing mappings by
968 ;; snippet uuid
969 ;;
970 ;; 2. `yas/add-template' to add the mappings again:
971 ;;
972 ;; Create or index the entry in TABLES's `yas/table-hash'
973 ;; linking KEY to a namehash. That namehash links NAME to
974 ;; TEMPLATE, and is also created a new namehash inside that
975 ;; entry.
976 ;;
977 (defun yas/remove-template-by-uuid (table uuid)
978 "Remove from TABLE a template identified by UUID."
979 (let ((template (gethash uuid (yas/table-uuidhash table))))
980 (when template
981 (let* ((name (yas/template-name template))
982 (empty-keys nil))
983 ;; Remove the name from each of the targeted namehashes
984 ;;
985 (maphash #'(lambda (k v)
986 (let ((template (gethash name v)))
987 (when (and template
988 (eq uuid (yas/template-uuid template)))
989 (remhash name v)
990 (when (zerop (hash-table-count v))
991 (push k empty-keys)))))
992 (yas/table-hash table))
993 ;; Remove the namehashed themselves if they've become empty
994 ;;
995 (dolist (key empty-keys)
996 (remhash key (yas/table-hash table)))
997
998 ;; Finally, remove the uuid from the uuidhash
999 ;;
1000 (remhash uuid (yas/table-uuidhash table))))))
1001
1002
1003 (defun yas/add-template (table template)
1004 "Store in TABLE the snippet template TEMPLATE.
1005
1006 KEY can be a string (trigger key) of a vector (direct
1007 keybinding)."
1008 (let ((name (yas/template-name template))
1009 (key (yas/template-key template))
1010 (keybinding (yas/template-keybinding template))
1011 (menu-binding (car (yas/template-menu-binding-pair template))))
1012 (dolist (k (remove nil (list key keybinding)))
1013 (puthash name
1014 template
1015 (or (gethash k
1016 (yas/table-hash table))
1017 (puthash k
1018 (make-hash-table :test 'equal)
1019 (yas/table-hash table))))
1020 (when (vectorp k)
1021 (define-key (yas/table-direct-keymap table) k 'yas/expand-from-keymap)))
1022
1023 (when menu-binding
1024 (setf (getf (cdr menu-binding) :keys)
1025 (or (and keybinding (key-description keybinding))
1026 (and key (concat key yas/trigger-symbol))))
1027 (setcar (cdr menu-binding)
1028 name))
1029
1030 (puthash (yas/template-uuid template) template (yas/table-uuidhash table))))
1031
1032 (defun yas/update-template (snippet-table template)
1033 "Add or update TEMPLATE in SNIPPET-TABLE.
1034
1035 Also takes care of adding and updaring to the associated menu."
1036 ;; Remove from table by uuid
1037 ;;
1038 (yas/remove-template-by-uuid snippet-table (yas/template-uuid template))
1039 ;; Add to table again
1040 ;;
1041 (yas/add-template snippet-table template)
1042 ;; Take care of the menu
1043 ;;
1044 (let ((keymap (yas/menu-keymap-get-create snippet-table))
1045 (group (yas/template-group template)))
1046 (when (and yas/use-menu
1047 keymap
1048 (not (cdr (yas/template-menu-binding-pair template))))
1049 ;; Remove from menu keymap
1050 ;;
1051 (yas/delete-from-keymap keymap (yas/template-uuid template))
1052
1053 ;; Add necessary subgroups as necessary.
1054 ;;
1055 (dolist (subgroup group)
1056 (let ((subgroup-keymap (lookup-key keymap (vector (make-symbol subgroup)))))
1057 (unless (and subgroup-keymap
1058 (keymapp subgroup-keymap))
1059 (setq subgroup-keymap (make-sparse-keymap))
1060 (define-key keymap (vector (make-symbol subgroup))
1061 `(menu-item ,subgroup ,subgroup-keymap)))
1062 (setq keymap subgroup-keymap)))
1063
1064 ;; Add this entry to the keymap
1065 ;;
1066 (let ((menu-binding-pair (yas/snippet-menu-binding-pair-get-create template)))
1067 (define-key keymap (vector (make-symbol (yas/template-uuid template))) (car menu-binding-pair))))))
1068
1069 (defun yas/namehash-templates-alist (namehash)
1070 (let (alist)
1071 (maphash #'(lambda (k v)
1072 (push (cons k v) alist))
1073 namehash)
1074 alist))
1075
1076 (defun yas/fetch (table key)
1077 "Fetch templates in TABLE by KEY.
1078
1079 Return a list of cons (NAME . TEMPLATE) where NAME is a
1080 string and TEMPLATE is a `yas/template' structure."
1081 (let* ((keyhash (yas/table-hash table))
1082 (namehash (and keyhash (gethash key keyhash))))
1083 (when namehash
1084 (yas/filter-templates-by-condition (yas/namehash-templates-alist namehash)))))
1085
1086 \f
1087 ;;; Filtering/condition logic
1088
1089 (defun yas/eval-condition (condition)
1090 (condition-case err
1091 (save-excursion
1092 (save-restriction
1093 (save-match-data
1094 (eval condition))))
1095 (error (progn
1096 (message (format "[yas] error in condition evaluation: %s"
1097 (error-message-string err)))
1098 nil))))
1099
1100
1101 (defun yas/filter-templates-by-condition (templates)
1102 "Filter the templates using the applicable condition.
1103
1104 TEMPLATES is a list of cons (NAME . TEMPLATE) where NAME is a
1105 string and TEMPLATE is a `yas/template' structure.
1106
1107 This function implements the rules described in
1108 `yas/buffer-local-condition'. See that variables documentation."
1109 (let ((requirement (yas/require-template-specific-condition-p)))
1110 (if (eq requirement 'always)
1111 templates
1112 (remove-if-not #'(lambda (pair)
1113 (yas/template-can-expand-p
1114 (yas/template-condition (cdr pair)) requirement))
1115 templates))))
1116
1117 (defun yas/require-template-specific-condition-p ()
1118 "Decides if this buffer requests/requires snippet-specific
1119 conditions to filter out potential expansions."
1120 (if (eq 'always yas/buffer-local-condition)
1121 'always
1122 (let ((local-condition (or (and (consp yas/buffer-local-condition)
1123 (yas/eval-condition yas/buffer-local-condition))
1124 yas/buffer-local-condition)))
1125 (when local-condition
1126 (if (eq local-condition t)
1127 t
1128 (and (consp local-condition)
1129 (eq 'require-snippet-condition (car local-condition))
1130 (symbolp (cdr local-condition))
1131 (cdr local-condition)))))))
1132
1133 (defun yas/template-can-expand-p (condition requirement)
1134 "Evaluates CONDITION and REQUIREMENT and returns a boolean"
1135 (let* ((result (or (null condition)
1136 (yas/eval-condition condition))))
1137 (cond ((eq requirement t)
1138 result)
1139 (t
1140 (eq requirement result)))))
1141
1142 (defun yas/table-get-all-parents (table)
1143 "Returns a list of all parent tables of TABLE"
1144 (let ((parents (yas/table-parents table)))
1145 (when parents
1146 (append (copy-list parents)
1147 (mapcan #'yas/table-get-all-parents parents)))))
1148
1149 (defun yas/table-templates (table)
1150 (when table
1151 (let ((acc (list)))
1152 (maphash #'(lambda (key namehash)
1153 (maphash #'(lambda (name template)
1154 (push (cons name template) acc))
1155 namehash))
1156 (yas/table-hash table))
1157 (yas/filter-templates-by-condition acc))))
1158
1159 (defun yas/current-key ()
1160 "Get the key under current position. A key is used to find
1161 the template of a snippet in the current snippet-table."
1162 (let ((start (point))
1163 (end (point))
1164 (syntaxes yas/key-syntaxes)
1165 syntax
1166 done
1167 templates)
1168 (while (and (not done) syntaxes)
1169 (setq syntax (car syntaxes))
1170 (setq syntaxes (cdr syntaxes))
1171 (save-excursion
1172 (skip-syntax-backward syntax)
1173 (setq start (point)))
1174 (setq templates
1175 (mapcan #'(lambda (table)
1176 (yas/fetch table (buffer-substring-no-properties start end)))
1177 (yas/get-snippet-tables)))
1178 (if templates
1179 (setq done t)
1180 (setq start end)))
1181 (list templates
1182 start
1183 end)))
1184
1185
1186 (defun yas/table-all-keys (table)
1187 (when table
1188 (let ((acc))
1189 (maphash #'(lambda (key namehash)
1190 (when (yas/filter-templates-by-condition (yas/namehash-templates-alist namehash))
1191 (push key acc)))
1192 (yas/table-hash table))
1193 acc)))
1194
1195 \f
1196 ;;; Internal functions
1197
1198 (defun yas/real-mode? (mode)
1199 "Try to find out if MODE is a real mode. The MODE bound to
1200 a function (like `c-mode') is considered real mode. Other well
1201 known mode like `ruby-mode' which is not part of Emacs might
1202 not bound to a function until it is loaded. So yasnippet keeps
1203 a list of modes like this to help the judgement."
1204 (or (fboundp mode)
1205 (find mode yas/known-modes)))
1206
1207 (defun yas/eval-lisp (form)
1208 "Evaluate FORM and convert the result to string."
1209 (let ((retval (catch 'yas/exception
1210 (condition-case err
1211 (save-excursion
1212 (save-restriction
1213 (save-match-data
1214 (widen)
1215 (let ((result (eval form)))
1216 (when result
1217 (format "%s" result))))))
1218 (error (if yas/good-grace
1219 (format "[yas] elisp error! %s" (error-message-string err))
1220 (error (format "[yas] elisp error: %s"
1221 (error-message-string err)))))))))
1222 (when (and (consp retval)
1223 (eq 'yas/exception (car retval)))
1224 (error (cdr retval)))
1225 retval))
1226
1227 (defun yas/eval-lisp-no-saves (form)
1228 (condition-case err
1229 (eval form)
1230 (error (if yas/good-grace
1231 (format "[yas] elisp error! %s" (error-message-string err))
1232 (error (format "[yas] elisp error: %s"
1233 (error-message-string err)))))))
1234
1235 (defun yas/read-lisp (string &optional nil-on-error)
1236 "Read STRING as a elisp expression and return it.
1237
1238 In case STRING in an invalid expression and NIL-ON-ERROR is nil,
1239 return an expression that when evaluated will issue an error."
1240 (condition-case err
1241 (read string)
1242 (error (and (not nil-on-error)
1243 `(error (error-message-string ,err))))))
1244
1245 (defun yas/read-keybinding (keybinding)
1246 "Read KEYBINDING as a snippet keybinding, return a vector."
1247 (when (and keybinding
1248 (not (string-match "keybinding" keybinding)))
1249 (condition-case err
1250 (let ((res (or (and (string-match "^\\[.*\\]$" keybinding)
1251 (read keybinding))
1252 (read-kbd-macro keybinding 'need-vector))))
1253 res)
1254 (error
1255 (message "[yas] warning: keybinding \"%s\" invalid since %s."
1256 keybinding (error-message-string err))
1257 nil))))
1258
1259 (defvar yas/extra-modes nil
1260 "If non-nil, also lookup snippets for this/these modes.
1261
1262 Can be a symbol or a list of symbols.
1263
1264 This variable probably makes more sense as buffer-local, so
1265 ensure your use `make-local-variable' when you set it.")
1266 (defun yas/extra-modes ()
1267 (if (listp yas/extra-modes) yas/extra-modes (list yas/extra-modes)))
1268 (defvaralias 'yas/mode-symbol 'yas/extra-modes)
1269
1270 (defun yas/table-get-create (mode)
1271 "Get the snippet table corresponding to MODE.
1272
1273 Optional DIRECTORY gets recorded as the default directory to
1274 search for snippet files if the retrieved/created table didn't
1275 already have such a property."
1276 (let ((table (gethash mode
1277 yas/tables)))
1278 (unless table
1279 (setq table (yas/make-snippet-table (symbol-name mode)))
1280 (puthash mode table yas/tables)
1281 (aput 'yas/direct-keymaps (intern (format "yas//direct-%s" mode))
1282 (yas/table-direct-keymap table)))
1283 table))
1284
1285 (defun yas/get-snippet-tables (&optional mode-symbol dont-search-parents)
1286 "Get snippet tables for current buffer.
1287
1288 Return a list of 'yas/table' objects indexed by mode.
1289
1290 The modes are tried in this order: optional MODE-SYMBOL, then
1291 `yas/extra-modes', then `major-mode' then, unless
1292 DONT-SEARCH-PARENTS is non-nil, the guessed parent mode of either
1293 MODE-SYMBOL or `major-mode'.
1294
1295 Guessing is done by looking up the MODE-SYMBOL's
1296 `derived-mode-parent' property, see also `derived-mode-p'."
1297 (let ((mode-tables
1298 (remove nil
1299 (mapcar #'(lambda (mode)
1300 (gethash mode yas/tables))
1301 (remove nil (append (list mode-symbol)
1302 (yas/extra-modes)
1303 (list major-mode
1304 (and (not dont-search-parents)
1305 (get major-mode
1306 'derived-mode-parent)))))))))
1307 (remove-duplicates
1308 (append mode-tables
1309 (mapcan #'yas/table-get-all-parents mode-tables)))))
1310
1311 (defun yas/menu-keymap-get-create (table)
1312 "Get or create the main menu keymap correspondong to MODE.
1313
1314 This may very well create a plethora of menu keymaps and arrange
1315 them in all `yas/menu-table'"
1316 (let* ((mode (intern (yas/table-name table)))
1317 (menu-keymap (or (gethash mode yas/menu-table)
1318 (puthash mode (make-sparse-keymap) yas/menu-table)))
1319 (parents (yas/table-parents table)))
1320 (mapc #'yas/menu-keymap-get-create parents)
1321 (define-key yas/minor-mode-menu (vector mode)
1322 `(menu-item ,(symbol-name mode) ,menu-keymap
1323 :visible (yas/show-menu-p ',mode)))
1324 menu-keymap))
1325
1326 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1327 ;;; Template-related and snippet loading functions
1328
1329 (defun yas/parse-template (&optional file)
1330 "Parse the template in the current buffer.
1331
1332 Optional FILE is the absolute file name of the file being
1333 parsed.
1334
1335 Optional GROUP is the group where the template is to go,
1336 otherwise we attempt to calculate it from FILE.
1337
1338 Return a snippet-definition, i.e. a list
1339
1340 (KEY TEMPLATE NAME CONDITION GROUP VARS FILE KEYBINDING UUID)
1341
1342 If the buffer contains a line of \"# --\" then the contents above
1343 this line are ignored. Directives can set most of these with the syntax:
1344
1345 # directive-name : directive-value
1346
1347 Here's a list of currently recognized directives:
1348
1349 * type
1350 * name
1351 * contributor
1352 * condition
1353 * group
1354 * key
1355 * expand-env
1356 * binding
1357 * uuid"
1358 (goto-char (point-min))
1359 (let* ((type 'snippet)
1360 (name (and file
1361 (file-name-nondirectory file)))
1362 (key nil)
1363 template
1364 bound
1365 condition
1366 (group (and file
1367 (yas/calculate-group file)))
1368 expand-env
1369 binding
1370 uuid)
1371 (if (re-search-forward "^# --\n" nil t)
1372 (progn (setq template
1373 (buffer-substring-no-properties (point)
1374 (point-max)))
1375 (setq bound (point))
1376 (goto-char (point-min))
1377 (while (re-search-forward "^# *\\([^ ]+?\\) *: *\\(.*\\)$" bound t)
1378 (when (string= "uuid" (match-string-no-properties 1))
1379 (setq uuid (match-string-no-properties 2)))
1380 (when (string= "type" (match-string-no-properties 1))
1381 (setq type (if (string= "command" (match-string-no-properties 2))
1382 'command
1383 'snippet)))
1384 (when (string= "key" (match-string-no-properties 1))
1385 (setq key (match-string-no-properties 2)))
1386 (when (string= "name" (match-string-no-properties 1))
1387 (setq name (match-string-no-properties 2)))
1388 (when (string= "condition" (match-string-no-properties 1))
1389 (setq condition (yas/read-lisp (match-string-no-properties 2))))
1390 (when (string= "group" (match-string-no-properties 1))
1391 (setq group (match-string-no-properties 2)))
1392 (when (string= "expand-env" (match-string-no-properties 1))
1393 (setq expand-env (yas/read-lisp (match-string-no-properties 2)
1394 'nil-on-error)))
1395 (when (string= "binding" (match-string-no-properties 1))
1396 (setq binding (match-string-no-properties 2)))))
1397 (setq template
1398 (buffer-substring-no-properties (point-min) (point-max))))
1399 (when (eq type 'command)
1400 (setq template (yas/read-lisp (concat "(progn" template ")"))))
1401 (when group
1402 (setq group (split-string group "\\.")))
1403 (list key template name condition group expand-env file binding uuid)))
1404
1405 (defun yas/calculate-group (file)
1406 "Calculate the group for snippet file path FILE."
1407 (let* ((dominating-dir (locate-dominating-file file
1408 ".yas-make-groups"))
1409 (extra-path (and dominating-dir
1410 (replace-regexp-in-string (concat "^"
1411 (expand-file-name dominating-dir))
1412 ""
1413 (expand-file-name file))))
1414 (extra-dir (and extra-path
1415 (file-name-directory extra-path)))
1416 (group (and extra-dir
1417 (replace-regexp-in-string "/"
1418 "."
1419 (directory-file-name extra-dir)))))
1420 group))
1421
1422 (defun yas/subdirs (directory &optional filep)
1423 "Return subdirs or files of DIRECTORY according to FILEP."
1424 (remove-if (lambda (file)
1425 (or (string-match "^\\."
1426 (file-name-nondirectory file))
1427 (string-match "^#.*#$"
1428 (file-name-nondirectory file))
1429 (string-match "~$"
1430 (file-name-nondirectory file))
1431 (if filep
1432 (file-directory-p file)
1433 (not (file-directory-p file)))))
1434 (directory-files directory t)))
1435
1436 (defun yas/make-menu-binding (template)
1437 (let ((mode (intern (yas/table-name (yas/template-table template)))))
1438 `(lambda () (interactive) (yas/expand-or-visit-from-menu ',mode ,(yas/template-uuid template)))))
1439
1440 (defun yas/expand-or-visit-from-menu (mode uuid)
1441 (let* ((table (yas/table-get-create mode))
1442 (yas/current-template (and table
1443 (gethash uuid (yas/table-uuidhash table)))))
1444 (when yas/current-template
1445 (if yas/visit-from-menu
1446 (yas/visit-snippet-file-1 yas/current-template)
1447 (let ((where (if (region-active-p)
1448 (cons (region-beginning) (region-end))
1449 (cons (point) (point)))))
1450 (yas/expand-snippet (yas/template-content yas/current-template)
1451 (car where)
1452 (cdr where)
1453 (yas/template-expand-env yas/current-template)))))))
1454
1455 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1456 ;; Popping up for keys and templates
1457 ;;
1458 (defvar yas/x-pretty-prompt-templates nil
1459 "If non-nil, attempt to prompt for templates like TextMate.")
1460
1461
1462 (defun yas/prompt-for-template (templates &optional prompt)
1463 "Interactively choose a template from the list TEMPLATES.
1464
1465 TEMPLATES is a list of `yas/template'."
1466 (when templates
1467 (setq templates
1468 (sort templates #'(lambda (t1 t2)
1469 (< (length (yas/template-name t1))
1470 (length (yas/template-name t2))))))
1471 (if yas/x-pretty-prompt-templates
1472 (yas/x-pretty-prompt-templates "Choose a snippet" templates)
1473 (some #'(lambda (fn)
1474 (funcall fn (or prompt "Choose a snippet: ")
1475 templates
1476 #'yas/template-name))
1477 yas/prompt-functions))))
1478
1479 (defun yas/prompt-for-keys (keys &optional prompt)
1480 "Interactively choose a template key from the list KEYS."
1481 (when keys
1482 (some #'(lambda (fn)
1483 (funcall fn (or prompt "Choose a snippet key: ") keys))
1484 yas/prompt-functions)))
1485
1486 (defun yas/prompt-for-table (tables &optional prompt)
1487 (when tables
1488 (some #'(lambda (fn)
1489 (funcall fn (or prompt "Choose a snippet table: ")
1490 tables
1491 #'yas/table-name))
1492 yas/prompt-functions)))
1493
1494 (defun yas/x-prompt (prompt choices &optional display-fn)
1495 "Display choices in a x-window prompt."
1496 ;; FIXME: HACK: if we notice that one of the objects in choices is
1497 ;; actually a `yas/template', defer to `yas/x-prompt-pretty-templates'
1498 ;;
1499 ;; This would be better implemented by passing CHOICES as a
1500 ;; strucutred tree rather than a list. Modifications would go as far
1501 ;; up as `yas/all-templates' I think.
1502 ;;
1503 (when (and window-system choices)
1504 (let ((chosen
1505 (let (menu d) ;; d for display
1506 (dolist (c choices)
1507 (setq d (or (and display-fn (funcall display-fn c))
1508 c))
1509 (cond ((stringp d)
1510 (push (cons (concat " " d) c) menu))
1511 ((listp d)
1512 (push (car d) menu))))
1513 (setq menu (list prompt (push "title" menu)))
1514 (x-popup-menu (if (fboundp 'posn-at-point)
1515 (let ((x-y (posn-x-y (posn-at-point (point)))))
1516 (list (list (+ (car x-y) 10)
1517 (+ (cdr x-y) 20))
1518 (selected-window)))
1519 t)
1520 menu))))
1521 (or chosen
1522 (keyboard-quit)))))
1523
1524 (defun yas/x-pretty-prompt-templates (prompt templates)
1525 "Display TEMPLATES, grouping neatly by table name."
1526 (let ((pretty-alist (list))
1527 menu
1528 more-than-one-table
1529 prefix)
1530 (dolist (tl templates)
1531 (aput 'pretty-alist (yas/template-table tl) (cons tl (aget pretty-alist (yas/template-table tl)))))
1532 (setq more-than-one-table (> (length pretty-alist) 1))
1533 (setq prefix (if more-than-one-table
1534 " " ""))
1535 (dolist (table-and-templates pretty-alist)
1536 (when (cdr table-and-templates)
1537 (if more-than-one-table
1538 (push (yas/table-name (car table-and-templates)) menu))
1539 (dolist (template (cdr table-and-templates))
1540 (push (cons (concat prefix (yas/template-name template))
1541 template) menu))))
1542 (setq menu (nreverse menu))
1543 (or (x-popup-menu (if (fboundp 'posn-at-point)
1544 (let ((x-y (posn-x-y (posn-at-point (point)))))
1545 (list (list (+ (car x-y) 10)
1546 (+ (cdr x-y) 20))
1547 (selected-window)))
1548 t)
1549 (list prompt (push "title" menu)))
1550 (keyboard-quit))))
1551
1552 (defun yas/ido-prompt (prompt choices &optional display-fn)
1553 (when (featurep 'ido)
1554 (yas/completing-prompt prompt choices display-fn #'ido-completing-read)))
1555
1556 (eval-when-compile (require 'dropdown-list nil t))
1557 (defun yas/dropdown-prompt (prompt choices &optional display-fn)
1558 (when (featurep 'dropdown-list)
1559 (let (formatted-choices
1560 filtered-choices
1561 d
1562 n)
1563 (dolist (choice choices)
1564 (setq d (or (and display-fn (funcall display-fn choice))
1565 choice))
1566 (when (stringp d)
1567 (push d formatted-choices)
1568 (push choice filtered-choices)))
1569
1570 (setq n (and formatted-choices (dropdown-list formatted-choices)))
1571 (if n
1572 (nth n filtered-choices)
1573 (keyboard-quit)))))
1574
1575 (defun yas/completing-prompt (prompt choices &optional display-fn completion-fn)
1576 (let (formatted-choices
1577 filtered-choices
1578 chosen
1579 d
1580 (completion-fn (or completion-fn
1581 #'completing-read)))
1582 (dolist (choice choices)
1583 (setq d (or (and display-fn (funcall display-fn choice))
1584 choice))
1585 (when (stringp d)
1586 (push d formatted-choices)
1587 (push choice filtered-choices)))
1588 (setq chosen (and formatted-choices
1589 (funcall completion-fn prompt
1590 formatted-choices
1591 nil
1592 'require-match
1593 nil
1594 nil)))
1595 (when chosen
1596 (nth (position chosen formatted-choices :test #'string=) filtered-choices))))
1597
1598 (defun yas/no-prompt (prompt choices &optional display-fn)
1599 (first choices))
1600
1601 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1602 ;; Loading snippets from files
1603 ;;
1604 (defun yas/load-directory-1 (directory mode-sym parents &optional no-compiled-snippets)
1605 "Recursively load snippet templates from DIRECTORY."
1606 (unless (file-exists-p (concat directory "/" ".yas-skip"))
1607 ;; Load .yas-setup.el files wherever we find them
1608 ;;
1609 (load (expand-file-name ".yas-setup" directory) 'noerror)
1610 (if (and (not no-compiled-snippets)
1611 (load (expand-file-name ".yas-compiled-snippets" directory) 'noerror))
1612 (message "Loading much faster .yas-compiled-snippets from %s" directory)
1613 (let* ((default-directory directory)
1614 (snippet-defs nil))
1615 ;; load the snippet files
1616 ;;
1617 (with-temp-buffer
1618 (dolist (file (yas/subdirs directory 'no-subdirs-just-files))
1619 (when (file-readable-p file)
1620 (insert-file-contents file nil nil nil t)
1621 (push (yas/parse-template file)
1622 snippet-defs))))
1623 (when (or snippet-defs
1624 (cdr major-mode-and-parents))
1625 (yas/define-snippets mode-sym
1626 snippet-defs
1627 parents))
1628 ;; now recurse to a lower level
1629 ;;
1630 (dolist (subdir (yas/subdirs directory))
1631 (yas/load-directory-1 subdir
1632 mode-sym
1633 parents
1634 t))))))
1635
1636 (defun yas/load-directory (top-level-dir)
1637 "Load snippet definition from directory hierarchy under TOP-LEVEL-DIR.
1638
1639 Below TOP-LEVEL-DIR., each directory is a mode name."
1640 (interactive "DSelect the root directory: ")
1641 (unless (file-directory-p top-level-dir)
1642 (error "%s is not a directory" top-level-dir))
1643 (unless yas/snippet-dirs
1644 (setq yas/snippet-dirs top-level-dir))
1645 (dolist (dir (yas/subdirs top-level-dir))
1646 (let ((major-mode-and-parents (yas/compute-major-mode-and-parents
1647 (concat dir "/dummy"))))
1648 (yas/load-directory-1 dir
1649 (car major-mode-and-parents)
1650 (cdr major-mode-and-parents))))
1651 (when (interactive-p)
1652 (message "[yas] Loaded snippets from %s." top-level-dir)))
1653
1654 (defun yas/load-snippet-dirs ()
1655 "Reload the directories listed in `yas/snippet-dirs' or
1656 prompt the user to select one."
1657 (let (errors)
1658 (if yas/snippet-dirs
1659 (dolist (directory (reverse (yas/snippet-dirs)))
1660 (condition-case oops
1661 (progn
1662 (yas/load-directory directory)
1663 (message "[yas] Loaded %s" directory))
1664 (error (push oops errors)
1665 (message "[yas] Check your `yas/snippet-dirs': %s" (second oops)))))
1666 (call-interactively 'yas/load-directory))
1667 errors))
1668
1669 (defun yas/reload-all (&optional interactive)
1670 "Reload all snippets and rebuild the YASnippet menu. "
1671 (interactive "p")
1672 (let ((errors))
1673 ;; Empty all snippet tables and all menu tables
1674 ;;
1675 (setq yas/tables (make-hash-table))
1676 (setq yas/menu-table (make-hash-table))
1677
1678 ;; Init the `yas/minor-mode-map', taking care not to break the
1679 ;; menu....
1680 ;;
1681 (setf (cdr yas/minor-mode-map)
1682 (cdr (yas/init-minor-keymap)))
1683
1684 ;; Reload the directories listed in `yas/snippet-dirs' or prompt
1685 ;; the user to select one.
1686 ;;
1687 (setq errors (yas/load-snippet-dirs))
1688 ;; Reload the direct keybindings
1689 ;;
1690 (yas/direct-keymaps-reload)
1691 (message "[yas] Reloaded everything...%s." (if errors " (some errors, check *Messages*)" ""))))
1692
1693 (defun yas/quote-string (string)
1694 "Escape and quote STRING.
1695 foo\"bar\\! -> \"foo\\\"bar\\\\!\""
1696 (concat "\""
1697 (replace-regexp-in-string "[\\\"]"
1698 "\\\\\\&"
1699 string
1700 t)
1701 "\""))
1702 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1703 ;;; Snippet compilation function
1704
1705 (defun yas/initialize ()
1706 "For backward compatibility, enable `yas/minor-mode' globally"
1707 (yas/global-mode 1))
1708
1709 (defun yas/compile-top-level-dir (top-level-dir)
1710 "Create .yas-compiled-snippets.el files under subdirs of TOP-LEVEL-DIR."
1711 (interactive "DTop level snippet directory?")
1712 (dolist (dir (yas/subdirs top-level-dir))
1713 (yas/compile-snippets dir)))
1714
1715 (defun yas/compile-snippets (input-dir &optional output-file)
1716 "Compile snippets files in INPUT-DIR to OUTPUT-FILE file.
1717
1718 Prompts for INPUT-DIR and OUTPUT-FILE if called-interactively"
1719 (interactive (let* ((input-dir (read-directory-name "Snippet dir "))
1720 (output-file (let ((ido-everywhere nil))
1721 (read-file-name "Output file "
1722 input-dir nil nil
1723 ".yas-compiled-snippets.el"
1724 nil))))
1725 (list input-dir output-file)))
1726 (let ((default-directory input-dir))
1727 (with-temp-file (setq output-file (or output-file ".yas-compiled-snippets.el"))
1728 (flet ((yas/define-snippets
1729 (mode snippets &optional parent-or-parents)
1730 (insert (format ";;; %s - automatically compiled snippets for `%s' , do not edit!\n"
1731 (file-name-nondirectory output-file) mode))
1732 (insert ";;;\n")
1733 (let ((literal-snippets (list)))
1734 (dolist (snippet snippets)
1735 (let ((key (first snippet))
1736 (template-content (second snippet))
1737 (name (third snippet))
1738 (condition (fourth snippet))
1739 (group (fifth snippet))
1740 (expand-env (sixth snippet))
1741 (file nil) ;; (seventh snippet)) ;; omit on purpose
1742 (binding (eighth snippet))
1743 (uuid (ninth snippet)))
1744 (push `(,key
1745 ,template-content
1746 ,name
1747 ,condition
1748 ,group
1749 ,expand-env
1750 ,file
1751 ,binding
1752 ,uuid)
1753 literal-snippets)))
1754 (insert (pp-to-string `(yas/define-snippets ',mode ',literal-snippets ',parent-or-parents)))
1755 (insert "\n\n")
1756 (insert (format ";;; %s - automatically compiled snippets for `%s' end here\n"
1757 (file-name-nondirectory output-file) mode))
1758 (insert ";;;"))))
1759 (yas/load-directory-1 input-dir nil nil 'no-compiled-snippets))))
1760
1761 (if (and (called-interactively-p)
1762 (yes-or-no-p (format "Open the resulting file (%s)? "
1763 (expand-file-name output-file))))
1764 (find-file-other-window output-file)))
1765
1766
1767
1768 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1769 ;;; Some user level functions
1770 ;;;
1771
1772 (defun yas/about ()
1773 (interactive)
1774 (message (concat "yasnippet (version "
1775 yas/version
1776 ") -- pluskid <pluskid@gmail.com>/joaotavora <joaotavora@gmail.com>")))
1777
1778 (defun yas/define-snippets (mode snippets &optional parent-mode)
1779 "Define SNIPPETS for MODE.
1780
1781 SNIPPETS is a list of snippet definitions, each taking the
1782 following form
1783
1784 (KEY TEMPLATE NAME CONDITION GROUP EXPAND-ENV FILE KEYBINDING UUID)
1785
1786 Within these, only KEY and TEMPLATE are actually mandatory.
1787
1788 TEMPLATE might be a lisp form or a string, depending on whether
1789 this is a snippet or a snippet-command.
1790
1791 CONDITION, EXPAND-ENV and KEYBINDING are lisp forms, they have
1792 been `yas/read-lisp'-ed and will eventually be
1793 `yas/eval-lisp'-ed.
1794
1795 The remaining elements are strings.
1796
1797 FILE is probably of very little use if you're programatically
1798 defining snippets.
1799
1800 UUID is the snippets \"unique-id\". Loading a second snippet file
1801 with the same uuid replaced the previous snippet.
1802
1803 You can use `yas/parse-template' to return such lists based on
1804 the current buffers contents.
1805
1806 Optional PARENT-MODE can be used to specify the parent tables of
1807 MODE. It can be a mode symbol of a list of mode symbols. It does
1808 not need to be a real mode."
1809 ;; X) `snippet-table' is created or retrieved for MODE, same goes
1810 ;; for the list of snippet tables `parent-tables'.
1811 ;;
1812 (let ((snippet-table (yas/table-get-create mode))
1813 (parent-tables (mapcar #'yas/table-get-create
1814 (if (listp parent-mode)
1815 parent-mode
1816 (list parent-mode))))
1817 (template nil))
1818 ;; X) Connect `snippet-table' with `parent-tables'.
1819 ;;
1820 ;; TODO: this should be a remove-duplicates of the concatenation
1821 ;; of `snippet-table's existings parents with the new parents...
1822 ;;
1823 (dolist (parent parent-tables)
1824 (unless (find parent (yas/table-parents snippet-table))
1825 (push parent
1826 (yas/table-parents snippet-table))))
1827
1828 ;; X) Now, iterate for evey snippet def list
1829 ;;
1830 (dolist (snippet snippets)
1831 (setq template (yas/define-snippets-1 snippet
1832 snippet-table)))
1833 template))
1834
1835 (defun yas/define-snippets-1 (snippet snippet-table)
1836 "Helper for `yas/define-snippets'."
1837 ;; X) Calculate some more defaults on the values returned by
1838 ;; `yas/parse-template'.
1839 ;;
1840 (let* ((file (seventh snippet))
1841 (key (car snippet))
1842 (name (or (third snippet)
1843 (and file
1844 (file-name-directory file))))
1845 (condition (fourth snippet))
1846 (group (fifth snippet))
1847 (keybinding (yas/read-keybinding (eighth snippet)))
1848 (uuid (or (ninth snippet)
1849 name))
1850 (template (or (gethash uuid (yas/table-uuidhash snippet-table))
1851 (yas/make-blank-template))))
1852 ;; X) populate the template object
1853 ;;
1854 (yas/populate-template template
1855 :table snippet-table
1856 :key key
1857 :content (second snippet)
1858 :name (or name key)
1859 :group group
1860 :condition condition
1861 :expand-env (sixth snippet)
1862 :file (seventh snippet)
1863 :keybinding keybinding
1864 :uuid uuid)
1865 ;; X) Update this template in the appropriate table. This step
1866 ;; also will take care of adding the key indicators in the
1867 ;; templates menu entry, if any
1868 ;;
1869 (yas/update-template snippet-table template)
1870 ;; X) Return the template
1871 ;;
1872 ;;
1873 template))
1874
1875 (defun yas/snippet-menu-binding-pair-get-create (template &optional type)
1876 "Get TEMPLATE's menu binding or assign it a new one."
1877 (or (yas/template-menu-binding-pair template)
1878 (let ((key (yas/template-key template))
1879 (keybinding (yas/template-keybinding template)))
1880 (setf (yas/template-menu-binding-pair template)
1881 (cons `(menu-item ,(or (yas/template-name template)
1882 (yas/template-uuid template))
1883 ,(yas/make-menu-binding template)
1884 :keys ,nil)
1885 type)))))
1886
1887 (defun yas/show-menu-p (mode)
1888 (cond ((eq yas/use-menu 'abbreviate)
1889 (find mode
1890 (mapcar #'(lambda (table)
1891 (intern (yas/table-name table)))
1892 (yas/get-snippet-tables))))
1893 ((eq yas/use-menu 'real-modes)
1894 (yas/real-mode? mode))
1895 (t
1896 t)))
1897
1898 (defun yas/delete-from-keymap (keymap uuid)
1899 "Recursively delete items with UUID from KEYMAP and its submenus."
1900
1901 ;; XXX: This used to skip any submenus named \"parent mode\"
1902 ;;
1903 ;; First of all, recursively enter submenus, i.e. the tree is
1904 ;; searched depth first so that stale submenus can be found in the
1905 ;; higher passes.
1906 ;;
1907 (mapc #'(lambda (item)
1908 (when (and (listp (cdr item))
1909 (keymapp (third (cdr item))))
1910 (yas/delete-from-keymap (third (cdr item)) uuid)))
1911 (rest keymap))
1912 ;; Set the uuid entry to nil
1913 ;;
1914 (define-key keymap (vector (make-symbol uuid)) nil)
1915 ;; Destructively modify keymap
1916 ;;
1917 (setcdr keymap (delete-if #'(lambda (item)
1918 (or (null (cdr item))
1919 (and (keymapp (third (cdr item)))
1920 (null (cdr (third (cdr item)))))))
1921 (rest keymap))))
1922
1923 (defun yas/define-menu (mode menu omit-items)
1924 "Define a snippet menu for MODE according to MENU, ommitting OMIT-ITEMS.
1925
1926 MENU is a list, its elements can be:
1927
1928 - (yas/item UUID) : Creates an entry the snippet identified with
1929 UUID. The menu entry for a snippet thus identified is
1930 permanent, i.e. it will never move in the menu.
1931
1932 - (yas/separator) : Creates a separator
1933
1934 - (yas/submenu NAME SUBMENU) : Creates a submenu with NAME,
1935 SUBMENU has the same form as MENU. NAME is also added to the
1936 list of groups of the snippets defined thereafter.
1937
1938 OMIT-ITEMS is a list of snippet uuid's that will always be
1939 ommited from MODE's menu, even if they're manually loaded.
1940 "
1941 (let* ((table (yas/table-get-create mode))
1942 (hash (yas/table-uuidhash table)))
1943 (yas/define-menu-1 table
1944 (yas/menu-keymap-get-create table)
1945 menu
1946 hash)
1947 (dolist (uuid omit-items)
1948 (let ((template (or (gethash uuid hash)
1949 (yas/populate-template (puthash uuid
1950 (yas/make-blank-template)
1951 hash)
1952 :table table
1953 :uuid uuid))))
1954 (setf (yas/template-menu-binding-pair template) (cons nil :none))))))
1955
1956 (defun yas/define-menu-1 (table keymap menu uuidhash &optional group-list)
1957 (dolist (e (reverse menu))
1958 (cond ((eq (first e) 'yas/item)
1959 (let ((template (or (gethash (second e) uuidhash)
1960 (yas/populate-template (puthash (second e)
1961 (yas/make-blank-template)
1962 uuidhash)
1963 :table table
1964 :perm-group group-list
1965 :uuid (second e)))))
1966 (define-key keymap (vector (gensym))
1967 (car (yas/snippet-menu-binding-pair-get-create template :stay)))))
1968 ((eq (first e) 'yas/submenu)
1969 (let ((subkeymap (make-sparse-keymap)))
1970 (define-key keymap (vector (gensym))
1971 `(menu-item ,(second e) ,subkeymap))
1972 (yas/define-menu-1 table
1973 subkeymap
1974 (third e)
1975 uuidhash
1976 (append group-list (list (second e))))))
1977 ((eq (first e) 'yas/separator)
1978 (define-key keymap (vector (gensym))
1979 '(menu-item "----")))
1980 (t
1981 (message "[yas] don't know anything about menu entry %s" (first e))))))
1982
1983 (defun yas/define (mode key template &optional name condition group)
1984 "Define a snippet. Expanding KEY into TEMPLATE.
1985
1986 NAME is a description to this template. Also update the menu if
1987 `yas/use-menu' is `t'. CONDITION is the condition attached to
1988 this snippet. If you attach a condition to a snippet, then it
1989 will only be expanded when the condition evaluated to non-nil."
1990 (yas/define-snippets mode
1991 (list (list key template name condition group))))
1992
1993 (defun yas/hippie-try-expand (first-time?)
1994 "Integrate with hippie expand. Just put this function in
1995 `hippie-expand-try-functions-list'."
1996 (if (not first-time?)
1997 (let ((yas/fallback-behavior 'return-nil))
1998 (yas/expand))
1999 (undo 1)
2000 nil))
2001
2002
2003 ;;; Apropos condition-cache:
2004 ;;;
2005 ;;;
2006 ;;;
2007 ;;;
2008 (defvar yas/condition-cache-timestamp nil)
2009 (defmacro yas/define-condition-cache (func doc &rest body)
2010 "Define a function FUNC with doc DOC and body BODY, BODY is
2011 executed at most once every snippet expansion attempt, to check
2012 expansion conditions.
2013
2014 It doesn't make any sense to call FUNC programatically."
2015 `(defun ,func () ,(if (and doc
2016 (stringp doc))
2017 (concat doc
2018 "\n\nFor use in snippets' conditions. Within each
2019 snippet-expansion routine like `yas/expand', computes actual
2020 value for the first time then always returns a cached value.")
2021 (setq body (cons doc body))
2022 nil)
2023 (let ((timestamp-and-value (get ',func 'yas/condition-cache)))
2024 (if (equal (car timestamp-and-value) yas/condition-cache-timestamp)
2025 (cdr timestamp-and-value)
2026 (let ((new-value (progn
2027 ,@body
2028 )))
2029 (put ',func 'yas/condition-cache (cons yas/condition-cache-timestamp new-value))
2030 new-value)))))
2031
2032 (defalias 'yas/expand 'yas/expand-from-trigger-key)
2033 (defun yas/expand-from-trigger-key (&optional field)
2034 "Expand a snippet before point.
2035
2036 If no snippet expansion is possible, fall back to the behaviour
2037 defined in `yas/fallback-behavior'.
2038
2039 Optional argument FIELD is for non-interactive use and is an
2040 object satisfying `yas/field-p' to restrict the expansion to."
2041 (interactive)
2042 (setq yas/condition-cache-timestamp (current-time))
2043 (let (templates-and-pos)
2044 (unless (and yas/expand-only-for-last-commands
2045 (not (member last-command yas/expand-only-for-last-commands)))
2046 (setq templates-and-pos (if field
2047 (save-restriction
2048 (narrow-to-region (yas/field-start field)
2049 (yas/field-end field))
2050 (yas/current-key))
2051 (yas/current-key))))
2052 (if (and templates-and-pos
2053 (first templates-and-pos))
2054 (yas/expand-or-prompt-for-template (first templates-and-pos)
2055 (second templates-and-pos)
2056 (third templates-and-pos))
2057 (yas/fallback 'trigger-key))))
2058
2059 (defun yas/expand-from-keymap ()
2060 "Directly expand some snippets, searching `yas/direct-keymaps'.
2061
2062 If expansion fails, execute the previous binding for this key"
2063 (interactive)
2064 (setq yas/condition-cache-timestamp (current-time))
2065 (let* ((yas/prefix current-prefix-arg)
2066 (vec (subseq (this-command-keys-vector) (if current-prefix-arg
2067 universal-argument-num-events
2068 0)))
2069 (templates (mapcan #'(lambda (table)
2070 (yas/fetch table vec))
2071 (yas/get-snippet-tables))))
2072 (if templates
2073 (yas/expand-or-prompt-for-template templates)
2074 (let ((yas/fallback-behavior 'call-other-command))
2075 (yas/fallback)))))
2076
2077 (defun yas/expand-or-prompt-for-template (templates &optional start end)
2078 "Expand one of TEMPLATES from START to END.
2079
2080 Prompt the user if TEMPLATES has more than one element, else
2081 expand immediately. Common gateway for
2082 `yas/expand-from-trigger-key' and `yas/expand-from-keymap'."
2083 (let ((yas/current-template (or (and (rest templates) ;; more than one
2084 (yas/prompt-for-template (mapcar #'cdr templates)))
2085 (cdar templates))))
2086 (when yas/current-template
2087 (yas/expand-snippet (yas/template-content yas/current-template)
2088 start
2089 end
2090 (yas/template-expand-env yas/current-template)))))
2091
2092 (defun yas/fallback (&optional from-trigger-key-p)
2093 "Fallback after expansion has failed.
2094
2095 Common gateway for `yas/expand-from-trigger-key' and
2096 `yas/expand-from-keymap'."
2097 (cond ((eq yas/fallback-behavior 'return-nil)
2098 ;; return nil
2099 nil)
2100 ((eq yas/fallback-behavior 'call-other-command)
2101 (let* ((yas/minor-mode nil)
2102 (yas/direct-keymaps nil)
2103 (keys-1 (this-command-keys-vector))
2104 (keys-2 (and yas/trigger-key
2105 from-trigger-key-p
2106 (stringp yas/trigger-key)
2107 (read-kbd-macro yas/trigger-key)))
2108 (command-1 (and keys-1 (key-binding keys-1)))
2109 (command-2 (and keys-2 (key-binding keys-2)))
2110 ;; An (ugly) safety: prevents infinite recursion of
2111 ;; yas/expand* calls.
2112 (command (or (and (symbolp command-1)
2113 (not (string-match "yas/expand" (symbol-name command-1)))
2114 command-1)
2115 (and (symbolp command-2)
2116 command-2))))
2117 (when (and (commandp command)
2118 (not (string-match "yas/expand" (symbol-name command))))
2119 (setq this-command command)
2120 (call-interactively command))))
2121 ((and (listp yas/fallback-behavior)
2122 (cdr yas/fallback-behavior)
2123 (eq 'apply (car yas/fallback-behavior)))
2124 (if (cddr yas/fallback-behavior)
2125 (apply (cadr yas/fallback-behavior)
2126 (cddr yas/fallback-behavior))
2127 (when (commandp (cadr yas/fallback-behavior))
2128 (setq this-command (cadr yas/fallback-behavior))
2129 (call-interactively (cadr yas/fallback-behavior)))))
2130 (t
2131 ;; also return nil if all the other fallbacks have failed
2132 nil)))
2133
2134
2135 \f
2136 ;;; Snippet development
2137
2138 (defun yas/all-templates (tables)
2139 "Return all snippet tables applicable for the current buffer.
2140
2141 Honours `yas/choose-tables-first', `yas/choose-keys-first' and
2142 `yas/buffer-local-condition'"
2143 (when yas/choose-tables-first
2144 (setq tables (list (yas/prompt-for-table tables))))
2145 (mapcar #'cdr
2146 (if yas/choose-keys-first
2147 (let ((key (yas/prompt-for-keys
2148 (mapcan #'yas/table-all-keys tables))))
2149 (when key
2150 (mapcan #'(lambda (table)
2151 (yas/fetch table key))
2152 tables)))
2153 (remove-duplicates (mapcan #'yas/table-templates tables)
2154 :test #'equal))))
2155
2156 (defun yas/insert-snippet (&optional no-condition)
2157 "Choose a snippet to expand, pop-up a list of choices according
2158 to `yas/prompt-function'.
2159
2160 With prefix argument NO-CONDITION, bypass filtering of snippets
2161 by condition."
2162 (interactive "P")
2163 (setq yas/condition-cache-timestamp (current-time))
2164 (let* ((yas/buffer-local-condition (or (and no-condition
2165 'always)
2166 yas/buffer-local-condition))
2167 (templates (yas/all-templates (yas/get-snippet-tables)))
2168 (yas/current-template (and templates
2169 (or (and (rest templates) ;; more than one template for same key
2170 (yas/prompt-for-template templates))
2171 (car templates))))
2172 (where (if (region-active-p)
2173 (cons (region-beginning) (region-end))
2174 (cons (point) (point)))))
2175 (if yas/current-template
2176 (yas/expand-snippet (yas/template-content yas/current-template)
2177 (car where)
2178 (cdr where)
2179 (yas/template-expand-env yas/current-template))
2180 (message "[yas] No snippets can be inserted here!"))))
2181
2182 (defun yas/visit-snippet-file ()
2183 "Choose a snippet to edit, selection like `yas/insert-snippet'.
2184
2185 Only success if selected snippet was loaded from a file. Put the
2186 visited file in `snippet-mode'."
2187 (interactive)
2188 (let* ((yas/buffer-local-condition 'always)
2189 (templates (yas/all-templates (yas/get-snippet-tables)))
2190 (yas/prompt-functions '(yas/ido-prompt yas/completing-prompt))
2191 (template (and templates
2192 (or (yas/prompt-for-template templates
2193 "Choose a snippet template to edit: ")
2194 (car templates)))))
2195
2196 (if template
2197 (yas/visit-snippet-file-1 template)
2198 (message "No snippets tables active!"))))
2199
2200 (defun yas/visit-snippet-file-1 (template)
2201 (let ((file (yas/template-file template)))
2202 (cond ((and file (file-readable-p file))
2203 (find-file-other-window file)
2204 (snippet-mode)
2205 (set (make-local-variable 'yas/editing-template) template))
2206 (file
2207 (message "Original file %s no longer exists!" file))
2208 (t
2209 (switch-to-buffer (format "*%s*"(yas/template-name template)))
2210 (let ((type 'snippet))
2211 (when (listp (yas/template-content template))
2212 (insert (format "# type: command\n"))
2213 (setq type 'command))
2214 (insert (format "# key: %s\n" (yas/template-key template)))
2215 (insert (format "# name: %s\n" (yas/template-name template)))
2216 (when (yas/template-keybinding template)
2217 (insert (format "# binding: %s\n" (yas/template-keybinding template))))
2218 (when (yas/template-expand-env template)
2219 (insert (format "# expand-env: %s\n" (yas/template-expand-env template))))
2220 (when (yas/template-condition template)
2221 (insert (format "# condition: %s\n" (yas/template-condition template))))
2222 (insert "# --\n")
2223 (insert (if (eq type 'command)
2224 (pp-to-string (yas/template-content template))
2225 (yas/template-content template))))
2226 (snippet-mode)
2227 (set (make-local-variable 'yas/editing-template) template)))))
2228
2229 (defun yas/guess-snippet-directories-1 (table)
2230 "Guesses possible snippet subdirectories for TABLE."
2231 (cons (yas/table-name table)
2232 (mapcan #'(lambda (parent)
2233 (yas/guess-snippet-directories-1
2234 parent))
2235 (yas/table-parents table))))
2236
2237 (defun yas/guess-snippet-directories (&optional table)
2238 "Try to guess suitable directories based on the current active
2239 tables (or optional TABLE).
2240
2241 Returns a list of elemts (TABLE . DIRS) where TABLE is a
2242 `yas/table' object and DIRS is a list of all possible directories
2243 where snippets of table might exist."
2244 (let ((main-dir (replace-regexp-in-string
2245 "/+$" ""
2246 (or (first (or (yas/snippet-dirs)
2247 (setq yas/snippet-dirs '("~/.emacs.d/snippets")))))))
2248 (tables (or (and table
2249 (list table))
2250 (yas/get-snippet-tables))))
2251 ;; HACK! the snippet table created here is actually registered!
2252 ;;
2253 (unless (or table (gethash major-mode yas/tables))
2254 (push (yas/table-get-create major-mode)
2255 tables))
2256
2257 (mapcar #'(lambda (table)
2258 (cons table
2259 (mapcar #'(lambda (subdir)
2260 (concat main-dir "/" subdir))
2261 (yas/guess-snippet-directories-1 table))))
2262 tables)))
2263
2264 (defun yas/make-directory-maybe (table-and-dirs &optional main-table-string)
2265 "Returns a dir inside TABLE-AND-DIRS, prompts for creation if none exists."
2266 (or (some #'(lambda (dir) (when (file-directory-p dir) dir)) (cdr table-and-dirs))
2267 (let ((candidate (first (cdr table-and-dirs))))
2268 (unless (file-writable-p (file-name-directory candidate))
2269 (error "[yas] %s is not writable." candidate))
2270 (if (y-or-n-p (format "Guessed directory (%s) for%s%s table \"%s\" does not exist! Create? "
2271 candidate
2272 (if (gethash (intern (yas/table-name (car table-and-dirs)))
2273 yas/tables)
2274 ""
2275 " brand new")
2276 (or main-table-string
2277 "")
2278 (yas/table-name (car table-and-dirs))))
2279 (progn
2280 (make-directory candidate 'also-make-parents)
2281 ;; create the .yas-parents file here...
2282 candidate)))))
2283
2284 (defun yas/new-snippet (&optional no-template)
2285 "Pops a new buffer for writing a snippet.
2286
2287 Expands a snippet-writing snippet, unless the optional prefix arg
2288 NO-TEMPLATE is non-nil."
2289 (interactive "P")
2290 (let ((guessed-directories (yas/guess-snippet-directories)))
2291
2292 (switch-to-buffer "*new snippet*")
2293 (erase-buffer)
2294 (kill-all-local-variables)
2295 (snippet-mode)
2296 (yas/minor-mode 1)
2297 (set (make-local-variable 'yas/guessed-modes) (mapcar #'(lambda (d)
2298 (intern (yas/table-name (car d))))
2299 guessed-directories))
2300 (unless no-template (yas/expand-snippet "\
2301 # -*- mode: snippet -*-
2302 # name: $1
2303 # key: $2${3:
2304 # binding: ${4:direct-keybinding}}${5:
2305 # expand-env: ((${6:some-var} ${7:some-value}))}${8:
2306 # type: command}
2307 # --
2308 $0"))))
2309
2310 (defun yas/find-snippets (&optional same-window )
2311 "Find snippet file in guessed current mode's directory.
2312
2313 Calls `find-file' interactively in the guessed directory.
2314
2315 With prefix arg SAME-WINDOW opens the buffer in the same window.
2316
2317 Because snippets can be loaded from many different locations,
2318 this has to guess the correct directory using
2319 `yas/guess-snippet-directories', which returns a list of
2320 options.
2321
2322 If any one of these exists, it is taken and `find-file' is called
2323 there, otherwise, proposes to create the first option returned by
2324 `yas/guess-snippet-directories'."
2325 (interactive "P")
2326 (let* ((guessed-directories (yas/guess-snippet-directories))
2327 (chosen)
2328 (buffer))
2329 (setq chosen (yas/make-directory-maybe (first guessed-directories) " main"))
2330 (unless chosen
2331 (if (y-or-n-p (format "Continue guessing for other active tables %s? "
2332 (mapcar #'(lambda (table-and-dirs)
2333 (yas/table-name (car table-and-dirs)))
2334 (rest guessed-directories))))
2335 (setq chosen (some #'yas/make-directory-maybe
2336 (rest guessed-directories)))))
2337 (unless chosen
2338 (when (y-or-n-p "Having trouble... go to snippet root dir? ")
2339 (setq chosen (first (yas/snippet-dirs)))))
2340 (if chosen
2341 (let ((default-directory chosen))
2342 (setq buffer (call-interactively (if same-window
2343 'find-file
2344 'find-file-other-window)))
2345 (when buffer
2346 (save-excursion
2347 (set-buffer buffer)
2348 (when (eq major-mode 'fundamental-mode)
2349 (snippet-mode)))))
2350 (message "Could not guess snippet dir!"))))
2351
2352 (defun yas/compute-major-mode-and-parents (file)
2353 "Given FILE, find the nearest snippet directory for a given
2354 mode, then return a list (MODE-SYM PARENTS), the mode's symbol and a list
2355 representing one or more of the mode's parents.
2356
2357 Note that MODE-SYM need not be the symbol of a real major mode,
2358 neither do the elements of PARENTS."
2359 (let* ((file-dir (and file
2360 (directory-file-name (or (some #'(lambda (special)
2361 (locate-dominating-file file special))
2362 '(".yas-setup.el"
2363 ".yas-make-groups"
2364 ".yas-parents"))
2365 (directory-file-name (file-name-directory file))))))
2366 (parents-file-name (concat file-dir "/.yas-parents"))
2367 (major-mode-name (and file-dir
2368 (file-name-nondirectory file-dir)))
2369 (major-mode-sym (or (and major-mode-name
2370 (intern major-mode-name))))
2371 (parents (when (file-readable-p parents-file-name)
2372 (mapcar #'intern
2373 (split-string
2374 (with-temp-buffer
2375 (insert-file-contents parents-file-name)
2376 (buffer-substring-no-properties (point-min)
2377 (point-max))))))))
2378 (when major-mode-sym
2379 (cons major-mode-sym parents))))
2380
2381 (defvar yas/editing-template nil
2382 "Supporting variable for `yas/load-snippet-buffer' and `yas/visit-snippet'")
2383
2384 (defvar yas/current-template nil
2385 "Holds the current template being expanded into a snippet.")
2386
2387 (defvar yas/guessed-modes nil
2388 "List of guessed modes supporting `yas/load-snippet-buffer'.")
2389
2390 (defun yas/load-snippet-buffer (&optional kill)
2391 "Parse and load current buffer's snippet definition.
2392
2393 With optional prefix argument KILL quit the window and buffer."
2394 (interactive "P")
2395 (cond
2396 ;; We have `yas/editing-template', this buffer's
2397 ;; content comes from a template which is already loaded and
2398 ;; neatly positioned,...
2399 ;;
2400 (yas/editing-template
2401 (yas/define-snippets-1 (yas/parse-template (yas/template-file yas/editing-template))
2402 (yas/template-table yas/editing-template)))
2403 ;; Try to use `yas/guessed-modes'. If we don't have that use the
2404 ;; value from `yas/compute-major-mode-and-parents'
2405 ;;
2406 (t
2407 (unless yas/guessed-modes
2408 (set (make-local-variable 'yas/guessed-modes) (or (yas/compute-major-mode-and-parents buffer-file-name))))
2409 (let* ((prompt (if (and (featurep 'ido)
2410 ido-mode)
2411 'ido-completing-read 'completing-read))
2412 (table (yas/table-get-create
2413 (intern
2414 (funcall prompt (format "Choose or enter a table (yas guesses %s): "
2415 (if yas/guessed-modes
2416 (first yas/guessed-modes)
2417 "nothing"))
2418 (mapcar #'symbol-name yas/guessed-modes)
2419 nil
2420 nil
2421 nil
2422 nil
2423 (if (first yas/guessed-modes)
2424 (symbol-name (first yas/guessed-modes))))))))
2425 (set (make-local-variable 'yas/editing-template)
2426 (yas/define-snippets-1 (yas/parse-template buffer-file-name)
2427 table)))))
2428 ;; Now, offer to save this shit iff:
2429 ;;
2430 ;; 1) `yas/snippet-dirs' is a list and its first element does not
2431 ;; match this template's file (i.e. this is a library snippet, not
2432 ;; a user snippet) OR
2433 ;;
2434 ;; 2) yas/editing-template comes from a file that we cannot write to...
2435 ;;
2436 (when (or (not (yas/template-file yas/editing-template))
2437 (not (file-writable-p (yas/template-file yas/editing-template)))
2438 (and (listp yas/snippet-dirs)
2439 (second yas/snippet-dirs)
2440 (not (string-match (expand-file-name (first yas/snippet-dirs))
2441 (yas/template-file yas/editing-template)))))
2442
2443 (when (y-or-n-p "[yas] Looks like a library or new snippet. Save to new file? ")
2444 (let* ((option (first (yas/guess-snippet-directories (yas/template-table yas/editing-template))))
2445 (chosen (and option
2446 (yas/make-directory-maybe option))))
2447 (when chosen
2448 (let ((default-file-name (or (and (yas/template-file yas/editing-template)
2449 (file-name-nondirectory (yas/template-file yas/editing-template)))
2450 (yas/template-name yas/editing-template))))
2451 (write-file (concat chosen "/"
2452 (read-from-minibuffer (format "File name to create in %s? " chosen)
2453 default-file-name)))
2454 (setf (yas/template-file yas/editing-template) buffer-file-name))))))
2455 (when kill
2456 (quit-window kill))
2457 (message "[yas] Snippet \"%s\" loaded for %s."
2458 (yas/template-name yas/editing-template)
2459 (yas/table-name (yas/template-table yas/editing-template))))
2460
2461
2462 (defun yas/tryout-snippet (&optional debug)
2463 "Test current buffers's snippet template in other buffer."
2464 (interactive "P")
2465 (let* ((major-mode-and-parent (yas/compute-major-mode-and-parents buffer-file-name))
2466 (parsed (yas/parse-template))
2467 (test-mode (or (and (car major-mode-and-parent)
2468 (fboundp (car major-mode-and-parent))
2469 (car major-mode-and-parent))
2470 (first yas/guessed-modes)
2471 (intern (read-from-minibuffer "[yas] please input a mode: "))))
2472 (yas/current-template
2473 (and parsed
2474 (fboundp test-mode)
2475 (yas/populate-template (yas/make-blank-template)
2476 :table nil ;; no tables for ephemeral snippets
2477 :key (first parsed)
2478 :content (second parsed)
2479 :name (third parsed)
2480 :expand-env (sixth parsed)))))
2481 (cond (yas/current-template
2482 (let ((buffer-name (format "*testing snippet: %s*" (yas/template-name yas/current-template))))
2483 (kill-buffer (get-buffer-create buffer-name))
2484 (switch-to-buffer (get-buffer-create buffer-name))
2485 (setq buffer-undo-list nil)
2486 (condition-case nil (funcall test-mode) (error nil))
2487 (setq buffer-read-only nil)
2488 (yas/expand-snippet (yas/template-content yas/current-template)
2489 (point-min)
2490 (point-max)
2491 (yas/template-expand-env yas/current-template))
2492 (when (and debug
2493 (require 'yasnippet-debug nil t))
2494 (add-hook 'post-command-hook 'yas/debug-snippet-vars nil t))))
2495 (t
2496 (message "[yas] Cannot test snippet for unknown major mode")))))
2497
2498 (defun yas/template-fine-group (template)
2499 (car (last (or (yas/template-group template)
2500 (yas/template-perm-group template)))))
2501
2502 (defun yas/describe-tables (&optional choose)
2503 "Display snippets for each table."
2504 (interactive "P")
2505 (let* ((by-name-hash (and choose
2506 (y-or-n-p "Show by namehash? ")))
2507 (buffer (get-buffer-create "*YASnippet tables*"))
2508 (active-tables (yas/get-snippet-tables))
2509 (remain-tables (let ((all))
2510 (maphash #'(lambda (k v)
2511 (unless (find v active-tables)
2512 (push v all)))
2513 yas/tables)
2514 all))
2515 (table-lists (list active-tables remain-tables))
2516 (original-buffer (current-buffer))
2517 (continue t)
2518 (yas/condition-cache-timestamp (current-time)))
2519 (with-current-buffer buffer
2520 (setq buffer-read-only nil)
2521 (erase-buffer)
2522 (cond ((not by-name-hash)
2523 (insert "YASnippet tables: \n")
2524 (while (and table-lists
2525 continue)
2526 (dolist (table (car table-lists))
2527 (yas/describe-pretty-table table original-buffer))
2528 (setq table-lists (cdr table-lists))
2529 (when table-lists
2530 (yas/create-snippet-xrefs)
2531 (display-buffer buffer)
2532 (setq continue (and choose (y-or-n-p "Show also non-active tables? ")))))
2533 (yas/create-snippet-xrefs)
2534 (help-mode)
2535 (goto-char 1))
2536 (t
2537 (insert "\n\nYASnippet tables by NAMEHASH: \n")
2538 (dolist (table (append active-tables remain-tables))
2539 (insert (format "\nSnippet table `%s':\n\n" (yas/table-name table)))
2540 (let ((keys))
2541 (maphash #'(lambda (k v)
2542 (push k keys))
2543 (yas/table-hash table))
2544 (dolist (key keys)
2545 (insert (format " key %s maps snippets: %s\n" key
2546 (let ((names))
2547 (maphash #'(lambda (k v)
2548 (push k names))
2549 (gethash key (yas/table-hash table)))
2550 names))))))))
2551 (goto-char 1)
2552 (setq buffer-read-only t))
2553 (display-buffer buffer)))
2554
2555 (defun yas/describe-pretty-table (table &optional original-buffer)
2556 (insert (format "\nSnippet table `%s'"
2557 (yas/table-name table)))
2558 (if (yas/table-parents table)
2559 (insert (format " parents: %s\n"
2560 (mapcar #'yas/table-name
2561 (yas/table-parents table))))
2562 (insert "\n"))
2563 (insert (make-string 100 ?-) "\n")
2564 (insert "group state name key binding\n")
2565 (let ((groups-alist (list))
2566 group)
2567 (maphash #'(lambda (k v)
2568 (setq group (or (yas/template-fine-group v)
2569 "(top level)"))
2570 (when (yas/template-name v)
2571
2572 (aput 'groups-alist group (cons v (aget groups-alist group)))))
2573 (yas/table-uuidhash table))
2574 (dolist (group-and-templates groups-alist)
2575 (when (rest group-and-templates)
2576 (setq group (truncate-string-to-width (car group-and-templates) 25 0 ? "..."))
2577 (insert (make-string 100 ?-) "\n")
2578 (dolist (p (cdr group-and-templates))
2579 (let ((name (truncate-string-to-width (propertize (format "\\\\snippet `%s'" (yas/template-name p))
2580 'yasnippet p)
2581 50 0 ? "..."))
2582 (group (prog1 group
2583 (setq group (make-string (length group) ? ))))
2584 (condition-string (let ((condition (yas/template-condition p)))
2585 (if (and condition
2586 original-buffer)
2587 (with-current-buffer original-buffer
2588 (if (yas/eval-condition condition)
2589 "(y)"
2590 "(s)"))
2591 "(a)"))))
2592 (insert group " ")
2593 (insert condition-string " ")
2594 (insert name
2595 (if (string-match "\\.\\.\\.$" name)
2596 "'"
2597 " ")
2598 " ")
2599 (insert (truncate-string-to-width (or (yas/template-key p) "")
2600 15 0 ? "...") " ")
2601 (insert (truncate-string-to-width (key-description (yas/template-keybinding p))
2602 15 0 ? "...") " ")
2603 (insert "\n")))))))
2604
2605
2606
2607
2608 \f
2609 ;;; User convenience functions, for using in snippet definitions
2610
2611 (defvar yas/modified-p nil
2612 "Non-nil if field has been modified by user or transformation.")
2613
2614 (defvar yas/moving-away-p nil
2615 "Non-nil if user is about to exit field.")
2616
2617 (defvar yas/text nil
2618 "Contains current field text.")
2619
2620 (defun yas/substr (str pattern &optional subexp)
2621 "Search PATTERN in STR and return SUBEXPth match.
2622
2623 If found, the content of subexp group SUBEXP (default 0) is
2624 returned, or else the original STR will be returned."
2625 (let ((grp (or subexp 0)))
2626 (save-match-data
2627 (if (string-match pattern str)
2628 (match-string-no-properties grp str)
2629 str))))
2630
2631 (defun yas/choose-value (possibilities)
2632 "Prompt for a string in the list POSSIBILITIES and return it."
2633 (unless (or yas/moving-away-p
2634 yas/modified-p)
2635 (some #'(lambda (fn)
2636 (funcall fn "Choose: " possibilities))
2637 yas/prompt-functions)))
2638
2639 (defun yas/key-to-value (alist)
2640 "Prompt for a string in the list POSSIBILITIES and return it."
2641 (unless (or yas/moving-away-p
2642 yas/modified-p)
2643 (let ((key (read-key-sequence "")))
2644 (when (stringp key)
2645 (or (cdr (find key alist :key #'car :test #'string=))
2646 key)))))
2647
2648 (defun yas/throw (text)
2649 "Throw a yas/exception with TEXT as the reason."
2650 (throw 'yas/exception (cons 'yas/exception text)))
2651
2652 (defun yas/verify-value (possibilities)
2653 "Verify that the current field value is in POSSIBILITIES
2654
2655 Otherwise throw exception."
2656 (when (and yas/moving-away-p (notany #'(lambda (pos) (string= pos yas/text)) possibilities))
2657 (yas/throw (format "[yas] field only allows %s" possibilities))))
2658
2659 (defun yas/field-value (number)
2660 "Get the string for field with NUMBER.
2661
2662 Use this in primary and mirror transformations to tget."
2663 (let* ((snippet (car (yas/snippets-at-point)))
2664 (field (and snippet
2665 (yas/snippet-find-field snippet number))))
2666 (when field
2667 (yas/field-text-for-display field))))
2668
2669 (defun yas/text ()
2670 "Return `yas/text' if that exists and is non-empty, else nil."
2671 (if (and yas/text
2672 (not (string= "" yas/text)))
2673 yas/text))
2674
2675 ;; (defun yas/selected-text ()
2676 ;; "Return `yas/selected-text' if that exists and is non-empty, else nil."
2677 ;; (if (and yas/selected-text
2678 ;; (not (string= "" yas/selected-text)))
2679 ;; yas/selected-text))
2680
2681 (defun yas/get-field-once (number &optional transform-fn)
2682 (unless yas/modified-p
2683 (if transform-fn
2684 (funcall transform-fn (yas/field-value number))
2685 (yas/field-value number))))
2686
2687 (defun yas/default-from-field (number)
2688 (unless yas/modified-p
2689 (yas/field-value number)))
2690
2691 (defun yas/inside-string ()
2692 (equal 'font-lock-string-face (get-char-property (1- (point)) 'face)))
2693
2694 (defun yas/unimplemented (&optional missing-feature)
2695 (if yas/current-template
2696 (if (y-or-n-p (format "This snippet is unimplemented (missing %s) Visit the snippet definition? "
2697 (or missing-feature
2698 "something")))
2699 (yas/visit-snippet-file-1 yas/current-template))
2700 (message "No implementation. Missing %s" (or missing-feature "something"))))
2701
2702 \f
2703 ;;; Snippet expansion and field management
2704
2705 (defvar yas/active-field-overlay nil
2706 "Overlays the currently active field.")
2707
2708 (defvar yas/field-protection-overlays nil
2709 "Two overlays protect the current active field ")
2710
2711 (defconst yas/prefix nil
2712 "A prefix argument for expansion direct from keybindings")
2713
2714 (defvar yas/selected-text nil
2715 "The selected region deleted on the last snippet expansion.")
2716
2717 (defvar yas/start-column nil
2718 "The column where the snippet expansion started.")
2719
2720 (make-variable-buffer-local 'yas/active-field-overlay)
2721 (make-variable-buffer-local 'yas/field-protection-overlays)
2722 (put 'yas/active-field-overlay 'permanent-local t)
2723 (put 'yas/field-protection-overlays 'permanent-local t)
2724
2725 (defstruct (yas/snippet (:constructor yas/make-snippet ()))
2726 "A snippet.
2727
2728 ..."
2729 (fields '())
2730 (exit nil)
2731 (id (yas/snippet-next-id) :read-only t)
2732 (control-overlay nil)
2733 active-field
2734 ;; stacked expansion: the `previous-active-field' slot saves the
2735 ;; active field where the child expansion took place
2736 previous-active-field
2737 force-exit)
2738
2739 (defstruct (yas/field (:constructor yas/make-field (number start end parent-field)))
2740 "A field."
2741 number
2742 start end
2743 parent-field
2744 (mirrors '())
2745 (transform nil)
2746 (modified-p nil)
2747 next)
2748
2749 (defstruct (yas/mirror (:constructor yas/make-mirror (start end transform)))
2750 "A mirror."
2751 start end
2752 (transform nil)
2753 parent-field
2754 next)
2755
2756 (defstruct (yas/exit (:constructor yas/make-exit (marker)))
2757 marker
2758 next)
2759
2760 (defun yas/apply-transform (field-or-mirror field &optional empty-on-nil-p)
2761 "Calculate transformed string for FIELD-OR-MIRROR from FIELD.
2762
2763 If there is no transform for ht field, return nil.
2764
2765 If there is a transform but it returns nil, return the empty
2766 string iff EMPTY-ON-NIL-P is true."
2767 (let* ((yas/text (yas/field-text-for-display field))
2768 (text yas/text)
2769 (yas/modified-p (yas/field-modified-p field))
2770 (yas/moving-away-p nil)
2771 (transform (if (yas/mirror-p field-or-mirror)
2772 (yas/mirror-transform field-or-mirror)
2773 (yas/field-transform field-or-mirror)))
2774 (start-point (if (yas/mirror-p field-or-mirror)
2775 (yas/mirror-start field-or-mirror)
2776 (yas/field-start field-or-mirror)))
2777 (transformed (and transform
2778 (save-excursion
2779 (goto-char start-point)
2780 (let ((ret (yas/eval-lisp transform)))
2781 (or ret (and empty-on-nil-p "")))))))
2782 transformed))
2783
2784 (defsubst yas/replace-all (from to &optional text)
2785 "Replace all occurance from FROM to TO.
2786
2787 With optional string TEXT do it in that string."
2788 (if text
2789 (replace-regexp-in-string (regexp-quote from) to text t t)
2790 (goto-char (point-min))
2791 (while (search-forward from nil t)
2792 (replace-match to t t text))))
2793
2794 (defun yas/snippet-find-field (snippet number)
2795 (find-if #'(lambda (field)
2796 (eq number (yas/field-number field)))
2797 (yas/snippet-fields snippet)))
2798
2799 (defun yas/snippet-sort-fields (snippet)
2800 "Sort the fields of SNIPPET in navigation order."
2801 (setf (yas/snippet-fields snippet)
2802 (sort (yas/snippet-fields snippet)
2803 #'yas/snippet-field-compare)))
2804
2805 (defun yas/snippet-field-compare (field1 field2)
2806 "Compare two fields. The field with a number is sorted first.
2807 If they both have a number, compare through the number. If neither
2808 have, compare through the field's start point"
2809 (let ((n1 (yas/field-number field1))
2810 (n2 (yas/field-number field2)))
2811 (if n1
2812 (if n2
2813 (or (zerop n2) (and (not (zerop n1))
2814 (< n1 n2)))
2815 (not (zerop n1)))
2816 (if n2
2817 (zerop n2)
2818 (< (yas/field-start field1)
2819 (yas/field-start field2))))))
2820
2821 (defun yas/field-probably-deleted-p (snippet field)
2822 "Guess if SNIPPET's FIELD should be skipped."
2823 (and (zerop (- (yas/field-start field) (yas/field-end field)))
2824 (or (yas/field-parent-field field)
2825 (and (eq field (car (last (yas/snippet-fields snippet))))
2826 (= (yas/field-start field) (overlay-end (yas/snippet-control-overlay snippet)))))
2827 ;; the field numbered 0, just before the exit marker, should
2828 ;; never be skipped
2829 (not (zerop (yas/field-number field)))))
2830
2831 (defun yas/snippets-at-point (&optional all-snippets)
2832 "Return a sorted list of snippets at point, most recently
2833 inserted first."
2834 (sort
2835 (remove nil (remove-duplicates (mapcar #'(lambda (ov)
2836 (overlay-get ov 'yas/snippet))
2837 (if all-snippets
2838 (overlays-in (point-min) (point-max))
2839 (nconc (overlays-at (point)) (overlays-at (1- (point))))))))
2840 #'(lambda (s1 s2)
2841 (<= (yas/snippet-id s2) (yas/snippet-id s1)))))
2842
2843 (defun yas/next-field-or-maybe-expand ()
2844 "Try to expand a snippet at a key before point, otherwise
2845 delegate to `yas/next-field'."
2846 (interactive)
2847 (if yas/triggers-in-field
2848 (let ((yas/fallback-behavior 'return-nil)
2849 (active-field (overlay-get yas/active-field-overlay 'yas/field)))
2850 (when active-field
2851 (unless (yas/expand-from-trigger-key active-field)
2852 (yas/next-field))))
2853 (yas/next-field)))
2854
2855 (defun yas/next-field (&optional arg)
2856 "Navigate to next field. If there's none, exit the snippet."
2857 (interactive)
2858 (let* ((arg (or arg
2859 1))
2860 (snippet (first (yas/snippets-at-point)))
2861 (active-field (overlay-get yas/active-field-overlay 'yas/field))
2862 (live-fields (remove-if #'(lambda (field)
2863 (and (not (eq field active-field))
2864 (yas/field-probably-deleted-p snippet field)))
2865 (yas/snippet-fields snippet)))
2866 (active-field-pos (position active-field live-fields))
2867 (target-pos (and active-field-pos (+ arg active-field-pos)))
2868 (target-field (and target-pos (nth target-pos live-fields))))
2869 ;; First check if we're moving out of a field with a transform
2870 ;;
2871 (when (and active-field
2872 (yas/field-transform active-field))
2873 (let* ((yas/moving-away-p t)
2874 (yas/text (yas/field-text-for-display active-field))
2875 (text yas/text)
2876 (yas/modified-p (yas/field-modified-p active-field)))
2877 ;; primary field transform: exit call to field-transform
2878 (yas/eval-lisp (yas/field-transform active-field))))
2879 ;; Now actually move...
2880 (cond ((and target-pos (>= target-pos (length live-fields)))
2881 (yas/exit-snippet snippet))
2882 (target-field
2883 (yas/move-to-field snippet target-field))
2884 (t
2885 nil))))
2886
2887 (defun yas/place-overlays (snippet field)
2888 "Correctly place overlays for SNIPPET's FIELD"
2889 (yas/make-move-field-protection-overlays snippet field)
2890 (yas/make-move-active-field-overlay snippet field))
2891
2892 (defun yas/move-to-field (snippet field)
2893 "Update SNIPPET to move to field FIELD.
2894
2895 Also create some protection overlays"
2896 (goto-char (yas/field-start field))
2897 (yas/place-overlays snippet field)
2898 (overlay-put yas/active-field-overlay 'yas/field field)
2899 (let ((number (yas/field-number field)))
2900 ;; check for the special ${0: ...} field
2901 (if (and number (zerop number))
2902 (progn
2903 (set-mark (yas/field-end field))
2904 (setf (yas/snippet-force-exit snippet)
2905 (or (yas/field-transform field)
2906 t)))
2907 ;; make this field active
2908 (setf (yas/snippet-active-field snippet) field)
2909 ;; primary field transform: first call to snippet transform
2910 (unless (yas/field-modified-p field)
2911 (if (yas/field-update-display field snippet)
2912 (yas/update-mirrors snippet)
2913 (setf (yas/field-modified-p field) nil))))))
2914
2915 (defun yas/prev-field ()
2916 "Navigate to prev field. If there's none, exit the snippet."
2917 (interactive)
2918 (yas/next-field -1))
2919
2920 (defun yas/abort-snippet (&optional snippet)
2921 (interactive)
2922 (let ((snippet (or snippet
2923 (car (yas/snippets-at-point)))))
2924 (when snippet
2925 (setf (yas/snippet-force-exit snippet) t))))
2926
2927 (defun yas/exit-snippet (snippet)
2928 "Goto exit-marker of SNIPPET."
2929 (interactive (list (first (yas/snippets-at-point))))
2930 (when snippet
2931 (setf (yas/snippet-force-exit snippet) t)
2932 (goto-char (if (yas/snippet-exit snippet)
2933 (yas/exit-marker (yas/snippet-exit snippet))
2934 (overlay-end (yas/snippet-control-overlay snippet))))))
2935
2936 (defun yas/exit-all-snippets ()
2937 "Exit all snippets."
2938 (interactive)
2939 (mapc #'(lambda (snippet)
2940 (yas/exit-snippet snippet)
2941 (yas/check-commit-snippet))
2942 (yas/snippets-at-point)))
2943
2944 \f
2945 ;;; Some low level snippet-routines
2946
2947 (defmacro yas/inhibit-overlay-hooks (&rest body)
2948 "Run BODY with `yas/inhibit-overlay-hooks' set to t."
2949 (declare (indent 0))
2950 `(let ((yas/inhibit-overlay-hooks t))
2951 (progn ,@body)))
2952
2953 (defvar yas/snippet-beg nil "Beginning position of the last snippet commited.")
2954 (defvar yas/snippet-end nil "End position of the last snippet commited.")
2955
2956 (defun yas/commit-snippet (snippet)
2957 "Commit SNIPPET, but leave point as it is. This renders the
2958 snippet as ordinary text."
2959
2960 (let ((control-overlay (yas/snippet-control-overlay snippet)))
2961 ;;
2962 ;; Save the end of the moribund snippet in case we need to revive it
2963 ;; its original expansion.
2964 ;;
2965 (when (and control-overlay
2966 (overlay-buffer control-overlay))
2967 (setq yas/snippet-beg (overlay-start control-overlay))
2968 (setq yas/snippet-end (overlay-end control-overlay))
2969 (delete-overlay control-overlay))
2970
2971 (yas/inhibit-overlay-hooks
2972 (when yas/active-field-overlay
2973 (delete-overlay yas/active-field-overlay))
2974 (when yas/field-protection-overlays
2975 (mapc #'delete-overlay yas/field-protection-overlays)))
2976
2977 ;; stacked expansion: if the original expansion took place from a
2978 ;; field, make sure we advance it here at least to
2979 ;; `yas/snippet-end'...
2980 ;;
2981 (let ((previous-field (yas/snippet-previous-active-field snippet)))
2982 (when (and yas/snippet-end previous-field)
2983 (yas/advance-end-maybe previous-field yas/snippet-end)))
2984
2985 ;; Convert all markers to points,
2986 ;;
2987 (yas/markers-to-points snippet)
2988
2989 ;; Take care of snippet revival
2990 ;;
2991 (if yas/snippet-revival
2992 (push `(apply yas/snippet-revive ,yas/snippet-beg ,yas/snippet-end ,snippet)
2993 buffer-undo-list)
2994 ;; Dismember the snippet... this is useful if we get called
2995 ;; again from `yas/take-care-of-redo'....
2996 (setf (yas/snippet-fields snippet) nil)))
2997
2998 (message "[yas] snippet %s exited." (yas/snippet-id snippet)))
2999
3000 (defun yas/safely-run-hooks (hook-var)
3001 (condition-case error
3002 (run-hooks hook-var)
3003 (error
3004 (message "[yas] %s error: %s" hook-var (error-message-string error)))))
3005
3006
3007 (defun yas/check-commit-snippet ()
3008 "Checks if point exited the currently active field of the
3009 snippet, if so cleans up the whole snippet up."
3010 (let* ((snippets (yas/snippets-at-point 'all-snippets))
3011 (snippets-left snippets)
3012 (snippet-exit-transform))
3013 (dolist (snippet snippets)
3014 (let ((active-field (yas/snippet-active-field snippet)))
3015 (setq snippet-exit-transform (yas/snippet-force-exit snippet))
3016 (cond ((or snippet-exit-transform
3017 (not (and active-field (yas/field-contains-point-p active-field))))
3018 (setq snippets-left (delete snippet snippets-left))
3019 (setf (yas/snippet-force-exit snippet) nil)
3020 (yas/commit-snippet snippet))
3021 ((and active-field
3022 (or (not yas/active-field-overlay)
3023 (not (overlay-buffer yas/active-field-overlay))))
3024 ;;
3025 ;; stacked expansion: this case is mainly for recent
3026 ;; snippet exits that place us back int the field of
3027 ;; another snippet
3028 ;;
3029 (save-excursion
3030 (yas/move-to-field snippet active-field)
3031 (yas/update-mirrors snippet)))
3032 (t
3033 nil))))
3034 (unless (or (null snippets) snippets-left)
3035 (if snippet-exit-transform
3036 (yas/eval-lisp-no-saves snippet-exit-transform))
3037 (yas/safely-run-hooks 'yas/after-exit-snippet-hook))))
3038
3039 ;; Apropos markers-to-points:
3040 ;;
3041 ;; This was found useful for performance reasons, so that an
3042 ;; excessive number of live markers aren't kept around in the
3043 ;; `buffer-undo-list'. However, in `markers-to-points', the
3044 ;; set-to-nil markers can't simply be discarded and replaced with
3045 ;; fresh ones in `points-to-markers'. The original marker that was
3046 ;; just set to nil has to be reused.
3047 ;;
3048 ;; This shouldn't bring horrible problems with undo/redo, but it
3049 ;; you never know
3050 ;;
3051 (defun yas/markers-to-points (snippet)
3052 "Convert all markers in SNIPPET to a cons (POINT . MARKER)
3053 where POINT is the original position of the marker and MARKER is
3054 the original marker object with the position set to nil."
3055 (dolist (field (yas/snippet-fields snippet))
3056 (let ((start (marker-position (yas/field-start field)))
3057 (end (marker-position (yas/field-end field))))
3058 (set-marker (yas/field-start field) nil)
3059 (set-marker (yas/field-end field) nil)
3060 (setf (yas/field-start field) (cons start (yas/field-start field)))
3061 (setf (yas/field-end field) (cons end (yas/field-end field))))
3062 (dolist (mirror (yas/field-mirrors field))
3063 (let ((start (marker-position (yas/mirror-start mirror)))
3064 (end (marker-position (yas/mirror-end mirror))))
3065 (set-marker (yas/mirror-start mirror) nil)
3066 (set-marker (yas/mirror-end mirror) nil)
3067 (setf (yas/mirror-start mirror) (cons start (yas/mirror-start mirror)))
3068 (setf (yas/mirror-end mirror) (cons end (yas/mirror-end mirror))))))
3069 (let ((snippet-exit (yas/snippet-exit snippet)))
3070 (when snippet-exit
3071 (let ((exit (marker-position (yas/exit-marker snippet-exit))))
3072 (set-marker (yas/exit-marker snippet-exit) nil)
3073 (setf (yas/exit-marker snippet-exit) (cons exit (yas/exit-marker snippet-exit)))))))
3074
3075 (defun yas/points-to-markers (snippet)
3076 "Convert all cons (POINT . MARKER) in SNIPPET to markers. This
3077 is done by setting MARKER to POINT with `set-marker'."
3078 (dolist (field (yas/snippet-fields snippet))
3079 (setf (yas/field-start field) (set-marker (cdr (yas/field-start field))
3080 (car (yas/field-start field))))
3081 (setf (yas/field-end field) (set-marker (cdr (yas/field-end field))
3082 (car (yas/field-end field))))
3083 (dolist (mirror (yas/field-mirrors field))
3084 (setf (yas/mirror-start mirror) (set-marker (cdr (yas/mirror-start mirror))
3085 (car (yas/mirror-start mirror))))
3086 (setf (yas/mirror-end mirror) (set-marker (cdr (yas/mirror-end mirror))
3087 (car (yas/mirror-end mirror))))))
3088 (let ((snippet-exit (yas/snippet-exit snippet)))
3089 (when snippet-exit
3090 (setf (yas/exit-marker snippet-exit) (set-marker (cdr (yas/exit-marker snippet-exit))
3091 (car (yas/exit-marker snippet-exit)))))))
3092
3093 (defun yas/field-contains-point-p (field &optional point)
3094 (let ((point (or point
3095 (point))))
3096 (and (>= point (yas/field-start field))
3097 (<= point (yas/field-end field)))))
3098
3099 (defun yas/field-text-for-display (field)
3100 "Return the propertized display text for field FIELD. "
3101 (buffer-substring (yas/field-start field) (yas/field-end field)))
3102
3103 (defun yas/undo-in-progress ()
3104 "True if some kind of undo is in progress"
3105 (or undo-in-progress
3106 (eq this-command 'undo)
3107 (eq this-command 'redo)))
3108
3109 (defun yas/make-control-overlay (snippet start end)
3110 "Creates the control overlay that surrounds the snippet and
3111 holds the keymap."
3112 (let ((overlay (make-overlay start
3113 end
3114 nil
3115 nil
3116 t)))
3117 (overlay-put overlay 'keymap yas/keymap)
3118 (overlay-put overlay 'priority 100)
3119 (overlay-put overlay 'yas/snippet snippet)
3120 overlay))
3121
3122 (defun yas/skip-and-clear-or-delete-char (&optional field)
3123 "Clears unmodified field if at field start, skips to next tab.
3124
3125 Otherwise deletes a character normally by calling `delete-char'."
3126 (interactive)
3127 (let ((field (or field
3128 (and yas/active-field-overlay
3129 (overlay-buffer yas/active-field-overlay)
3130 (overlay-get yas/active-field-overlay 'yas/field)))))
3131 (cond ((and field
3132 (not (yas/field-modified-p field))
3133 (eq (point) (marker-position (yas/field-start field))))
3134 (yas/skip-and-clear field)
3135 (yas/next-field 1))
3136 (t
3137 (call-interactively 'delete-char)))))
3138
3139 (defun yas/skip-and-clear (field)
3140 "Deletes the region of FIELD and sets it modified state to t"
3141 ;; Just before skipping-and-clearing the field, mark its children
3142 ;; fields as modified, too. If the childen have mirrors-in-fields
3143 ;; this prevents them from updating erroneously (we're skipping and
3144 ;; deleting!).
3145 ;;
3146 (yas/mark-this-and-children-modified field)
3147 (delete-region (yas/field-start field) (yas/field-end field)))
3148
3149 (defun yas/mark-this-and-children-modified (field)
3150 (setf (yas/field-modified-p field) t)
3151 (let ((fom (yas/field-next field)))
3152 (while (and fom
3153 (yas/fom-parent-field fom))
3154 (when (and (eq (yas/fom-parent-field fom) field)
3155 (yas/field-p fom))
3156 (yas/mark-this-and-children-modified fom))
3157 (setq fom (yas/fom-next fom)))))
3158
3159 (defun yas/make-move-active-field-overlay (snippet field)
3160 "Place the active field overlay in SNIPPET's FIELD.
3161
3162 Move the overlay, or create it if it does not exit."
3163 (if (and yas/active-field-overlay
3164 (overlay-buffer yas/active-field-overlay))
3165 (move-overlay yas/active-field-overlay
3166 (yas/field-start field)
3167 (yas/field-end field))
3168 (setq yas/active-field-overlay
3169 (make-overlay (yas/field-start field)
3170 (yas/field-end field)
3171 nil nil t))
3172 (overlay-put yas/active-field-overlay 'priority 100)
3173 (overlay-put yas/active-field-overlay 'face 'yas/field-highlight-face)
3174 (overlay-put yas/active-field-overlay 'yas/snippet snippet)
3175 (overlay-put yas/active-field-overlay 'modification-hooks '(yas/on-field-overlay-modification))
3176 (overlay-put yas/active-field-overlay 'insert-in-front-hooks
3177 '(yas/on-field-overlay-modification))
3178 (overlay-put yas/active-field-overlay 'insert-behind-hooks
3179 '(yas/on-field-overlay-modification))))
3180
3181 (defvar yas/inhibit-overlay-hooks nil
3182 "Bind this temporarity to non-nil to prevent running `yas/on-*-modification'.")
3183
3184 (defun yas/on-field-overlay-modification (overlay after? beg end &optional length)
3185 "Clears the field and updates mirrors, conditionally.
3186
3187 Only clears the field if it hasn't been modified and it point it
3188 at field start. This hook doesn't do anything if an undo is in
3189 progress."
3190 (unless (or yas/inhibit-overlay-hooks
3191 (yas/undo-in-progress))
3192 (let* ((field (overlay-get overlay 'yas/field))
3193 (number (and field (yas/field-number field)))
3194 (snippet (overlay-get yas/active-field-overlay 'yas/snippet)))
3195 (cond (after?
3196 (yas/advance-end-maybe field (overlay-end overlay))
3197 (save-excursion
3198 (yas/field-update-display field snippet))
3199 (yas/update-mirrors snippet))
3200 (field
3201 (when (and (not after?)
3202 (not (yas/field-modified-p field))
3203 (eq (point) (if (markerp (yas/field-start field))
3204 (marker-position (yas/field-start field))
3205 (yas/field-start field))))
3206 (yas/skip-and-clear field))
3207 (setf (yas/field-modified-p field) t))))))
3208 \f
3209 ;;; Apropos protection overlays:
3210 ;;
3211 ;; These exist for nasty users who will try to delete parts of the
3212 ;; snippet outside the active field. Actual protection happens in
3213 ;; `yas/on-protection-overlay-modification'.
3214 ;;
3215 ;; Currently this signals an error which inhibits the command. For
3216 ;; commands that move point (like `kill-line'), point is restored in
3217 ;; the `yas/post-command-handler' using a global
3218 ;; `yas/protection-violation' variable.
3219 ;;
3220 ;; Alternatively, I've experimented with an implementation that
3221 ;; commits the snippet before actually calling `this-command'
3222 ;; interactively, and then signals an eror, which is ignored. but
3223 ;; blocks all other million modification hooks. This presented some
3224 ;; problems with stacked expansion.
3225 ;;
3226
3227 (defun yas/make-move-field-protection-overlays (snippet field)
3228 "Place protection overlays surrounding SNIPPET's FIELD.
3229
3230 Move the overlays, or create them if they do not exit."
3231 (let ((start (yas/field-start field))
3232 (end (yas/field-end field)))
3233 ;; First check if the (1+ end) is contained in the buffer,
3234 ;; otherwise we'll have to do a bit of cheating and silently
3235 ;; insert a newline. the `(1+ (buffer-size))' should prevent this
3236 ;; when using stacked expansion
3237 ;;
3238 (when (< (buffer-size) end)
3239 (save-excursion
3240 (yas/inhibit-overlay-hooks
3241 (goto-char (point-max))
3242 (newline))))
3243 ;; go on to normal overlay creation/moving
3244 ;;
3245 (cond ((and yas/field-protection-overlays
3246 (every #'overlay-buffer yas/field-protection-overlays))
3247 (move-overlay (first yas/field-protection-overlays) (1- start) start)
3248 (move-overlay (second yas/field-protection-overlays) end (1+ end)))
3249 (t
3250 (setq yas/field-protection-overlays
3251 (list (make-overlay (1- start) start nil t nil)
3252 (make-overlay end (1+ end) nil t nil)))
3253 (dolist (ov yas/field-protection-overlays)
3254 (overlay-put ov 'face 'yas/field-debug-face)
3255 (overlay-put ov 'yas/snippet snippet)
3256 ;; (overlay-put ov 'evaporate t)
3257 (overlay-put ov 'modification-hooks '(yas/on-protection-overlay-modification)))))))
3258
3259 (defvar yas/protection-violation nil
3260 "When non-nil, signals attempts to erronesly exit or modify the snippet.
3261
3262 Functions in the `post-command-hook', for example
3263 `yas/post-command-handler' can check it and reset its value to
3264 nil. The variables value is the point where the violation
3265 originated")
3266
3267 (defun yas/on-protection-overlay-modification (overlay after? beg end &optional length)
3268 "Signals a snippet violation, then issues error.
3269
3270 The error should be ignored in `debug-ignored-errors'"
3271 (unless yas/inhibit-overlay-hooks
3272 (cond ((not (or after?
3273 (yas/undo-in-progress)))
3274 (setq yas/protection-violation (point))
3275 (error "Exit the snippet first!")))))
3276
3277 (add-to-list 'debug-ignored-errors "^Exit the snippet first!$")
3278
3279 \f
3280 ;;; Apropos stacked expansion:
3281 ;;
3282 ;; the parent snippet does not run its fields modification hooks
3283 ;; (`yas/on-field-overlay-modification' and
3284 ;; `yas/on-protection-overlay-modification') while the child snippet
3285 ;; is active. This means, among other things, that the mirrors of the
3286 ;; parent snippet are not updated, this only happening when one exits
3287 ;; the child snippet.
3288 ;;
3289 ;; Unfortunately, this also puts some ugly (and not fully-tested)
3290 ;; bits of code in `yas/expand-snippet' and
3291 ;; `yas/commit-snippet'. I've tried to mark them with "stacked
3292 ;; expansion:".
3293 ;;
3294 ;; This was thought to be safer in in an undo/redo perpective, but
3295 ;; maybe the correct implementation is to make the globals
3296 ;; `yas/active-field-overlay' and `yas/field-protection-overlays' be
3297 ;; snippet-local and be active even while the child snippet is
3298 ;; running. This would mean a lot of overlay modification hooks
3299 ;; running, but if managed correctly (including overlay priorities)
3300 ;; they should account for all situations...
3301 ;;
3302
3303 (defun yas/expand-snippet (content &optional start end expand-env)
3304 "Expand snippet CONTENT at current point.
3305
3306 Text between START and END will be deleted before inserting
3307 template. EXPAND-ENV is are let-style variable to value bindings
3308 considered when expanding the snippet."
3309 (run-hooks 'yas/before-expand-snippet-hook)
3310
3311 ;; If a region is active, set `yas/selected-text'
3312 (setq yas/selected-text
3313 (when (region-active-p)
3314 (prog1 (buffer-substring-no-properties (region-beginning)
3315 (region-end))
3316 (unless start (setq start (region-beginning))
3317 (unless end (setq end (region-end)))))))
3318
3319 (when start
3320 (goto-char start))
3321
3322 ;;
3323 (let ((to-delete (and start end (buffer-substring-no-properties start end)))
3324 (start (or start (point)))
3325 (end (or end (point)))
3326 snippet)
3327 (setq yas/indent-original-column (current-column))
3328 ;; Delete the region to delete, this *does* get undo-recorded.
3329 ;;
3330 (when (and to-delete
3331 (> end start))
3332 (delete-region start end))
3333
3334 (cond ((listp content)
3335 ;; x) This is a snippet-command
3336 ;;
3337 (yas/eval-lisp-no-saves content))
3338 (t
3339 ;; x) This is a snippet-snippet :-)
3340 ;;
3341 ;; Narrow the region down to the content, shoosh the
3342 ;; `buffer-undo-list', and create the snippet, the new
3343 ;; snippet updates its mirrors once, so we are left with
3344 ;; some plain text. The undo action for deleting this
3345 ;; plain text will get recorded at the end.
3346 ;;
3347 ;; stacked expansion: also shoosh the overlay modification hooks
3348 (save-restriction
3349 (narrow-to-region start start)
3350 (let ((buffer-undo-list t))
3351 ;; snippet creation might evaluate users elisp, which
3352 ;; might generate errors, so we have to be ready to catch
3353 ;; them mostly to make the undo information
3354 ;;
3355 (setq yas/start-column (save-restriction (widen) (current-column)))
3356 (yas/inhibit-overlay-hooks
3357 (setq snippet
3358 (if expand-env
3359 (eval `(let* ,expand-env
3360 (insert content)
3361 (yas/snippet-create (point-min) (point-max))))
3362 (insert content)
3363 (yas/snippet-create (point-min) (point-max)))))))
3364
3365 ;; stacked-expansion: This checks for stacked expansion, save the
3366 ;; `yas/previous-active-field' and advance its boudary.
3367 ;;
3368 (let ((existing-field (and yas/active-field-overlay
3369 (overlay-buffer yas/active-field-overlay)
3370 (overlay-get yas/active-field-overlay 'yas/field))))
3371 (when existing-field
3372 (setf (yas/snippet-previous-active-field snippet) existing-field)
3373 (yas/advance-end-maybe existing-field (overlay-end yas/active-field-overlay))))
3374
3375 ;; Exit the snippet immediately if no fields
3376 ;;
3377 (unless (yas/snippet-fields snippet)
3378 (yas/exit-snippet snippet))
3379
3380 ;; Push two undo actions: the deletion of the inserted contents of
3381 ;; the new snippet (without the "key") followed by an apply of
3382 ;; `yas/take-care-of-redo' on the newly inserted snippet boundaries
3383 ;;
3384 ;; A small exception, if `yas/also-auto-indent-first-line'
3385 ;; is t and `yas/indent' decides to indent the line to a
3386 ;; point before the actual expansion point, undo would be
3387 ;; messed up. We call the early point "newstart"". case,
3388 ;; and attempt to fix undo.
3389 ;;
3390 (let ((newstart (overlay-start (yas/snippet-control-overlay snippet)))
3391 (end (overlay-end (yas/snippet-control-overlay snippet))))
3392 (when (< newstart start)
3393 (push (cons (make-string (- start newstart) ? ) newstart) buffer-undo-list))
3394 (push (cons newstart end) buffer-undo-list)
3395 (push `(apply yas/take-care-of-redo ,start ,end ,snippet)
3396 buffer-undo-list))
3397 ;; Now, schedule a move to the first field
3398 ;;
3399 (let ((first-field (car (yas/snippet-fields snippet))))
3400 (when first-field
3401 (sit-for 0) ;; fix issue 125
3402 (yas/move-to-field snippet first-field)))
3403 (message "[yas] snippet expanded.")
3404 t))))
3405
3406 (defun yas/take-care-of-redo (beg end snippet)
3407 "Commits SNIPPET, which in turn pushes an undo action for
3408 reviving it.
3409
3410 Meant to exit in the `buffer-undo-list'."
3411 ;; slightly optimize: this action is only needed for snippets with
3412 ;; at least one field
3413 (when (yas/snippet-fields snippet)
3414 (yas/commit-snippet snippet)))
3415
3416 (defun yas/snippet-revive (beg end snippet)
3417 "Revives the SNIPPET and creates a control overlay from BEG to
3418 END.
3419
3420 BEG and END are, we hope, the original snippets boudaries. All
3421 the markers/points exiting existing inside SNIPPET should point
3422 to their correct locations *at the time the snippet is revived*.
3423
3424 After revival, push the `yas/take-care-of-redo' in the
3425 `buffer-undo-list'"
3426 ;; Reconvert all the points to markers
3427 ;;
3428 (yas/points-to-markers snippet)
3429 ;; When at least one editable field existed in the zombie snippet,
3430 ;; try to revive the whole thing...
3431 ;;
3432 (let ((target-field (or (yas/snippet-active-field snippet)
3433 (car (yas/snippet-fields snippet)))))
3434 (when target-field
3435 (setf (yas/snippet-control-overlay snippet) (yas/make-control-overlay snippet beg end))
3436 (overlay-put (yas/snippet-control-overlay snippet) 'yas/snippet snippet)
3437
3438 (yas/move-to-field snippet target-field)
3439
3440 (push `(apply yas/take-care-of-redo ,beg ,end ,snippet)
3441 buffer-undo-list))))
3442
3443 (defun yas/snippet-create (begin end)
3444 "Creates a snippet from an template inserted between BEGIN and END.
3445
3446 Returns the newly created snippet."
3447 (let ((snippet (yas/make-snippet)))
3448 (goto-char begin)
3449 (yas/snippet-parse-create snippet)
3450
3451 ;; Sort and link each field
3452 (yas/snippet-sort-fields snippet)
3453
3454 ;; Create keymap overlay for snippet
3455 (setf (yas/snippet-control-overlay snippet)
3456 (yas/make-control-overlay snippet (point-min) (point-max)))
3457
3458 ;; Move to end
3459 (goto-char (point-max))
3460
3461 snippet))
3462
3463 \f
3464 ;;; Apropos adjacencies and "fom's":
3465 ;;
3466 ;; Once the $-constructs bits like "$n" and "${:n" are deleted in the
3467 ;; recently expanded snippet, we might actually have many fields,
3468 ;; mirrors (and the snippet exit) in the very same position in the
3469 ;; buffer. Therefore we need to single-link the
3470 ;; fields-or-mirrors-or-exit, which I have called "fom", according to
3471 ;; their original positions in the buffer.
3472 ;;
3473 ;; Then we have operation `yas/advance-end-maybe' and
3474 ;; `yas/advance-start-maybe', which conditionally push the starts and
3475 ;; ends of these foms down the chain.
3476 ;;
3477 ;; This allows for like the printf with the magic ",":
3478 ;;
3479 ;; printf ("${1:%s}\\n"${1:$(if (string-match "%" text) "," "\);")} \
3480 ;; $2${1:$(if (string-match "%" text) "\);" "")}$0
3481 ;;
3482 (defun yas/fom-start (fom)
3483 (cond ((yas/field-p fom)
3484 (yas/field-start fom))
3485 ((yas/mirror-p fom)
3486 (yas/mirror-start fom))
3487 (t
3488 (yas/exit-marker fom))))
3489
3490 (defun yas/fom-end (fom)
3491 (cond ((yas/field-p fom)
3492 (yas/field-end fom))
3493 ((yas/mirror-p fom)
3494 (yas/mirror-end fom))
3495 (t
3496 (yas/exit-marker fom))))
3497
3498 (defun yas/fom-next (fom)
3499 (cond ((yas/field-p fom)
3500 (yas/field-next fom))
3501 ((yas/mirror-p fom)
3502 (yas/mirror-next fom))
3503 (t
3504 (yas/exit-next fom))))
3505
3506 (defun yas/fom-parent-field (fom)
3507 (cond ((yas/field-p fom)
3508 (yas/field-parent-field fom))
3509 ((yas/mirror-p fom)
3510 (yas/mirror-parent-field fom))
3511 (t
3512 nil)))
3513
3514 (defun yas/calculate-adjacencies (snippet)
3515 "Calculate adjacencies for fields or mirrors of SNIPPET.
3516
3517 This is according to their relative positions in the buffer, and
3518 has to be called before the $-constructs are deleted."
3519 (flet ((yas/fom-set-next-fom (fom nextfom)
3520 (cond ((yas/field-p fom)
3521 (setf (yas/field-next fom) nextfom))
3522 ((yas/mirror-p fom)
3523 (setf (yas/mirror-next fom) nextfom))
3524 (t
3525 (setf (yas/exit-next fom) nextfom))))
3526 (yas/compare-fom-begs (fom1 fom2)
3527 (if (= (yas/fom-start fom2) (yas/fom-start fom1))
3528 (yas/mirror-p fom2)
3529 (>= (yas/fom-start fom2) (yas/fom-start fom1))))
3530 (yas/link-foms (fom1 fom2)
3531 (yas/fom-set-next-fom fom1 fom2)))
3532 ;; make some yas/field, yas/mirror and yas/exit soup
3533 (let ((soup))
3534 (when (yas/snippet-exit snippet)
3535 (push (yas/snippet-exit snippet) soup))
3536 (dolist (field (yas/snippet-fields snippet))
3537 (push field soup)
3538 (dolist (mirror (yas/field-mirrors field))
3539 (push mirror soup)))
3540 (setq soup
3541 (sort soup
3542 #'yas/compare-fom-begs))
3543 (when soup
3544 (reduce #'yas/link-foms soup)))))
3545
3546 (defun yas/calculate-mirrors-in-fields (snippet mirror)
3547 "Attempt to assign a parent field of SNIPPET to the mirror MIRROR.
3548
3549 Use the tighest containing field if more than one field contains
3550 the mirror. Intended to be called *before* the dollar-regions are
3551 deleted."
3552 (let ((min (point-min))
3553 (max (point-max)))
3554 (dolist (field (yas/snippet-fields snippet))
3555 (when (and (<= (yas/field-start field) (yas/mirror-start mirror))
3556 (<= (yas/mirror-end mirror) (yas/field-end field))
3557 (< min (yas/field-start field))
3558 (< (yas/field-end field) max))
3559 (setq min (yas/field-start field)
3560 max (yas/field-end field))
3561 (setf (yas/mirror-parent-field mirror) field)))))
3562
3563 (defun yas/advance-end-maybe (fom newend)
3564 "Maybe advance FOM's end to NEWEND if it needs it.
3565
3566 If it does, also:
3567
3568 * call `yas/advance-start-maybe' on FOM's next fom.
3569
3570 * in case FOM is field call `yas/advance-end-maybe' on its parent
3571 field
3572
3573 Also, if FOM is an exit-marker, always call
3574 `yas/advance-start-maybe' on its next fom. This is beacuse
3575 exit-marker have identical start and end markers.
3576
3577 "
3578 (cond ((and fom (< (yas/fom-end fom) newend))
3579 (set-marker (yas/fom-end fom) newend)
3580 (yas/advance-start-maybe (yas/fom-next fom) newend)
3581 (yas/advance-end-of-parents-maybe (yas/fom-parent-field fom) newend))
3582 ((yas/exit-p fom)
3583 (yas/advance-start-maybe (yas/fom-next fom) newend))))
3584
3585 (defun yas/advance-start-maybe (fom newstart)
3586 "Maybe advance FOM's start to NEWSTART if it needs it.
3587
3588 If it does, also call `yas/advance-end-maybe' on FOM."
3589 (when (and fom (< (yas/fom-start fom) newstart))
3590 (set-marker (yas/fom-start fom) newstart)
3591 (yas/advance-end-maybe fom newstart)))
3592
3593 (defun yas/advance-end-of-parents-maybe (field newend)
3594 "Like `yas/advance-end-maybe' but for parent fields.
3595
3596 Only works for fields and doesn't care about the start of the
3597 next FOM. Works its way up recursively for parents of parents."
3598 (when (and field
3599 (< (yas/field-end field) newend))
3600 (set-marker (yas/field-end field) newend)
3601 (yas/advance-end-of-parents-maybe (yas/field-parent-field field) newend)))
3602
3603 (defvar yas/dollar-regions nil
3604 "When expanding the snippet the \"parse-create\" functions add
3605 cons cells to this var")
3606
3607 (defun yas/snippet-parse-create (snippet)
3608 "Parse a recently inserted snippet template, creating all
3609 necessary fields, mirrors and exit points.
3610
3611 Meant to be called in a narrowed buffer, does various passes"
3612 (let ((parse-start (point)))
3613 ;; Reset the yas/dollar-regions
3614 ;;
3615 (setq yas/dollar-regions nil)
3616 ;; protect escaped quote, backquotes and backslashes
3617 ;;
3618 (yas/protect-escapes nil `(?\\ ?` ?'))
3619 ;; replace all backquoted expressions
3620 ;;
3621 (goto-char parse-start)
3622 (yas/replace-backquotes)
3623 ;; protect escapes again since previous steps might have generated
3624 ;; more characters needing escaping
3625 ;;
3626 (goto-char parse-start)
3627 (yas/protect-escapes)
3628 ;; parse fields with {}
3629 ;;
3630 (goto-char parse-start)
3631 (yas/field-parse-create snippet)
3632 ;; parse simple mirrors and fields
3633 ;;
3634 (goto-char parse-start)
3635 (yas/simple-mirror-parse-create snippet)
3636 ;; parse mirror transforms
3637 ;;
3638 (goto-char parse-start)
3639 (yas/transform-mirror-parse-create snippet)
3640 ;; calculate adjacencies of fields and mirrors
3641 ;;
3642 (yas/calculate-adjacencies snippet)
3643 ;; Delete $-constructs
3644 ;;
3645 (yas/delete-regions yas/dollar-regions)
3646 ;; restore escapes
3647 ;;
3648 (goto-char parse-start)
3649 (yas/restore-escapes)
3650 ;; update mirrors for the first time
3651 ;;
3652 (yas/update-mirrors snippet)
3653 ;; indent the best we can
3654 ;;
3655 (goto-char parse-start)
3656 (yas/indent snippet)))
3657
3658 (defun yas/indent-according-to-mode (snippet-markers)
3659 "Indent current line according to mode, preserving
3660 SNIPPET-MARKERS."
3661 ;;; Apropos indenting problems....
3662 ;;
3663 ;; `indent-according-to-mode' uses whatever `indent-line-function'
3664 ;; is available. Some implementations of these functions delete text
3665 ;; before they insert. If there happens to be a marker just after
3666 ;; the text being deleted, the insertion actually happens after the
3667 ;; marker, which misplaces it.
3668 ;;
3669 ;; This would also happen if we had used overlays with the
3670 ;; `front-advance' property set to nil.
3671 ;;
3672 ;; This is why I have these `trouble-markers', they are the ones at
3673 ;; they are the ones at the first non-whitespace char at the line
3674 ;; (i.e. at `yas/real-line-beginning'. After indentation takes place
3675 ;; we should be at the correct to restore them to. All other
3676 ;; non-trouble-markers have been *pushed* and don't need special
3677 ;; attention.
3678 ;;
3679 (goto-char (yas/real-line-beginning))
3680 (let ((trouble-markers (remove-if-not #'(lambda (marker)
3681 (= marker (point)))
3682 snippet-markers)))
3683 (save-restriction
3684 (widen)
3685 (condition-case err
3686 (indent-according-to-mode)
3687 (error (message "[yas] warning: yas/indent-according-to-mode habing problems running %s" indent-line-function)
3688 nil)))
3689 (mapc #'(lambda (marker)
3690 (set-marker marker (point)))
3691 trouble-markers)))
3692
3693 (defvar yas/indent-original-column nil)
3694 (defun yas/indent (snippet)
3695 (let ((snippet-markers (yas/collect-snippet-markers snippet)))
3696 ;; Look for those $>
3697 (save-excursion
3698 (while (re-search-forward "$>" nil t)
3699 (delete-region (match-beginning 0) (match-end 0))
3700 (when (not (eq yas/indent-line 'auto))
3701 (yas/indent-according-to-mode snippet-markers))))
3702 ;; Now do stuff for 'fixed and 'auto
3703 (save-excursion
3704 (cond ((eq yas/indent-line 'fixed)
3705 (while (and (zerop (forward-line))
3706 (zerop (current-column)))
3707 (indent-to-column yas/indent-original-column)))
3708 ((eq yas/indent-line 'auto)
3709 (let ((end (set-marker (make-marker) (point-max)))
3710 (indent-first-line-p yas/also-auto-indent-first-line))
3711 (while (and (zerop (if indent-first-line-p
3712 (prog1
3713 (forward-line 0)
3714 (setq indent-first-line-p nil))
3715 (forward-line 1)))
3716 (not (eobp))
3717 (<= (point) end))
3718 (yas/indent-according-to-mode snippet-markers))))
3719 (t
3720 nil)))))
3721
3722 (defun yas/collect-snippet-markers (snippet)
3723 "Make a list of all the markers used by SNIPPET."
3724 (let (markers)
3725 (dolist (field (yas/snippet-fields snippet))
3726 (push (yas/field-start field) markers)
3727 (push (yas/field-end field) markers)
3728 (dolist (mirror (yas/field-mirrors field))
3729 (push (yas/mirror-start mirror) markers)
3730 (push (yas/mirror-end mirror) markers)))
3731 (let ((snippet-exit (yas/snippet-exit snippet)))
3732 (when (and snippet-exit
3733 (marker-buffer (yas/exit-marker snippet-exit)))
3734 (push (yas/exit-marker snippet-exit) markers)))
3735 markers))
3736
3737 (defun yas/real-line-beginning ()
3738 (let ((c (char-after (line-beginning-position)))
3739 (n (line-beginning-position)))
3740 (while (or (eql c ?\ )
3741 (eql c ?\t))
3742 (incf n)
3743 (setq c (char-after n)))
3744 n))
3745
3746 (defun yas/escape-string (escaped)
3747 (concat "YASESCAPE" (format "%d" escaped) "PROTECTGUARD"))
3748
3749 (defun yas/protect-escapes (&optional text escaped)
3750 "Protect all escaped characters with their numeric ASCII value.
3751
3752 With optional string TEXT do it in string instead of buffer."
3753 (let ((changed-text text)
3754 (text-provided-p text))
3755 (mapc #'(lambda (escaped)
3756 (setq changed-text
3757 (yas/replace-all (concat "\\" (char-to-string escaped))
3758 (yas/escape-string escaped)
3759 (when text-provided-p changed-text))))
3760 (or escaped yas/escaped-characters))
3761 changed-text))
3762
3763 (defun yas/restore-escapes (&optional text escaped)
3764 "Restore all escaped characters from their numeric ASCII value.
3765
3766 With optional string TEXT do it in string instead of the buffer."
3767 (let ((changed-text text)
3768 (text-provided-p text))
3769 (mapc #'(lambda (escaped)
3770 (setq changed-text
3771 (yas/replace-all (yas/escape-string escaped)
3772 (char-to-string escaped)
3773 (when text-provided-p changed-text))))
3774 (or escaped yas/escaped-characters))
3775 changed-text))
3776
3777 (defun yas/replace-backquotes ()
3778 "Replace all the \"`(lisp-expression)`\"-style expression
3779 with their evaluated value"
3780 (while (re-search-forward yas/backquote-lisp-expression-regexp nil t)
3781 (let ((current-string (match-string 1)) transformed)
3782 (delete-region (match-beginning 0) (match-end 0))
3783 (setq transformed (yas/eval-lisp (yas/read-lisp (yas/restore-escapes current-string))))
3784 (goto-char (match-beginning 0))
3785 (when transformed (insert transformed)))))
3786
3787 (defun yas/scan-sexps (from count)
3788 (condition-case err
3789 (with-syntax-table (standard-syntax-table)
3790 (scan-sexps from count))
3791 (error
3792 nil)))
3793
3794 (defun yas/make-marker (pos)
3795 "Create a marker at POS with `nil' `marker-insertion-type'"
3796 (let ((marker (set-marker (make-marker) pos)))
3797 (set-marker-insertion-type marker nil)
3798 marker))
3799
3800 (defun yas/field-parse-create (snippet &optional parent-field)
3801 "Parse most field expressions, except for the simple one \"$n\".
3802
3803 The following count as a field:
3804
3805 * \"${n: text}\", for a numbered field with default text, as long as N is not 0;
3806
3807 * \"${n: text$(expression)}, the same with a lisp expression;
3808 this is caught with the curiously named `yas/multi-dollar-lisp-expression-regexp'
3809
3810 * the same as above but unnumbered, (no N:) and number is calculated automatically.
3811
3812 When multiple expressions are found, only the last one counts."
3813 ;;
3814 (save-excursion
3815 (while (re-search-forward yas/field-regexp nil t)
3816 (let* ((real-match-end-0 (yas/scan-sexps (1+ (match-beginning 0)) 1))
3817 (number (and (match-string-no-properties 1)
3818 (string-to-number (match-string-no-properties 1))))
3819 (brand-new-field (and real-match-end-0
3820 ;; break if on "$(" immediately
3821 ;; after the ":", this will be
3822 ;; caught as a mirror with
3823 ;; transform later.
3824 (not (save-match-data
3825 (eq (string-match "$[ \t\n]*("
3826 (match-string-no-properties 2)) 0)))
3827 ;; allow ${0: some exit text}
3828 ;; (not (and number (zerop number)))
3829 (yas/make-field number
3830 (yas/make-marker (match-beginning 2))
3831 (yas/make-marker (1- real-match-end-0))
3832 parent-field))))
3833 (when brand-new-field
3834 (goto-char real-match-end-0)
3835 (push (cons (1- real-match-end-0) real-match-end-0)
3836 yas/dollar-regions)
3837 (push (cons (match-beginning 0) (match-beginning 2))
3838 yas/dollar-regions)
3839 (push brand-new-field (yas/snippet-fields snippet))
3840 (save-excursion
3841 (save-restriction
3842 (narrow-to-region (yas/field-start brand-new-field) (yas/field-end brand-new-field))
3843 (goto-char (point-min))
3844 (yas/field-parse-create snippet brand-new-field)))))))
3845 ;; if we entered from a parent field, now search for the
3846 ;; `yas/multi-dollar-lisp-expression-regexp'. THis is used for
3847 ;; primary field transformations
3848 ;;
3849 (when parent-field
3850 (save-excursion
3851 (while (re-search-forward yas/multi-dollar-lisp-expression-regexp nil t)
3852 (let* ((real-match-end-1 (yas/scan-sexps (match-beginning 1) 1)))
3853 ;; commit the primary field transformation if:
3854 ;;
3855 ;; 1. we don't find it in yas/dollar-regions (a subnested
3856 ;; field) might have already caught it.
3857 ;;
3858 ;; 2. we really make sure we have either two '$' or some
3859 ;; text and a '$' after the colon ':'. This is a FIXME: work
3860 ;; my regular expressions and end these ugly hacks.
3861 ;;
3862 (when (and real-match-end-1
3863 (not (member (cons (match-beginning 0)
3864 real-match-end-1)
3865 yas/dollar-regions))
3866 (not (eq ?:
3867 (char-before (1- (match-beginning 1))))))
3868 (let ((lisp-expression-string (buffer-substring-no-properties (match-beginning 1)
3869 real-match-end-1)))
3870 (setf (yas/field-transform parent-field)
3871 (yas/read-lisp (yas/restore-escapes lisp-expression-string))))
3872 (push (cons (match-beginning 0) real-match-end-1)
3873 yas/dollar-regions)))))))
3874
3875 (defun yas/transform-mirror-parse-create (snippet)
3876 "Parse the \"${n:$(lisp-expression)}\" mirror transformations."
3877 (while (re-search-forward yas/transform-mirror-regexp nil t)
3878 (let* ((real-match-end-0 (yas/scan-sexps (1+ (match-beginning 0)) 1))
3879 (number (string-to-number (match-string-no-properties 1)))
3880 (field (and number
3881 (not (zerop number))
3882 (yas/snippet-find-field snippet number)))
3883 (brand-new-mirror
3884 (and real-match-end-0
3885 field
3886 (yas/make-mirror (yas/make-marker (match-beginning 0))
3887 (yas/make-marker (match-beginning 0))
3888 (yas/read-lisp
3889 (yas/restore-escapes
3890 (buffer-substring-no-properties (match-beginning 2)
3891 (1- real-match-end-0))))))))
3892 (when brand-new-mirror
3893 (push brand-new-mirror
3894 (yas/field-mirrors field))
3895 (yas/calculate-mirrors-in-fields snippet brand-new-mirror)
3896 (push (cons (match-beginning 0) real-match-end-0) yas/dollar-regions)))))
3897
3898 (defun yas/simple-mirror-parse-create (snippet)
3899 "Parse the simple \"$n\" fields/mirrors/exitmarkers."
3900 (while (re-search-forward yas/simple-mirror-regexp nil t)
3901 (let ((number (string-to-number (match-string-no-properties 1))))
3902 (cond ((zerop number)
3903
3904 (setf (yas/snippet-exit snippet)
3905 (yas/make-exit (yas/make-marker (match-end 0))))
3906 (save-excursion
3907 (goto-char (match-beginning 0))
3908 (when yas/wrap-around-region
3909 (cond (yas/selected-text
3910 (insert yas/selected-text))
3911 ((and (eq yas/wrap-around-region 'cua)
3912 cua-mode
3913 (get-register ?0))
3914 (insert (prog1 (get-register ?0)
3915 (set-register ?0 nil))))))
3916 (push (cons (point) (yas/exit-marker (yas/snippet-exit snippet)))
3917 yas/dollar-regions)))
3918 (t
3919 (let ((field (yas/snippet-find-field snippet number)))
3920 (if field
3921 (let ((brand-new-mirror (yas/make-mirror
3922 (yas/make-marker (match-beginning 0))
3923 (yas/make-marker (match-beginning 0))
3924 nil)))
3925 (push brand-new-mirror
3926 (yas/field-mirrors field))
3927 (yas/calculate-mirrors-in-fields snippet brand-new-mirror))
3928 (push (yas/make-field number
3929 (yas/make-marker (match-beginning 0))
3930 (yas/make-marker (match-beginning 0))
3931 nil)
3932 (yas/snippet-fields snippet))))
3933 (push (cons (match-beginning 0) (match-end 0))
3934 yas/dollar-regions))))))
3935
3936 (defun yas/delete-regions (regions)
3937 "Sort disjuct REGIONS by start point, then delete from the back."
3938 (mapc #'(lambda (reg)
3939 (delete-region (car reg) (cdr reg)))
3940 (sort regions
3941 #'(lambda (r1 r2)
3942 (>= (car r1) (car r2))))))
3943
3944 (defun yas/update-mirrors (snippet)
3945 "Updates all the mirrors of SNIPPET."
3946 (save-excursion
3947 (let* ((fields (copy-list (yas/snippet-fields snippet)))
3948 (field (car fields)))
3949 (while field
3950 (dolist (mirror (yas/field-mirrors field))
3951 (let ((mirror-parent-field (yas/mirror-parent-field mirror)))
3952 ;; updatte this mirror
3953 ;;
3954 (yas/mirror-update-display mirror field)
3955 ;; for mirrors-in-fields: schedule a possible
3956 ;; parent field for reupdting later on
3957 ;;
3958 (when mirror-parent-field
3959 (add-to-list 'fields mirror-parent-field 'append #'eq))
3960 ;; `yas/place-overlays' is needed if the active field and
3961 ;; protected overlays have been changed because of insertions
3962 ;; in `yas/mirror-update-display'
3963 ;;
3964 (when (eq field (yas/snippet-active-field snippet))
3965 (yas/place-overlays snippet field))))
3966 (setq fields (cdr fields))
3967 (setq field (car fields))))))
3968
3969 (defun yas/mirror-update-display (mirror field)
3970 "Update MIRROR according to FIELD (and mirror transform)."
3971
3972 (let* ((mirror-parent-field (yas/mirror-parent-field mirror))
3973 (reflection (and (not (and mirror-parent-field
3974 (yas/field-modified-p mirror-parent-field)))
3975 (or (yas/apply-transform mirror field 'empty-on-nil)
3976 (yas/field-text-for-display field)))))
3977 (when (and reflection
3978 (not (string= reflection (buffer-substring-no-properties (yas/mirror-start mirror)
3979 (yas/mirror-end mirror)))))
3980 (goto-char (yas/mirror-start mirror))
3981 (yas/inhibit-overlay-hooks
3982 (insert reflection))
3983 (if (> (yas/mirror-end mirror) (point))
3984 (delete-region (point) (yas/mirror-end mirror))
3985 (set-marker (yas/mirror-end mirror) (point))
3986 (yas/advance-start-maybe (yas/mirror-next mirror) (point))
3987 ;; super-special advance
3988 (yas/advance-end-of-parents-maybe mirror-parent-field (point))))))
3989
3990 (defun yas/field-update-display (field snippet)
3991 "Much like `yas/mirror-update-display', but for fields"
3992 (when (yas/field-transform field)
3993 (let ((transformed (and (not (eq (yas/field-number field) 0))
3994 (yas/apply-transform field field)))
3995 (point (point)))
3996 (when (and transformed
3997 (not (string= transformed (buffer-substring-no-properties (yas/field-start field)
3998 (yas/field-end field)))))
3999 (setf (yas/field-modified-p field) t)
4000 (goto-char (yas/field-start field))
4001 (yas/inhibit-overlay-hooks
4002 (insert transformed)
4003 (if (> (yas/field-end field) (point))
4004 (delete-region (point) (yas/field-end field))
4005 (set-marker (yas/field-end field) (point))
4006 (yas/advance-start-maybe (yas/field-next field) (point)))
4007 t)))))
4008
4009 \f
4010 ;;; Post-command hooks:
4011
4012 (defvar yas/post-command-runonce-actions nil
4013 "List of actions to run once in `post-command-hook'.
4014
4015 Each element of this list looks like (FN . ARGS) where FN is
4016 called with ARGS as its arguments after the currently executing
4017 snippet command.
4018
4019 After all actions have been run, this list is emptied, and after
4020 that the rest of `yas/post-command-handler' runs.")
4021
4022 (defun yas/post-command-handler ()
4023 "Handles various yasnippet conditions after each command."
4024 (when yas/post-command-runonce-actions
4025 (condition-case err
4026 (mapc #'(lambda (fn-and-args)
4027 (apply (car fn-and-args)
4028 (cdr fn-and-args)))
4029 yas/post-command-runonce-actions)
4030 (error (message "[yas] problem running `yas/post-command-runonce-actions'!")))
4031 (setq yas/post-command-runonce-actions nil))
4032 (cond (yas/protection-violation
4033 (goto-char yas/protection-violation)
4034 (setq yas/protection-violation nil))
4035 ((eq 'undo this-command)
4036 ;;
4037 ;; After undo revival the correct field is sometimes not
4038 ;; restored correctly, this condition handles that
4039 ;;
4040 (let* ((snippet (car (yas/snippets-at-point)))
4041 (target-field (and snippet
4042 (find-if-not #'(lambda (field)
4043 (yas/field-probably-deleted-p snippet field))
4044 (remove nil
4045 (cons (yas/snippet-active-field snippet)
4046 (yas/snippet-fields snippet)))))))
4047 (when target-field
4048 (yas/move-to-field snippet target-field))))
4049 ((not (yas/undo-in-progress))
4050 ;; When not in an undo, check if we must commit the snippet
4051 ;; (user exited it).
4052 (yas/check-commit-snippet))))
4053 \f
4054 ;;; Fancy docs:
4055
4056 (put 'yas/expand 'function-documentation
4057 '(yas/expand-from-trigger-key-doc))
4058 (defun yas/expand-from-trigger-key-doc ()
4059 "A doc synthethizer for `yas/expand-from-trigger-key-doc'."
4060 (let ((fallback-description
4061 (cond ((eq yas/fallback-behavior 'call-other-command)
4062 (let* ((yas/minor-mode nil)
4063 (fallback (key-binding (read-kbd-macro yas/trigger-key))))
4064 (or (and fallback
4065 (format " call command `%s'." (pp-to-string fallback)))
4066 " do nothing.")))
4067 ((eq yas/fallback-behavior 'return-nil)
4068 ", do nothing.")
4069 (t
4070 ", defer to `yas/fallback-behaviour' :-)"))))
4071 (concat "Expand a snippet before point. If no snippet
4072 expansion is possible,"
4073 fallback-description
4074 "\n\nOptional argument FIELD is for non-interactive use and is an
4075 object satisfying `yas/field-p' to restrict the expansion to.")))
4076
4077 (put 'yas/expand-from-keymap 'function-documentation '(yas/expand-from-keymap-doc))
4078 (defun yas/expand-from-keymap-doc ()
4079 "A doc synthethizer for `yas/expand-from-keymap-doc'."
4080 (add-hook 'temp-buffer-show-hook 'yas/snippet-description-finish-runonce)
4081 (concat "Expand/run snippets from keymaps, possibly falling back to original binding.\n"
4082 (when (eq this-command 'describe-key)
4083 (let* ((vec (this-single-command-keys))
4084 (templates (mapcan #'(lambda (table)
4085 (yas/fetch table vec))
4086 (yas/get-snippet-tables)))
4087 (yas/direct-keymaps nil)
4088 (fallback (key-binding vec)))
4089 (concat "In this case, "
4090 (when templates
4091 (concat "these snippets are bound to this key:\n"
4092 (yas/template-pretty-list templates)
4093 "\n\nIf none of these expands, "))
4094 (or (and fallback
4095 (format "fallback `%s' will be called." (pp-to-string fallback)))
4096 "no fallback keybinding is called."))))))
4097
4098 (defun yas/template-pretty-list (templates)
4099 (let ((acc)
4100 (yas/buffer-local-condition 'always))
4101 (dolist (plate templates)
4102 (setq acc (concat acc "\n*) "
4103 (propertize (concat "\\\\snippet `" (car plate) "'")
4104 'yasnippet (cdr plate)))))
4105 acc))
4106
4107 (define-button-type 'help-snippet-def
4108 :supertype 'help-xref
4109 'help-function (lambda (template) (yas/visit-snippet-file-1 template))
4110 'help-echo (purecopy "mouse-2, RET: find snippets's definition"))
4111
4112 (defun yas/snippet-description-finish-runonce ()
4113 "Final adjustments for the help buffer when snippets are concerned."
4114 (yas/create-snippet-xrefs)
4115 (remove-hook 'temp-buffer-show-hook 'yas/snippet-description-finish-runonce))
4116
4117 (defun yas/create-snippet-xrefs ()
4118 (save-excursion
4119 (goto-char (point-min))
4120 (while (search-forward-regexp "\\\\\\\\snippet[ \s\t]+`\\([^']+\\)'" nil t)
4121 (let ((template (get-text-property (match-beginning 1)
4122 'yasnippet)))
4123 (when template
4124 (help-xref-button 1 'help-snippet-def template)
4125 (kill-region (match-end 1) (match-end 0))
4126 (kill-region (match-beginning 0) (match-beginning 1)))))))
4127
4128 (defun yas/expand-uuid (mode-symbol uuid &optional start end expand-env)
4129 "Expand a snippet registered in MODE-SYMBOL's table with UUID.
4130
4131 Remaining args as in `yas/expand-snippet'."
4132 (let* ((table (gethash mode-symbol yas/tables))
4133 (yas/current-template (and table
4134 (gethash uuid (yas/table-uuidhash table)))))
4135 (when yas/current-template
4136 (yas/expand-snippet (yas/template-content yas/current-template)))))
4137
4138 \f
4139 ;;; Some hacks:
4140 ;;;
4141 ;; `locate-dominating-file'
4142 ;; `region-active-p'
4143 ;;
4144 ;; added for compatibility in emacs < 23
4145 (unless (>= emacs-major-version 23)
4146 (unless (fboundp 'region-active-p)
4147 (defun region-active-p () (and transient-mark-mode mark-active)))
4148
4149 (unless (fboundp 'locate-dominating-file)
4150 (defvar locate-dominating-stop-dir-regexp
4151 "\\`\\(?:[\\/][\\/][^\\/]+[\\/]\\|/\\(?:net\\|afs\\|\\.\\.\\.\\)/\\)\\'"
4152 "Regexp of directory names which stop the search in `locate-dominating-file'.
4153 Any directory whose name matches this regexp will be treated like
4154 a kind of root directory by `locate-dominating-file' which will stop its search
4155 when it bumps into it.
4156 The default regexp prevents fruitless and time-consuming attempts to find
4157 special files in directories in which filenames are interpreted as hostnames,
4158 or mount points potentially requiring authentication as a different user.")
4159
4160 (defun locate-dominating-file (file name)
4161 "Look up the directory hierarchy from FILE for a file named NAME.
4162 Stop at the first parent directory containing a file NAME,
4163 and return the directory. Return nil if not found."
4164 ;; We used to use the above locate-dominating-files code, but the
4165 ;; directory-files call is very costly, so we're much better off doing
4166 ;; multiple calls using the code in here.
4167 ;;
4168 ;; Represent /home/luser/foo as ~/foo so that we don't try to look for
4169 ;; `name' in /home or in /.
4170 (setq file (abbreviate-file-name file))
4171 (let ((root nil)
4172 (prev-file file)
4173 ;; `user' is not initialized outside the loop because
4174 ;; `file' may not exist, so we may have to walk up part of the
4175 ;; hierarchy before we find the "initial UUID".
4176 (user nil)
4177 try)
4178 (while (not (or root
4179 (null file)
4180 ;; FIXME: Disabled this heuristic because it is sometimes
4181 ;; inappropriate.
4182 ;; As a heuristic, we stop looking up the hierarchy of
4183 ;; directories as soon as we find a directory belonging
4184 ;; to another user. This should save us from looking in
4185 ;; things like /net and /afs. This assumes that all the
4186 ;; files inside a project belong to the same user.
4187 ;; (let ((prev-user user))
4188 ;; (setq user (nth 2 (file-attributes file)))
4189 ;; (and prev-user (not (equal user prev-user))))
4190 (string-match locate-dominating-stop-dir-regexp file)))
4191 (setq try (file-exists-p (expand-file-name name file)))
4192 (cond (try (setq root file))
4193 ((equal file (setq prev-file file
4194 file (file-name-directory
4195 (directory-file-name file))))
4196 (setq file nil))))
4197 root))))
4198
4199 ;; `c-neutralize-syntax-in-CPP` sometimes fires "End of Buffer" error
4200 ;; (when it execute forward-char) and interrupt the after change
4201 ;; hook. Thus prevent the insert-behind hook of yasnippet to be
4202 ;; invoked. Here's a way to reproduce it:
4203
4204 ;; # open a *new* Emacs.
4205 ;; # load yasnippet.
4206 ;; # open a *new* .cpp file.
4207 ;; # input "inc" and press TAB to expand the snippet.
4208 ;; # select the `#include <...>` snippet.
4209 ;; # type inside `<>`
4210
4211 (defadvice c-neutralize-syntax-in-CPP
4212 (around yas-mp/c-neutralize-syntax-in-CPP activate)
4213 "Adviced `c-neutralize-syntax-in-CPP' to properly
4214 handle the end-of-buffer error fired in it by calling
4215 `forward-char' at the end of buffer."
4216 (condition-case err
4217 ad-do-it
4218 (error (message (error-message-string err)))))
4219
4220 ;; disable c-electric-* serial command in YAS fields
4221 (add-hook 'c-mode-common-hook
4222 '(lambda ()
4223 (dolist (k '(":" ">" ";" "<" "{" "}"))
4224 (define-key (symbol-value (make-local-variable 'yas/keymap))
4225 k 'self-insert-command))))
4226
4227 (provide 'yasnippet)
4228
4229 ;;; yasnippet.el ends here