1 ;;; Yasnippet.el --- Yet another snippet extension for Emacs.
3 ;; Copyright 2008 pluskid
4 ;; 2009 pluskid, joaotavora
6 ;; Authors: pluskid <pluskid@gmail.com>, joaotavora <joaotavora@gmail.com>
8 ;; Package-version: 0.7.0
9 ;; X-URL: http://code.google.com/p/yasnippet/
10 ;; Keywords: convenience, emulation
11 ;; URL: http://code.google.com/p/yasnippet/
12 ;; EmacsWiki: YaSnippetMode
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)
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.
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.
31 ;; Basic steps to setup:
33 ;; 1. In your .emacs file:
34 ;; (add-to-list 'load-path "/dir/to/yasnippet.el")
35 ;; (require 'yasnippet)
36 ;; 2. Place the `snippets' directory somewhere. E.g: ~/.emacs.d/snippets
37 ;; 3. In your .emacs file
38 ;; (setq yas/snippet-dirs "~/.emacs/snippets")
39 ;; (yas/load-directory yas/snippet-dirs)
40 ;; 4. To enable the YASnippet menu and tab-trigger expansion
42 ;; 5. To globally enable the minor mode in *all* buffers
43 ;; M-x yas/global-mode
45 ;; Steps 4. and 5. are optional, you don't have to use the minor
46 ;; mode to use YASnippet.
48 ;; Interesting variables are:
52 ;; The directory where user-created snippets are to be
53 ;; stored. Can also be a list of directories. In that case,
54 ;; when used for bulk (re)loading of snippets (at startup or
55 ;; via `yas/reload-all'), directories appearing earlier in
56 ;; the list shadow other dir's snippets. Also, the first
57 ;; directory is taken as the default for storing the user's
60 ;; The deprecated `yas/root-directory' aliases this variable
61 ;; for backward-compatibility.
65 ;; A local variable that you can set in a hook to override
66 ;; snippet-lookup based on major mode. It is a a symbol (or
67 ;; list of symbols) that correspond to subdirectories of
68 ;; `yas/snippet-dirs' and is used for deciding which
69 ;; snippets to consider for the active buffer.
71 ;; Deprecated `yas/mode-symbol' aliases this variable for
72 ;; backward-compatibility.
74 ;; Major commands are:
78 ;; Try to expand snippets before point. In `yas/minor-mode',
79 ;; this is bound to `yas/trigger-key' which you can customize.
81 ;; M-x yas/load-directory
83 ;; Prompts you for a directory hierarchy of snippets to load.
85 ;; M-x yas/insert-snippet
87 ;; Prompts you for possible snippet expansion if that is
88 ;; possible according to buffer-local and snippet-local
89 ;; expansion conditions. With prefix argument, ignore these
92 ;; M-x yas/find-snippets
94 ;; Lets you find the snippet files in the correct
95 ;; subdirectory of `yas/snippet-dirs', according to the
96 ;; active major mode (if it exists) like
97 ;; `find-file-other-window'.
99 ;; M-x yas/visit-snippet-file
101 ;; Prompts you for possible snippet expansions like
102 ;; `yas/insert-snippet', but instead of expanding it, takes
103 ;; you directly to the snippet definition's file, if it
106 ;; M-x yas/new-snippet
108 ;; Lets you create a new snippet file in the correct
109 ;; subdirectory of `yas/snippet-dirs', according to the
110 ;; active major mode.
112 ;; M-x yas/load-snippet-buffer
114 ;; When editing a snippet, this loads the snippet. This is
115 ;; bound to "C-c C-c" while in the `snippet-mode' editing
118 ;; M-x yas/tryout-snippet
120 ;; When editing a snippet, this opens a new empty buffer,
121 ;; sets it to the appropriate major mode and inserts the
122 ;; snippet there, so you can see what it looks like. This is
123 ;; bound to "C-c C-t" while in `snippet-mode'.
125 ;; M-x yas/describe-tables
127 ;; Lists known snippets in a separate buffer. User is
128 ;; prompted as to whether only the currently active tables
129 ;; are to be displayed, or all the tables for all major
132 ;; The `dropdown-list.el' extension is bundled with YASnippet, you
133 ;; can optionally use it the preferred "prompting method", puting in
134 ;; your .emacs file, for example:
136 ;; (require 'dropdown-list)
137 ;; (setq yas/prompt-functions '(yas/dropdown-prompt
139 ;; yas/completing-prompt))
141 ;; Also check out the customization group
143 ;; M-x customize-group RET yasnippet RET
145 ;; If you use the customization group to set variables
146 ;; `yas/snippet-dirs' or `yas/global-mode', make sure the path to
147 ;; "yasnippet.el" is present in the `load-path' *before* the
148 ;; `custom-set-variables' is executed in your .emacs file.
150 ;; For more information and detailed usage, refer to the project page:
151 ;; http://code.google.com/p/yasnippet/
161 ;;; User customizable variables
163 (defgroup yasnippet nil
164 "Yet Another Snippet extension"
168 (defcustom yas/snippet-dirs (list "~/.emacs.d/snippets"
169 (concat (file-name-directory load-file-name) "snippets"))
170 "Directory or list of snippet dirs for each major mode.
172 The directory where user-created snippets are to be stored. Can
173 also be a list of directories. In that case, when used for
174 bulk (re)loading of snippets (at startup or via
175 `yas/reload-all'), directories appearing earlier in the list
176 shadow other dir's snippets. Also, the first directory is taken
177 as the default for storing the user's new snippets."
178 :type '(choice (string :tag "Single directory (string)")
179 (repeat :args (string) :tag "List of directories (strings)"))
182 :set #'(lambda (symbol new)
183 (let ((old (and (boundp symbol)
184 (symbol-value symbol))))
185 (set-default symbol new)
186 (unless (or (not (fboundp 'yas/reload-all))
189 (defun yas/snippet-dirs ()
190 (if (listp yas/snippet-dirs) yas/snippet-dirs (list yas/snippet-dirs)))
191 (defvaralias 'yas/root-directory 'yas/snippet-dirs)
193 (defcustom yas/prompt-functions '(yas/x-prompt
195 yas/completing-prompt
198 "Functions to prompt for keys, templates, etc interactively.
200 These functions are called with the following arguments:
202 - PROMPT: A string to prompt the user
204 - CHOICES: a list of strings or objects.
206 - optional DISPLAY-FN : A function that, when applied to each of
207 the objects in CHOICES will return a string.
209 The return value of any function you put here should be one of
210 the objects in CHOICES, properly formatted with DISPLAY-FN (if
213 - To signal that your particular style of prompting is
214 unavailable at the moment, you can also have the function return
217 - To signal that the user quit the prompting process, you can
220 (signal 'quit \"user quit!\")."
221 :type '(repeat function)
224 (defcustom yas/indent-line 'auto
225 "Controls indenting applied to a recent snippet expansion.
227 The following values are possible:
229 - `fixed' Indent the snippet to the current column;
231 - `auto' Indent each line of the snippet with `indent-according-to-mode'
233 Every other value means don't apply any snippet-side indendation
234 after expansion (the manual per-line \"$>\" indentation still
236 :type '(choice (const :tag "Nothing" nothing)
237 (const :tag "Fixed" fixed)
238 (const :tag "Auto" auto))
241 (defcustom yas/also-auto-indent-first-line nil
242 "Non-nil means also auto indent first line according to mode.
244 Naturally this is only valid when `yas/indent-line' is `auto'"
248 (defcustom yas/snippet-revival t
249 "Non-nil means re-activate snippet fields after undo/redo."
253 (defcustom yas/trigger-key "TAB"
254 "The key bound to `yas/expand' when function `yas/minor-mode' is active.
256 Value is a string that is converted to the internal Emacs key
257 representation using `read-kbd-macro'."
260 :set #'(lambda (symbol key)
261 (let ((old (and (boundp symbol)
262 (symbol-value symbol))))
263 (set-default symbol key)
264 ;; On very first loading of this defcustom,
265 ;; `yas/trigger-key' is *not* loaded.
266 (if (fboundp 'yas/trigger-key-reload)
267 (yas/trigger-key-reload old)))))
269 (defcustom yas/next-field-key '("TAB" "<tab>")
270 "The key to navigate to next field when a snippet is active.
272 Value is a string that is converted to the internal Emacs key
273 representation using `read-kbd-macro'.
275 Can also be a list of strings."
276 :type '(choice (string :tag "String")
277 (repeat :args (string) :tag "List of strings"))
279 :set #'(lambda (symbol val)
280 (set-default symbol val)
281 (if (fboundp 'yas/init-yas-in-snippet-keymap)
282 (yas/init-yas-in-snippet-keymap))))
285 (defcustom yas/prev-field-key '("<backtab>" "<S-tab>")
286 "The key to navigate to previous field when a snippet is active.
288 Value is a string that is converted to the internal Emacs key
289 representation using `read-kbd-macro'.
291 Can also be a list of strings."
292 :type '(choice (string :tag "String")
293 (repeat :args (string) :tag "List of strings"))
295 :set #'(lambda (symbol val)
296 (set-default symbol val)
297 (if (fboundp 'yas/init-yas-in-snippet-keymap)
298 (yas/init-yas-in-snippet-keymap))))
300 (defcustom yas/skip-and-clear-key '("C-d" "<delete>" "<deletechar>")
301 "The key to clear the currently active field.
303 Value is a string that is converted to the internal Emacs key
304 representation using `read-kbd-macro'.
306 Can also be a list of strings."
307 :type '(choice (string :tag "String")
308 (repeat :args (string) :tag "List of strings"))
310 :set #'(lambda (symbol val)
311 (set-default symbol val)
312 (if (fboundp 'yas/init-yas-in-snippet-keymap)
313 (yas/init-yas-in-snippet-keymap))))
315 (defcustom yas/triggers-in-field nil
316 "If non-nil, `yas/next-field-key' can trigger stacked expansions.
318 Otherwise, `yas/next-field-key' just tries to move on to the next
323 (defcustom yas/fallback-behavior 'call-other-command
324 "How to act when `yas/trigger-key' does *not* expand a snippet.
326 - `call-other-command' means try to temporarily disable YASnippet
327 and call the next command bound to `yas/trigger-key'.
329 - nil or the symbol `return-nil' mean do nothing. (and
330 `yas/expand-returns' nil)
332 - A lisp form (apply COMMAND . ARGS) means interactively call
333 COMMAND, if ARGS is non-nil, call COMMAND non-interactively
334 with ARGS as arguments."
335 :type '(choice (const :tag "Call previous command" call-other-command)
336 (const :tag "Do nothing" return-nil))
339 (defcustom yas/choose-keys-first nil
340 "If non-nil, prompt for snippet key first, then for template.
342 Otherwise prompts for all possible snippet names.
344 This affects `yas/insert-snippet' and `yas/visit-snippet-file'."
348 (defcustom yas/choose-tables-first nil
349 "If non-nil, and multiple eligible snippet tables, prompts user for tables first.
351 Otherwise, user chooses between the merging together of all
354 This affects `yas/insert-snippet', `yas/visit-snippet-file'"
358 (defcustom yas/use-menu 'abbreviate
359 "Display a YASnippet menu in the menu bar.
361 When non-nil, submenus for each snippet table will be listed
362 under the menu \"Yasnippet\".
364 - If set to `real-modes' only submenus whose name more or less
365 corresponds to a major mode are listed.
367 - If set to `abbreviate', only the current major-mode
368 menu and the modes set in `yas/extra-modes' are listed.
370 Any other non-nil value, every submenu is listed."
371 :type '(choice (const :tag "Full" t)
372 (const :tag "Real modes only" real-modes)
373 (const :tag "Abbreviate" abbreviate))
376 (defcustom yas/trigger-symbol " =>"
377 "The text that will be used in menu to represent the trigger."
381 (defcustom yas/wrap-around-region nil
382 "If non-nil, snippet expansion wraps around selected region.
384 The wrapping occurs just before the snippet's exit marker. This
385 can be overriden on a per-snippet basis."
389 (defcustom yas/good-grace t
390 "If non-nil, don't raise errors in inline elisp evaluation.
392 An error string \"[yas] error\" is returned instead."
396 (defcustom yas/ignore-filenames-as-triggers nil
397 "If non-nil, don't derive tab triggers from filenames.
399 This means a snippet without a \"# key:'\ directive won't have a
404 (defcustom yas/visit-from-menu nil
405 "If non-nil visit snippets's files from menu, instead of expanding them.
407 This cafn only work when snippets are loaded from files."
411 (defcustom yas/expand-only-for-last-commands nil
412 "List of `last-command' values to restrict tab-triggering to, or nil.
414 Leave this set at nil (the default) to be able to trigger an
415 expansion simply by placing the cursor after a valid tab trigger,
416 using whichever commands.
418 Optionallly, set this to something like '(self-insert-command) if
419 you to wish restrict expansion to only happen when the last
420 letter of the snippet tab trigger was typed immediately before
421 the trigger key itself."
422 :type '(repeat function)
425 ;; Only two faces, and one of them shouldn't even be used...
427 (defface yas/field-highlight-face
428 '((t (:inherit 'region)))
429 "The face used to highlight the currently active field of a snippet"
432 (defface yas/field-debug-face
434 "The face used for debugging some overlays normally hidden"
438 ;;; User can also customize the next defvars
439 (defun yas/define-some-keys (keys keymap definition)
440 "Bind KEYS to DEFINITION in KEYMAP, read with `read-kbd-macro'."
441 (let ((keys (or (and (listp keys) keys)
444 (define-key keymap (read-kbd-macro key) definition))))
447 (let ((map (make-sparse-keymap)))
448 (mapc #'(lambda (binding)
449 (yas/define-some-keys (car binding) map (cdr binding)))
450 `((,yas/next-field-key . yas/next-field-or-maybe-expand)
451 (,yas/prev-field-key . yas/prev-field)
452 ("C-g" . yas/abort-snippet)
453 (,yas/skip-and-clear-key . yas/skip-and-clear-or-delete-char)))
455 "The keymap active while a snippet expansion is in progress.")
457 (defvar yas/key-syntaxes (list "w" "w_" "w_." "w_.()" "^ ")
458 "List of character syntaxes used to find a trigger key before point.
459 The list is tried in the order while scanning characters
460 backwards from point. For example, if the list is '(\"w\" \"w_\")
461 first look for trigger keys which are composed exclusively of
462 \"word\"-syntax characters, and then, if that fails, look for
463 keys which are either of \"word\" or \"symbol\"
464 syntax. Triggering after
468 will, according to the \"w\" element first try \"bar\". If that
469 isn't a trigger key, \"foo-bar\" is tried, respecting a second
472 (defvar yas/after-exit-snippet-hook
474 "Hooks to run after a snippet exited.
476 The hooks will be run in an environment where some variables bound to
479 `yas/snippet-beg' : The beginning of the region of the snippet.
481 `yas/snippet-end' : Similar to beg.
483 Attention: These hooks are not run when exiting nested/stackd snippet expansion!")
485 (defvar yas/before-expand-snippet-hook
487 "Hooks to run just before expanding a snippet.")
489 (defvar yas/buffer-local-condition
490 '(if (and (or (fourth (syntax-ppss))
491 (fifth (syntax-ppss)))
492 (eq (symbol-function this-command) 'yas/expand-from-trigger-key))
493 '(require-snippet-condition . force-in-comment)
495 "Snippet expanding condition.
497 This variable is a lisp form:
499 * If it evaluates to nil, no snippets can be expanded.
501 * If it evaluates to the a cons (require-snippet-condition
504 * Snippets bearing no \"# condition:\" directive are not
507 * Snippets bearing conditions that evaluate to nil (or
508 produce an error) won't be onsidered.
510 * If the snippet has a condition that evaluates to non-nil
513 * If REQUIREMENT is t, the snippet is considered
515 * If REQUIREMENT is `eq' RESULT, the snippet is
518 * Otherwise, the snippet is not considered.
520 * If it evaluates to the symbol 'always, all snippets are
521 considered for expansion, regardless of any conditions.
523 * If it evaluates to t or some other non-nil value
525 * Snippet bearing no conditions, or conditions that
526 evaluate to non-nil, are considered for expansion.
528 * Otherwise, the snippet is not considered.
530 Here's an example preventing snippets from being expanded from
531 inside comments, in `python-mode' only, with the exception of
532 snippets returning the symbol 'force-in-comment in their
535 (add-hook 'python-mode-hook
537 (setq yas/buffer-local-condition
538 '(if (python-in-string/comment)
539 '(require-snippet-condition . force-in-comment)
542 The default value is similar, it filters out potential snippet
543 expansions inside comments and string literals, unless the
544 snippet itself contains a condition that returns the symbol
545 `force-in-comment'.")
548 ;;; Internal variables
550 (defvar yas/version "0.7.0")
552 (defvar yas/menu-table (make-hash-table)
553 "A hash table of MAJOR-MODE symbols to menu keymaps.")
555 (defvar yas/known-modes
556 '(ruby-mode rst-mode markdown-mode)
557 "A list of mode which is well known but not part of emacs.")
559 (defvar yas/escaped-characters
560 '(?\\ ?` ?' ?$ ?} ?{ ?\( ?\))
561 "List of characters which *might* need to be escaped.")
563 (defconst yas/field-regexp
564 "${\\([0-9]+:\\)?\\([^}]*\\)}"
565 "A regexp to *almost* recognize a field.")
567 (defconst yas/multi-dollar-lisp-expression-regexp
568 "$+[ \t\n]*\\(([^)]*)\\)"
569 "A regexp to *almost* recognize a \"$(...)\" expression.")
571 (defconst yas/backquote-lisp-expression-regexp
573 "A regexp to recognize a \"`lisp-expression`\" expression." )
575 (defconst yas/transform-mirror-regexp
576 "${\\(?:\\([0-9]+\\):\\)?$\\([ \t\n]*([^}]*\\)"
577 "A regexp to *almost* recognize a mirror with a transform.")
579 (defconst yas/simple-mirror-regexp
581 "A regexp to recognize a simple mirror.")
583 (defvar yas/snippet-id-seed 0
584 "Contains the next id for a snippet.")
586 (defun yas/snippet-next-id ()
587 (let ((id yas/snippet-id-seed))
588 (incf yas/snippet-id-seed)
594 ;; XXX: `last-buffer-undo-list' is somehow needed in Carbon Emacs for MacOSX
595 (defvar last-buffer-undo-list nil)
597 (defvar yas/minor-mode-menu nil
598 "Holds the YASnippet menu")
600 (defun yas/init-minor-keymap ()
601 (let ((map (make-sparse-keymap)))
602 (easy-menu-define yas/minor-mode-menu
604 "Menu used when YAS/minor-mode is active."
607 ["Expand trigger" yas/expand
608 :help "Possibly expand tab trigger before point"]
609 ["Insert at point..." yas/insert-snippet
610 :help "Prompt for an expandable snippet and expand it at point"]
611 ["New snippet..." yas/new-snippet
612 :help "Create a new snippet in an appropriate directory"]
613 ["Visit snippet file..." yas/visit-snippet-file
614 :help "Prompt for an expandable snippet and find its file"]
615 ["Find snippets..." yas/find-snippets
616 :help "Invoke `find-file' in the appropriate snippet directory"]
618 ("Snippet menu behaviour"
619 ["Visit snippets" (setq yas/visit-from-menu t)
620 :help "Visit snippets from the menu"
621 :active t :style radio :selected yas/visit-from-menu]
622 ["Expand snippets" (setq yas/visit-from-menu nil)
623 :help "Expand snippets from the menu"
624 :active t :style radio :selected (not yas/visit-from-menu)]
626 ["Show \"Real\" modes only" (setq yas/use-menu 'real-modes)
627 :help "Show snippet submenus for modes that appear to be real major modes"
628 :active t :style radio :selected (eq yas/use-menu 'real-modes)]
629 ["Show all modes" (setq yas/use-menu 't)
630 :help "Show one snippet submenu for each loaded table"
631 :active t :style radio :selected (eq yas/use-menu 't)]
632 ["Abbreviate according to current mode" (setq yas/use-menu 'abbreviate)
633 :help "Show only snippet submenus for the current active modes"
634 :active t :style radio :selected (eq yas/use-menu 'abbreviate)])
636 ["Auto" (setq yas/indent-line 'auto)
637 :help "Indent each line of the snippet with `indent-according-to-mode'"
638 :active t :style radio :selected (eq yas/indent-line 'auto)]
639 ["Fixed" (setq yas/indent-line 'fixed)
640 :help "Indent the snippet to the current column"
641 :active t :style radio :selected (eq yas/indent-line 'fixed)]
642 ["None" (setq yas/indent-line 'none)
643 :help "Don't apply any particular snippet indentation after expansion"
644 :active t :style radio :selected (not (member yas/indent-line '(fixed auto)))]
646 ["Also auto indent first line" (setq yas/also-auto-indent-first-line
647 (not yas/also-auto-indent-first-line))
648 :help "When auto-indenting also, auto indent the first line menu"
649 :active (eq yas/indent-line 'auto)
650 :style toggle :selected yas/also-auto-indent-first-line]
653 ["System X-widget" (setq yas/prompt-functions
655 (remove 'yas/x-prompt
656 yas/prompt-functions)))
657 :help "Use your windowing system's (gtk, mac, windows, etc...) default menu"
658 :active t :style radio :selected (eq (car yas/prompt-functions)
660 ["Dropdown-list" (setq yas/prompt-functions
661 (cons 'yas/dropdown-prompt
662 (remove 'yas/dropdown-prompt
663 yas/prompt-functions)))
664 :help "Use a special dropdown list"
665 :active t :style radio :selected (eq (car yas/prompt-functions)
666 'yas/dropdown-prompt)]
667 ["Ido" (setq yas/prompt-functions
668 (cons 'yas/ido-prompt
669 (remove 'yas/ido-prompt
670 yas/prompt-functions)))
671 :help "Use an ido-style minibuffer prompt"
672 :active t :style radio :selected (eq (car yas/prompt-functions)
674 ["Completing read" (setq yas/prompt-functions
675 (cons 'yas/completing-prompt
676 (remove 'yas/completing-prompt-prompt
677 yas/prompt-functions)))
678 :help "Use a normal minibuffer prompt"
679 :active t :style radio :selected (eq (car yas/prompt-functions)
680 'yas/completing-prompt-prompt)]
683 ["Wrap region in exit marker"
684 (setq yas/wrap-around-region
685 (not yas/wrap-around-region))
686 :help "If non-nil automatically wrap the selected text in the $0 snippet exit"
687 :style toggle :selected yas/wrap-around-region]
688 ["Allow stacked expansions "
689 (setq yas/triggers-in-field
690 (not yas/triggers-in-field))
691 :help "If non-nil allow snippets to be triggered inside other snippet fields"
692 :style toggle :selected yas/triggers-in-field]
693 ["Revive snippets on undo "
694 (setq yas/snippet-revival
695 (not yas/snippet-revival))
696 :help "If non-nil allow snippets to become active again after undo"
697 :style toggle :selected yas/snippet-revival]
700 (not yas/good-grace))
701 :help "If non-nil don't raise errors in bad embedded eslip in snippets"
702 :style toggle :selected yas/good-grace]
703 ["Ignore filenames as triggers"
704 (setq yas/ignore-filenames-as-triggers
705 (not yas/ignore-filenames-as-triggers))
706 :help "If non-nil don't derive tab triggers from filenames"
707 :style toggle :selected yas/ignore-filenames-as-triggers]
710 ["Load snippets..." yas/load-directory
711 :help "Load snippets from a specific directory"]
712 ["Reload everything" yas/reload-all
713 :help "Cleanup stuff, reload snippets, rebuild menus"]
715 :help "Display some information about YASsnippet"]))
716 ;; Now for the stuff that has direct keybindings
718 (define-key map "\C-c&\C-s" 'yas/insert-snippet)
719 (define-key map "\C-c&\C-n" 'yas/new-snippet)
720 (define-key map "\C-c&\C-v" 'yas/visit-snippet-file)
721 (define-key map "\C-c&\C-f" 'yas/find-snippets)
724 (defvar yas/minor-mode-map (yas/init-minor-keymap)
725 "The keymap used when `yas/minor-mode' is active.")
727 (defun yas/trigger-key-reload (&optional unbind-key)
728 "Rebind `yas/expand' to the new value of `yas/trigger-key'.
730 With optional UNBIND-KEY, try to unbind that key from
731 `yas/minor-mode-map'."
732 (when (and unbind-key
734 (not (string= unbind-key "")))
735 (define-key yas/minor-mode-map (read-kbd-macro unbind-key) nil))
736 (when (and yas/trigger-key
737 (stringp yas/trigger-key)
738 (not (string= yas/trigger-key "")))
739 (define-key yas/minor-mode-map (read-kbd-macro yas/trigger-key) 'yas/expand)))
741 (defvar yas/tables (make-hash-table)
742 "A hash table of MAJOR-MODE symbols to `yas/table' objects.")
744 (defvar yas/direct-keymaps (list)
745 "Keymap alist supporting direct snippet keybindings.
747 This variable is is placed `emulation-mode-map-alists'.
749 Its elements looks like (TABLE-NAME . KEYMAP) and are
750 calculated when loading snippets. TABLE-NAME is a variable
751 set buffer-locally when entering `yas/minor-mode'. KEYMAP binds
752 all defined direct keybindings to the command
753 `yas/expand-from-keymap', which acts similarly to `yas/expand'")
755 (defun yas/direct-keymaps-reload ()
756 "Force reload the direct keybinding for active snippet tables."
758 (setq yas/direct-keymaps nil)
759 (maphash #'(lambda (name table)
760 (mapc #'(lambda (table)
761 (push (cons (intern (format "yas//direct-%s" name))
762 (yas/table-direct-keymap table))
764 (cons table (yas/table-get-all-parents table))))
767 (defun yas/direct-keymaps-set-vars ()
768 (let ((modes-to-activate (list major-mode))
770 (while (setq mode (get mode 'derived-mode-parent))
771 (push mode modes-to-activate))
772 (dolist (mode (yas/extra-modes))
773 (push mode modes-to-activate))
774 (dolist (mode modes-to-activate)
775 (let ((name (intern (format "yas//direct-%s" mode))))
776 (set-default name nil)
777 (set (make-local-variable name) t)))))
779 (defvar yas/minor-mode-hook nil
780 "Hook run when yas/minor-mode is turned on")
783 (define-minor-mode yas/minor-mode
784 "Toggle YASnippet mode.
786 When YASnippet mode is enabled, the `tas/trigger-key' key expands
787 snippets of code depending on the mode.
789 With no argument, this command toggles the mode.
790 positive prefix argument turns on the mode.
791 Negative prefix argument turns off the mode.
793 You can customize the key through `yas/trigger-key'.
796 \\{yas/minor-mode-map}"
798 ;; The indicator for the mode line.
801 (cond (yas/minor-mode
802 ;; Reload the trigger key
804 (yas/trigger-key-reload)
805 ;; Install the direct keymaps in `emulation-mode-map-alists'
806 ;; (we use `add-hook' even though it's not technically a hook,
807 ;; but it works). Then define variables named after modes to
808 ;; index `yas/direct-keymaps'.
810 ;; Also install the post-command-hook.
812 (add-hook 'emulation-mode-map-alists 'yas/direct-keymaps)
813 (add-hook 'post-command-hook 'yas/post-command-handler nil t)
814 (add-hook 'yas/minor-mode-hook 'yas/direct-keymaps-set-vars-runonce 'append))
816 ;; Uninstall the direct keymaps and the post-command hook
818 (remove-hook 'post-command-hook 'yas/post-command-handler t)
819 (remove-hook 'emulation-mode-map-alists 'yas/direct-keymaps))))
821 (defun yas/direct-keymaps-set-vars-runonce ()
822 (yas/direct-keymaps-set-vars)
823 (remove-hook 'yas/minor-mode-hook 'yas/direct-keymaps-set-vars-runonce))
825 (defvar yas/dont-activate nil
826 "If non-nil don't let `yas/minor-mode-on' active yas for this buffer.
828 `yas/minor-mode-on' is usually called by `yas/global-mode' so
829 this effectively lets you define exceptions to the \"global\"
830 behaviour. Can also be a function of zero arguments.")
831 (make-variable-buffer-local 'yas/dont-activate)
833 (defun yas/minor-mode-on ()
834 "Turn on YASnippet minor mode.
836 Do this unless `yas/dont-activate' is truish "
838 (unless (or (minibufferp)
839 (if (functionp yas/dont-activate)
840 (funcall yas/dont-activate)
842 ;; Load all snippets definitions unless we still don't have a
843 ;; root-directory or some snippets have already been loaded.
845 (unless (or (null yas/snippet-dirs)
846 (> (hash-table-count yas/tables) 0))
850 (defun yas/minor-mode-off ()
851 "Turn off YASnippet minor mode."
855 (define-globalized-minor-mode yas/global-mode yas/minor-mode yas/minor-mode-on
859 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
862 (defvar yas/font-lock-keywords
863 (append '(("^#.*$" . font-lock-comment-face))
864 lisp-font-lock-keywords
865 lisp-font-lock-keywords-1
866 lisp-font-lock-keywords-2
868 (0 font-lock-keyword-face)
869 (1 font-lock-string-face t))
871 (0 font-lock-keyword-face)
872 (1 font-lock-warning-face t))
873 ("${" font-lock-keyword-face)
874 ("$[0-9]+?" font-lock-preprocessor-face)
875 ("\\(\\$(\\)" 1 font-lock-preprocessor-face)
877 (0 font-lock-keyword-face)))))
879 (defun yas/init-major-keymap ()
880 (let ((map (make-sparse-keymap)))
881 (easy-menu-define nil
883 "Menu used when snippet-mode is active."
885 (mapcar #'(lambda (ent)
887 (define-key map (third ent) (second ent)))
888 (vector (first ent) (second ent) t))
890 (list "Load this snippet" 'yas/load-snippet-buffer "\C-c\C-c")
891 (list "Try out this snippet" 'yas/tryout-snippet "\C-c\C-t")))))
894 (defvar snippet-mode-map
895 (yas/init-major-keymap)
896 "The keymap used when `snippet-mode' is active")
899 (define-derived-mode snippet-mode text-mode "Snippet"
900 "A mode for editing yasnippets"
901 (set-syntax-table (standard-syntax-table))
902 (setq font-lock-defaults '(yas/font-lock-keywords))
903 (set (make-local-variable 'require-final-newline) nil)
904 (use-local-map snippet-mode-map))
908 ;;; Internal structs for template management
910 (defstruct (yas/template (:constructor yas/make-blank-template))
911 "A template for a snippet."
922 group ;; as dictated by the #group: directive or .yas-make-groups
923 perm-group ;; as dictated by `yas/define-menu'
926 (defun yas/populate-template (template &rest args)
927 "Helper function to populate a template with properties"
931 (position (intern (substring (symbol-name (car args)) 1))
932 (mapcar #'car (get 'yas/template 'cl-struct-slots)))
934 (setq args (cddr args)))
937 (defstruct (yas/table (:constructor yas/make-snippet-table (name)))
938 "A table to store snippets for a particular mode.
940 Has the following fields:
944 A symbol name normally corresponding to a major mode, but can
945 also be a pseudo major-mode to be referenced in
946 `yas/extra-modes', for example.
950 A hash table (KEY . NAMEHASH), known as the \"keyhash\". KEY is
951 a string or a vector, where the former is the snippet's trigger
952 and the latter means it's a direct keybinding. NAMEHASH is yet
953 another hash of (NAME . TEMPLATE) where NAME is the snippet's
954 name and TEMPLATE is a `yas/template' object.
958 A list of tables considered parents of this table: i.e. when
959 searching for expansions they are searched as well.
961 `yas/table-direct-keymap'
963 A keymap for the snippets in this table that have direct
964 keybindings. This is kept in sync with the keyhash, i.e., all
965 the elements of the keyhash that are vectors appear here as
966 bindings to `yas/expand-from-keymap'.
970 A hash table mapping snippets uuid's to the same `yas/template'
971 objects. A snippet uuid defaults to the snippet's name.
974 (hash (make-hash-table :test 'equal))
975 (uuidhash (make-hash-table :test 'equal))
977 (direct-keymap (make-sparse-keymap)))
979 (defun yas/get-template-by-uuid (mode uuid)
980 "Find the snippet template in MODE by its UUID."
981 (let* ((table (gethash mode yas/tables mode)))
983 (gethash uuid (yas/table-uuidhash table)))))
985 ;; Apropos storing/updating, this works with two steps:
987 ;; 1. `yas/remove-template-by-uuid' to remove any existing mappings by
990 ;; 2. `yas/add-template' to add the mappings again:
992 ;; Create or index the entry in TABLES's `yas/table-hash'
993 ;; linking KEY to a namehash. That namehash links NAME to
994 ;; TEMPLATE, and is also created a new namehash inside that
997 (defun yas/remove-template-by-uuid (table uuid)
998 "Remove from TABLE a template identified by UUID."
999 (let ((template (gethash uuid (yas/table-uuidhash table))))
1001 (let* ((name (yas/template-name template))
1003 ;; Remove the name from each of the targeted namehashes
1005 (maphash #'(lambda (k v)
1006 (let ((template (gethash name v)))
1008 (eq uuid (yas/template-uuid template)))
1010 (when (zerop (hash-table-count v))
1011 (push k empty-keys)))))
1012 (yas/table-hash table))
1013 ;; Remove the namehashed themselves if they've become empty
1015 (dolist (key empty-keys)
1016 (remhash key (yas/table-hash table)))
1018 ;; Finally, remove the uuid from the uuidhash
1020 (remhash uuid (yas/table-uuidhash table))))))
1023 (defun yas/add-template (table template)
1024 "Store in TABLE the snippet template TEMPLATE.
1026 KEY can be a string (trigger key) of a vector (direct
1028 (let ((name (yas/template-name template))
1029 (key (yas/template-key template))
1030 (keybinding (yas/template-keybinding template))
1031 (menu-binding (car (yas/template-menu-binding-pair template))))
1032 (dolist (k (remove nil (list key keybinding)))
1036 (yas/table-hash table))
1038 (make-hash-table :test 'equal)
1039 (yas/table-hash table))))
1041 (define-key (yas/table-direct-keymap table) k 'yas/expand-from-keymap)))
1044 (setf (getf (cdr menu-binding) :keys)
1045 (or (and keybinding (key-description keybinding))
1046 (and key (concat key yas/trigger-symbol))))
1047 (setcar (cdr menu-binding)
1050 (puthash (yas/template-uuid template) template (yas/table-uuidhash table))))
1052 (defun yas/update-template (snippet-table template)
1053 "Add or update TEMPLATE in SNIPPET-TABLE.
1055 Also takes care of adding and updaring to the associated menu."
1056 ;; Remove from table by uuid
1058 (yas/remove-template-by-uuid snippet-table (yas/template-uuid template))
1059 ;; Add to table again
1061 (yas/add-template snippet-table template)
1062 ;; Take care of the menu
1064 (let ((keymap (yas/menu-keymap-get-create snippet-table))
1065 (group (yas/template-group template)))
1066 (when (and yas/use-menu
1068 (not (cdr (yas/template-menu-binding-pair template))))
1069 ;; Remove from menu keymap
1071 (yas/delete-from-keymap keymap (yas/template-uuid template))
1073 ;; Add necessary subgroups as necessary.
1075 (dolist (subgroup group)
1076 (let ((subgroup-keymap (lookup-key keymap (vector (make-symbol subgroup)))))
1077 (unless (and subgroup-keymap
1078 (keymapp subgroup-keymap))
1079 (setq subgroup-keymap (make-sparse-keymap))
1080 (define-key keymap (vector (make-symbol subgroup))
1081 `(menu-item ,subgroup ,subgroup-keymap)))
1082 (setq keymap subgroup-keymap)))
1084 ;; Add this entry to the keymap
1086 (let ((menu-binding-pair (yas/snippet-menu-binding-pair-get-create template)))
1087 (define-key keymap (vector (make-symbol (yas/template-uuid template))) (car menu-binding-pair))))))
1089 (defun yas/namehash-templates-alist (namehash)
1091 (maphash #'(lambda (k v)
1092 (push (cons k v) alist))
1096 (defun yas/fetch (table key)
1097 "Fetch templates in TABLE by KEY.
1099 Return a list of cons (NAME . TEMPLATE) where NAME is a
1100 string and TEMPLATE is a `yas/template' structure."
1101 (let* ((keyhash (yas/table-hash table))
1102 (namehash (and keyhash (gethash key keyhash))))
1104 (yas/filter-templates-by-condition (yas/namehash-templates-alist namehash)))))
1107 ;;; Filtering/condition logic
1109 (defun yas/eval-condition (condition)
1116 (message (format "[yas] error in condition evaluation: %s"
1117 (error-message-string err)))
1121 (defun yas/filter-templates-by-condition (templates)
1122 "Filter the templates using the applicable condition.
1124 TEMPLATES is a list of cons (NAME . TEMPLATE) where NAME is a
1125 string and TEMPLATE is a `yas/template' structure.
1127 This function implements the rules described in
1128 `yas/buffer-local-condition'. See that variables documentation."
1129 (let ((requirement (yas/require-template-specific-condition-p)))
1130 (if (eq requirement 'always)
1132 (remove-if-not #'(lambda (pair)
1133 (yas/template-can-expand-p
1134 (yas/template-condition (cdr pair)) requirement))
1137 (defun yas/require-template-specific-condition-p ()
1138 "Decides if this buffer requests/requires snippet-specific
1139 conditions to filter out potential expansions."
1140 (if (eq 'always yas/buffer-local-condition)
1142 (let ((local-condition (or (and (consp yas/buffer-local-condition)
1143 (yas/eval-condition yas/buffer-local-condition))
1144 yas/buffer-local-condition)))
1145 (when local-condition
1146 (if (eq local-condition t)
1148 (and (consp local-condition)
1149 (eq 'require-snippet-condition (car local-condition))
1150 (symbolp (cdr local-condition))
1151 (cdr local-condition)))))))
1153 (defun yas/template-can-expand-p (condition requirement)
1154 "Evaluates CONDITION and REQUIREMENT and returns a boolean"
1155 (let* ((result (or (null condition)
1156 (yas/eval-condition condition))))
1157 (cond ((eq requirement t)
1160 (eq requirement result)))))
1162 (defun yas/table-get-all-parents (table)
1163 "Returns a list of all parent tables of TABLE"
1164 (let ((parents (yas/table-parents table)))
1166 (append (copy-list parents)
1167 (mapcan #'yas/table-get-all-parents parents)))))
1169 (defun yas/table-templates (table)
1172 (maphash #'(lambda (key namehash)
1173 (maphash #'(lambda (name template)
1174 (push (cons name template) acc))
1176 (yas/table-hash table))
1177 (yas/filter-templates-by-condition acc))))
1179 (defun yas/current-key ()
1180 "Get the key under current position. A key is used to find
1181 the template of a snippet in the current snippet-table."
1182 (let ((start (point))
1184 (syntaxes yas/key-syntaxes)
1188 (while (and (not done) syntaxes)
1189 (setq syntax (car syntaxes))
1190 (setq syntaxes (cdr syntaxes))
1192 (skip-syntax-backward syntax)
1193 (setq start (point)))
1195 (mapcan #'(lambda (table)
1196 (yas/fetch table (buffer-substring-no-properties start end)))
1197 (yas/get-snippet-tables)))
1206 (defun yas/table-all-keys (table)
1209 (maphash #'(lambda (key namehash)
1210 (when (yas/filter-templates-by-condition (yas/namehash-templates-alist namehash))
1212 (yas/table-hash table))
1216 ;;; Internal functions
1218 (defun yas/real-mode? (mode)
1219 "Try to find out if MODE is a real mode. The MODE bound to
1220 a function (like `c-mode') is considered real mode. Other well
1221 known mode like `ruby-mode' which is not part of Emacs might
1222 not bound to a function until it is loaded. So yasnippet keeps
1223 a list of modes like this to help the judgement."
1225 (find mode yas/known-modes)))
1227 (defun yas/eval-lisp (form)
1228 "Evaluate FORM and convert the result to string."
1229 (let ((retval (catch 'yas/exception
1235 (let ((result (eval form)))
1237 (format "%s" result))))))
1238 (error (if yas/good-grace
1239 (format "[yas] elisp error! %s" (error-message-string err))
1240 (error (format "[yas] elisp error: %s"
1241 (error-message-string err)))))))))
1242 (when (and (consp retval)
1243 (eq 'yas/exception (car retval)))
1244 (error (cdr retval)))
1247 (defun yas/eval-lisp-no-saves (form)
1250 (error (if yas/good-grace
1251 (format "[yas] elisp error! %s" (error-message-string err))
1252 (error (format "[yas] elisp error: %s"
1253 (error-message-string err)))))))
1255 (defun yas/read-lisp (string &optional nil-on-error)
1256 "Read STRING as a elisp expression and return it.
1258 In case STRING in an invalid expression and NIL-ON-ERROR is nil,
1259 return an expression that when evaluated will issue an error."
1262 (error (and (not nil-on-error)
1263 `(error (error-message-string err))))))
1265 (defun yas/read-keybinding (keybinding)
1266 "Read KEYBINDING as a snippet keybinding, return a vector."
1267 (when (and keybinding
1268 (not (string-match "keybinding" keybinding)))
1270 (let ((res (or (and (string-match "^\\[.*\\]$" keybinding)
1272 (read-kbd-macro keybinding 'need-vector))))
1275 (message "[yas] warning: keybinding \"%s\" invalid since %s."
1276 keybinding (error-message-string err))
1279 (defvar yas/extra-modes nil
1280 "If non-nil, also lookup snippets for this/these modes.
1282 Can be a symbol or a list of symbols.
1284 This variable probably makes more sense as buffer-local, so
1285 ensure your use `make-local-variable' when you set it.")
1286 (defun yas/extra-modes ()
1287 (if (listp yas/extra-modes) yas/extra-modes (list yas/extra-modes)))
1288 (defvaralias 'yas/mode-symbol 'yas/extra-modes)
1290 (defun yas/table-get-create (mode)
1291 "Get the snippet table corresponding to MODE.
1293 Optional DIRECTORY gets recorded as the default directory to
1294 search for snippet files if the retrieved/created table didn't
1295 already have such a property."
1296 (let ((table (gethash mode
1299 (setq table (yas/make-snippet-table (symbol-name mode)))
1300 (puthash mode table yas/tables)
1301 (aput 'yas/direct-keymaps (intern (format "yas//direct-%s" mode))
1302 (yas/table-direct-keymap table)))
1305 (defun yas/get-snippet-tables (&optional mode-symbol dont-search-parents)
1306 "Get snippet tables for current buffer.
1308 Return a list of 'yas/table' objects indexed by mode.
1310 The modes are tried in this order: optional MODE-SYMBOL, then
1311 `yas/extra-modes', then `major-mode' then, unless
1312 DONT-SEARCH-PARENTS is non-nil, the guessed parent mode of either
1313 MODE-SYMBOL or `major-mode'.
1315 Guessing is done by looking up the MODE-SYMBOL's
1316 `derived-mode-parent' property, see also `derived-mode-p'."
1319 (mapcar #'(lambda (mode)
1320 (gethash mode yas/tables))
1321 (remove nil (append (list mode-symbol)
1324 (and (not dont-search-parents)
1326 'derived-mode-parent)))))))))
1329 (mapcan #'yas/table-get-all-parents mode-tables)))))
1331 (defun yas/menu-keymap-get-create (table)
1332 "Get or create the main menu keymap correspondong to MODE.
1334 This may very well create a plethora of menu keymaps and arrange
1335 them in all `yas/menu-table'"
1336 (let* ((mode (intern (yas/table-name table)))
1337 (menu-keymap (or (gethash mode yas/menu-table)
1338 (puthash mode (make-sparse-keymap) yas/menu-table)))
1339 (parents (yas/table-parents table)))
1340 (mapc #'yas/menu-keymap-get-create parents)
1341 (define-key yas/minor-mode-menu (vector mode)
1342 `(menu-item ,(symbol-name mode) ,menu-keymap
1343 :visible (yas/show-menu-p ',mode)))
1346 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1347 ;;; Template-related and snippet loading functions
1349 (defun yas/parse-template (&optional file)
1350 "Parse the template in the current buffer.
1352 Optional FILE is the absolute file name of the file being
1355 Optional GROUP is the group where the template is to go,
1356 otherwise we attempt to calculate it from FILE.
1358 Return a snippet-definition, i.e. a list
1360 (KEY TEMPLATE NAME CONDITION GROUP VARS FILE KEYBINDING UUID)
1362 If the buffer contains a line of \"# --\" then the contents above
1363 this line are ignored. Directives can set most of these with the syntax:
1365 # directive-name : directive-value
1367 Here's a list of currently recognized directives:
1378 (goto-char (point-min))
1379 (let* ((type 'snippet)
1381 (file-name-nondirectory file)))
1382 (key (unless yas/ignore-filenames-as-triggers
1384 (file-name-sans-extension name))))
1389 (yas/calculate-group file)))
1393 (if (re-search-forward "^# --\n" nil t)
1394 (progn (setq template
1395 (buffer-substring-no-properties (point)
1397 (setq bound (point))
1398 (goto-char (point-min))
1399 (while (re-search-forward "^# *\\([^ ]+?\\) *: *\\(.*\\)$" bound t)
1400 (when (string= "uuid" (match-string-no-properties 1))
1401 (setq uuid (match-string-no-properties 2)))
1402 (when (string= "type" (match-string-no-properties 1))
1403 (setq type (if (string= "command" (match-string-no-properties 2))
1406 (when (string= "key" (match-string-no-properties 1))
1407 (setq key (match-string-no-properties 2)))
1408 (when (string= "name" (match-string-no-properties 1))
1409 (setq name (match-string-no-properties 2)))
1410 (when (string= "condition" (match-string-no-properties 1))
1411 (setq condition (yas/read-lisp (match-string-no-properties 2))))
1412 (when (string= "group" (match-string-no-properties 1))
1413 (setq group (match-string-no-properties 2)))
1414 (when (string= "expand-env" (match-string-no-properties 1))
1415 (setq expand-env (yas/read-lisp (match-string-no-properties 2)
1417 (when (string= "binding" (match-string-no-properties 1))
1418 (setq binding (match-string-no-properties 2)))))
1420 (buffer-substring-no-properties (point-min) (point-max))))
1421 (when (eq type 'command)
1422 (setq template (yas/read-lisp (concat "(progn" template ")"))))
1424 (setq group (split-string group "\\.")))
1425 (list key template name condition group expand-env file binding uuid)))
1427 (defun yas/calculate-group (file)
1428 "Calculate the group for snippet file path FILE."
1429 (let* ((dominating-dir (locate-dominating-file file
1430 ".yas-make-groups"))
1431 (extra-path (and dominating-dir
1432 (replace-regexp-in-string (concat "^"
1433 (expand-file-name dominating-dir))
1435 (expand-file-name file))))
1436 (extra-dir (and extra-path
1437 (file-name-directory extra-path)))
1438 (group (and extra-dir
1439 (replace-regexp-in-string "/"
1441 (directory-file-name extra-dir)))))
1444 (defun yas/subdirs (directory &optional file?)
1445 "Return subdirs or files of DIRECTORY according to FILE?."
1446 (remove-if (lambda (file)
1447 (or (string-match "^\\."
1448 (file-name-nondirectory file))
1449 (string-match "^#.*#$"
1450 (file-name-nondirectory file))
1452 (file-name-nondirectory file))
1454 (file-directory-p file)
1455 (not (file-directory-p file)))))
1456 (directory-files directory t)))
1458 (defun yas/make-menu-binding (template)
1459 (let ((mode (intern (yas/table-name (yas/template-table template)))))
1460 `(lambda () (interactive) (yas/expand-or-visit-from-menu ',mode ,(yas/template-uuid template)))))
1462 (defun yas/expand-or-visit-from-menu (mode uuid)
1463 (let* ((table (yas/table-get-create mode))
1464 (yas/current-template (and table
1465 (gethash uuid (yas/table-uuidhash table)))))
1466 (when yas/current-template
1467 (if yas/visit-from-menu
1468 (yas/visit-snippet-file-1 yas/current-template)
1469 (let ((where (if (region-active-p)
1470 (cons (region-beginning) (region-end))
1471 (cons (point) (point)))))
1472 (yas/expand-snippet (yas/template-content yas/current-template)
1475 (yas/template-expand-env yas/current-template)))))))
1477 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1478 ;; Popping up for keys and templates
1480 (defun yas/prompt-for-template (templates &optional prompt)
1481 "Interactively choose a template from the list TEMPLATES.
1483 TEMPLATES is a list of `yas/template'."
1486 (sort templates #'(lambda (t1 t2)
1487 (< (length (yas/template-name t1))
1488 (length (yas/template-name t2))))))
1489 (if yas/x-pretty-prompt-templates
1490 (yas/x-pretty-prompt-templates "Choose a snippet" templates)
1491 (some #'(lambda (fn)
1492 (funcall fn (or prompt "Choose a snippet: ")
1494 #'yas/template-name))
1495 yas/prompt-functions))))
1497 (defun yas/prompt-for-keys (keys &optional prompt)
1498 "Interactively choose a template key from the list KEYS."
1500 (some #'(lambda (fn)
1501 (funcall fn (or prompt "Choose a snippet key: ") keys))
1502 yas/prompt-functions)))
1504 (defun yas/prompt-for-table (tables &optional prompt)
1506 (some #'(lambda (fn)
1507 (funcall fn (or prompt "Choose a snippet table: ")
1510 yas/prompt-functions)))
1512 (defun yas/x-prompt (prompt choices &optional display-fn)
1513 "Display choices in a x-window prompt."
1514 ;; FIXME: HACK: if we notice that one of the objects in choices is
1515 ;; actually a `yas/template', defer to `yas/x-prompt-pretty-templates'
1517 ;; This would be better implemented by passing CHOICES as a
1518 ;; strucutred tree rather than a list. Modifications would go as far
1519 ;; up as `yas/all-templates' I think.
1521 (when (and window-system choices)
1523 (let (menu d) ;; d for display
1525 (setq d (or (and display-fn (funcall display-fn c))
1528 (push (cons (concat " " d) c) menu))
1530 (push (car d) menu))))
1531 (setq menu (list prompt (push "title" menu)))
1532 (x-popup-menu (if (fboundp 'posn-at-point)
1533 (let ((x-y (posn-x-y (posn-at-point (point)))))
1534 (list (list (+ (car x-y) 10)
1542 (defvar yas/x-pretty-prompt-templates nil
1543 "If non-nil, attempt to prompt for templates like TextMate.")
1544 (defun yas/x-pretty-prompt-templates (prompt templates)
1545 "Display TEMPLATES, grouping neatly by table name."
1546 (let ((pretty-alist (list))
1550 (dolist (tl templates)
1551 (aput 'pretty-alist (yas/template-table tl) (cons tl (aget pretty-alist (yas/template-table tl)))))
1552 (setq more-than-one-table (> (length pretty-alist) 1))
1553 (setq prefix (if more-than-one-table
1555 (dolist (table-and-templates pretty-alist)
1556 (when (cdr table-and-templates)
1557 (if more-than-one-table
1558 (push (yas/table-name (car table-and-templates)) menu))
1559 (dolist (template (cdr table-and-templates))
1560 (push (cons (concat prefix (yas/template-name template))
1562 (setq menu (nreverse menu))
1563 (or (x-popup-menu (if (fboundp 'posn-at-point)
1564 (let ((x-y (posn-x-y (posn-at-point (point)))))
1565 (list (list (+ (car x-y) 10)
1569 (list prompt (push "title" menu)))
1572 (defun yas/ido-prompt (prompt choices &optional display-fn)
1573 (when (featurep 'ido)
1574 (yas/completing-prompt prompt choices display-fn #'ido-completing-read)))
1576 (eval-when-compile (require 'dropdown-list nil t))
1577 (defun yas/dropdown-prompt (prompt choices &optional display-fn)
1578 (when (featurep 'dropdown-list)
1579 (let (formatted-choices
1583 (dolist (choice choices)
1584 (setq d (or (and display-fn (funcall display-fn choice))
1587 (push d formatted-choices)
1588 (push choice filtered-choices)))
1590 (setq n (and formatted-choices (dropdown-list formatted-choices)))
1592 (nth n filtered-choices)
1595 (defun yas/completing-prompt (prompt choices &optional display-fn completion-fn)
1596 (let (formatted-choices
1600 (completion-fn (or completion-fn
1601 #'completing-read)))
1602 (dolist (choice choices)
1603 (setq d (or (and display-fn (funcall display-fn choice))
1606 (push d formatted-choices)
1607 (push choice filtered-choices)))
1608 (setq chosen (and formatted-choices
1609 (funcall completion-fn prompt
1616 (nth (position chosen formatted-choices :test #'string=) filtered-choices))))
1618 (defun yas/no-prompt (prompt choices &optional display-fn)
1621 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1622 ;; Loading snippets from files
1624 (defun yas/load-directory-1 (directory &optional mode-sym parents)
1625 "Recursively load snippet templates from DIRECTORY."
1627 ;; Load .yas-setup.el files wherever we find them
1629 (let ((file (concat directory "/" ".yas-setup")))
1630 (when (or (file-readable-p (concat file ".el"))
1631 (file-readable-p (concat file ".elc")))
1636 (unless (file-exists-p (concat directory "/" ".yas-skip"))
1637 (let* ((major-mode-and-parents (if mode-sym
1638 (cons mode-sym parents)
1639 (yas/compute-major-mode-and-parents (concat directory
1641 (default-directory directory)
1642 (yas/ignore-filenames-as-triggers
1643 (or yas/ignore-filenames-as-triggers
1644 (file-exists-p (concat directory "/"
1645 ".yas-ignore-filenames-as-triggers"))))
1647 ;; load the snippet files
1650 (dolist (file (yas/subdirs directory 'no-subdirs-just-files))
1651 (when (file-readable-p file)
1652 (insert-file-contents file nil nil nil t)
1653 (push (yas/parse-template file)
1655 (when (or snippet-defs
1656 (cdr major-mode-and-parents))
1657 (yas/define-snippets (car major-mode-and-parents)
1659 (cdr major-mode-and-parents)))
1660 ;; now recurse to a lower level
1662 (dolist (subdir (yas/subdirs directory))
1663 (yas/load-directory-1 subdir
1664 (car major-mode-and-parents)
1665 (cdr major-mode-and-parents))))))
1667 (defun yas/load-directory (directory)
1668 "Load snippet definition from a directory hierarchy.
1670 Below the top-level directory, each directory is a mode
1671 name. And under each subdirectory, each file is a definition
1672 of a snippet. The file name is the trigger key and the
1673 content of the file is the template."
1674 (interactive "DSelect the root directory: ")
1675 (unless (file-directory-p directory)
1676 (error "%s is not a directory" directory))
1677 (unless yas/snippet-dirs
1678 (setq yas/snippet-dirs directory))
1679 (dolist (dir (yas/subdirs directory))
1680 (yas/load-directory-1 dir))
1681 (when (interactive-p)
1682 (message "[yas] Loaded snippets from %s." directory)))
1684 (defun yas/load-snippet-dirs ()
1685 "Reload the directories listed in `yas/snippet-dirs' or
1686 prompt the user to select one."
1687 (if yas/snippet-dirs
1688 (dolist (directory (reverse (yas/snippet-dirs)))
1689 (yas/load-directory directory))
1690 (call-interactively 'yas/load-directory)))
1692 (defun yas/reload-all (&optional interactive)
1693 "Reload all snippets and rebuild the YASnippet menu. "
1695 ;; Turn off global modes and minor modes, save their state though
1698 ;; Empty all snippet tables and all menu tables
1700 (setq yas/tables (make-hash-table))
1701 (setq yas/menu-table (make-hash-table))
1703 ;; Init the `yas/minor-mode-map', taking care not to break the
1706 (setf (cdr yas/minor-mode-map)
1707 (cdr (yas/init-minor-keymap)))
1709 ;; Reload the directories listed in `yas/snippet-dirs' or prompt
1710 ;; the user to select one.
1712 (condition-case oops
1713 (yas/load-snippet-dirs)
1714 (error (push oops errors)
1715 (message "[yas] Check your `yas/snippet-dirs': %s" (second oops))))
1716 ;; Reload the direct keybindings
1718 (yas/direct-keymaps-reload)
1719 (message "[yas] Reloaded everything...%s." (if errors " (some errors, check *Messages*)" ""))))
1721 (defun yas/quote-string (string)
1722 "Escape and quote STRING.
1723 foo\"bar\\! -> \"foo\\\"bar\\\\!\""
1725 (replace-regexp-in-string "[\\\"]"
1730 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1731 ;;; Yasnippet Bundle
1733 (defun yas/initialize ()
1734 "For backward compatibility, enable `yas/minor-mode' globally"
1735 (yas/global-mode 1))
1737 (defun yas/compile-bundle
1738 (&optional yasnippet yasnippet-bundle snippet-roots code dropdown)
1739 "Compile snippets in SNIPPET-ROOTS to a single bundle file.
1741 YASNIPPET is the yasnippet.el file path.
1743 YASNIPPET-BUNDLE is the output file of the compile result.
1745 SNIPPET-ROOTS is a list of root directories that contains the
1746 snippets definition.
1748 CODE is the code to be placed at the end of the generated file
1749 and that can initialize the YASnippet bundle.
1751 Last optional argument DROPDOWN is the filename of the
1752 dropdown-list.el library.
1754 Here's the default value for all the parameters:
1756 (yas/compile-bundle \"yasnippet.el\"
1757 \"yasnippet-bundle.el\"
1759 \"(yas/initialize-bundle)
1761 (require 'yasnippet-bundle)`\"
1762 \"dropdown-list.el\")
1764 (interactive (concat "ffind the yasnippet.el file: \nFTarget bundle file: "
1765 "\nDSnippet directory to bundle: \nMExtra code? \nfdropdown-library: "))
1767 (let* ((yasnippet (or yasnippet
1769 (yasnippet-bundle (or yasnippet-bundle
1770 "./yasnippet-bundle.el"))
1771 (snippet-roots (or snippet-roots
1773 (dropdown (or dropdown
1774 "dropdown-list.el"))
1776 (condition-case err (read code) (error nil))
1778 (concat "(yas/initialize-bundle)"
1779 "\n;;;###autoload" ; break through so that won't
1780 "(require 'yasnippet-bundle)")))
1781 (dirs (or (and (listp snippet-roots) snippet-roots)
1782 (list snippet-roots)))
1783 (bundle-buffer nil))
1784 (with-temp-file yasnippet-bundle
1785 (insert ";;; yasnippet-bundle.el --- "
1786 "Yet another snippet extension (Auto compiled bundle)\n")
1787 (insert-file-contents yasnippet)
1788 (goto-char (point-max))
1791 (insert-file-contents dropdown))
1792 (goto-char (point-max))
1793 (insert ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n")
1794 (insert ";;;; Auto-generated code ;;;;\n")
1795 (insert ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n")
1796 (insert "(defun yas/initialize-bundle ()\n"
1797 " \"Initialize YASnippet and load snippets in the bundle.\"")
1798 (flet ((yas/define-snippets
1799 (mode snippets &optional parent-or-parents)
1800 (insert ";;; snippets for " (symbol-name mode) ", subdir " (file-name-nondirectory (replace-regexp-in-string "/$" "" default-directory)) "\n")
1801 (let ((literal-snippets (list)))
1802 (dolist (snippet snippets)
1803 (let ((key (first snippet))
1804 (template-content (second snippet))
1805 (name (third snippet))
1806 (condition (fourth snippet))
1807 (group (fifth snippet))
1808 (expand-env (sixth snippet))
1809 (file nil) ;; (seventh snippet)) ;; omit on purpose
1810 (binding (eighth snippet))
1811 (uuid (ninth snippet)))
1822 (insert (pp-to-string `(yas/define-snippets ',mode ',literal-snippets ',parent-or-parents)))
1825 (dolist (subdir (yas/subdirs dir))
1826 (let ((file (concat subdir "/.yas-setup.el")))
1827 (when (file-readable-p file)
1828 (insert "\n;; Supporting elisp for subdir " (file-name-nondirectory subdir) "\n\n")
1830 (insert-file-contents file)
1831 (replace-regexp "^;;.*$" "" nil (point-min) (point-max))
1832 (replace-regexp "^[\s\t]*\n\\([\s\t]*\n\\)+" "\n" nil (point-min) (point-max))
1833 (kill-region (point-min) (point-max)))
1835 (yas/load-directory-1 subdir nil))))
1837 (insert (pp-to-string `(yas/global-mode 1)))
1838 (insert ")\n\n" code "\n")
1840 ;; bundle-specific provide and value for yas/dont-activate
1841 (let ((bundle-feature-name (file-name-nondirectory
1842 (file-name-sans-extension
1843 yasnippet-bundle))))
1844 (insert (pp-to-string `(set-default 'yas/dont-activate
1846 (and (or yas/snippet-dirs
1847 (featurep ',(make-symbol bundle-feature-name)))
1848 (null (yas/get-snippet-tables)))))))
1849 (insert (pp-to-string `(provide ',(make-symbol bundle-feature-name)))))
1852 (file-name-nondirectory yasnippet-bundle)
1855 (defun yas/compile-textmate-bundle ()
1857 (yas/compile-bundle "yasnippet.el"
1858 "./yasnippet-textmate-bundle.el"
1860 (concat "(yas/initialize-bundle)"
1861 "\n;;;###autoload" ; break through so that won't
1862 "(require 'yasnippet-textmate-bundle)")
1863 "dropdown-list.el"))
1865 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1866 ;;; Some user level functions
1871 (message (concat "yasnippet (version "
1873 ") -- pluskid <pluskid@gmail.com>/joaotavora <joaotavora@gmail.com>")))
1875 (defun yas/define-snippets (mode snippets &optional parent-mode)
1876 "Define SNIPPETS for MODE.
1878 SNIPPETS is a list of snippet definitions, each taking the
1881 (KEY TEMPLATE NAME CONDITION GROUP EXPAND-ENV FILE KEYBINDING UUID)
1883 Within these, only KEY and TEMPLATE are actually mandatory.
1885 TEMPLATE might be a lisp form or a string, depending on whether
1886 this is a snippet or a snippet-command.
1888 CONDITION, EXPAND-ENV and KEYBINDING are lisp forms, they have
1889 been `yas/read-lisp'-ed and will eventually be
1892 The remaining elements are strings.
1894 FILE is probably of very little use if you're programatically
1897 UUID is the snippets \"unique-id\". Loading a second snippet file
1898 with the same uuid replaced the previous snippet.
1900 You can use `yas/parse-template' to return such lists based on
1901 the current buffers contents.
1903 Optional PARENT-MODE can be used to specify the parent tables of
1904 MODE. It can be a mode symbol of a list of mode symbols. It does
1905 not need to be a real mode."
1906 ;; X) `snippet-table' is created or retrieved for MODE, same goes
1907 ;; for the list of snippet tables `parent-tables'.
1909 (let ((snippet-table (yas/table-get-create mode))
1910 (parent-tables (mapcar #'yas/table-get-create
1911 (if (listp parent-mode)
1913 (list parent-mode))))
1915 ;; X) Connect `snippet-table' with `parent-tables'.
1917 ;; TODO: this should be a remove-duplicates of the concatenation
1918 ;; of `snippet-table's existings parents with the new parents...
1920 (dolist (parent parent-tables)
1921 (unless (find parent (yas/table-parents snippet-table))
1923 (yas/table-parents snippet-table))))
1925 ;; X) Now, iterate for evey snippet def list
1927 (dolist (snippet snippets)
1928 (setq template (yas/define-snippets-1 snippet
1932 (defun yas/define-snippets-1 (snippet snippet-table)
1933 "Helper for `yas/define-snippets'."
1934 ;; X) Calculate some more defaults on the values returned by
1935 ;; `yas/parse-template'.
1937 (let* ((file (seventh snippet))
1938 (key (or (car snippet)
1939 (unless yas/ignore-filenames-as-triggers
1941 (file-name-sans-extension (file-name-nondirectory file))))))
1942 (name (or (third snippet)
1944 (file-name-directory file))))
1945 (condition (fourth snippet))
1946 (group (fifth snippet))
1947 (keybinding (yas/read-keybinding (eighth snippet)))
1948 (uuid (or (ninth snippet)
1950 (template (or (gethash uuid (yas/table-uuidhash snippet-table))
1951 (yas/make-blank-template))))
1952 ;; X) populate the template object
1954 (yas/populate-template template
1955 :table snippet-table
1957 :content (second snippet)
1960 :condition condition
1961 :expand-env (sixth snippet)
1962 :file (seventh snippet)
1963 :keybinding keybinding
1965 ;; X) Update this template in the appropriate table. This step
1966 ;; also will take care of adding the key indicators in the
1967 ;; templates menu entry, if any
1969 (yas/update-template snippet-table template)
1970 ;; X) Return the template
1975 (defun yas/snippet-menu-binding-pair-get-create (template &optional type)
1976 "Get TEMPLATE's menu binding or assign it a new one."
1977 (or (yas/template-menu-binding-pair template)
1978 (let ((key (yas/template-key template))
1979 (keybinding (yas/template-keybinding template)))
1980 (setf (yas/template-menu-binding-pair template)
1981 (cons `(menu-item ,(or (yas/template-name template)
1982 (yas/template-uuid template))
1983 ,(yas/make-menu-binding template)
1987 (defun yas/show-menu-p (mode)
1988 (cond ((eq yas/use-menu 'abbreviate)
1990 (mapcar #'(lambda (table)
1991 (intern (yas/table-name table)))
1992 (yas/get-snippet-tables))))
1993 ((eq yas/use-menu 'real-modes)
1994 (yas/real-mode? mode))
1998 (defun yas/delete-from-keymap (keymap uuid)
1999 "Recursively delete items with UUID from KEYMAP and its submenus."
2001 ;; XXX: This used to skip any submenus named \"parent mode\"
2003 ;; First of all, recursively enter submenus, i.e. the tree is
2004 ;; searched depth first so that stale submenus can be found in the
2007 (mapc #'(lambda (item)
2008 (when (and (listp (cdr item))
2009 (keymapp (third (cdr item))))
2010 (yas/delete-from-keymap (third (cdr item)) uuid)))
2012 ;; Set the uuid entry to nil
2014 (define-key keymap (vector (make-symbol uuid)) nil)
2015 ;; Destructively modify keymap
2017 (setcdr keymap (delete-if #'(lambda (item)
2018 (or (null (cdr item))
2019 (and (keymapp (third (cdr item)))
2020 (null (cdr (third (cdr item)))))))
2023 (defun yas/define-menu (mode menu omit-items)
2024 "Define a snippet menu for MODE according to MENU, ommitting OMIT-ITEMS.
2026 MENU is a list, its elements can be:
2028 - (yas/item UUID) : Creates an entry the snippet identified with
2029 UUID. The menu entry for a snippet thus identified is
2030 permanent, i.e. it will never move in the menu.
2032 - (yas/separator) : Creates a separator
2034 - (yas/submenu NAME SUBMENU) : Creates a submenu with NAME,
2035 SUBMENU has the same form as MENU. NAME is also added to the
2036 list of groups of the snippets defined thereafter.
2038 OMIT-ITEMS is a list of snippet uuid's that will always be
2039 ommited from MODE's menu, even if they're manually loaded.
2041 (let* ((table (yas/table-get-create mode))
2042 (hash (yas/table-uuidhash table)))
2043 (yas/define-menu-1 table
2044 (yas/menu-keymap-get-create table)
2047 (dolist (uuid omit-items)
2048 (let ((template (or (gethash uuid hash)
2049 (yas/populate-template (puthash uuid
2050 (yas/make-blank-template)
2054 (setf (yas/template-menu-binding-pair template) (cons nil :none))))))
2056 (defun yas/define-menu-1 (table keymap menu uuidhash &optional group-list)
2057 (dolist (e (reverse menu))
2058 (cond ((eq (first e) 'yas/item)
2059 (let ((template (or (gethash (second e) uuidhash)
2060 (yas/populate-template (puthash (second e)
2061 (yas/make-blank-template)
2064 :perm-group group-list
2065 :uuid (second e)))))
2066 (define-key keymap (vector (gensym))
2067 (car (yas/snippet-menu-binding-pair-get-create template :stay)))))
2068 ((eq (first e) 'yas/submenu)
2069 (let ((subkeymap (make-sparse-keymap)))
2070 (define-key keymap (vector (gensym))
2071 `(menu-item ,(second e) ,subkeymap))
2072 (yas/define-menu-1 table
2076 (append group-list (list (second e))))))
2077 ((eq (first e) 'yas/separator)
2078 (define-key keymap (vector (gensym))
2079 '(menu-item "----")))
2081 (message "[yas] don't know anything about menu entry %s" (first e))))))
2083 (defun yas/define (mode key template &optional name condition group)
2084 "Define a snippet. Expanding KEY into TEMPLATE.
2086 NAME is a description to this template. Also update the menu if
2087 `yas/use-menu' is `t'. CONDITION is the condition attached to
2088 this snippet. If you attach a condition to a snippet, then it
2089 will only be expanded when the condition evaluated to non-nil."
2090 (yas/define-snippets mode
2091 (list (list key template name condition group))))
2093 (defun yas/hippie-try-expand (first-time?)
2094 "Integrate with hippie expand. Just put this function in
2095 `hippie-expand-try-functions-list'."
2096 (if (not first-time?)
2097 (let ((yas/fallback-behavior 'return-nil))
2103 ;;; Apropos condition-cache:
2108 (defvar yas/condition-cache-timestamp nil)
2109 (defmacro yas/define-condition-cache (func doc &rest body)
2110 "Define a function FUNC with doc DOC and body BODY, BODY is
2111 executed at most once every snippet expansion attempt, to check
2112 expansion conditions.
2114 It doesn't make any sense to call FUNC programatically."
2115 `(defun ,func () ,(if (and doc
2118 "\n\nFor use in snippets' conditions. Within each
2119 snippet-expansion routine like `yas/expand', computes actual
2120 value for the first time then always returns a cached value.")
2121 (setq body (cons doc body))
2123 (let ((timestamp-and-value (get ',func 'yas/condition-cache)))
2124 (if (equal (car timestamp-and-value) yas/condition-cache-timestamp)
2125 (cdr timestamp-and-value)
2126 (let ((new-value (progn
2129 (put ',func 'yas/condition-cache (cons yas/condition-cache-timestamp new-value))
2132 (defalias 'yas/expand 'yas/expand-from-trigger-key)
2133 (defun yas/expand-from-trigger-key (&optional field)
2134 "Expand a snippet before point.
2136 If no snippet expansion is possible, fall back to the behaviour
2137 defined in `yas/fallback-behavior'.
2139 Optional argument FIELD is for non-interactive use and is an
2140 object satisfying `yas/field-p' to restrict the expansion to."
2142 (setq yas/condition-cache-timestamp (current-time))
2143 (let (templates-and-pos)
2144 (unless (and yas/expand-only-for-last-commands
2145 (not (member last-command yas/expand-only-for-last-commands)))
2146 (setq templates-and-pos (if field
2148 (narrow-to-region (yas/field-start field)
2149 (yas/field-end field))
2151 (yas/current-key))))
2152 (if (and templates-and-pos
2153 (first templates-and-pos))
2154 (yas/expand-or-prompt-for-template (first templates-and-pos)
2155 (second templates-and-pos)
2156 (third templates-and-pos))
2157 (yas/fallback 'trigger-key))))
2159 (defun yas/expand-from-keymap ()
2160 "Directly expand some snippets, searching `yas/direct-keymaps'.
2162 If expansion fails, execute the previous binding for this key"
2164 (setq yas/condition-cache-timestamp (current-time))
2165 (let* ((vec (this-command-keys-vector))
2166 (templates (mapcan #'(lambda (table)
2167 (yas/fetch table vec))
2168 (yas/get-snippet-tables))))
2170 (yas/expand-or-prompt-for-template templates)
2171 (let ((yas/fallback-behavior 'call-other-command))
2174 (defun yas/expand-or-prompt-for-template (templates &optional start end)
2175 "Expand one of TEMPLATES from START to END.
2177 Prompt the user if TEMPLATES has more than one element, else
2178 expand immediately. Common gateway for
2179 `yas/expand-from-trigger-key' and `yas/expand-from-keymap'."
2180 (let ((yas/current-template (or (and (rest templates) ;; more than one
2181 (yas/prompt-for-template (mapcar #'cdr templates)))
2183 (when yas/current-template
2184 (yas/expand-snippet (yas/template-content yas/current-template)
2187 (yas/template-expand-env yas/current-template)))))
2189 (defun yas/fallback (&optional from-trigger-key-p)
2190 "Fallback after expansion has failed.
2192 Common gateway for `yas/expand-from-trigger-key' and
2193 `yas/expand-from-keymap'."
2194 (cond ((eq yas/fallback-behavior 'return-nil)
2197 ((eq yas/fallback-behavior 'call-other-command)
2198 (let* ((yas/minor-mode nil)
2199 (yas/direct-keymaps nil)
2200 (keys-1 (this-command-keys-vector))
2201 (keys-2 (and yas/trigger-key
2203 (stringp yas/trigger-key)
2204 (read-kbd-macro yas/trigger-key)))
2205 (command-1 (and keys-1 (key-binding keys-1)))
2206 (command-2 (and keys-2 (key-binding keys-2)))
2207 ;; An (ugly) safety: prevents infinite recursion of
2208 ;; yas/expand* calls.
2209 (command (or (and (symbolp command-1)
2210 (not (string-match "yas/expand" (symbol-name command-1)))
2212 (and (symbolp command-2)
2214 (when (and (commandp command)
2215 (not (string-match "yas/expand" (symbol-name command))))
2216 (setq this-command command)
2217 (call-interactively command))))
2218 ((and (listp yas/fallback-behavior)
2219 (cdr yas/fallback-behavior)
2220 (eq 'apply (car yas/fallback-behavior)))
2221 (if (cddr yas/fallback-behavior)
2222 (apply (cadr yas/fallback-behavior)
2223 (cddr yas/fallback-behavior))
2224 (when (commandp (cadr yas/fallback-behavior))
2225 (setq this-command (cadr yas/fallback-behavior))
2226 (call-interactively (cadr yas/fallback-behavior)))))
2228 ;; also return nil if all the other fallbacks have failed
2233 ;;; Snippet development
2235 (defun yas/all-templates (tables)
2236 "Return all snippet tables applicable for the current buffer.
2238 Honours `yas/choose-tables-first', `yas/choose-keys-first' and
2239 `yas/buffer-local-condition'"
2240 (when yas/choose-tables-first
2241 (setq tables (list (yas/prompt-for-table tables))))
2243 (if yas/choose-keys-first
2244 (let ((key (yas/prompt-for-keys
2245 (mapcan #'yas/table-all-keys tables))))
2247 (mapcan #'(lambda (table)
2248 (yas/fetch table key))
2250 (remove-duplicates (mapcan #'yas/table-templates tables)
2253 (defun yas/insert-snippet (&optional no-condition)
2254 "Choose a snippet to expand, pop-up a list of choices according
2255 to `yas/prompt-function'.
2257 With prefix argument NO-CONDITION, bypass filtering of snippets
2260 (setq yas/condition-cache-timestamp (current-time))
2261 (let* ((yas/buffer-local-condition (or (and no-condition
2263 yas/buffer-local-condition))
2264 (templates (yas/all-templates (yas/get-snippet-tables)))
2265 (yas/current-template (and templates
2266 (or (and (rest templates) ;; more than one template for same key
2267 (yas/prompt-for-template templates))
2269 (where (if (region-active-p)
2270 (cons (region-beginning) (region-end))
2271 (cons (point) (point)))))
2272 (if yas/current-template
2273 (yas/expand-snippet (yas/template-content yas/current-template)
2276 (yas/template-expand-env yas/current-template))
2277 (message "[yas] No snippets can be inserted here!"))))
2279 (defun yas/visit-snippet-file ()
2280 "Choose a snippet to edit, selection like `yas/insert-snippet'.
2282 Only success if selected snippet was loaded from a file. Put the
2283 visited file in `snippet-mode'."
2285 (let* ((yas/buffer-local-condition 'always)
2286 (templates (yas/all-templates (yas/get-snippet-tables)))
2287 (yas/prompt-functions '(yas/ido-prompt yas/completing-prompt))
2288 (template (and templates
2289 (or (yas/prompt-for-template templates
2290 "Choose a snippet template to edit: ")
2294 (yas/visit-snippet-file-1 template)
2295 (message "No snippets tables active!"))))
2297 (defun yas/visit-snippet-file-1 (template)
2298 (let ((file (yas/template-file template)))
2299 (cond ((and file (file-readable-p file))
2300 (find-file-other-window file)
2302 (set (make-local-variable 'yas/editing-template) template))
2304 (message "Original file %s no longer exists!" file))
2306 (switch-to-buffer (format "*%s*"(yas/template-name template)))
2307 (let ((type 'snippet))
2308 (when (listp (yas/template-content template))
2309 (insert (format "# type: command\n"))
2310 (setq type 'command))
2311 (insert (format "# key: %s\n" (yas/template-key template)))
2312 (insert (format "# name: %s\n" (yas/template-name template)))
2313 (when (yas/template-keybinding template)
2314 (insert (format "# binding: %s\n" (yas/template-keybinding template))))
2315 (when (yas/template-expand-env template)
2316 (insert (format "# expand-env: %s\n" (yas/template-expand-env template))))
2317 (when (yas/template-condition template)
2318 (insert (format "# condition: %s\n" (yas/template-condition template))))
2320 (insert (if (eq type 'command)
2321 (pp-to-string (yas/template-content template))
2322 (yas/template-content template))))
2324 (set (make-local-variable 'yas/editing-template) template)))))
2326 (defun yas/guess-snippet-directories-1 (table)
2327 "Guesses possible snippet subdirectories for TABLE."
2328 (cons (yas/table-name table)
2329 (mapcan #'(lambda (parent)
2330 (yas/guess-snippet-directories-1
2332 (yas/table-parents table))))
2334 (defun yas/guess-snippet-directories (&optional table)
2335 "Try to guess suitable directories based on the current active
2336 tables (or optional TABLE).
2338 Returns a list of elemts (TABLE . DIRS) where TABLE is a
2339 `yas/table' object and DIRS is a list of all possible directories
2340 where snippets of table might exist."
2341 (let ((main-dir (replace-regexp-in-string
2343 (or (first (or (yas/snippet-dirs)
2344 (setq yas/snippet-dirs '("~/.emacs.d/snippets")))))))
2345 (tables (or (and table
2347 (yas/get-snippet-tables))))
2348 ;; HACK! the snippet table created here is actually registered!
2350 (unless (or table (gethash major-mode yas/tables))
2351 (push (yas/table-get-create major-mode)
2354 (mapcar #'(lambda (table)
2356 (mapcar #'(lambda (subdir)
2357 (concat main-dir "/" subdir))
2358 (yas/guess-snippet-directories-1 table))))
2361 (defun yas/make-directory-maybe (table-and-dirs &optional main-table-string)
2362 "Returns a dir inside TABLE-AND-DIRS, prompts for creation if none exists."
2363 (or (some #'(lambda (dir) (when (file-directory-p dir) dir)) (cdr table-and-dirs))
2364 (let ((candidate (first (cdr table-and-dirs))))
2365 (unless (file-writable-p (file-name-directory candidate))
2366 (error "[yas] %s is not writable." candidate))
2367 (if (y-or-n-p (format "Guessed directory (%s) for%s%s table \"%s\" does not exist! Create? "
2369 (if (gethash (intern (yas/table-name (car table-and-dirs)))
2373 (or main-table-string
2375 (yas/table-name (car table-and-dirs))))
2377 (make-directory candidate 'also-make-parents)
2378 ;; create the .yas-parents file here...
2381 (defun yas/new-snippet (&optional choose-instead-of-guess)
2384 (let ((guessed-directories (yas/guess-snippet-directories)))
2386 (switch-to-buffer "*new snippet*")
2388 (kill-all-local-variables)
2390 (set (make-local-variable 'yas/guessed-modes) (mapcar #'(lambda (d)
2391 (intern (yas/table-name (car d))))
2392 guessed-directories))
2393 (unless (and choose-instead-of-guess
2394 (not (y-or-n-p "Insert a snippet with useful headers? ")))
2395 (yas/expand-snippet "\
2396 # -*- mode: snippet -*-
2399 # binding: ${4:direct-keybinding}}${5:
2400 # expand-env: ((${6:some-var} ${7:some-value}))}${8:
2405 (defun yas/find-snippets (&optional same-window )
2406 "Find snippet file in guessed current mode's directory.
2408 Calls `find-file' interactively in the guessed directory.
2410 With prefix arg SAME-WINDOW opens the buffer in the same window.
2412 Because snippets can be loaded from many different locations,
2413 this has to guess the correct directory using
2414 `yas/guess-snippet-directories', which returns a list of
2417 If any one of these exists, it is taken and `find-file' is called
2418 there, otherwise, proposes to create the first option returned by
2419 `yas/guess-snippet-directories'."
2421 (let* ((guessed-directories (yas/guess-snippet-directories))
2424 (setq chosen (yas/make-directory-maybe (first guessed-directories) " main"))
2426 (if (y-or-n-p (format "Continue guessing for other active tables %s? "
2427 (mapcar #'(lambda (table-and-dirs)
2428 (yas/table-name (car table-and-dirs)))
2429 (rest guessed-directories))))
2430 (setq chosen (some #'yas/make-directory-maybe
2431 (rest guessed-directories)))))
2433 (when (y-or-n-p "Having trouble... go to snippet root dir? ")
2434 (setq chosen (first (yas/snippet-dirs)))))
2436 (let ((default-directory chosen))
2437 (setq buffer (call-interactively (if same-window
2439 'find-file-other-window)))
2443 (when (eq major-mode 'fundamental-mode)
2445 (message "Could not guess snippet dir!"))))
2447 (defun yas/compute-major-mode-and-parents (file &optional prompt-if-failed)
2448 (let* ((file-dir (and file
2449 (directory-file-name (or (some #'(lambda (special)
2450 (locate-dominating-file file special))
2454 (directory-file-name (file-name-directory file))))))
2455 (parents-file-name (concat file-dir "/.yas-parents"))
2456 (major-mode-name (and file-dir
2457 (file-name-nondirectory file-dir)))
2458 (major-mode-sym (or (and major-mode-name
2459 (intern major-mode-name))
2460 (when prompt-if-failed
2461 (read-from-minibuffer
2462 "[yas] Cannot auto-detect major mode! Enter a major mode: "))))
2463 (parents (when (file-readable-p parents-file-name)
2467 (insert-file-contents parents-file-name)
2468 (buffer-substring-no-properties (point-min)
2470 (when major-mode-sym
2471 (cons major-mode-sym parents))))
2473 (defvar yas/editing-template nil
2474 "Supporting variable for `yas/load-snippet-buffer' and `yas/visit-snippet'")
2476 (defvar yas/current-template nil
2477 "Holds the current template being expanded into a snippet.")
2479 (defvar yas/guessed-modes nil
2480 "List of guessed modes supporting `yas/load-snippet-buffer'.")
2482 (defun yas/load-snippet-buffer (&optional kill)
2483 "Parse and load current buffer's snippet definition.
2485 With optional prefix argument KILL quit the window and buffer."
2487 (let ((yas/ignore-filenames-as-triggers
2488 (or yas/ignore-filenames-as-triggers
2489 (and buffer-file-name
2490 (locate-dominating-file
2492 ".yas-ignore-filenames-as-triggers")))))
2494 ;; We have `yas/editing-template', this buffer's
2495 ;; content comes from a template which is already loaded and
2496 ;; neatly positioned,...
2498 (yas/editing-template
2499 (yas/define-snippets-1 (yas/parse-template (yas/template-file yas/editing-template))
2500 (yas/template-table yas/editing-template)))
2501 ;; Try to use `yas/guessed-modes'. If we don't have that use the
2502 ;; value from `yas/compute-major-mode-and-parents'
2505 (unless yas/guessed-modes
2506 (set (make-local-variable 'yas/guessed-modes) (or (yas/compute-major-mode-and-parents buffer-file-name))))
2507 (let* ((prompt (if (and (featurep 'ido)
2509 'ido-completing-read 'completing-read))
2510 (table (yas/table-get-create
2512 (funcall prompt (format "Choose or enter a table (yas guesses %s): "
2513 (if yas/guessed-modes
2514 (first yas/guessed-modes)
2516 (mapcar #'symbol-name yas/guessed-modes)
2521 (if (first yas/guessed-modes)
2522 (symbol-name (first yas/guessed-modes))))))))
2523 (set (make-local-variable 'yas/editing-template)
2524 (yas/define-snippets-1 (yas/parse-template buffer-file-name)
2526 ;; Now, offer to save this shit
2528 ;; 1) if `yas/snippet-dirs' is a list and its first element does not
2529 ;; match this template's file (i.e. this is a library snippet, not
2532 ;; 2) yas/editing-template comes from a file that we cannot write to...
2534 (when (or (not (yas/template-file yas/editing-template))
2535 (not (file-writable-p (yas/template-file yas/editing-template)))
2536 (and (listp yas/snippet-dirs)
2537 (second yas/snippet-dirs)
2538 (not (string-match (expand-file-name (first yas/snippet-dirs))
2539 (yas/template-file yas/editing-template)))))
2541 (when (y-or-n-p "[yas] Looks like a library or new snippet. Save to new file? ")
2542 (let* ((option (first (yas/guess-snippet-directories (yas/template-table yas/editing-template))))
2544 (yas/make-directory-maybe option))))
2546 (let ((default-file-name (or (and (yas/template-file yas/editing-template)
2547 (file-name-nondirectory (yas/template-file yas/editing-template)))
2548 (yas/template-name yas/editing-template))))
2549 (write-file (concat chosen "/"
2550 (read-from-minibuffer (format "File name to create in %s? " chosen)
2551 default-file-name)))
2552 (setf (yas/template-file yas/editing-template) buffer-file-name))))))
2555 (message "[yas] Snippet \"%s\" loaded for %s."
2556 (yas/template-name yas/editing-template)
2557 (yas/table-name (yas/template-table yas/editing-template))))
2560 (defun yas/tryout-snippet (&optional debug)
2561 "Test current buffers's snippet template in other buffer."
2563 (let* ((major-mode-and-parent (yas/compute-major-mode-and-parents buffer-file-name))
2564 (parsed (yas/parse-template))
2565 (test-mode (or (and (car major-mode-and-parent)
2566 (fboundp (car major-mode-and-parent))
2567 (car major-mode-and-parent))
2568 (first yas/guessed-modes)
2569 (intern (read-from-minibuffer "[yas] please input a mode: "))))
2570 (yas/current-template
2573 (yas/populate-template (yas/make-blank-template)
2574 :table nil ;; no tables for ephemeral snippets
2576 :content (second parsed)
2577 :name (third parsed)
2578 :expand-env (sixth parsed)))))
2579 (cond (yas/current-template
2580 (let ((buffer-name (format "*testing snippet: %s*" (yas/template-name yas/current-template))))
2581 (kill-buffer (get-buffer-create buffer-name))
2582 (switch-to-buffer (get-buffer-create buffer-name))
2583 (setq buffer-undo-list nil)
2584 (condition-case nil (funcall test-mode) (error nil))
2585 (yas/expand-snippet (yas/template-content yas/current-template)
2588 (yas/template-expand-env yas/current-template))
2590 (require 'yasnippet-debug nil t))
2591 (add-hook 'post-command-hook 'yas/debug-snippet-vars nil t))))
2593 (message "[yas] Cannot test snippet for unknown major mode")))))
2595 (defun yas/template-fine-group (template)
2596 (car (last (or (yas/template-group template)
2597 (yas/template-perm-group template)))))
2599 (defun yas/describe-tables (&optional choose)
2600 "Display snippets for each table."
2602 (let* ((by-name-hash (and choose
2603 (y-or-n-p "Show by namehash? ")))
2604 (buffer (get-buffer-create "*YASnippet tables*"))
2605 (active-tables (yas/get-snippet-tables))
2606 (remain-tables (let ((all))
2607 (maphash #'(lambda (k v)
2608 (unless (find v active-tables)
2612 (table-lists (list active-tables remain-tables))
2613 (original-buffer (current-buffer))
2615 (yas/condition-cache-timestamp (current-time)))
2616 (with-current-buffer buffer
2617 (setq buffer-read-only nil)
2619 (cond ((not by-name-hash)
2620 (insert "YASnippet tables: \n")
2621 (while (and table-lists
2623 (dolist (table (car table-lists))
2624 (yas/describe-pretty-table table original-buffer))
2625 (setq table-lists (cdr table-lists))
2627 (yas/create-snippet-xrefs)
2628 (display-buffer buffer)
2629 (setq continue (and choose (y-or-n-p "Show also non-active tables? ")))))
2630 (yas/create-snippet-xrefs)
2634 (insert "\n\nYASnippet tables by NAMEHASH: \n")
2635 (dolist (table (append active-tables remain-tables))
2636 (insert (format "\nSnippet table `%s':\n\n" (yas/table-name table)))
2638 (maphash #'(lambda (k v)
2640 (yas/table-hash table))
2642 (insert (format " key %s maps snippets: %s\n" key
2644 (maphash #'(lambda (k v)
2646 (gethash key (yas/table-hash table)))
2649 (setq buffer-read-only t))
2650 (display-buffer buffer)))
2652 (defun yas/describe-pretty-table (table &optional original-buffer)
2653 (insert (format "\nSnippet table `%s'"
2654 (yas/table-name table)))
2655 (if (yas/table-parents table)
2656 (insert (format " parents: %s\n"
2657 (mapcar #'yas/table-name
2658 (yas/table-parents table))))
2660 (insert (make-string 100 ?-) "\n")
2661 (insert "group state name key binding\n")
2662 (let ((groups-alist (list))
2664 (maphash #'(lambda (k v)
2665 (setq group (or (yas/template-fine-group v)
2667 (when (yas/template-name v)
2669 (aput 'groups-alist group (cons v (aget groups-alist group)))))
2670 (yas/table-uuidhash table))
2671 (dolist (group-and-templates groups-alist)
2672 (when (rest group-and-templates)
2673 (setq group (truncate-string-to-width (car group-and-templates) 25 0 ? "..."))
2674 (insert (make-string 100 ?-) "\n")
2675 (dolist (p (cdr group-and-templates))
2676 (let ((name (truncate-string-to-width (propertize (format "\\\\snippet `%s'" (yas/template-name p))
2680 (setq group (make-string (length group) ? ))))
2681 (condition-string (let ((condition (yas/template-condition p)))
2684 (with-current-buffer original-buffer
2685 (if (yas/eval-condition condition)
2690 (insert condition-string " ")
2692 (if (string-match "\\.\\.\\.$" name)
2696 (insert (truncate-string-to-width (or (yas/template-key p) "")
2698 (insert (truncate-string-to-width (key-description (yas/template-keybinding p))
2706 ;;; User convenience functions, for using in snippet definitions
2708 (defvar yas/modified-p nil
2709 "Non-nil if field has been modified by user or transformation.")
2711 (defvar yas/moving-away-p nil
2712 "Non-nil if user is about to exit field.")
2714 (defvar yas/text nil
2715 "Contains current field text.")
2717 (defun yas/substr (str pattern &optional subexp)
2718 "Search PATTERN in STR and return SUBEXPth match.
2720 If found, the content of subexp group SUBEXP (default 0) is
2721 returned, or else the original STR will be returned."
2722 (let ((grp (or subexp 0)))
2724 (if (string-match pattern str)
2725 (match-string-no-properties grp str)
2728 (defun yas/choose-value (possibilities)
2729 "Prompt for a string in the list POSSIBILITIES and return it."
2730 (unless (or yas/moving-away-p
2732 (some #'(lambda (fn)
2733 (funcall fn "Choose: " possibilities))
2734 yas/prompt-functions)))
2736 (defun yas/key-to-value (alist)
2737 "Prompt for a string in the list POSSIBILITIES and return it."
2738 (unless (or yas/moving-away-p
2740 (let ((key (read-key-sequence "")))
2742 (or (cdr (find key alist :key #'car :test #'string=))
2745 (defun yas/throw (text)
2746 "Throw a yas/exception with TEXT as the reason."
2747 (throw 'yas/exception (cons 'yas/exception text)))
2749 (defun yas/verify-value (possibilities)
2750 "Verify that the current field value is in POSSIBILITIES
2752 Otherwise throw exception."
2753 (when (and yas/moving-away-p (notany #'(lambda (pos) (string= pos yas/text)) possibilities))
2754 (yas/throw (format "[yas] field only allows %s" possibilities))))
2756 (defun yas/field-value (number)
2757 "Get the string for field with NUMBER.
2759 Use this in primary and mirror transformations to tget."
2760 (let* ((snippet (car (yas/snippets-at-point)))
2762 (yas/snippet-find-field snippet number))))
2764 (yas/field-text-for-display field))))
2767 "Return `yas/text' if that exists and is non-empty, else nil."
2769 (not (string= "" yas/text)))
2772 ;; (defun yas/selected-text ()
2773 ;; "Return `yas/selected-text' if that exists and is non-empty, else nil."
2774 ;; (if (and yas/selected-text
2775 ;; (not (string= "" yas/selected-text)))
2776 ;; yas/selected-text))
2778 (defun yas/get-field-once (number &optional transform-fn)
2779 (unless yas/modified-p
2781 (funcall transform-fn (yas/field-value number))
2782 (yas/field-value number))))
2784 (defun yas/default-from-field (number)
2785 (unless yas/modified-p
2786 (yas/field-value number)))
2788 (defun yas/inside-string ()
2789 (equal 'font-lock-string-face (get-char-property (1- (point)) 'face)))
2791 (defun yas/unimplemented (&optional missing-feature)
2792 (if yas/current-template
2793 (if (y-or-n-p (format "This snippet is unimplemented (missing %s) Visit the snippet definition? "
2796 (yas/visit-snippet-file-1 yas/current-template))
2797 (message "No implementation. Missing %s" (or missing-feature "something"))))
2800 ;;; Snippet expansion and field management
2802 (defvar yas/active-field-overlay nil
2803 "Overlays the currently active field.")
2805 (defvar yas/field-protection-overlays nil
2806 "Two overlays protect the current active field ")
2808 (defconst yas/prefix nil
2809 "A prefix argument for expansion direct from keybindings")
2811 (defvar yas/selected-text nil
2812 "The selected region deleted on the last snippet expansion.")
2814 (defvar yas/start-column nil
2815 "The column where the snippet expansion started.")
2817 (make-variable-buffer-local 'yas/active-field-overlay)
2818 (make-variable-buffer-local 'yas/field-protection-overlays)
2819 (put 'yas/active-field-overlay 'permanent-local t)
2820 (put 'yas/field-protection-overlays 'permanent-local t)
2822 (defstruct (yas/snippet (:constructor yas/make-snippet ()))
2828 (id (yas/snippet-next-id) :read-only t)
2829 (control-overlay nil)
2831 ;; stacked expansion: the `previous-active-field' slot saves the
2832 ;; active field where the child expansion took place
2833 previous-active-field
2836 (defstruct (yas/field (:constructor yas/make-field (number start end parent-field)))
2846 (defstruct (yas/mirror (:constructor yas/make-mirror (start end transform)))
2853 (defstruct (yas/exit (:constructor yas/make-exit (marker)))
2857 (defun yas/apply-transform (field-or-mirror field &optional empty-on-nil-p)
2858 "Calculate transformed string for FIELD-OR-MIRROR from FIELD.
2860 If there is no transform for ht field, return nil.
2862 If there is a transform but it returns nil, return the empty
2863 string iff EMPTY-ON-NIL-P is true."
2864 (let* ((yas/text (yas/field-text-for-display field))
2866 (yas/modified-p (yas/field-modified-p field))
2867 (yas/moving-away-p nil)
2868 (transform (if (yas/mirror-p field-or-mirror)
2869 (yas/mirror-transform field-or-mirror)
2870 (yas/field-transform field-or-mirror)))
2871 (start-point (if (yas/mirror-p field-or-mirror)
2872 (yas/mirror-start field-or-mirror)
2873 (yas/field-start field-or-mirror)))
2874 (transformed (and transform
2876 (goto-char start-point)
2877 (let ((ret (yas/eval-lisp transform)))
2878 (or ret (and empty-on-nil-p "")))))))
2881 (defsubst yas/replace-all (from to &optional text)
2882 "Replace all occurance from FROM to TO.
2884 With optional string TEXT do it in that string."
2886 (replace-regexp-in-string (regexp-quote from) to text t t)
2887 (goto-char (point-min))
2888 (while (search-forward from nil t)
2889 (replace-match to t t text))))
2891 (defun yas/snippet-find-field (snippet number)
2892 (find-if #'(lambda (field)
2893 (eq number (yas/field-number field)))
2894 (yas/snippet-fields snippet)))
2896 (defun yas/snippet-sort-fields (snippet)
2897 "Sort the fields of SNIPPET in navigation order."
2898 (setf (yas/snippet-fields snippet)
2899 (sort (yas/snippet-fields snippet)
2900 #'yas/snippet-field-compare)))
2902 (defun yas/snippet-field-compare (field1 field2)
2903 "Compare two fields. The field with a number is sorted first.
2904 If they both have a number, compare through the number. If neither
2905 have, compare through the field's start point"
2906 (let ((n1 (yas/field-number field1))
2907 (n2 (yas/field-number field2)))
2910 (or (zerop n2) (and (not (zerop n1))
2915 (< (yas/field-start field1)
2916 (yas/field-start field2))))))
2918 (defun yas/field-probably-deleted-p (snippet field)
2919 "Guess if SNIPPET's FIELD should be skipped."
2920 (and (zerop (- (yas/field-start field) (yas/field-end field)))
2921 (or (yas/field-parent-field field)
2922 (and (eq field (car (last (yas/snippet-fields snippet))))
2923 (= (yas/field-start field) (overlay-end (yas/snippet-control-overlay snippet)))))
2924 ;; the field numbered 0, just before the exit marker, should
2926 (not (zerop (yas/field-number field)))))
2928 (defun yas/snippets-at-point (&optional all-snippets)
2929 "Return a sorted list of snippets at point, most recently
2932 (remove nil (remove-duplicates (mapcar #'(lambda (ov)
2933 (overlay-get ov 'yas/snippet))
2935 (overlays-in (point-min) (point-max))
2936 (nconc (overlays-at (point)) (overlays-at (1- (point))))))))
2938 (<= (yas/snippet-id s2) (yas/snippet-id s1)))))
2940 (defun yas/next-field-or-maybe-expand ()
2941 "Try to expand a snippet at a key before point, otherwise
2942 delegate to `yas/next-field'."
2944 (if yas/triggers-in-field
2945 (let ((yas/fallback-behavior 'return-nil)
2946 (active-field (overlay-get yas/active-field-overlay 'yas/field)))
2948 (unless (yas/expand-from-trigger-key active-field)
2952 (defun yas/next-field (&optional arg)
2953 "Navigate to next field. If there's none, exit the snippet."
2957 (snippet (first (yas/snippets-at-point)))
2958 (active-field (overlay-get yas/active-field-overlay 'yas/field))
2959 (live-fields (remove-if #'(lambda (field)
2960 (and (not (eq field active-field))
2961 (yas/field-probably-deleted-p snippet field)))
2962 (yas/snippet-fields snippet)))
2963 (active-field-pos (position active-field live-fields))
2964 (target-pos (and active-field-pos (+ arg active-field-pos)))
2965 (target-field (and target-pos (nth target-pos live-fields))))
2966 ;; First check if we're moving out of a field with a transform
2968 (when (and active-field
2969 (yas/field-transform active-field))
2970 (let* ((yas/moving-away-p t)
2971 (yas/text (yas/field-text-for-display active-field))
2973 (yas/modified-p (yas/field-modified-p active-field)))
2974 ;; primary field transform: exit call to field-transform
2975 (yas/eval-lisp (yas/field-transform active-field))))
2976 ;; Now actually move...
2977 (cond ((and target-pos (>= target-pos (length live-fields)))
2978 (yas/exit-snippet snippet))
2980 (yas/move-to-field snippet target-field))
2984 (defun yas/place-overlays (snippet field)
2985 "Correctly place overlays for SNIPPET's FIELD"
2986 (yas/make-move-field-protection-overlays snippet field)
2987 (yas/make-move-active-field-overlay snippet field))
2989 (defun yas/move-to-field (snippet field)
2990 "Update SNIPPET to move to field FIELD.
2992 Also create some protection overlays"
2993 (goto-char (yas/field-start field))
2994 (yas/place-overlays snippet field)
2995 (overlay-put yas/active-field-overlay 'yas/field field)
2996 (let ((number (yas/field-number field)))
2997 ;; check for the special ${0: ...} field
2998 (if (and number (zerop number))
3000 (set-mark (yas/field-end field))
3001 (setf (yas/snippet-force-exit snippet)
3002 (or (yas/field-transform field)
3004 ;; make this field active
3005 (setf (yas/snippet-active-field snippet) field)
3006 ;; primary field transform: first call to snippet transform
3007 (unless (yas/field-modified-p field)
3008 (if (yas/field-update-display field snippet)
3009 (yas/update-mirrors snippet)
3010 (setf (yas/field-modified-p field) nil))))))
3012 (defun yas/prev-field ()
3013 "Navigate to prev field. If there's none, exit the snippet."
3015 (yas/next-field -1))
3017 (defun yas/abort-snippet (&optional snippet)
3019 (let ((snippet (or snippet
3020 (car (yas/snippets-at-point)))))
3022 (setf (yas/snippet-force-exit snippet) t))))
3024 (defun yas/exit-snippet (snippet)
3025 "Goto exit-marker of SNIPPET."
3027 (setf (yas/snippet-force-exit snippet) t)
3028 (goto-char (if (yas/snippet-exit snippet)
3029 (yas/exit-marker (yas/snippet-exit snippet))
3030 (overlay-end (yas/snippet-control-overlay snippet)))))
3032 (defun yas/exit-all-snippets ()
3033 "Exit all snippets."
3035 (mapc #'(lambda (snippet)
3036 (yas/exit-snippet snippet)
3037 (yas/check-commit-snippet))
3038 (yas/snippets-at-point)))
3041 ;;; Some low level snippet-routines
3043 (defmacro yas/inhibit-overlay-hooks (&rest body)
3044 "Run BODY with `yas/inhibit-overlay-hooks' set to t."
3045 (declare (indent 0))
3046 `(let ((yas/inhibit-overlay-hooks t))
3049 (defun yas/commit-snippet (snippet)
3050 "Commit SNIPPET, but leave point as it is. This renders the
3051 snippet as ordinary text.
3053 Return a buffer position where the point should be placed if
3054 exiting the snippet."
3056 (let ((control-overlay (yas/snippet-control-overlay snippet))
3060 ;; Save the end of the moribund snippet in case we need to revive it
3061 ;; its original expansion.
3063 (when (and control-overlay
3064 (overlay-buffer control-overlay))
3065 (setq yas/snippet-beg (overlay-start control-overlay))
3066 (setq yas/snippet-end (overlay-end control-overlay))
3067 (delete-overlay control-overlay))
3069 (yas/inhibit-overlay-hooks
3070 (when yas/active-field-overlay
3071 (delete-overlay yas/active-field-overlay))
3072 (when yas/field-protection-overlays
3073 (mapc #'delete-overlay yas/field-protection-overlays)))
3075 ;; stacked expansion: if the original expansion took place from a
3076 ;; field, make sure we advance it here at least to
3077 ;; `yas/snippet-end'...
3079 (let ((previous-field (yas/snippet-previous-active-field snippet)))
3080 (when (and yas/snippet-end previous-field)
3081 (yas/advance-end-maybe previous-field yas/snippet-end)))
3083 ;; Convert all markers to points,
3085 (yas/markers-to-points snippet)
3087 ;; Take care of snippet revival
3089 (if yas/snippet-revival
3090 (push `(apply yas/snippet-revive ,yas/snippet-beg ,yas/snippet-end ,snippet)
3092 ;; Dismember the snippet... this is useful if we get called
3093 ;; again from `yas/take-care-of-redo'....
3094 (setf (yas/snippet-fields snippet) nil)))
3096 (message "[yas] snippet %s exited." (yas/snippet-id snippet)))
3098 (defun yas/safely-run-hooks (hook-var)
3099 (condition-case error
3100 (run-hooks hook-var)
3102 (message "[yas] %s error: %s" hook-var (error-message-string error)))))
3105 (defun yas/check-commit-snippet ()
3106 "Checks if point exited the currently active field of the
3107 snippet, if so cleans up the whole snippet up."
3108 (let* ((snippets (yas/snippets-at-point 'all-snippets))
3109 (snippets-left snippets)
3110 (snippet-exit-transform))
3111 (dolist (snippet snippets)
3112 (let ((active-field (yas/snippet-active-field snippet)))
3113 (setq snippet-exit-transform (yas/snippet-force-exit snippet))
3114 (cond ((or snippet-exit-transform
3115 (not (and active-field (yas/field-contains-point-p active-field))))
3116 (setq snippets-left (delete snippet snippets-left))
3117 (setf (yas/snippet-force-exit snippet) nil)
3118 (yas/commit-snippet snippet))
3120 (or (not yas/active-field-overlay)
3121 (not (overlay-buffer yas/active-field-overlay))))
3123 ;; stacked expansion: this case is mainly for recent
3124 ;; snippet exits that place us back int the field of
3128 (yas/move-to-field snippet active-field)
3129 (yas/update-mirrors snippet)))
3132 (unless (or (null snippets) snippets-left)
3133 (if snippet-exit-transform
3134 (yas/eval-lisp-no-saves snippet-exit-transform))
3135 (yas/safely-run-hooks 'yas/after-exit-snippet-hook))))
3137 ;; Apropos markers-to-points:
3139 ;; This was found useful for performance reasons, so that an
3140 ;; excessive number of live markers aren't kept around in the
3141 ;; `buffer-undo-list'. However, in `markers-to-points', the
3142 ;; set-to-nil markers can't simply be discarded and replaced with
3143 ;; fresh ones in `points-to-markers'. The original marker that was
3144 ;; just set to nil has to be reused.
3146 ;; This shouldn't bring horrible problems with undo/redo, but it
3149 (defun yas/markers-to-points (snippet)
3150 "Convert all markers in SNIPPET to a cons (POINT . MARKER)
3151 where POINT is the original position of the marker and MARKER is
3152 the original marker object with the position set to nil."
3153 (dolist (field (yas/snippet-fields snippet))
3154 (let ((start (marker-position (yas/field-start field)))
3155 (end (marker-position (yas/field-end field))))
3156 (set-marker (yas/field-start field) nil)
3157 (set-marker (yas/field-end field) nil)
3158 (setf (yas/field-start field) (cons start (yas/field-start field)))
3159 (setf (yas/field-end field) (cons end (yas/field-end field))))
3160 (dolist (mirror (yas/field-mirrors field))
3161 (let ((start (marker-position (yas/mirror-start mirror)))
3162 (end (marker-position (yas/mirror-end mirror))))
3163 (set-marker (yas/mirror-start mirror) nil)
3164 (set-marker (yas/mirror-end mirror) nil)
3165 (setf (yas/mirror-start mirror) (cons start (yas/mirror-start mirror)))
3166 (setf (yas/mirror-end mirror) (cons end (yas/mirror-end mirror))))))
3167 (let ((snippet-exit (yas/snippet-exit snippet)))
3169 (let ((exit (marker-position (yas/exit-marker snippet-exit))))
3170 (set-marker (yas/exit-marker snippet-exit) nil)
3171 (setf (yas/exit-marker snippet-exit) (cons exit (yas/exit-marker snippet-exit)))))))
3173 (defun yas/points-to-markers (snippet)
3174 "Convert all cons (POINT . MARKER) in SNIPPET to markers. This
3175 is done by setting MARKER to POINT with `set-marker'."
3176 (dolist (field (yas/snippet-fields snippet))
3177 (setf (yas/field-start field) (set-marker (cdr (yas/field-start field))
3178 (car (yas/field-start field))))
3179 (setf (yas/field-end field) (set-marker (cdr (yas/field-end field))
3180 (car (yas/field-end field))))
3181 (dolist (mirror (yas/field-mirrors field))
3182 (setf (yas/mirror-start mirror) (set-marker (cdr (yas/mirror-start mirror))
3183 (car (yas/mirror-start mirror))))
3184 (setf (yas/mirror-end mirror) (set-marker (cdr (yas/mirror-end mirror))
3185 (car (yas/mirror-end mirror))))))
3186 (let ((snippet-exit (yas/snippet-exit snippet)))
3188 (setf (yas/exit-marker snippet-exit) (set-marker (cdr (yas/exit-marker snippet-exit))
3189 (car (yas/exit-marker snippet-exit)))))))
3191 (defun yas/field-contains-point-p (field &optional point)
3192 (let ((point (or point
3194 (and (>= point (yas/field-start field))
3195 (<= point (yas/field-end field)))))
3197 (defun yas/field-text-for-display (field)
3198 "Return the propertized display text for field FIELD. "
3199 (buffer-substring (yas/field-start field) (yas/field-end field)))
3201 (defun yas/undo-in-progress ()
3202 "True if some kind of undo is in progress"
3203 (or undo-in-progress
3204 (eq this-command 'undo)
3205 (eq this-command 'redo)))
3207 (defun yas/make-control-overlay (snippet start end)
3208 "Creates the control overlay that surrounds the snippet and
3210 (let ((overlay (make-overlay start
3215 (overlay-put overlay 'keymap yas/keymap)
3216 (overlay-put overlay 'priority 100)
3217 (overlay-put overlay 'yas/snippet snippet)
3220 (defun yas/skip-and-clear-or-delete-char (&optional field)
3221 "Clears unmodified field if at field start, skips to next tab.
3223 Otherwise deletes a character normally by calling `delete-char'."
3225 (let ((field (or field
3226 (and yas/active-field-overlay
3227 (overlay-buffer yas/active-field-overlay)
3228 (overlay-get yas/active-field-overlay 'yas/field)))))
3230 (not (yas/field-modified-p field))
3231 (eq (point) (marker-position (yas/field-start field))))
3232 (yas/skip-and-clear field)
3235 (call-interactively 'delete-char)))))
3237 (defun yas/skip-and-clear (field)
3238 "Deletes the region of FIELD and sets it modified state to t"
3239 ;; Just before skipping-and-clearing the field, mark its children
3240 ;; fields as modified, too. If the childen have mirrors-in-fields
3241 ;; this prevents them from updating erroneously (we're skipping and
3244 (yas/mark-this-and-children-modified field)
3245 (delete-region (yas/field-start field) (yas/field-end field)))
3247 (defun yas/mark-this-and-children-modified (field)
3248 (setf (yas/field-modified-p field) t)
3249 (let ((fom (yas/field-next field)))
3251 (yas/fom-parent-field fom))
3252 (when (and (eq (yas/fom-parent-field fom) field)
3254 (yas/mark-this-and-children-modified fom))
3255 (setq fom (yas/fom-next fom)))))
3257 (defun yas/make-move-active-field-overlay (snippet field)
3258 "Place the active field overlay in SNIPPET's FIELD.
3260 Move the overlay, or create it if it does not exit."
3261 (if (and yas/active-field-overlay
3262 (overlay-buffer yas/active-field-overlay))
3263 (move-overlay yas/active-field-overlay
3264 (yas/field-start field)
3265 (yas/field-end field))
3266 (setq yas/active-field-overlay
3267 (make-overlay (yas/field-start field)
3268 (yas/field-end field)
3270 (overlay-put yas/active-field-overlay 'priority 100)
3271 (overlay-put yas/active-field-overlay 'face 'yas/field-highlight-face)
3272 (overlay-put yas/active-field-overlay 'yas/snippet snippet)
3273 (overlay-put yas/active-field-overlay 'modification-hooks '(yas/on-field-overlay-modification))
3274 (overlay-put yas/active-field-overlay 'insert-in-front-hooks
3275 '(yas/on-field-overlay-modification))
3276 (overlay-put yas/active-field-overlay 'insert-behind-hooks
3277 '(yas/on-field-overlay-modification))))
3279 (defvar yas/inhibit-overlay-hooks nil
3280 "Bind this temporarity to non-nil to prevent running `yas/on-*-modification'.")
3282 (defun yas/on-field-overlay-modification (overlay after? beg end &optional length)
3283 "Clears the field and updates mirrors, conditionally.
3285 Only clears the field if it hasn't been modified and it point it
3286 at field start. This hook doesn't do anything if an undo is in
3288 (unless (or yas/inhibit-overlay-hooks
3289 (yas/undo-in-progress))
3290 (let* ((field (overlay-get overlay 'yas/field))
3291 (number (and field (yas/field-number field)))
3292 (snippet (overlay-get yas/active-field-overlay 'yas/snippet)))
3294 (yas/advance-end-maybe field (overlay-end overlay))
3296 (yas/field-update-display field snippet))
3297 (yas/update-mirrors snippet))
3299 (when (and (not after?)
3300 (not (yas/field-modified-p field))
3301 (eq (point) (if (markerp (yas/field-start field))
3302 (marker-position (yas/field-start field))
3303 (yas/field-start field))))
3304 (yas/skip-and-clear field))
3305 (setf (yas/field-modified-p field) t))))))
3307 ;;; Apropos protection overlays:
3309 ;; These exist for nasty users who will try to delete parts of the
3310 ;; snippet outside the active field. Actual protection happens in
3311 ;; `yas/on-protection-overlay-modification'.
3313 ;; Currently this signals an error which inhibits the command. For
3314 ;; commands that move point (like `kill-line'), point is restored in
3315 ;; the `yas/post-command-handler' using a global
3316 ;; `yas/protection-violation' variable.
3318 ;; Alternatively, I've experimented with an implementation that
3319 ;; commits the snippet before actually calling `this-command'
3320 ;; interactively, and then signals an eror, which is ignored. but
3321 ;; blocks all other million modification hooks. This presented some
3322 ;; problems with stacked expansion.
3325 (defun yas/make-move-field-protection-overlays (snippet field)
3326 "Place protection overlays surrounding SNIPPET's FIELD.
3328 Move the overlays, or create them if they do not exit."
3329 (let ((start (yas/field-start field))
3330 (end (yas/field-end field)))
3331 ;; First check if the (1+ end) is contained in the buffer,
3332 ;; otherwise we'll have to do a bit of cheating and silently
3333 ;; insert a newline. the `(1+ (buffer-size))' should prevent this
3334 ;; when using stacked expansion
3336 (when (< (buffer-size) end)
3338 (yas/inhibit-overlay-hooks
3339 (goto-char (point-max))
3341 ;; go on to normal overlay creation/moving
3343 (cond ((and yas/field-protection-overlays
3344 (every #'overlay-buffer yas/field-protection-overlays))
3345 (move-overlay (first yas/field-protection-overlays) (1- start) start)
3346 (move-overlay (second yas/field-protection-overlays) end (1+ end)))
3348 (setq yas/field-protection-overlays
3349 (list (make-overlay (1- start) start nil t nil)
3350 (make-overlay end (1+ end) nil t nil)))
3351 (dolist (ov yas/field-protection-overlays)
3352 (overlay-put ov 'face 'yas/field-debug-face)
3353 (overlay-put ov 'yas/snippet snippet)
3354 ;; (overlay-put ov 'evaporate t)
3355 (overlay-put ov 'modification-hooks '(yas/on-protection-overlay-modification)))))))
3357 (defvar yas/protection-violation nil
3358 "When non-nil, signals attempts to erronesly exit or modify the snippet.
3360 Functions in the `post-command-hook', for example
3361 `yas/post-command-handler' can check it and reset its value to
3362 nil. The variables value is the point where the violation
3365 (defun yas/on-protection-overlay-modification (overlay after? beg end &optional length)
3366 "Signals a snippet violation, then issues error.
3368 The error should be ignored in `debug-ignored-errors'"
3369 (unless yas/inhibit-overlay-hooks
3370 (cond ((not (or after?
3371 (yas/undo-in-progress)))
3372 (setq yas/protection-violation (point))
3373 (error "Exit the snippet first!")))))
3375 (add-to-list 'debug-ignored-errors "^Exit the snippet first!$")
3378 ;;; Apropos stacked expansion:
3380 ;; the parent snippet does not run its fields modification hooks
3381 ;; (`yas/on-field-overlay-modification' and
3382 ;; `yas/on-protection-overlay-modification') while the child snippet
3383 ;; is active. This means, among other things, that the mirrors of the
3384 ;; parent snippet are not updated, this only happening when one exits
3385 ;; the child snippet.
3387 ;; Unfortunately, this also puts some ugly (and not fully-tested)
3388 ;; bits of code in `yas/expand-snippet' and
3389 ;; `yas/commit-snippet'. I've tried to mark them with "stacked
3392 ;; This was thought to be safer in in an undo/redo perpective, but
3393 ;; maybe the correct implementation is to make the globals
3394 ;; `yas/active-field-overlay' and `yas/field-protection-overlays' be
3395 ;; snippet-local and be active even while the child snippet is
3396 ;; running. This would mean a lot of overlay modification hooks
3397 ;; running, but if managed correctly (including overlay priorities)
3398 ;; they should account for all situations...
3401 (defun yas/expand-snippet (content &optional start end expand-env)
3402 "Expand snippet CONTENT at current point.
3404 Text between START and END will be deleted before inserting
3405 template. EXPAND-ENV is are let-style variable to value bindings
3406 considered when expanding the snippet."
3407 (run-hooks 'yas/before-expand-snippet-hook)
3409 ;; If a region is active, set `yas/selected-text'
3410 (setq yas/selected-text
3411 (when (region-active-p)
3412 (prog1 (buffer-substring-no-properties (region-beginning)
3414 (unless start (setq start (region-beginning))
3415 (unless end (setq end (region-end)))))))
3421 (let ((to-delete (and start end (buffer-substring-no-properties start end)))
3422 (start (or start (point)))
3423 (end (or end (point)))
3425 (setq yas/indent-original-column (current-column))
3426 ;; Delete the region to delete, this *does* get undo-recorded.
3428 (when (and to-delete
3430 (delete-region start end))
3432 (cond ((listp content)
3433 ;; x) This is a snippet-command
3435 (yas/eval-lisp-no-saves content))
3437 ;; x) This is a snippet-snippet :-)
3439 ;; Narrow the region down to the content, shoosh the
3440 ;; `buffer-undo-list', and create the snippet, the new
3441 ;; snippet updates its mirrors once, so we are left with
3442 ;; some plain text. The undo action for deleting this
3443 ;; plain text will get recorded at the end.
3445 ;; stacked expansion: also shoosh the overlay modification hooks
3447 (narrow-to-region start start)
3448 (let ((buffer-undo-list t))
3449 ;; snippet creation might evaluate users elisp, which
3450 ;; might generate errors, so we have to be ready to catch
3451 ;; them mostly to make the undo information
3453 (setq yas/start-column (save-restriction (widen) (current-column)))
3454 (yas/inhibit-overlay-hooks
3457 (eval `(let ,expand-env
3459 (yas/snippet-create (point-min) (point-max))))
3461 (yas/snippet-create (point-min) (point-max)))))))
3463 ;; stacked-expansion: This checks for stacked expansion, save the
3464 ;; `yas/previous-active-field' and advance its boudary.
3466 (let ((existing-field (and yas/active-field-overlay
3467 (overlay-buffer yas/active-field-overlay)
3468 (overlay-get yas/active-field-overlay 'yas/field))))
3469 (when existing-field
3470 (setf (yas/snippet-previous-active-field snippet) existing-field)
3471 (yas/advance-end-maybe existing-field (overlay-end yas/active-field-overlay))))
3473 ;; Exit the snippet immediately if no fields
3475 (unless (yas/snippet-fields snippet)
3476 (yas/exit-snippet snippet))
3478 ;; Push two undo actions: the deletion of the inserted contents of
3479 ;; the new snippet (without the "key") followed by an apply of
3480 ;; `yas/take-care-of-redo' on the newly inserted snippet boundaries
3482 ;; A small exception, if `yas/also-auto-indent-first-line'
3483 ;; is t and `yas/indent' decides to indent the line to a
3484 ;; point before the actual expansion point, undo would be
3485 ;; messed up. We call the early point "newstart"". case,
3486 ;; and attempt to fix undo.
3488 (let ((newstart (overlay-start (yas/snippet-control-overlay snippet)))
3489 (end (overlay-end (yas/snippet-control-overlay snippet))))
3490 (when (< newstart start)
3491 (push (cons (make-string (- start newstart) ? ) newstart) buffer-undo-list))
3492 (push (cons newstart end) buffer-undo-list)
3493 (push `(apply yas/take-care-of-redo ,start ,end ,snippet)
3495 ;; Now, schedule a move to the first field
3497 (let ((first-field (car (yas/snippet-fields snippet))))
3499 (sit-for 0) ;; fix issue 125
3500 (yas/move-to-field snippet first-field)))
3501 (message "[yas] snippet expanded.")
3504 (defun yas/take-care-of-redo (beg end snippet)
3505 "Commits SNIPPET, which in turn pushes an undo action for
3508 Meant to exit in the `buffer-undo-list'."
3509 ;; slightly optimize: this action is only needed for snippets with
3510 ;; at least one field
3511 (when (yas/snippet-fields snippet)
3512 (yas/commit-snippet snippet)))
3514 (defun yas/snippet-revive (beg end snippet)
3515 "Revives the SNIPPET and creates a control overlay from BEG to
3518 BEG and END are, we hope, the original snippets boudaries. All
3519 the markers/points exiting existing inside SNIPPET should point
3520 to their correct locations *at the time the snippet is revived*.
3522 After revival, push the `yas/take-care-of-redo' in the
3524 ;; Reconvert all the points to markers
3526 (yas/points-to-markers snippet)
3527 ;; When at least one editable field existed in the zombie snippet,
3528 ;; try to revive the whole thing...
3530 (let ((target-field (or (yas/snippet-active-field snippet)
3531 (car (yas/snippet-fields snippet)))))
3533 (setf (yas/snippet-control-overlay snippet) (yas/make-control-overlay snippet beg end))
3534 (overlay-put (yas/snippet-control-overlay snippet) 'yas/snippet snippet)
3536 (yas/move-to-field snippet target-field)
3538 (push `(apply yas/take-care-of-redo ,beg ,end ,snippet)
3539 buffer-undo-list))))
3541 (defun yas/snippet-create (begin end)
3542 "Creates a snippet from an template inserted between BEGIN and END.
3544 Returns the newly created snippet."
3545 (let ((snippet (yas/make-snippet)))
3547 (yas/snippet-parse-create snippet)
3549 ;; Sort and link each field
3550 (yas/snippet-sort-fields snippet)
3552 ;; Create keymap overlay for snippet
3553 (setf (yas/snippet-control-overlay snippet)
3554 (yas/make-control-overlay snippet (point-min) (point-max)))
3557 (goto-char (point-max))
3562 ;;; Apropos adjacencies and "fom's":
3564 ;; Once the $-constructs bits like "$n" and "${:n" are deleted in the
3565 ;; recently expanded snippet, we might actually have many fields,
3566 ;; mirrors (and the snippet exit) in the very same position in the
3567 ;; buffer. Therefore we need to single-link the
3568 ;; fields-or-mirrors-or-exit, which I have called "fom", according to
3569 ;; their original positions in the buffer.
3571 ;; Then we have operation `yas/advance-end-maybe' and
3572 ;; `yas/advance-start-maybe', which conditionally push the starts and
3573 ;; ends of these foms down the chain.
3575 ;; This allows for like the printf with the magic ",":
3577 ;; printf ("${1:%s}\\n"${1:$(if (string-match "%" text) "," "\);")} \
3578 ;; $2${1:$(if (string-match "%" text) "\);" "")}$0
3580 (defun yas/fom-start (fom)
3581 (cond ((yas/field-p fom)
3582 (yas/field-start fom))
3584 (yas/mirror-start fom))
3586 (yas/exit-marker fom))))
3588 (defun yas/fom-end (fom)
3589 (cond ((yas/field-p fom)
3590 (yas/field-end fom))
3592 (yas/mirror-end fom))
3594 (yas/exit-marker fom))))
3596 (defun yas/fom-next (fom)
3597 (cond ((yas/field-p fom)
3598 (yas/field-next fom))
3600 (yas/mirror-next fom))
3602 (yas/exit-next fom))))
3604 (defun yas/fom-parent-field (fom)
3605 (cond ((yas/field-p fom)
3606 (yas/field-parent-field fom))
3608 (yas/mirror-parent-field fom))
3612 (defun yas/calculate-adjacencies (snippet)
3613 "Calculate adjacencies for fields or mirrors of SNIPPET.
3615 This is according to their relative positions in the buffer, and
3616 has to be called before the $-constructs are deleted."
3617 (flet ((yas/fom-set-next-fom (fom nextfom)
3618 (cond ((yas/field-p fom)
3619 (setf (yas/field-next fom) nextfom))
3621 (setf (yas/mirror-next fom) nextfom))
3623 (setf (yas/exit-next fom) nextfom))))
3624 (yas/compare-fom-begs (fom1 fom2)
3625 (if (= (yas/fom-start fom2) (yas/fom-start fom1))
3627 (>= (yas/fom-start fom2) (yas/fom-start fom1))))
3628 (yas/link-foms (fom1 fom2)
3629 (yas/fom-set-next-fom fom1 fom2)))
3630 ;; make some yas/field, yas/mirror and yas/exit soup
3632 (when (yas/snippet-exit snippet)
3633 (push (yas/snippet-exit snippet) soup))
3634 (dolist (field (yas/snippet-fields snippet))
3636 (dolist (mirror (yas/field-mirrors field))
3637 (push mirror soup)))
3640 #'yas/compare-fom-begs))
3642 (reduce #'yas/link-foms soup)))))
3644 (defun yas/calculate-mirrors-in-fields (snippet mirror)
3645 "Attempt to assign a parent field of SNIPPET to the mirror MIRROR.
3647 Use the tighest containing field if more than one field contains
3648 the mirror. Intended to be called *before* the dollar-regions are
3650 (let ((min (point-min))
3652 (dolist (field (yas/snippet-fields snippet))
3653 (when (and (<= (yas/field-start field) (yas/mirror-start mirror))
3654 (<= (yas/mirror-end mirror) (yas/field-end field))
3655 (< min (yas/field-start field))
3656 (< (yas/field-end field) max))
3657 (setq min (yas/field-start field)
3658 max (yas/field-end field))
3659 (setf (yas/mirror-parent-field mirror) field)))))
3661 (defun yas/advance-end-maybe (fom newend)
3662 "Maybe advance FOM's end to NEWEND if it needs it.
3666 * call `yas/advance-start-maybe' on FOM's next fom.
3668 * in case FOM is field call `yas/advance-end-maybe' on its parent
3671 Also, if FOM is an exit-marker, always call
3672 `yas/advance-start-maybe' on its next fom. This is beacuse
3673 exit-marker have identical start and end markers.
3676 (cond ((and fom (< (yas/fom-end fom) newend))
3677 (set-marker (yas/fom-end fom) newend)
3678 (yas/advance-start-maybe (yas/fom-next fom) newend)
3679 (yas/advance-end-of-parents-maybe (yas/fom-parent-field fom) newend))
3681 (yas/advance-start-maybe (yas/fom-next fom) newend))))
3683 (defun yas/advance-start-maybe (fom newstart)
3684 "Maybe advance FOM's start to NEWSTART if it needs it.
3686 If it does, also call `yas/advance-end-maybe' on FOM."
3687 (when (and fom (< (yas/fom-start fom) newstart))
3688 (set-marker (yas/fom-start fom) newstart)
3689 (yas/advance-end-maybe fom newstart)))
3691 (defun yas/advance-end-of-parents-maybe (field newend)
3692 "Like `yas/advance-end-maybe' but for parent fields.
3694 Only works for fields and doesn't care about the start of the
3695 next FOM. Works its way up recursively for parents of parents."
3697 (< (yas/field-end field) newend))
3698 (set-marker (yas/field-end field) newend)
3699 (yas/advance-end-of-parents-maybe (yas/field-parent-field field) newend)))
3701 (defvar yas/dollar-regions nil
3702 "When expanding the snippet the \"parse-create\" functions add
3703 cons cells to this var")
3705 (defun yas/snippet-parse-create (snippet)
3706 "Parse a recently inserted snippet template, creating all
3707 necessary fields, mirrors and exit points.
3709 Meant to be called in a narrowed buffer, does various passes"
3710 (let ((parse-start (point)))
3711 ;; Reset the yas/dollar-regions
3713 (setq yas/dollar-regions nil)
3714 ;; protect escaped quote, backquotes and backslashes
3716 (yas/protect-escapes nil '(?\\ ?` ?'))
3717 ;; replace all backquoted expressions
3719 (goto-char parse-start)
3720 (yas/replace-backquotes)
3721 ;; protect escapes again since previous steps might have generated
3722 ;; more characters needing escaping
3724 (goto-char parse-start)
3725 (yas/protect-escapes)
3726 ;; parse fields with {}
3728 (goto-char parse-start)
3729 (yas/field-parse-create snippet)
3730 ;; parse simple mirrors and fields
3732 (goto-char parse-start)
3733 (yas/simple-mirror-parse-create snippet)
3734 ;; parse mirror transforms
3736 (goto-char parse-start)
3737 (yas/transform-mirror-parse-create snippet)
3738 ;; calculate adjacencies of fields and mirrors
3740 (yas/calculate-adjacencies snippet)
3741 ;; Delete $-constructs
3743 (yas/delete-regions yas/dollar-regions)
3746 (goto-char parse-start)
3747 (yas/restore-escapes)
3748 ;; update mirrors for the first time
3750 (yas/update-mirrors snippet)
3751 ;; indent the best we can
3753 (goto-char parse-start)
3754 (yas/indent snippet)))
3756 (defun yas/indent-according-to-mode (snippet-markers)
3757 "Indent current line according to mode, preserving
3759 ;;; Apropos indenting problems....
3761 ;; `indent-according-to-mode' uses whatever `indent-line-function'
3762 ;; is available. Some implementations of these functions delete text
3763 ;; before they insert. If there happens to be a marker just after
3764 ;; the text being deleted, the insertion actually happens after the
3765 ;; marker, which misplaces it.
3767 ;; This would also happen if we had used overlays with the
3768 ;; `front-advance' property set to nil.
3770 ;; This is why I have these `trouble-markers', they are the ones at
3771 ;; they are the ones at the first non-whitespace char at the line
3772 ;; (i.e. at `yas/real-line-beginning'. After indentation takes place
3773 ;; we should be at the correct to restore them to. All other
3774 ;; non-trouble-markers have been *pushed* and don't need special
3777 (goto-char (yas/real-line-beginning))
3778 (let ((trouble-markers (remove-if-not #'(lambda (marker)
3784 (indent-according-to-mode)
3785 (error (message "[yas] warning: yas/indent-according-to-mode habing problems running %s" indent-line-function)
3787 (mapc #'(lambda (marker)
3788 (set-marker marker (point)))
3791 (defvar yas/indent-original-column nil)
3792 (defun yas/indent (snippet)
3793 (let ((snippet-markers (yas/collect-snippet-markers snippet)))
3794 ;; Look for those $>
3796 (while (re-search-forward "$>" nil t)
3797 (delete-region (match-beginning 0) (match-end 0))
3798 (when (not (eq yas/indent-line 'auto))
3799 (yas/indent-according-to-mode snippet-markers))))
3800 ;; Now do stuff for 'fixed and 'auto
3802 (cond ((eq yas/indent-line 'fixed)
3803 (while (and (zerop (forward-line))
3804 (zerop (current-column)))
3805 (indent-to-column yas/indent-original-column)))
3806 ((eq yas/indent-line 'auto)
3807 (let ((end (set-marker (make-marker) (point-max)))
3808 (indent-first-line-p yas/also-auto-indent-first-line))
3809 (while (and (zerop (if indent-first-line-p
3812 (setq indent-first-line-p nil))
3816 (yas/indent-according-to-mode snippet-markers))))
3820 (defun yas/collect-snippet-markers (snippet)
3821 "Make a list of all the markers used by SNIPPET."
3823 (dolist (field (yas/snippet-fields snippet))
3824 (push (yas/field-start field) markers)
3825 (push (yas/field-end field) markers)
3826 (dolist (mirror (yas/field-mirrors field))
3827 (push (yas/mirror-start mirror) markers)
3828 (push (yas/mirror-end mirror) markers)))
3829 (let ((snippet-exit (yas/snippet-exit snippet)))
3830 (when (and snippet-exit
3831 (marker-buffer (yas/exit-marker snippet-exit)))
3832 (push (yas/exit-marker snippet-exit) markers)))
3835 (defun yas/real-line-beginning ()
3836 (let ((c (char-after (line-beginning-position)))
3837 (n (line-beginning-position)))
3838 (while (or (eql c ?\ )
3841 (setq c (char-after n)))
3844 (defun yas/escape-string (escaped)
3845 (concat "YASESCAPE" (format "%d" escaped) "PROTECTGUARD"))
3847 (defun yas/protect-escapes (&optional text escaped)
3848 "Protect all escaped characters with their numeric ASCII value.
3850 With optional string TEXT do it in string instead of buffer."
3851 (let ((changed-text text)
3852 (text-provided-p text))
3853 (mapc #'(lambda (escaped)
3855 (yas/replace-all (concat "\\" (char-to-string escaped))
3856 (yas/escape-string escaped)
3857 (when text-provided-p changed-text))))
3858 (or escaped yas/escaped-characters))
3861 (defun yas/restore-escapes (&optional text escaped)
3862 "Restore all escaped characters from their numeric ASCII value.
3864 With optional string TEXT do it in string instead of the buffer."
3865 (let ((changed-text text)
3866 (text-provided-p text))
3867 (mapc #'(lambda (escaped)
3869 (yas/replace-all (yas/escape-string escaped)
3870 (char-to-string escaped)
3871 (when text-provided-p changed-text))))
3872 (or escaped yas/escaped-characters))
3875 (defun yas/replace-backquotes ()
3876 "Replace all the \"`(lisp-expression)`\"-style expression
3877 with their evaluated value"
3878 (while (re-search-forward yas/backquote-lisp-expression-regexp nil t)
3879 (let ((current-string (match-string 1)) transformed)
3880 (delete-region (match-beginning 0) (match-end 0))
3881 (setq transformed (yas/eval-lisp (yas/read-lisp (yas/restore-escapes current-string))))
3882 (goto-char (match-beginning 0))
3883 (when transformed (insert transformed)))))
3885 (defun yas/scan-sexps (from count)
3887 (with-syntax-table (standard-syntax-table)
3888 (scan-sexps from count))
3892 (defun yas/make-marker (pos)
3893 "Create a marker at POS with `nil' `marker-insertion-type'"
3894 (let ((marker (set-marker (make-marker) pos)))
3895 (set-marker-insertion-type marker nil)
3898 (defun yas/field-parse-create (snippet &optional parent-field)
3899 "Parse most field expressions, except for the simple one \"$n\".
3901 The following count as a field:
3903 * \"${n: text}\", for a numbered field with default text, as long as N is not 0;
3905 * \"${n: text$(expression)}, the same with a lisp expression;
3906 this is caught with the curiously named `yas/multi-dollar-lisp-expression-regexp'
3908 * the same as above but unnumbered, (no N:) and number is calculated automatically.
3910 When multiple expressions are found, only the last one counts."
3913 (while (re-search-forward yas/field-regexp nil t)
3914 (let* ((real-match-end-0 (yas/scan-sexps (1+ (match-beginning 0)) 1))
3915 (number (and (match-string-no-properties 1)
3916 (string-to-number (match-string-no-properties 1))))
3917 (brand-new-field (and real-match-end-0
3918 ;; break if on "$(" immediately
3919 ;; after the ":", this will be
3920 ;; caught as a mirror with
3922 (not (save-match-data
3923 (eq (string-match "$[ \t\n]*("
3924 (match-string-no-properties 2)) 0)))
3925 ;; allow ${0: some exit text}
3926 ;; (not (and number (zerop number)))
3927 (yas/make-field number
3928 (yas/make-marker (match-beginning 2))
3929 (yas/make-marker (1- real-match-end-0))
3931 (when brand-new-field
3932 (goto-char real-match-end-0)
3933 (push (cons (1- real-match-end-0) real-match-end-0)
3935 (push (cons (match-beginning 0) (match-beginning 2))
3937 (push brand-new-field (yas/snippet-fields snippet))
3940 (narrow-to-region (yas/field-start brand-new-field) (yas/field-end brand-new-field))
3941 (goto-char (point-min))
3942 (yas/field-parse-create snippet brand-new-field)))))))
3943 ;; if we entered from a parent field, now search for the
3944 ;; `yas/multi-dollar-lisp-expression-regexp'. THis is used for
3945 ;; primary field transformations
3949 (while (re-search-forward yas/multi-dollar-lisp-expression-regexp nil t)
3950 (let* ((real-match-end-1 (yas/scan-sexps (match-beginning 1) 1)))
3951 ;; commit the primary field transformation if:
3953 ;; 1. we don't find it in yas/dollar-regions (a subnested
3954 ;; field) might have already caught it.
3956 ;; 2. we really make sure we have either two '$' or some
3957 ;; text and a '$' after the colon ':'. This is a FIXME: work
3958 ;; my regular expressions and end these ugly hacks.
3960 (when (and real-match-end-1
3961 (not (member (cons (match-beginning 0)
3963 yas/dollar-regions))
3965 (char-before (1- (match-beginning 1))))))
3966 (let ((lisp-expression-string (buffer-substring-no-properties (match-beginning 1)
3968 (setf (yas/field-transform parent-field)
3969 (yas/read-lisp (yas/restore-escapes lisp-expression-string))))
3970 (push (cons (match-beginning 0) real-match-end-1)
3971 yas/dollar-regions)))))))
3973 (defun yas/transform-mirror-parse-create (snippet)
3974 "Parse the \"${n:$(lisp-expression)}\" mirror transformations."
3975 (while (re-search-forward yas/transform-mirror-regexp nil t)
3976 (let* ((real-match-end-0 (yas/scan-sexps (1+ (match-beginning 0)) 1))
3977 (number (string-to-number (match-string-no-properties 1)))
3979 (not (zerop number))
3980 (yas/snippet-find-field snippet number)))
3982 (and real-match-end-0
3984 (yas/make-mirror (yas/make-marker (match-beginning 0))
3985 (yas/make-marker (match-beginning 0))
3987 (yas/restore-escapes
3988 (buffer-substring-no-properties (match-beginning 2)
3989 (1- real-match-end-0))))))))
3990 (when brand-new-mirror
3991 (push brand-new-mirror
3992 (yas/field-mirrors field))
3993 (yas/calculate-mirrors-in-fields snippet brand-new-mirror)
3994 (push (cons (match-beginning 0) real-match-end-0) yas/dollar-regions)))))
3996 (defun yas/simple-mirror-parse-create (snippet)
3997 "Parse the simple \"$n\" fields/mirrors/exitmarkers."
3998 (while (re-search-forward yas/simple-mirror-regexp nil t)
3999 (let ((number (string-to-number (match-string-no-properties 1))))
4000 (cond ((zerop number)
4002 (setf (yas/snippet-exit snippet)
4003 (yas/make-exit (yas/make-marker (match-end 0))))
4005 (goto-char (match-beginning 0))
4006 (when yas/wrap-around-region
4007 (cond (yas/selected-text
4008 (insert yas/selected-text))
4009 ((and (eq yas/wrap-around-region 'cua)
4012 (insert (prog1 (get-register ?0)
4013 (set-register ?0 nil))))))
4014 (push (cons (point) (yas/exit-marker (yas/snippet-exit snippet)))
4015 yas/dollar-regions)))
4017 (let ((field (yas/snippet-find-field snippet number)))
4019 (let ((brand-new-mirror (yas/make-mirror
4020 (yas/make-marker (match-beginning 0))
4021 (yas/make-marker (match-beginning 0))
4023 (push brand-new-mirror
4024 (yas/field-mirrors field))
4025 (yas/calculate-mirrors-in-fields snippet brand-new-mirror))
4026 (push (yas/make-field number
4027 (yas/make-marker (match-beginning 0))
4028 (yas/make-marker (match-beginning 0))
4030 (yas/snippet-fields snippet))))
4031 (push (cons (match-beginning 0) (match-end 0))
4032 yas/dollar-regions))))))
4034 (defun yas/delete-regions (regions)
4035 "Sort disjuct REGIONS by start point, then delete from the back."
4036 (mapc #'(lambda (reg)
4037 (delete-region (car reg) (cdr reg)))
4040 (>= (car r1) (car r2))))))
4042 (defun yas/update-mirrors (snippet)
4043 "Updates all the mirrors of SNIPPET."
4045 (let* ((fields (copy-list (yas/snippet-fields snippet)))
4046 (field (car fields)))
4048 (dolist (mirror (yas/field-mirrors field))
4049 (let ((mirror-parent-field (yas/mirror-parent-field mirror)))
4050 ;; updatte this mirror
4052 (yas/mirror-update-display mirror field)
4053 ;; for mirrors-in-fields: schedule a possible
4054 ;; parent field for reupdting later on
4056 (when mirror-parent-field
4057 (add-to-list 'fields mirror-parent-field 'append #'eq))
4058 ;; `yas/place-overlays' is needed if the active field and
4059 ;; protected overlays have been changed because of insertions
4060 ;; in `yas/mirror-update-display'
4062 (when (eq field (yas/snippet-active-field snippet))
4063 (yas/place-overlays snippet field))))
4064 (setq fields (cdr fields))
4065 (setq field (car fields))))))
4067 (defun yas/mirror-update-display (mirror field)
4068 "Update MIRROR according to FIELD (and mirror transform)."
4070 (let* ((mirror-parent-field (yas/mirror-parent-field mirror))
4071 (reflection (and (not (and mirror-parent-field
4072 (yas/field-modified-p mirror-parent-field)))
4073 (or (yas/apply-transform mirror field 'empty-on-nil)
4074 (yas/field-text-for-display field)))))
4075 (when (and reflection
4076 (not (string= reflection (buffer-substring-no-properties (yas/mirror-start mirror)
4077 (yas/mirror-end mirror)))))
4078 (goto-char (yas/mirror-start mirror))
4079 (yas/inhibit-overlay-hooks
4080 (insert reflection))
4081 (if (> (yas/mirror-end mirror) (point))
4082 (delete-region (point) (yas/mirror-end mirror))
4083 (set-marker (yas/mirror-end mirror) (point))
4084 (yas/advance-start-maybe (yas/mirror-next mirror) (point))
4085 ;; super-special advance
4086 (yas/advance-end-of-parents-maybe mirror-parent-field (point))))))
4088 (defun yas/field-update-display (field snippet)
4089 "Much like `yas/mirror-update-display', but for fields"
4090 (when (yas/field-transform field)
4091 (let ((transformed (and (not (eq (yas/field-number field) 0))
4092 (yas/apply-transform field field)))
4094 (when (and transformed
4095 (not (string= transformed (buffer-substring-no-properties (yas/field-start field)
4096 (yas/field-end field)))))
4097 (setf (yas/field-modified-p field) t)
4098 (goto-char (yas/field-start field))
4099 (yas/inhibit-overlay-hooks
4100 (insert transformed)
4101 (if (> (yas/field-end field) (point))
4102 (delete-region (point) (yas/field-end field))
4103 (set-marker (yas/field-end field) (point))
4104 (yas/advance-start-maybe (yas/field-next field) (point)))
4108 ;;; Post-command hooks:
4110 (defvar yas/post-command-runonce-actions nil
4111 "List of actions to run once in `post-command-hook'.
4113 Each element of this list looks like (FN . ARGS) where FN is
4114 called with ARGS as its arguments after the currently executing
4117 After all actions have been run, this list is emptied, and after
4118 that the rest of `yas/post-command-handler' runs.")
4120 (defun yas/post-command-handler ()
4121 "Handles various yasnippet conditions after each command."
4122 (when yas/post-command-runonce-actions
4124 (mapc #'(lambda (fn-and-args)
4125 (apply (car fn-and-args)
4127 yas/post-command-runonce-actions)
4128 (error (message "[yas] problem running `yas/post-command-runonce-actions'!")))
4129 (setq yas/post-command-runonce-actions nil))
4130 (cond (yas/protection-violation
4131 (goto-char yas/protection-violation)
4132 (setq yas/protection-violation nil))
4133 ((eq 'undo this-command)
4135 ;; After undo revival the correct field is sometimes not
4136 ;; restored correctly, this condition handles that
4138 (let* ((snippet (car (yas/snippets-at-point)))
4139 (target-field (and snippet
4140 (find-if-not #'(lambda (field)
4141 (yas/field-probably-deleted-p snippet field))
4143 (cons (yas/snippet-active-field snippet)
4144 (yas/snippet-fields snippet)))))))
4146 (yas/move-to-field snippet target-field))))
4147 ((not (yas/undo-in-progress))
4148 ;; When not in an undo, check if we must commit the snippet
4149 ;; (user exited it).
4150 (yas/check-commit-snippet))))
4154 (put 'yas/expand 'function-documentation
4155 '(yas/expand-from-trigger-key-doc))
4156 (defun yas/expand-from-trigger-key-doc ()
4157 "A doc synthethizer for `yas/expand-from-trigger-key-doc'."
4158 (let ((fallback-description
4159 (cond ((eq yas/fallback-behavior 'call-other-command)
4160 (let* ((yas/minor-mode nil)
4161 (fallback (key-binding (read-kbd-macro yas/trigger-key))))
4163 (format " call command `%s'." (pp-to-string fallback)))
4165 ((eq yas/fallback-behavior 'return-nil)
4168 ", defer to `yas/fallback-behaviour' :-)"))))
4169 (concat "Expand a snippet before point. If no snippet
4170 expansion is possible,"
4171 fallback-description
4172 "\n\nOptional argument FIELD is for non-interactive use and is an
4173 object satisfying `yas/field-p' to restrict the expansion to.")))
4175 (put 'yas/expand-from-keymap 'function-documentation '(yas/expand-from-keymap-doc))
4176 (defun yas/expand-from-keymap-doc ()
4177 "A doc synthethizer for `yas/expand-from-keymap-doc'."
4178 (add-hook 'temp-buffer-show-hook 'yas/snippet-description-finish-runonce)
4179 (concat "Expand/run snippets from keymaps, possibly falling back to original binding.\n"
4180 (when (eq this-command 'describe-key)
4181 (let* ((vec (this-single-command-keys))
4182 (templates (mapcan #'(lambda (table)
4183 (yas/fetch table vec))
4184 (yas/get-snippet-tables)))
4185 (yas/direct-keymaps nil)
4186 (fallback (key-binding vec)))
4187 (concat "In this case, "
4189 (concat "these snippets are bound to this key:\n"
4190 (yas/template-pretty-list templates)
4191 "\n\nIf none of these expands, "))
4193 (format "fallback `%s' will be called." (pp-to-string fallback)))
4194 "no fallback keybinding is called."))))))
4196 (defun yas/template-pretty-list (templates)
4198 (yas/buffer-local-condition 'always))
4199 (dolist (plate templates)
4200 (setq acc (concat acc "\n*) "
4201 (propertize (concat "\\\\snippet `" (car plate) "'")
4202 'yasnippet (cdr plate)))))
4205 (define-button-type 'help-snippet-def
4206 :supertype 'help-xref
4207 'help-function (lambda (template) (yas/visit-snippet-file-1 template))
4208 'help-echo (purecopy "mouse-2, RET: find snippets's definition"))
4210 (defun yas/snippet-description-finish-runonce ()
4211 "Final adjustments for the help buffer when snippets are concerned."
4212 (yas/create-snippet-xrefs)
4213 (remove-hook 'temp-buffer-show-hook 'yas/snippet-description-finish-runonce))
4215 (defun yas/create-snippet-xrefs ()
4217 (goto-char (point-min))
4218 (while (search-forward-regexp "\\\\\\\\snippet[ \s\t]+`\\([^']+\\)'" nil t)
4219 (let ((template (get-text-property (match-beginning 1)
4222 (help-xref-button 1 'help-snippet-def template)
4223 (kill-region (match-end 1) (match-end 0))
4224 (kill-region (match-beginning 0) (match-beginning 1)))))))
4226 (defun yas/expand-uuid (mode-symbol uuid &optional start end expand-env)
4227 "Expand a snippet registered in MODE-SYMBOL's table with UUID.
4229 Remaining args as in `yas/expand-snippet'."
4230 (let* ((table (gethash mode-symbol yas/tables))
4231 (yas/current-template (and table
4232 (gethash uuid (yas/table-uuidhash table)))))
4233 (when yas/current-template
4234 (yas/expand-snippet (yas/template-content yas/current-template)))))
4239 ;; `locate-dominating-file'
4240 ;; `region-active-p'
4242 ;; added for compatibility in emacs < 23
4243 (unless (>= emacs-major-version 23)
4244 (unless (fboundp 'region-active-p)
4245 (defun region-active-p () (and transient-mark-mode mark-active)))
4247 (unless (fboundp 'locate-dominating-file)
4248 (defvar locate-dominating-stop-dir-regexp
4249 "\\`\\(?:[\\/][\\/][^\\/]+[\\/]\\|/\\(?:net\\|afs\\|\\.\\.\\.\\)/\\)\\'"
4250 "Regexp of directory names which stop the search in `locate-dominating-file'.
4251 Any directory whose name matches this regexp will be treated like
4252 a kind of root directory by `locate-dominating-file' which will stop its search
4253 when it bumps into it.
4254 The default regexp prevents fruitless and time-consuming attempts to find
4255 special files in directories in which filenames are interpreted as hostnames,
4256 or mount points potentially requiring authentication as a different user.")
4258 (defun locate-dominating-file (file name)
4259 "Look up the directory hierarchy from FILE for a file named NAME.
4260 Stop at the first parent directory containing a file NAME,
4261 and return the directory. Return nil if not found."
4262 ;; We used to use the above locate-dominating-files code, but the
4263 ;; directory-files call is very costly, so we're much better off doing
4264 ;; multiple calls using the code in here.
4266 ;; Represent /home/luser/foo as ~/foo so that we don't try to look for
4267 ;; `name' in /home or in /.
4268 (setq file (abbreviate-file-name file))
4271 ;; `user' is not initialized outside the loop because
4272 ;; `file' may not exist, so we may have to walk up part of the
4273 ;; hierarchy before we find the "initial UUID".
4276 (while (not (or root
4278 ;; FIXME: Disabled this heuristic because it is sometimes
4280 ;; As a heuristic, we stop looking up the hierarchy of
4281 ;; directories as soon as we find a directory belonging
4282 ;; to another user. This should save us from looking in
4283 ;; things like /net and /afs. This assumes that all the
4284 ;; files inside a project belong to the same user.
4285 ;; (let ((prev-user user))
4286 ;; (setq user (nth 2 (file-attributes file)))
4287 ;; (and prev-user (not (equal user prev-user))))
4288 (string-match locate-dominating-stop-dir-regexp file)))
4289 (setq try (file-exists-p (expand-file-name name file)))
4290 (cond (try (setq root file))
4291 ((equal file (setq prev-file file
4292 file (file-name-directory
4293 (directory-file-name file))))
4297 ;; `c-neutralize-syntax-in-CPP` sometimes fires "End of Buffer" error
4298 ;; (when it execute forward-char) and interrupt the after change
4299 ;; hook. Thus prevent the insert-behind hook of yasnippet to be
4300 ;; invoked. Here's a way to reproduce it:
4302 ;; # open a *new* Emacs.
4303 ;; # load yasnippet.
4304 ;; # open a *new* .cpp file.
4305 ;; # input "inc" and press TAB to expand the snippet.
4306 ;; # select the `#include <...>` snippet.
4307 ;; # type inside `<>`
4309 (defadvice c-neutralize-syntax-in-CPP
4310 (around yas-mp/c-neutralize-syntax-in-CPP activate)
4311 "Adviced `c-neutralize-syntax-in-CPP' to properly
4312 handle the end-of-buffer error fired in it by calling
4313 `forward-char' at the end of buffer."
4316 (error (message (error-message-string err)))))
4318 ;; disable c-electric-* serial command in YAS fields
4319 (add-hook 'c-mode-common-hook
4321 (dolist (k '(":" ">" ";" "<" "{" "}"))
4322 (define-key (symbol-value (make-local-variable 'yas/keymap))
4323 k 'self-insert-command))))
4325 (provide 'yasnippet)
4327 ;;; yasnippet.el ends here