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