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