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 nil
169 "Directory or list of snippet dirs for each major mode.
171 The directory where user-created snippets are to be stored. Can
172 also be a list of directories. In that case, when used for
173 bulk (re)loading of snippets (at startup or via
174 `yas/reload-all'), directories appearing earlier in the list
175 shadow other dir's snippets. Also, the first directory is taken
176 as the default for storing the user's new snippets."
177 :type '(choice (string :tag "Single directory (string)")
178 (repeat :args (string) :tag "List of directories (strings)"))
181 :set #'(lambda (symbol new)
182 (let ((old (and (boundp symbol)
183 (symbol-value symbol))))
184 (set-default symbol new)
185 (unless (or (not (fboundp 'yas/reload-all))
188 (defun yas/snippet-dirs ()
189 (if (listp yas/snippet-dirs) yas/snippet-dirs (list yas/snippet-dirs)))
190 (defvaralias 'yas/root-directory 'yas/snippet-dirs)
192 (defcustom yas/prompt-functions '(yas/x-prompt
194 yas/completing-prompt
197 "Functions to prompt for keys, templates, etc interactively.
199 These functions are called with the following arguments:
201 - PROMPT: A string to prompt the user
203 - CHOICES: a list of strings or objects.
205 - optional DISPLAY-FN : A function that, when applied to each of
206 the objects in CHOICES will return a string.
208 The return value of any function you put here should be one of
209 the objects in CHOICES, properly formatted with DISPLAY-FN (if
212 - To signal that your particular style of prompting is
213 unavailable at the moment, you can also have the function return
216 - To signal that the user quit the prompting process, you can
219 (signal 'quit \"user quit!\")."
220 :type '(repeat function)
223 (defcustom yas/indent-line 'auto
224 "Controls indenting applied to a recent snippet expansion.
226 The following values are possible:
228 - `fixed' Indent the snippet to the current column;
230 - `auto' Indent each line of the snippet with `indent-according-to-mode'
232 Every other value means don't apply any snippet-side indendation
233 after expansion (the manual per-line \"$>\" indentation still
235 :type '(choice (const :tag "Nothing" nothing)
236 (const :tag "Fixed" fixed)
237 (const :tag "Auto" auto))
240 (defcustom yas/also-auto-indent-first-line nil
241 "Non-nil means also auto indent first line according to mode.
243 Naturally this is only valid when `yas/indent-line' is `auto'"
247 (defcustom yas/snippet-revival t
248 "Non-nil means re-activate snippet fields after undo/redo."
252 (defcustom yas/trigger-key "TAB"
253 "The key bound to `yas/expand' when function `yas/minor-mode' is active.
255 Value is a string that is converted to the internal Emacs key
256 representation using `read-kbd-macro'."
259 :set #'(lambda (symbol key)
260 (let ((old (and (boundp symbol)
261 (symbol-value symbol))))
262 (set-default symbol key)
263 ;; On very first loading of this defcustom,
264 ;; `yas/trigger-key' is *not* loaded.
265 (if (fboundp 'yas/trigger-key-reload)
266 (yas/trigger-key-reload old)))))
268 (defcustom yas/next-field-key '("TAB" "<tab>")
269 "The key to navigate to next field when a snippet is active.
271 Value is a string that is converted to the internal Emacs key
272 representation using `read-kbd-macro'.
274 Can also be a list of strings."
275 :type '(choice (string :tag "String")
276 (repeat :args (string) :tag "List of strings"))
278 :set #'(lambda (symbol val)
279 (set-default symbol val)
280 (if (fboundp 'yas/init-yas-in-snippet-keymap)
281 (yas/init-yas-in-snippet-keymap))))
284 (defcustom yas/prev-field-key '("<backtab>" "<S-tab>")
285 "The key to navigate to previous field when a snippet is active.
287 Value is a string that is converted to the internal Emacs key
288 representation using `read-kbd-macro'.
290 Can also be a list of strings."
291 :type '(choice (string :tag "String")
292 (repeat :args (string) :tag "List of strings"))
294 :set #'(lambda (symbol val)
295 (set-default symbol val)
296 (if (fboundp 'yas/init-yas-in-snippet-keymap)
297 (yas/init-yas-in-snippet-keymap))))
299 (defcustom yas/skip-and-clear-key "C-d"
300 "The key to clear the currently active field.
302 Value is a string that is converted to the internal Emacs key
303 representation using `read-kbd-macro'.
305 Can also be a list of strings."
306 :type '(choice (string :tag "String")
307 (repeat :args (string) :tag "List of strings"))
309 :set #'(lambda (symbol val)
310 (set-default symbol val)
311 (if (fboundp 'yas/init-yas-in-snippet-keymap)
312 (yas/init-yas-in-snippet-keymap))))
314 (defcustom yas/triggers-in-field nil
315 "If non-nil, `yas/next-field-key' can trigger stacked expansions.
317 Otherwise, `yas/next-field-key' just tries to move on to the next
322 (defcustom yas/fallback-behavior 'call-other-command
323 "How to act when `yas/trigger-key' does *not* expand a snippet.
325 - `call-other-command' means try to temporarily disable YASnippet
326 and call the next command bound to `yas/trigger-key'.
328 - nil or the symbol `return-nil' mean do nothing. (and
329 `yas/expand-returns' nil)
331 - A lisp form (apply COMMAND . ARGS) means interactively call
332 COMMAND, if ARGS is non-nil, call COMMAND non-interactively
333 with ARGS as arguments."
334 :type '(choice (const :tag "Call previous command" call-other-command)
335 (const :tag "Do nothing" return-nil))
338 (defcustom yas/choose-keys-first nil
339 "If non-nil, prompt for snippet key first, then for template.
341 Otherwise prompts for all possible snippet names.
343 This affects `yas/insert-snippet' and `yas/visit-snippet-file'."
347 (defcustom yas/choose-tables-first nil
348 "If non-nil, and multiple eligible snippet tables, prompts user for tables first.
350 Otherwise, user chooses between the merging together of all
353 This affects `yas/insert-snippet', `yas/visit-snippet-file'"
357 (defcustom yas/use-menu 'abbreviate
358 "Display a YASnippet menu in the menu bar.
360 When non-nil, submenus for each snippet table will be listed
361 under the menu \"Yasnippet\".
363 - If set to `real-modes' only submenus whose name more or less
364 corresponds to a major mode are listed.
366 - If set to `abbreviate', only the current major-mode
367 menu and the modes set in `yas/extra-modes' are listed.
369 Any other non-nil value, every submenu is listed."
370 :type '(choice (const :tag "Full" t)
371 (const :tag "Real modes only" real-modes)
372 (const :tag "Abbreviate" abbreviate))
375 (defcustom yas/trigger-symbol " =>"
376 "The text that will be used in menu to represent the trigger."
380 (defcustom yas/wrap-around-region nil
381 "If non-nil, snippet expansion wraps around selected region.
383 The wrapping occurs just before the snippet's exit marker. This
384 can be overriden on a per-snippet basis."
388 (defcustom yas/good-grace t
389 "If non-nil, don't raise errors in inline elisp evaluation.
391 An error string \"[yas] error\" is returned instead."
395 (defcustom yas/ignore-filenames-as-triggers nil
396 "If non-nil, don't derive tab triggers from filenames.
398 This means a snippet without a \"# key:'\ directive won't have a
403 (defcustom yas/visit-from-menu nil
404 "If non-nil visit snippets's files from menu, instead of expanding them.
406 This cafn only work when snippets are loaded from files."
410 (defcustom yas/expand-only-for-last-commands nil
411 "List of `last-command' values to restrict tab-triggering to, or nil.
413 Leave this set at nil (the default) to be able to trigger an
414 expansion simply by placing the cursor after a valid tab trigger,
415 using whichever commands.
417 Optionallly, set this to something like '(self-insert-command) if
418 you to wish restrict expansion to only happen when the last
419 letter of the snippet tab trigger was typed immediately before
420 the trigger key itself."
421 :type '(repeat function)
424 ;; Only two faces, and one of them shouldn't even be used...
426 (defface yas/field-highlight-face
427 '((t (:inherit 'region)))
428 "The face used to highlight the currently active field of a snippet"
431 (defface yas/field-debug-face
433 "The face used for debugging some overlays normally hidden"
437 ;;; User can also customize the next defvars
438 (defun yas/define-some-keys (keys keymap definition)
439 "Bind KEYS to DEFINITION in KEYMAP, read with `read-kbd-macro'."
440 (let ((keys (or (and (listp keys) keys)
443 (define-key keymap (read-kbd-macro key) definition))))
446 (let ((map (make-sparse-keymap)))
447 (mapc #'(lambda (binding)
448 (yas/define-some-keys (car binding) map (cdr binding)))
449 `((,yas/next-field-key . yas/next-field-or-maybe-expand)
450 (,yas/prev-field-key . yas/prev-field)
451 ("C-g" . yas/abort-snippet)
452 (,yas/skip-and-clear-key . yas/skip-and-clear-or-delete-char)))
454 "The keymap active while a snippet expansion is in progress.")
456 (defvar yas/key-syntaxes (list "w" "w_" "w_.()" "^ ")
457 "A list of syntax of a key. This list is tried in the order
458 to try to find a key. For example, if the list is '(\"w\" \"w_\").
459 And in emacs-lisp-mode, where \"-\" has the syntax of \"_\":
463 will first try \"bar\", if not found, then \"foo-bar\" is tried.")
465 (defvar yas/after-exit-snippet-hook
467 "Hooks to run after a snippet exited.
469 The hooks will be run in an environment where some variables bound to
472 `yas/snippet-beg' : The beginning of the region of the snippet.
474 `yas/snippet-end' : Similar to beg.
476 Attention: These hooks are not run when exiting nested/stackd snippet expansion!")
478 (defvar yas/before-expand-snippet-hook
480 "Hooks to run just before expanding a snippet.")
482 (defvar yas/buffer-local-condition
483 '(if (and (or (fourth (syntax-ppss))
484 (fifth (syntax-ppss)))
485 (eq (symbol-function this-command) 'yas/expand-from-trigger-key))
486 '(require-snippet-condition . force-in-comment)
488 "Snippet expanding condition.
490 This variable is a lisp form:
492 * If it evaluates to nil, no snippets can be expanded.
494 * If it evaluates to the a cons (require-snippet-condition
497 * Snippets bearing no \"# condition:\" directive are not
500 * Snippets bearing conditions that evaluate to nil (or
501 produce an error) won't be onsidered.
503 * If the snippet has a condition that evaluates to non-nil
506 * If REQUIREMENT is t, the snippet is considered
508 * If REQUIREMENT is `eq' RESULT, the snippet is
511 * Otherwise, the snippet is not considered.
513 * If it evaluates to the symbol 'always, all snippets are
514 considered for expansion, regardless of any conditions.
516 * If it evaluates to t or some other non-nil value
518 * Snippet bearing no conditions, or conditions that
519 evaluate to non-nil, are considered for expansion.
521 * Otherwise, the snippet is not considered.
523 Here's an example preventing snippets from being expanded from
524 inside comments, in `python-mode' only, with the exception of
525 snippets returning the symbol 'force-in-comment in their
528 (add-hook 'python-mode-hook
530 (setq yas/buffer-local-condition
531 '(if (python-in-string/comment)
532 '(require-snippet-condition . force-in-comment)
535 The default value is similar, it filters out potential snippet
536 expansions inside comments and string literals, unless the
537 snippet itself contains a condition that returns the symbol
538 `force-in-comment'.")
541 ;;; Internal variables
543 (defvar yas/version "0.7.0")
545 (defvar yas/menu-table (make-hash-table)
546 "A hash table of MAJOR-MODE symbols to menu keymaps.")
552 (defvar yas/known-modes
553 '(ruby-mode rst-mode markdown-mode)
554 "A list of mode which is well known but not part of emacs.")
556 (defvar yas/escaped-characters
557 '(?\\ ?` ?' ?$ ?} ?\( ?\))
558 "List of characters which *might* need to be escaped.")
560 (defconst yas/field-regexp
561 "${\\([0-9]+:\\)?\\([^}]*\\)}"
562 "A regexp to *almost* recognize a field.")
564 (defconst yas/multi-dollar-lisp-expression-regexp
565 "$+[ \t\n]*\\(([^)]*)\\)"
566 "A regexp to *almost* recognize a \"$(...)\" expression.")
568 (defconst yas/backquote-lisp-expression-regexp
570 "A regexp to recognize a \"`lisp-expression`\" expression." )
572 (defconst yas/transform-mirror-regexp
573 "${\\(?:\\([0-9]+\\):\\)?$\\([ \t\n]*([^}]*\\)"
574 "A regexp to *almost* recognize a mirror with a transform.")
576 (defconst yas/simple-mirror-regexp
578 "A regexp to recognize a simple mirror.")
580 (defvar yas/snippet-id-seed 0
581 "Contains the next id for a snippet.")
583 (defun yas/snippet-next-id ()
584 (let ((id yas/snippet-id-seed))
585 (incf yas/snippet-id-seed)
591 ;; XXX: `last-buffer-undo-list' is somehow needed in Carbon Emacs for MacOSX
592 (defvar last-buffer-undo-list nil)
594 (defvar yas/minor-mode-menu nil
595 "Holds the YASnippet menu")
597 (defun yas/init-minor-keymap ()
598 (let ((map (make-sparse-keymap)))
599 (easy-menu-define yas/minor-mode-menu
601 "Menu used when YAS/minor-mode is active."
604 ["Expand trigger" yas/expand
605 :help "Possibly expand tab trigger before point"]
606 ["Insert at point..." yas/insert-snippet
607 :help "Prompt for an expandable snippet and expand it at point"]
608 ["New snippet..." yas/new-snippet
609 :help "Create a new snippet in an appropriate directory"]
610 ["Visit snippet file..." yas/visit-snippet-file
611 :help "Prompt for an expandable snippet and find its file"]
612 ["Find snippets..." yas/find-snippets
613 :help "Invoke `find-file' in the appropriate snippet directory"]
615 ("Snippet menu behaviour"
616 ["Visit snippets" (setq yas/visit-from-menu t)
617 :help "Visit snippets from the menu"
618 :active t :style radio :selected yas/visit-from-menu]
619 ["Expand snippets" (setq yas/visit-from-menu nil)
620 :help "Expand snippets from the menu"
621 :active t :style radio :selected (not yas/visit-from-menu)]
623 ["Show \"Real\" modes only" (setq yas/use-menu 'real-modes)
624 :help "Show snippet submenus for modes that appear to be real major modes"
625 :active t :style radio :selected (eq yas/use-menu 'real-modes)]
626 ["Show all modes" (setq yas/use-menu 't)
627 :help "Show one snippet submenu for each loaded table"
628 :active t :style radio :selected (eq yas/use-menu 't)]
629 ["Abbreviate according to current mode" (setq yas/use-menu 'abbreviate)
630 :help "Show only snippet submenus for the current active modes"
631 :active t :style radio :selected (eq yas/use-menu 'abbreviate)])
633 ["Auto" (setq yas/indent-line 'auto)
634 :help "Indent each line of the snippet with `indent-according-to-mode'"
635 :active t :style radio :selected (eq yas/indent-line 'auto)]
636 ["Fixed" (setq yas/indent-line 'fixed)
637 :help "Indent the snippet to the current column"
638 :active t :style radio :selected (eq yas/indent-line 'fixed)]
639 ["None" (setq yas/indent-line 'none)
640 :help "Don't apply any particular snippet indentation after expansion"
641 :active t :style radio :selected (not (member yas/indent-line '(fixed auto)))]
643 ["Also auto indent first line" (setq yas/also-auto-indent-first-line
644 (not yas/also-auto-indent-first-line))
645 :help "When auto-indenting also, auto indent the first line menu"
646 :active (eq yas/indent-line 'auto)
647 :style toggle :selected yas/also-auto-indent-first-line]
650 ["System X-widget" (setq yas/prompt-functions
652 (remove 'yas/x-prompt
653 yas/prompt-functions)))
654 :help "Use your windowing system's (gtk, mac, windows, etc...) default menu"
655 :active t :style radio :selected (eq (car yas/prompt-functions)
657 ["Dropdown-list" (setq yas/prompt-functions
658 (cons 'yas/dropdown-prompt
659 (remove 'yas/dropdown-prompt
660 yas/prompt-functions)))
661 :help "Use a special dropdown list"
662 :active t :style radio :selected (eq (car yas/prompt-functions)
663 'yas/dropdown-prompt)]
664 ["Ido" (setq yas/prompt-functions
665 (cons 'yas/ido-prompt
666 (remove 'yas/ido-prompt
667 yas/prompt-functions)))
668 :help "Use an ido-style minibuffer prompt"
669 :active t :style radio :selected (eq (car yas/prompt-functions)
671 ["Completing read" (setq yas/prompt-functions
672 (cons 'yas/completing-prompt
673 (remove 'yas/completing-prompt-prompt
674 yas/prompt-functions)))
675 :help "Use a normal minibuffer prompt"
676 :active t :style radio :selected (eq (car yas/prompt-functions)
677 'yas/completing-prompt-prompt)]
680 ["Wrap region in exit marker"
681 (setq yas/wrap-around-region
682 (not yas/wrap-around-region))
683 :help "If non-nil automatically wrap the selected text in the $0 snippet exit"
684 :style toggle :selected yas/wrap-around-region]
685 ["Allow stacked expansions "
686 (setq yas/triggers-in-field
687 (not yas/triggers-in-field))
688 :help "If non-nil allow snippets to be triggered inside other snippet fields"
689 :style toggle :selected yas/triggers-in-field]
690 ["Revive snippets on undo "
691 (setq yas/snippet-revival
692 (not yas/snippet-revival))
693 :help "If non-nil allow snippets to become active again after undo"
694 :style toggle :selected yas/snippet-revival]
697 (not yas/good-grace))
698 :help "If non-nil don't raise errors in bad embedded eslip in snippets"
699 :style toggle :selected yas/good-grace]
700 ["Ignore filenames as triggers"
701 (setq yas/ignore-filenames-as-triggers
702 (not yas/ignore-filenames-as-triggers))
703 :help "If non-nil don't derive tab triggers from filenames"
704 :style toggle :selected yas/ignore-filenames-as-triggers]
707 ["Load snippets..." yas/load-directory
708 :help "Load snippets from a specific directory"]
709 ["Reload everything" yas/reload-all
710 :help "Cleanup stuff, reload snippets, rebuild menus"]
712 :help "Display some information about YASsnippet"]))
713 ;; Now for the stuff that has direct keybindings
715 (define-key map "\C-c&\C-s" 'yas/insert-snippet)
716 (define-key map "\C-c&\C-n" 'yas/new-snippet)
717 (define-key map "\C-c&\C-v" 'yas/visit-snippet-file)
718 (define-key map "\C-c&\C-f" 'yas/find-snippets)
721 (defvar yas/minor-mode-map (yas/init-minor-keymap)
722 "The keymap used when `yas/minor-mode' is active.")
724 (defun yas/trigger-key-reload (&optional unbind-key)
725 "Rebind `yas/expand' to the new value of `yas/trigger-key'.
727 With optional UNBIND-KEY, try to unbind that key from
728 `yas/minor-mode-map'."
729 (when (and unbind-key
731 (not (string= unbind-key "")))
732 (define-key yas/minor-mode-map (read-kbd-macro unbind-key) nil))
733 (when (and yas/trigger-key
734 (stringp yas/trigger-key)
735 (not (string= yas/trigger-key "")))
736 (define-key yas/minor-mode-map (read-kbd-macro yas/trigger-key) 'yas/expand)))
738 (defvar yas/tables (make-hash-table)
739 "A hash table of MAJOR-MODE symbols to `yas/table' objects.")
741 (defvar yas/direct-keymaps (list)
742 "Keymap alist supporting direct snippet keybindings.
744 This variable is is placed `emulation-mode-map-alists'.
746 Its elements looks like (TABLE-NAME . KEYMAP) and are
747 calculated when loading snippets. TABLE-NAME is a variable
748 set buffer-locally when entering `yas/minor-mode'. KEYMAP binds
749 all defined direct keybindings to the command
750 `yas/expand-from-keymap', which acts similarly to `yas/expand'")
752 (defun yas/direct-keymaps-reload ()
753 "Force reload the direct keybinding for active snippet tables."
755 (setq yas/direct-keymaps nil)
756 (maphash #'(lambda (name table)
757 (mapc #'(lambda (table)
758 (push (cons (intern (format "yas//direct-%s" name))
759 (yas/table-direct-keymap table))
761 (cons table (yas/table-get-all-parents table))))
764 (defun yas/direct-keymaps-set-vars ()
765 (let ((modes-to-activate (list major-mode))
767 (while (setq mode (get mode 'derived-mode-parent))
768 (push mode modes-to-activate))
769 (dolist (mode (yas/extra-modes))
770 (push mode modes-to-activate))
771 (dolist (mode modes-to-activate)
772 (let ((name (intern (format "yas//direct-%s" mode))))
773 (set-default name nil)
774 (set (make-local-variable name) t)))))
776 (defvar yas/minor-mode-hook nil
777 "Hook run when yas/minor-mode is turned on")
780 (define-minor-mode yas/minor-mode
781 "Toggle YASnippet mode.
783 When YASnippet mode is enabled, the `tas/trigger-key' key expands
784 snippets of code depending on the mode.
786 With no argument, this command toggles the mode.
787 positive prefix argument turns on the mode.
788 Negative prefix argument turns off the mode.
790 You can customize the key through `yas/trigger-key'.
793 \\{yas/minor-mode-map}"
795 ;; The indicator for the mode line.
798 (cond (yas/minor-mode
799 ;; Reload the trigger key
801 (yas/trigger-key-reload)
802 ;; Load all snippets definitions unless we still don't have a
803 ;; root-directory or some snippets have already been loaded.
805 (unless (or (null yas/snippet-dirs)
806 (> (hash-table-count yas/tables) 0))
808 ;; Install the direct keymaps in `emulation-mode-map-alists'
809 ;; (we use `add-hook' even though it's not technically a hook,
810 ;; but it works). Then define variables named after modes to
811 ;; index `yas/direct-keymaps'.
813 ;; Also install the post-command-hook.
815 (add-hook 'emulation-mode-map-alists 'yas/direct-keymaps)
816 (add-hook 'post-command-hook 'yas/post-command-handler nil t)
817 (add-hook 'yas/minor-mode-hook 'yas/direct-keymaps-set-vars-runonce 'append))
819 ;; Uninstall the direct keymaps and the post-command hook
821 (remove-hook 'post-command-hook 'yas/post-command-handler t)
822 (remove-hook 'emulation-mode-map-alists 'yas/direct-keymaps))))
824 (defun yas/direct-keymaps-set-vars-runonce ()
825 (yas/direct-keymaps-set-vars)
826 (remove-hook 'yas/minor-mode-hook 'yas/direct-keymaps-set-vars-runonce))
828 (defvar yas/dont-activate #'(lambda ()
829 (and yas/snippet-dirs
830 (null (yas/get-snippet-tables))))
831 "If non-nil don't let `yas/minor-mode-on' active yas for this buffer.
833 `yas/minor-mode-on' is usually called by `yas/global-mode' so
834 this effectively lets you define exceptions to the \"global\"
836 (make-variable-buffer-local 'yas/dont-activate)
838 (defun yas/minor-mode-on ()
839 "Turn on YASnippet minor mode.
841 Do this unless `yas/dont-activate' is t "
843 (unless (or (minibufferp)
844 (and (functionp yas/dont-activate)
845 (funcall yas/dont-activate))
846 (and (not (functionp yas/dont-activate))
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/fetch (table key)
1090 "Fetch templates in TABLE by KEY.
1092 Return a list of cons (NAME . TEMPLATE) where NAME is a
1093 string and TEMPLATE is a `yas/template' structure."
1094 (let* ((keyhash (yas/table-hash table))
1095 (namehash (and keyhash (gethash key keyhash))))
1097 (yas/filter-templates-by-condition
1099 (maphash #'(lambda (k v)
1100 (push (cons k v) alist))
1105 ;;; Filtering/condition logic
1107 (defun yas/eval-condition (condition)
1114 (message (format "[yas] error in condition evaluation: %s"
1115 (error-message-string err)))
1119 (defun yas/filter-templates-by-condition (templates)
1120 "Filter the templates using the applicable condition.
1122 TEMPLATES is a list of cons (NAME . TEMPLATE) where NAME is a
1123 string and TEMPLATE is a `yas/template' structure.
1125 This function implements the rules described in
1126 `yas/buffer-local-condition'. See that variables documentation."
1127 (let ((requirement (yas/require-template-specific-condition-p)))
1128 (if (eq requirement 'always)
1130 (remove-if-not #'(lambda (pair)
1131 (yas/template-can-expand-p
1132 (yas/template-condition (cdr pair)) requirement))
1135 (defun yas/require-template-specific-condition-p ()
1136 "Decides if this buffer requests/requires snippet-specific
1137 conditions to filter out potential expansions."
1138 (if (eq 'always yas/buffer-local-condition)
1140 (let ((local-condition (or (and (consp yas/buffer-local-condition)
1141 (yas/eval-condition yas/buffer-local-condition))
1142 yas/buffer-local-condition)))
1143 (when local-condition
1144 (if (eq local-condition t)
1146 (and (consp local-condition)
1147 (eq 'require-snippet-condition (car local-condition))
1148 (symbolp (cdr local-condition))
1149 (cdr local-condition)))))))
1151 (defun yas/template-can-expand-p (condition requirement)
1152 "Evaluates CONDITION and REQUIREMENT and returns a boolean"
1153 (let* ((result (or (null condition)
1154 (yas/eval-condition condition))))
1155 (cond ((eq requirement t)
1158 (eq requirement result)))))
1160 (defun yas/table-get-all-parents (table)
1161 "Returns a list of all parent tables of TABLE"
1162 (let ((parents (yas/table-parents table)))
1164 (append (copy-list parents)
1165 (mapcan #'yas/table-get-all-parents parents)))))
1167 (defun yas/table-templates (table)
1170 (maphash #'(lambda (key namehash)
1171 (maphash #'(lambda (name template)
1172 (push (cons name template) acc))
1174 (yas/table-hash table))
1175 (yas/filter-templates-by-condition acc))))
1177 (defun yas/current-key ()
1178 "Get the key under current position. A key is used to find
1179 the template of a snippet in the current snippet-table."
1180 (let ((start (point))
1182 (syntaxes yas/key-syntaxes)
1186 (while (and (not done) syntaxes)
1187 (setq syntax (car syntaxes))
1188 (setq syntaxes (cdr syntaxes))
1190 (skip-syntax-backward syntax)
1191 (setq start (point)))
1193 (mapcan #'(lambda (table)
1194 (yas/fetch table (buffer-substring-no-properties start end)))
1195 (yas/get-snippet-tables)))
1204 (defun yas/table-all-keys (table)
1207 (maphash #'(lambda (key templates)
1208 (when (yas/filter-templates-by-condition templates)
1210 (yas/table-hash table))
1214 ;;; Internal functions
1216 (defun yas/real-mode? (mode)
1217 "Try to find out if MODE is a real mode. The MODE bound to
1218 a function (like `c-mode') is considered real mode. Other well
1219 known mode like `ruby-mode' which is not part of Emacs might
1220 not bound to a function until it is loaded. So yasnippet keeps
1221 a list of modes like this to help the judgement."
1223 (find mode yas/known-modes)))
1225 (defun yas/eval-lisp (form)
1226 "Evaluate FORM and convert the result to string."
1227 (let ((retval (catch 'yas/exception
1233 (let ((result (eval form)))
1235 (format "%s" result))))))
1236 (error (if yas/good-grace
1237 (format "[yas] elisp error! %s" (error-message-string err))
1238 (error (format "[yas] elisp error: %s"
1239 (error-message-string err)))))))))
1240 (when (and (consp retval)
1241 (eq 'yas/exception (car retval)))
1242 (error (cdr retval)))
1245 (defun yas/eval-lisp-no-saves (form)
1248 (error (if yas/good-grace
1249 (format "[yas] elisp error! %s" (error-message-string err))
1250 (error (format "[yas] elisp error: %s"
1251 (error-message-string err)))))))
1253 (defun yas/read-lisp (string &optional nil-on-error)
1254 "Read STRING as a elisp expression and return it.
1256 In case STRING in an invalid expression and NIL-ON-ERROR is nil,
1257 return an expression that when evaluated will issue an error."
1260 (error (and (not nil-on-error)
1261 `(error (error-message-string err))))))
1263 (defun yas/read-keybinding (keybinding)
1264 "Read KEYBINDING as a snippet keybinding, return a vector."
1265 (when (and keybinding
1266 (not (string-match "keybinding" keybinding)))
1268 (let ((res (or (and (string-match "^\\[.*\\]$" keybinding)
1270 (read-kbd-macro keybinding 'need-vector))))
1273 (message "[yas] warning: keybinding \"%s\" invalid since %s."
1274 keybinding (error-message-string err))
1277 (defvar yas/extra-modes nil
1278 "If non-nil, also lookup snippets for this/these modes.
1280 Can be a symbol or a list of symbols.
1282 This variable probably makes more sense as buffer-local, so
1283 ensure your use `make-local-variable' when you set it.")
1284 (defun yas/extra-modes ()
1285 (if (listp yas/extra-modes) yas/extra-modes (list yas/extra-modes)))
1286 (defvaralias 'yas/mode-symbol 'yas/extra-modes)
1288 (defun yas/table-get-create (mode)
1289 "Get the snippet table corresponding to MODE.
1291 Optional DIRECTORY gets recorded as the default directory to
1292 search for snippet files if the retrieved/created table didn't
1293 already have such a property."
1294 (let ((table (gethash mode
1297 (setq table (yas/make-snippet-table (symbol-name mode)))
1298 (puthash mode table yas/tables)
1299 (aput 'yas/direct-keymaps (intern (format "yas//direct-%s" mode))
1300 (yas/table-direct-keymap table)))
1303 (defun yas/get-snippet-tables (&optional mode-symbol dont-search-parents)
1304 "Get snippet tables for current buffer.
1306 Return a list of 'yas/table' objects indexed by mode.
1308 The modes are tried in this order: optional MODE-SYMBOL, then
1309 `yas/extra-modes', then `major-mode' then, unless
1310 DONT-SEARCH-PARENTS is non-nil, the guessed parent mode of either
1311 MODE-SYMBOL or `major-mode'.
1313 Guessing is done by looking up the MODE-SYMBOL's
1314 `derived-mode-parent' property, see also `derived-mode-p'."
1317 (mapcar #'(lambda (mode)
1318 (gethash mode yas/tables))
1319 (remove nil (append (list mode-symbol)
1322 (and (not dont-search-parents)
1324 'derived-mode-parent)))))))))
1327 (mapcan #'yas/table-get-all-parents mode-tables)))))
1329 (defun yas/menu-keymap-get-create (table)
1330 "Get or create the main menu keymap correspondong to MODE.
1332 This may very well create a plethora of menu keymaps and arrange
1333 them in all `yas/menu-table'"
1334 (let* ((mode (intern (yas/table-name table)))
1335 (menu-keymap (or (gethash mode yas/menu-table)
1336 (puthash mode (make-sparse-keymap) yas/menu-table)))
1337 (parents (yas/table-parents table)))
1338 (mapc #'yas/menu-keymap-get-create parents)
1339 (define-key yas/minor-mode-menu (vector mode)
1340 `(menu-item ,(symbol-name mode) ,menu-keymap
1341 :visible (yas/show-menu-p ',mode)))
1344 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1345 ;;; Template-related and snippet loading functions
1347 (defun yas/parse-template (&optional file)
1348 "Parse the template in the current buffer.
1350 Optional FILE is the absolute file name of the file being
1353 Optional GROUP is the group where the template is to go,
1354 otherwise we attempt to calculate it from FILE.
1356 Return a snippet-definition, i.e. a list
1358 (KEY TEMPLATE NAME CONDITION GROUP VARS FILE KEYBINDING UUID)
1360 If the buffer contains a line of \"# --\" then the contents above
1361 this line are ignored. Directives can set most of these with the syntax:
1363 # directive-name : directive-value
1365 Here's a list of currently recognized directives:
1376 (goto-char (point-min))
1377 (let* ((type 'snippet)
1379 (file-name-nondirectory file)))
1380 (key (unless yas/ignore-filenames-as-triggers
1382 (file-name-sans-extension name))))
1387 (yas/calculate-group file)))
1391 (if (re-search-forward "^# --\n" nil t)
1392 (progn (setq template
1393 (buffer-substring-no-properties (point)
1395 (setq bound (point))
1396 (goto-char (point-min))
1397 (while (re-search-forward "^# *\\([^ ]+?\\) *: *\\(.*\\)$" bound t)
1398 (when (string= "uuid" (match-string-no-properties 1))
1399 (setq uuid (match-string-no-properties 2)))
1400 (when (string= "type" (match-string-no-properties 1))
1401 (setq type (if (string= "command" (match-string-no-properties 2))
1404 (when (string= "key" (match-string-no-properties 1))
1405 (setq key (match-string-no-properties 2)))
1406 (when (string= "name" (match-string-no-properties 1))
1407 (setq name (match-string-no-properties 2)))
1408 (when (string= "condition" (match-string-no-properties 1))
1409 (setq condition (yas/read-lisp (match-string-no-properties 2))))
1410 (when (string= "group" (match-string-no-properties 1))
1411 (setq group (match-string-no-properties 2)))
1412 (when (string= "expand-env" (match-string-no-properties 1))
1413 (setq expand-env (yas/read-lisp (match-string-no-properties 2)
1415 (when (string= "binding" (match-string-no-properties 1))
1416 (setq binding (match-string-no-properties 2)))))
1418 (buffer-substring-no-properties (point-min) (point-max))))
1419 (when (eq type 'command)
1420 (setq template (yas/read-lisp (concat "(progn" template ")"))))
1422 (setq group (split-string group "\\.")))
1423 (list key template name condition group expand-env file binding uuid)))
1425 (defun yas/calculate-group (file)
1426 "Calculate the group for snippet file path FILE."
1427 (let* ((dominating-dir (locate-dominating-file file
1428 ".yas-make-groups"))
1429 (extra-path (and dominating-dir
1430 (replace-regexp-in-string (concat "^"
1431 (expand-file-name dominating-dir))
1433 (expand-file-name file))))
1434 (extra-dir (and extra-path
1435 (file-name-directory extra-path)))
1436 (group (and extra-dir
1437 (replace-regexp-in-string "/"
1439 (directory-file-name extra-dir)))))
1442 (defun yas/subdirs (directory &optional file?)
1443 "Return subdirs or files of DIRECTORY according to FILE?."
1444 (remove-if (lambda (file)
1445 (or (string-match "^\\."
1446 (file-name-nondirectory file))
1447 (string-match "^#.*#$"
1448 (file-name-nondirectory file))
1450 (file-name-nondirectory file))
1452 (file-directory-p file)
1453 (not (file-directory-p file)))))
1454 (directory-files directory t)))
1456 (defun yas/make-menu-binding (template)
1457 (let ((mode (intern (yas/table-name (yas/template-table template)))))
1458 `(lambda () (interactive) (yas/expand-or-visit-from-menu ',mode ,(yas/template-uuid template)))))
1460 (defun yas/expand-or-visit-from-menu (mode uuid)
1461 (let* ((table (yas/table-get-create mode))
1462 (yas/current-template (and table
1463 (gethash uuid (yas/table-uuidhash table)))))
1464 (when yas/current-template
1465 (if yas/visit-from-menu
1466 (yas/visit-snippet-file-1 yas/current-template)
1467 (let ((where (if (region-active-p)
1468 (cons (region-beginning) (region-end))
1469 (cons (point) (point)))))
1470 (yas/expand-snippet (yas/template-content yas/current-template)
1474 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1475 ;; Popping up for keys and templates
1477 (defun yas/prompt-for-template (templates &optional prompt)
1478 "Interactively choose a template from the list TEMPLATES.
1480 TEMPLATES is a list of `yas/template'."
1483 (sort templates #'(lambda (t1 t2)
1484 (< (length (yas/template-name t1))
1485 (length (yas/template-name t2))))))
1486 (if yas/x-pretty-prompt-templates
1487 (yas/x-pretty-prompt-templates "Choose a snippet" templates)
1488 (some #'(lambda (fn)
1489 (funcall fn (or prompt "Choose a snippet: ")
1491 #'yas/template-name))
1492 yas/prompt-functions))))
1494 (defun yas/prompt-for-keys (keys &optional prompt)
1495 "Interactively choose a template key from the list KEYS."
1497 (some #'(lambda (fn)
1498 (funcall fn (or prompt "Choose a snippet key: ") keys))
1499 yas/prompt-functions)))
1501 (defun yas/prompt-for-table (tables &optional prompt)
1503 (some #'(lambda (fn)
1504 (funcall fn (or prompt "Choose a snippet table: ")
1507 yas/prompt-functions)))
1509 (defun yas/x-prompt (prompt choices &optional display-fn)
1510 "Display choices in a x-window prompt."
1511 ;; FIXME: HACK: if we notice that one of the objects in choices is
1512 ;; actually a `yas/template', defer to `yas/x-prompt-pretty-templates'
1514 ;; This would be better implemented by passing CHOICES as a
1515 ;; strucutred tree rather than a list. Modifications would go as far
1516 ;; up as `yas/all-templates' I think.
1518 (when (and window-system choices)
1520 (let (menu d) ;; d for display
1522 (setq d (or (and display-fn (funcall display-fn c))
1525 (push (cons (concat " " d) c) menu))
1527 (push (car d) menu))))
1528 (setq menu (list prompt (push "title" menu)))
1529 (x-popup-menu (if (fboundp 'posn-at-point)
1530 (let ((x-y (posn-x-y (posn-at-point (point)))))
1531 (list (list (+ (car x-y) 10)
1539 (defvar yas/x-pretty-prompt-templates nil
1540 "If non-nil, attempt to prompt for templates like TextMate.")
1541 (defun yas/x-pretty-prompt-templates (prompt templates)
1542 "Display TEMPLATES, grouping neatly by table name."
1543 (let ((pretty-alist (list))
1547 (dolist (tl templates)
1548 (aput 'pretty-alist (yas/template-table tl) (cons tl (aget pretty-alist (yas/template-table tl)))))
1549 (setq more-than-one-table (> (length pretty-alist) 1))
1550 (setq prefix (if more-than-one-table
1552 (dolist (table-and-templates pretty-alist)
1553 (when (cdr table-and-templates)
1554 (if more-than-one-table
1555 (push (yas/table-name (car table-and-templates)) menu))
1556 (dolist (template (cdr table-and-templates))
1557 (push (cons (concat prefix (yas/template-name template))
1559 (setq menu (nreverse menu))
1560 (or (x-popup-menu (if (fboundp 'posn-at-point)
1561 (let ((x-y (posn-x-y (posn-at-point (point)))))
1562 (list (list (+ (car x-y) 10)
1566 (list prompt (push "title" menu)))
1569 (defun yas/ido-prompt (prompt choices &optional display-fn)
1570 (when (and (featurep 'ido)
1572 (yas/completing-prompt prompt choices display-fn #'ido-completing-read)))
1574 (eval-when-compile (require 'dropdown-list nil t))
1575 (defun yas/dropdown-prompt (prompt choices &optional display-fn)
1576 (when (featurep 'dropdown-list)
1577 (let (formatted-choices
1581 (dolist (choice choices)
1582 (setq d (or (and display-fn (funcall display-fn choice))
1585 (push d formatted-choices)
1586 (push choice filtered-choices)))
1588 (setq n (and formatted-choices (dropdown-list formatted-choices)))
1590 (nth n filtered-choices)
1593 (defun yas/completing-prompt (prompt choices &optional display-fn completion-fn)
1594 (let (formatted-choices
1598 (completion-fn (or completion-fn
1599 #'completing-read)))
1600 (dolist (choice choices)
1601 (setq d (or (and display-fn (funcall display-fn choice))
1604 (push d formatted-choices)
1605 (push choice filtered-choices)))
1606 (setq chosen (and formatted-choices
1607 (funcall completion-fn prompt
1614 (nth (position chosen formatted-choices :test #'string=) filtered-choices))))
1616 (defun yas/no-prompt (prompt choices &optional display-fn)
1619 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1620 ;; Loading snippets from files
1622 (defun yas/load-directory-1 (directory &optional mode-sym parents)
1623 "Recursively load snippet templates from DIRECTORY."
1625 ;; Load .yas-setup.el files wherever we find them
1627 (let ((file (concat directory "/" ".yas-setup")))
1628 (when (or (file-readable-p (concat file ".el"))
1629 (file-readable-p (concat file ".elc")))
1634 (unless (file-exists-p (concat directory "/" ".yas-skip"))
1635 (let* ((major-mode-and-parents (if mode-sym
1636 (cons mode-sym parents)
1637 (yas/compute-major-mode-and-parents (concat directory
1639 (yas/ignore-filenames-as-triggers
1640 (or yas/ignore-filenames-as-triggers
1641 (file-exists-p (concat directory "/"
1642 ".yas-ignore-filenames-as-triggers"))))
1644 ;; load the snippet files
1647 (dolist (file (yas/subdirs directory 'no-subdirs-just-files))
1648 (when (file-readable-p file)
1649 (insert-file-contents file nil nil nil t)
1650 (push (yas/parse-template file)
1653 (yas/define-snippets (car major-mode-and-parents)
1655 (cdr major-mode-and-parents)))
1656 ;; now recurse to a lower level
1658 (dolist (subdir (yas/subdirs directory))
1659 (yas/load-directory-1 subdir
1660 (car major-mode-and-parents)
1661 (cdr major-mode-and-parents))))))
1663 (defun yas/load-directory (directory)
1664 "Load snippet definition from a directory hierarchy.
1666 Below the top-level directory, each directory is a mode
1667 name. And under each subdirectory, each file is a definition
1668 of a snippet. The file name is the trigger key and the
1669 content of the file is the template."
1670 (interactive "DSelect the root directory: ")
1671 (unless (file-directory-p directory)
1672 (error "Error %s not a directory" directory))
1673 (unless yas/snippet-dirs
1674 (setq yas/snippet-dirs directory))
1675 (dolist (dir (yas/subdirs directory))
1676 (yas/load-directory-1 dir))
1677 (when (interactive-p)
1678 (message "[yas] Loaded snippets from %s." directory)))
1680 (defun yas/load-snippet-dirs ()
1681 "Reload the directories listed in `yas/snippet-dirs' or
1682 prompt the user to select one."
1683 (if yas/snippet-dirs
1684 (dolist (directory (reverse (yas/snippet-dirs)))
1685 (yas/load-directory directory))
1686 (call-interactively 'yas/load-directory)))
1688 (defun yas/reload-all (&optional reset-root-directory)
1689 "Reload all snippets and rebuild the YASnippet menu. "
1691 ;; Turn off global modes and minor modes, save their state though
1693 (let ((restore-global-mode (prog1 yas/global-mode
1694 (yas/global-mode -1)))
1695 (restore-minor-mode (prog1 yas/minor-mode
1696 (yas/minor-mode -1))))
1697 ;; Empty all snippet tables and all menu tables
1699 (setq yas/tables (make-hash-table))
1700 (setq yas/menu-table (make-hash-table))
1702 ;; Init the `yas/minor-mode-map', taking care not to break the
1705 (setf (cdr yas/minor-mode-map)
1706 (cdr (yas/init-minor-keymap)))
1708 (when reset-root-directory
1709 (setq yas/snippet-dirs nil))
1711 ;; Reload the directories listed in `yas/snippet-dirs' or prompt
1712 ;; the user to select one.
1714 (yas/load-snippet-dirs)
1715 ;; Reload the direct keybindings
1717 (yas/direct-keymaps-reload)
1718 ;; Restore the mode configuration
1720 (when restore-minor-mode
1722 (when restore-global-mode
1723 (yas/global-mode 1))
1725 (message "[yas] Reloading everything... Done.")))
1727 (defun yas/quote-string (string)
1728 "Escape and quote STRING.
1729 foo\"bar\\! -> \"foo\\\"bar\\\\!\""
1731 (replace-regexp-in-string "[\\\"]"
1736 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1737 ;;; Yasnippet Bundle
1739 (defun yas/initialize ()
1740 "For backward compatibility, enable `yas/minor-mode' globally"
1741 (yas/global-mode 1))
1743 (defun yas/compile-bundle
1744 (&optional yasnippet yasnippet-bundle snippet-roots code dropdown)
1745 "Compile snippets in SNIPPET-ROOTS to a single bundle file.
1747 YASNIPPET is the yasnippet.el file path.
1749 YASNIPPET-BUNDLE is the output file of the compile result.
1751 SNIPPET-ROOTS is a list of root directories that contains the
1752 snippets definition.
1754 CODE is the code to be placed at the end of the generated file
1755 and that can initialize the YASnippet bundle.
1757 Last optional argument DROPDOWN is the filename of the
1758 dropdown-list.el library.
1760 Here's the default value for all the parameters:
1762 (yas/compile-bundle \"yasnippet.el\"
1763 \"yasnippet-bundle.el\"
1765 \"(yas/initialize-bundle)
1767 (require 'yasnippet-bundle)`\"
1768 \"dropdown-list.el\")
1770 (interactive (concat "ffind the yasnippet.el file: \nFTarget bundle file: "
1771 "\nDSnippet directory to bundle: \nMExtra code? \nfdropdown-library: "))
1773 (let* ((yasnippet (or yasnippet
1775 (yasnippet-bundle (or yasnippet-bundle
1776 "./yasnippet-bundle.el"))
1777 (snippet-roots (or snippet-roots
1779 (dropdown (or dropdown
1780 "dropdown-list.el"))
1782 (condition-case err (read code) (error nil))
1784 (concat "(yas/initialize-bundle)"
1785 "\n;;;###autoload" ; break through so that won't
1786 "(require 'yasnippet-bundle)")))
1787 (dirs (or (and (listp snippet-roots) snippet-roots)
1788 (list snippet-roots)))
1789 (bundle-buffer nil))
1790 (with-temp-file yasnippet-bundle
1791 (insert ";;; yasnippet-bundle.el --- "
1792 "Yet another snippet extension (Auto compiled bundle)\n")
1793 (insert-file-contents yasnippet)
1794 (goto-char (point-max))
1797 (insert-file-contents dropdown))
1798 (goto-char (point-max))
1799 (insert ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n")
1800 (insert ";;;; Auto-generated code ;;;;\n")
1801 (insert ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n")
1802 (insert "(defun yas/initialize-bundle ()\n"
1803 " \"Initialize YASnippet and load snippets in the bundle.\"")
1804 (flet ((yas/define-snippets
1805 (mode snippets &optional parent-or-parents)
1806 (insert ";;; snippets for " (symbol-name mode) "\n")
1807 (let ((literal-snippets (list)))
1808 (dolist (snippet snippets)
1809 (let ((key (first snippet))
1810 (template-content (second snippet))
1811 (name (third snippet))
1812 (condition (fourth snippet))
1813 (group (fifth snippet))
1814 (expand-env (sixth snippet))
1815 (file nil) ;; (seventh snippet)) ;; omit on purpose
1816 (binding (eighth snippet))
1817 (uuid (ninth snippet)))
1828 (insert (pp-to-string `(yas/define-snippets ',mode ',literal-snippets ',parent-or-parents)))
1831 (dolist (subdir (yas/subdirs dir))
1832 (let ((file (concat subdir "/.yas-setup.el")))
1833 (when (file-readable-p file)
1834 (insert ";; Supporting elisp for subdir " (file-name-nondirectory subdir) "\n\n")
1835 (goto-char (+ (point)
1836 (second (insert-file-contents file))))))
1837 (yas/load-directory-1 subdir nil))))
1839 (insert (pp-to-string `(yas/global-mode 1)))
1840 (insert ")\n\n" code "\n")
1842 ;; bundle-specific provide and value for yas/dont-activate
1843 (let ((bundle-feature-name (file-name-nondirectory
1844 (file-name-sans-extension
1845 yasnippet-bundle))))
1846 (insert (pp-to-string `(set-default 'yas/dont-activate
1848 (and (or yas/snippet-dirs
1849 (featurep ',(make-symbol bundle-feature-name)))
1850 (null (yas/get-snippet-tables)))))))
1851 (insert (pp-to-string `(provide ',(make-symbol bundle-feature-name)))))
1854 (file-name-nondirectory yasnippet-bundle)
1857 (defun yas/compile-textmate-bundle ()
1859 (yas/compile-bundle "yasnippet.el"
1860 "./yasnippet-textmate-bundle.el"
1862 (concat "(yas/initialize-bundle)"
1863 "\n;;;###autoload" ; break through so that won't
1864 "(require 'yasnippet-textmate-bundle)")
1865 "dropdown-list.el"))
1867 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1868 ;;; Some user level functions
1873 (message (concat "yasnippet (version "
1875 ") -- pluskid <pluskid@gmail.com>/joaotavora <joaotavora@gmail.com>")))
1877 (defun yas/define-snippets (mode snippets &optional parent-mode)
1878 "Define SNIPPETS for MODE.
1880 SNIPPETS is a list of snippet definitions, each taking the
1883 (KEY TEMPLATE NAME CONDITION GROUP EXPAND-ENV FILE KEYBINDING UUID)
1885 Within these, only KEY and TEMPLATE are actually mandatory.
1887 TEMPLATE might be a lisp form or a string, depending on whether
1888 this is a snippet or a snippet-command.
1890 CONDITION, EXPAND-ENV and KEYBINDING are lisp forms, they have
1891 been `yas/read-lisp'-ed and will eventually be
1894 The remaining elements are strings.
1896 FILE is probably of very little use if you're programatically
1899 UUID is the snippets \"unique-id\". Loading a second snippet file
1900 with the same uuid replaced the previous snippet.
1902 You can use `yas/parse-template' to return such lists based on
1903 the current buffers contents.
1905 Optional PARENT-MODE can be used to specify the parent tables of
1906 MODE. It can be a mode symbol of a list of mode symbols. It does
1907 not need to be a real mode."
1908 ;; X) `snippet-table' is created or retrieved for MODE, same goes
1909 ;; for the list of snippet tables `parent-tables'.
1911 (let ((snippet-table (yas/table-get-create mode))
1912 (parent-tables (mapcar #'yas/table-get-create
1913 (if (listp parent-mode)
1915 (list parent-mode))))
1917 ;; X) Connect `snippet-table' with `parent-tables'.
1919 ;; TODO: this should be a remove-duplicates of the concatenation
1920 ;; of `snippet-table's existings parents with the new parents...
1922 (dolist (parent parent-tables)
1923 (unless (find parent (yas/table-parents snippet-table))
1925 (yas/table-parents snippet-table))))
1927 ;; X) Now, iterate for evey snippet def list
1929 (dolist (snippet snippets)
1930 (setq template (yas/define-snippets-1 snippet
1934 (defun yas/define-snippets-1 (snippet snippet-table)
1935 "Helper for `yas/define-snippets'."
1936 ;; X) Calculate some more defaults on the values returned by
1937 ;; `yas/parse-template'.
1939 (let* ((file (seventh snippet))
1940 (key (or (car snippet)
1941 (unless yas/ignore-filenames-as-triggers
1943 (file-name-sans-extension (file-name-nondirectory file))))))
1944 (name (or (third snippet)
1946 (file-name-directory file))))
1947 (condition (fourth snippet))
1948 (group (fifth snippet))
1949 (keybinding (yas/read-keybinding (eighth snippet)))
1950 (uuid (or (ninth snippet)
1952 (template (or (gethash uuid (yas/table-uuidhash snippet-table))
1953 (yas/make-blank-template))))
1954 ;; X) populate the template object
1956 (yas/populate-template template
1957 :table snippet-table
1959 :content (second snippet)
1962 :condition condition
1963 :expand-env (sixth snippet)
1964 :file (seventh snippet)
1965 :keybinding keybinding
1967 ;; X) Update this template in the appropriate table. This step
1968 ;; also will take care of adding the key indicators in the
1969 ;; templates menu entry, if any
1971 (yas/update-template snippet-table template)
1972 ;; X) Return the template
1977 (defun yas/snippet-menu-binding-pair-get-create (template &optional type)
1978 "Get TEMPLATE's menu binding or assign it a new one."
1979 (or (yas/template-menu-binding-pair template)
1980 (let ((key (yas/template-key template))
1981 (keybinding (yas/template-keybinding template)))
1982 (setf (yas/template-menu-binding-pair template)
1983 (cons `(menu-item ,(or (yas/template-name template)
1984 (yas/template-uuid template))
1985 ,(yas/make-menu-binding template)
1989 (defun yas/show-menu-p (mode)
1990 (cond ((eq yas/use-menu 'abbreviate)
1992 (mapcar #'(lambda (table)
1993 (intern (yas/table-name table)))
1994 (yas/get-snippet-tables))))
1995 ((eq yas/use-menu 'real-modes)
1996 (yas/real-mode? mode))
2000 (defun yas/delete-from-keymap (keymap uuid)
2001 "Recursively delete items with UUID from KEYMAP and its submenus."
2003 ;; XXX: This used to skip any submenus named \"parent mode\"
2005 ;; First of all, recursively enter submenus, i.e. the tree is
2006 ;; searched depth first so that stale submenus can be found in the
2009 (mapc #'(lambda (item)
2010 (when (and (listp (cdr item))
2011 (keymapp (third (cdr item))))
2012 (yas/delete-from-keymap (third (cdr item)) uuid)))
2014 ;; Set the uuid entry to nil
2016 (define-key keymap (vector (make-symbol uuid)) nil)
2017 ;; Destructively modify keymap
2019 (setcdr keymap (delete-if #'(lambda (item)
2020 (or (null (cdr item))
2021 (and (keymapp (third (cdr item)))
2022 (null (cdr (third (cdr item)))))))
2025 (defun yas/define-menu (mode menu omit-items)
2026 "Define a snippet menu for MODE according to MENU, ommitting OMIT-ITEMS.
2028 MENU is a list, its elements can be:
2030 - (yas/item UUID) : Creates an entry the snippet identified with
2031 UUID. The menu entry for a snippet thus identified is
2032 permanent, i.e. it will never move in the menu.
2034 - (yas/separator) : Creates a separator
2036 - (yas/submenu NAME SUBMENU) : Creates a submenu with NAME,
2037 SUBMENU has the same form as MENU. NAME is also added to the
2038 list of groups of the snippets defined thereafter.
2040 OMIT-ITEMS is a list of snippet uuid's that will always be
2041 ommited from MODE's menu, even if they're manually loaded.
2043 (let* ((table (yas/table-get-create mode))
2044 (hash (yas/table-uuidhash table)))
2045 (yas/define-menu-1 table
2046 (yas/menu-keymap-get-create table)
2049 (dolist (uuid omit-items)
2050 (let ((template (or (gethash uuid hash)
2051 (yas/populate-template (puthash uuid
2052 (yas/make-blank-template)
2056 (setf (yas/template-menu-binding-pair template) (cons nil :none))))))
2058 (defun yas/define-menu-1 (table keymap menu uuidhash &optional group-list)
2059 (dolist (e (reverse menu))
2060 (cond ((eq (first e) 'yas/item)
2061 (let ((template (or (gethash (second e) uuidhash)
2062 (yas/populate-template (puthash (second e)
2063 (yas/make-blank-template)
2066 :perm-group group-list
2067 :uuid (second e)))))
2068 (define-key keymap (vector (make-symbol (second e)))
2069 (car (yas/snippet-menu-binding-pair-get-create template :stay)))))
2070 ((eq (first e) 'yas/submenu)
2071 (let ((subkeymap (make-sparse-keymap)))
2072 (define-key keymap (vector (make-symbol(second e)))
2073 `(menu-item ,(second e) ,subkeymap))
2074 (yas/define-menu-1 table
2078 (append group-list (list (second e))))))
2079 ((eq (first e) 'yas/separator)
2080 (define-key keymap (vector (gensym))
2081 '(menu-item "----")))
2083 (message "[yas] don't know anything about menu entry %s" (first e))))))
2085 (defun yas/define (mode key template &optional name condition group)
2086 "Define a snippet. Expanding KEY into TEMPLATE.
2088 NAME is a description to this template. Also update the menu if
2089 `yas/use-menu' is `t'. CONDITION is the condition attached to
2090 this snippet. If you attach a condition to a snippet, then it
2091 will only be expanded when the condition evaluated to non-nil."
2092 (yas/define-snippets mode
2093 (list (list key template name condition group))))
2095 (defun yas/hippie-try-expand (first-time?)
2096 "Integrate with hippie expand. Just put this function in
2097 `hippie-expand-try-functions-list'."
2098 (if (not first-time?)
2099 (let ((yas/fallback-behavior 'return-nil))
2105 ;;; Apropos condition-cache:
2110 (defvar yas/condition-cache-timestamp nil)
2111 (defmacro yas/define-condition-cache (func doc &rest body)
2112 "Define a function FUNC with doc DOC and body BODY, BODY is
2113 executed at most once every snippet expansion attempt, to check
2114 expansion conditions.
2116 It doesn't make any sense to call FUNC programatically."
2117 `(defun ,func () ,(if (and doc
2120 "\n\nFor use in snippets' conditions. Within each
2121 snippet-expansion routine like `yas/expand', computes actual
2122 value for the first time then always returns a cached value.")
2123 (setq body (cons doc body))
2125 (let ((timestamp-and-value (get ',func 'yas/condition-cache)))
2126 (if (equal (car timestamp-and-value) yas/condition-cache-timestamp)
2127 (cdr timestamp-and-value)
2128 (let ((new-value (progn
2131 (put ',func 'yas/condition-cache (cons yas/condition-cache-timestamp new-value))
2134 (defalias 'yas/expand 'yas/expand-from-trigger-key)
2135 (defun yas/expand-from-trigger-key (&optional field)
2136 "Expand a snippet before point.
2138 If no snippet expansion is possible, fall back to the behaviour
2139 defined in `yas/fallback-behavior'.
2141 Optional argument FIELD is for non-interactive use and is an
2142 object satisfying `yas/field-p' to restrict the expansion to."
2144 (setq yas/condition-cache-timestamp (current-time))
2145 (let (templates-and-pos)
2146 (unless (and yas/expand-only-for-last-commands
2147 (not (member last-command yas/expand-only-for-last-commands)))
2148 (setq templates-and-pos (if field
2150 (narrow-to-region (yas/field-start field)
2151 (yas/field-end field))
2153 (yas/current-key))))
2154 (if (and templates-and-pos
2155 (first templates-and-pos))
2156 (yas/expand-or-prompt-for-template (first templates-and-pos)
2157 (second templates-and-pos)
2158 (third templates-and-pos))
2159 (yas/fallback 'trigger-key))))
2161 (defun yas/expand-from-keymap ()
2162 "Directly expand some snippets, searching `yas/direct-keymaps'.
2164 If expansion fails, execute the previous binding for this key"
2166 (setq yas/condition-cache-timestamp (current-time))
2167 (let* ((vec (this-command-keys-vector))
2168 (templates (mapcan #'(lambda (table)
2169 (yas/fetch table vec))
2170 (yas/get-snippet-tables))))
2172 (yas/expand-or-prompt-for-template templates)
2173 (let ((yas/fallback-behavior 'call-other-command))
2176 (defun yas/expand-or-prompt-for-template (templates &optional start end)
2177 "Expand one of TEMPLATES from START to END.
2179 Prompt the user if TEMPLATES has more than one element, else
2180 expand immediately. Common gateway for
2181 `yas/expand-from-trigger-key' and `yas/expand-from-keymap'."
2182 (let ((yas/current-template (or (and (rest templates) ;; more than one
2183 (yas/prompt-for-template (mapcar #'cdr templates)))
2185 (when yas/current-template
2186 (yas/expand-snippet (yas/template-content yas/current-template)
2189 (yas/template-expand-env yas/current-template)))))
2191 (defun yas/fallback (&optional from-trigger-key-p)
2192 "Fallback after expansion has failed.
2194 Common gateway for `yas/expand-from-trigger-key' and
2195 `yas/expand-from-keymap'."
2196 (cond ((eq yas/fallback-behavior 'return-nil)
2199 ((eq yas/fallback-behavior 'call-other-command)
2200 (let* ((yas/minor-mode nil)
2201 (yas/direct-keymaps nil)
2202 (keys-1 (this-command-keys-vector))
2203 (keys-2 (and yas/trigger-key
2205 (stringp yas/trigger-key)
2206 (read-kbd-macro yas/trigger-key)))
2207 (command-1 (and keys-1 (key-binding keys-1)))
2208 (command-2 (and keys-2 (key-binding keys-2)))
2209 ;; An (ugly) safety: prevents infinite recursion of
2210 ;; yas/expand* calls.
2211 (command (or (and (symbolp command-1)
2212 (not (string-match "yas/expand" (symbol-name command-1)))
2214 (and (symbolp command-2)
2216 (when (and (commandp command)
2217 (not (string-match "yas/expand" (symbol-name command))))
2218 (setq this-command command)
2219 (call-interactively command))))
2220 ((and (listp yas/fallback-behavior)
2221 (cdr yas/fallback-behavior)
2222 (eq 'apply (car yas/fallback-behavior)))
2223 (if (cddr yas/fallback-behavior)
2224 (apply (cadr yas/fallback-behavior)
2225 (cddr yas/fallback-behavior))
2226 (when (commandp (cadr yas/fallback-behavior))
2227 (setq this-command (cadr yas/fallback-behavior))
2228 (call-interactively (cadr yas/fallback-behavior)))))
2230 ;; also return nil if all the other fallbacks have failed
2235 ;;; Snippet development
2237 (defun yas/all-templates (tables)
2238 "Return all snippet tables applicable for the current buffer.
2240 Honours `yas/choose-tables-first', `yas/choose-keys-first' and
2241 `yas/buffer-local-condition'"
2242 (when yas/choose-tables-first
2243 (setq tables (list (yas/prompt-for-table tables))))
2245 (if yas/choose-keys-first
2246 (let ((key (yas/prompt-for-keys
2247 (mapcan #'yas/table-all-keys tables))))
2249 (mapcan #'(lambda (table)
2250 (yas/fetch table key))
2252 (remove-duplicates (mapcan #'yas/table-templates tables)
2255 (defun yas/insert-snippet (&optional no-condition)
2256 "Choose a snippet to expand, pop-up a list of choices according
2257 to `yas/prompt-function'.
2259 With prefix argument NO-CONDITION, bypass filtering of snippets
2262 (setq yas/condition-cache-timestamp (current-time))
2263 (let* ((yas/buffer-local-condition (or (and no-condition
2265 yas/buffer-local-condition))
2266 (templates (yas/all-templates (yas/get-snippet-tables)))
2267 (yas/current-template (and templates
2268 (or (and (rest templates) ;; more than one template for same key
2269 (yas/prompt-for-template templates))
2271 (where (if (region-active-p)
2272 (cons (region-beginning) (region-end))
2273 (cons (point) (point)))))
2274 (if yas/current-template
2275 (yas/expand-snippet (yas/template-content yas/current-template)
2278 (yas/template-expand-env yas/current-template))
2279 (message "[yas] No snippets can be inserted here!"))))
2281 (defun yas/visit-snippet-file ()
2282 "Choose a snippet to edit, selection like `yas/insert-snippet'.
2284 Only success if selected snippet was loaded from a file. Put the
2285 visited file in `snippet-mode'."
2287 (let* ((yas/buffer-local-condition 'always)
2288 (templates (yas/all-templates (yas/get-snippet-tables)))
2289 (yas/prompt-functions '(yas/ido-prompt yas/completing-prompt))
2290 (template (and templates
2291 (or (yas/prompt-for-template templates
2292 "Choose a snippet template to edit: ")
2296 (yas/visit-snippet-file-1 template)
2297 (message "No snippets tables active!"))))
2299 (defun yas/visit-snippet-file-1 (template)
2300 (let ((file (yas/template-file template)))
2301 (cond ((and file (file-readable-p file))
2302 (find-file-other-window file)
2304 (set (make-local-variable 'yas/editing-template) template))
2306 (message "Original file %s no longer exists!" file))
2308 (switch-to-buffer (format "*%s*"(yas/template-name template)))
2309 (let ((type 'snippet))
2310 (when (listp (yas/template-content template))
2311 (insert (format "# type: command\n"))
2312 (setq type 'command))
2313 (insert (format "# key: %s\n" (yas/template-key template)))
2314 (insert (format "# name: %s\n" (yas/template-name template)))
2315 (when (yas/template-keybinding template)
2316 (insert (format "# binding: %s\n" (yas/template-keybinding template))))
2317 (when (yas/template-expand-env template)
2318 (insert (format "# expand-env: %s\n" (yas/template-expand-env template))))
2319 (when (yas/template-condition template)
2320 (insert (format "# condition: %s\n" (yas/template-condition template))))
2322 (insert (if (eq type 'command)
2323 (pp-to-string (yas/template-content template))
2324 (yas/template-content template))))
2326 (set (make-local-variable 'yas/editing-template) template)))))
2328 (defun yas/guess-snippet-directories-1 (table)
2329 "Guesses possible snippet subdirectories for TABLE."
2330 (cons (yas/table-name table)
2331 (mapcan #'(lambda (parent)
2332 (yas/guess-snippet-directories-1
2334 (yas/table-parents table))))
2336 (defun yas/guess-snippet-directories (&optional table)
2337 "Try to guess suitable directories based on the current active
2338 tables (or optional TABLE).
2340 Returns a list of elemts (TABLE . DIRS) where TABLE is a
2341 `yas/table' object and DIRS is a list of all possible directories
2342 where snippets of table might exist."
2343 (let ((main-dir (replace-regexp-in-string
2345 (or (first (or (yas/snippet-dirs)
2346 (setq yas/snippet-dirs '("~/.emacs.d/snippets")))))))
2347 (tables (or (and table
2349 (yas/get-snippet-tables))))
2350 ;; HACK! the snippet table created here is actually registered!
2352 (unless (or table (gethash major-mode yas/tables))
2353 (push (yas/table-get-create major-mode)
2356 (mapcar #'(lambda (table)
2358 (mapcar #'(lambda (subdir)
2359 (concat main-dir "/" subdir))
2360 (yas/guess-snippet-directories-1 table))))
2363 (defun yas/make-directory-maybe (table-and-dirs &optional main-table-string)
2364 "Returns a dir inside TABLE-AND-DIRS, prompts for creation if none exists."
2365 (or (some #'(lambda (dir) (when (file-directory-p dir) dir)) (cdr table-and-dirs))
2366 (let ((candidate (first (cdr table-and-dirs))))
2367 (unless (file-writable-p (file-name-directory candidate))
2368 (error "[yas] %s is not writable." candidate))
2369 (if (y-or-n-p (format "Guessed directory (%s) for%s%s table \"%s\" does not exist! Create? "
2371 (if (gethash (intern (yas/table-name (car table-and-dirs)))
2375 (or main-table-string
2377 (yas/table-name (car table-and-dirs))))
2379 (make-directory candidate 'also-make-parents)
2380 ;; create the .yas-parents file here...
2383 (defun yas/new-snippet (&optional choose-instead-of-guess)
2386 (let ((guessed-directories (yas/guess-snippet-directories)))
2388 (switch-to-buffer "*new snippet*")
2390 (kill-all-local-variables)
2392 (set (make-local-variable 'yas/guessed-modes) (mapcar #'(lambda (d)
2393 (intern (yas/table-name (car d))))
2394 guessed-directories))
2395 (unless (and choose-instead-of-guess
2396 (not (y-or-n-p "Insert a snippet with useful headers? ")))
2397 (yas/expand-snippet "\
2398 # -*- mode: snippet -*-
2401 # binding: ${4:direct-keybinding}}${5:
2402 # expand-env: ((${6:some-var} ${7:some-value}))}${8:
2407 (defun yas/find-snippets (&optional same-window )
2408 "Find snippet file in guessed current mode's directory.
2410 Calls `find-file' interactively in the guessed directory.
2412 With prefix arg SAME-WINDOW opens the buffer in the same window.
2414 Because snippets can be loaded from many different locations,
2415 this has to guess the correct directory using
2416 `yas/guess-snippet-directories', which returns a list of
2419 If any one of these exists, it is taken and `find-file' is called
2420 there, otherwise, proposes to create the first option returned by
2421 `yas/guess-snippet-directories'."
2423 (let* ((guessed-directories (yas/guess-snippet-directories))
2426 (setq chosen (yas/make-directory-maybe (first guessed-directories) " main"))
2428 (if (y-or-n-p (format "Continue guessing for other active tables %s? "
2429 (mapcar #'(lambda (table-and-dirs)
2430 (yas/table-name (car table-and-dirs)))
2431 (rest guessed-directories))))
2432 (setq chosen (some #'yas/make-directory-maybe
2433 (rest guessed-directories)))))
2435 (when (y-or-n-p "Having trouble... go to snippet root dir? ")
2436 (setq chosen (first (yas/snippet-dirs)))))
2438 (let ((default-directory chosen))
2439 (setq buffer (call-interactively (if same-window
2441 'find-file-other-window)))
2445 (when (eq major-mode 'fundamental-mode)
2447 (message "Could not guess snippet dir!"))))
2449 (defun yas/compute-major-mode-and-parents (file &optional prompt-if-failed)
2450 (let* ((file-dir (and file
2451 (directory-file-name (or (some #'(lambda (special)
2452 (locate-dominating-file file special))
2456 (directory-file-name (file-name-directory file))))))
2457 (parents-file-name (concat file-dir "/.yas-parents"))
2458 (major-mode-name (and file-dir
2459 (file-name-nondirectory file-dir)))
2460 (major-mode-sym (or (and major-mode-name
2461 (intern major-mode-name))
2462 (when prompt-if-failed
2463 (read-from-minibuffer
2464 "[yas] Cannot auto-detect major mode! Enter a major mode: "))))
2465 (parents (when (file-readable-p parents-file-name)
2469 (insert-file-contents parents-file-name)
2470 (buffer-substring-no-properties (point-min)
2472 (when major-mode-sym
2473 (cons major-mode-sym parents))))
2475 (defvar yas/editing-template nil
2476 "Supporting variable for `yas/load-snippet-buffer' and `yas/visit-snippet'")
2478 (defvar yas/current-template nil
2479 "Holds the current template being expanded into a snippet.")
2481 (defvar yas/guessed-modes nil
2482 "List of guessed modes supporting `yas/load-snippet-buffer'.")
2484 (defun yas/load-snippet-buffer (&optional kill)
2485 "Parse and load current buffer's snippet definition.
2487 With optional prefix argument KILL quit the window and buffer."
2489 (let ((yas/ignore-filenames-as-triggers
2490 (or yas/ignore-filenames-as-triggers
2491 (and buffer-file-name
2492 (locate-dominating-file
2494 ".yas-ignore-filenames-as-triggers")))))
2496 ;; We have `yas/editing-template', this buffer's
2497 ;; content comes from a template which is already loaded and
2498 ;; neatly positioned,...
2500 (yas/editing-template
2501 (yas/define-snippets-1 (yas/parse-template (yas/template-file yas/editing-template))
2502 (yas/template-table yas/editing-template)))
2503 ;; Try to use `yas/guessed-modes'. If we don't have that use the
2504 ;; value from `yas/compute-major-mode-and-parents'
2507 (unless yas/guessed-modes
2508 (set (make-local-variable 'yas/guessed-modes) (or (yas/compute-major-mode-and-parents buffer-file-name))))
2509 (let* ((prompt (if (and (featurep 'ido)
2511 'ido-completing-read 'completing-read))
2512 (table (yas/table-get-create
2514 (funcall prompt (format "Choose or enter a table (yas guesses %s): "
2515 (if yas/guessed-modes
2516 (first yas/guessed-modes)
2518 (mapcar #'symbol-name yas/guessed-modes)
2523 (if (first yas/guessed-modes)
2524 (symbol-name (first yas/guessed-modes))))))))
2525 (set (make-local-variable 'yas/editing-template)
2526 (yas/define-snippets-1 (yas/parse-template buffer-file-name)
2528 ;; Now, offer to save this shit
2530 ;; 1) if `yas/snippet-dirs' is a list and its first element does not
2531 ;; match this template's file (i.e. this is a library snippet, not
2534 ;; 2) yas/editing-template comes from a file that we cannot write to...
2536 (when (or (not (yas/template-file yas/editing-template))
2537 (not (file-writable-p (yas/template-file yas/editing-template)))
2538 (and (listp yas/snippet-dirs)
2539 (second yas/snippet-dirs)
2540 (not (string-match (expand-file-name (first yas/snippet-dirs))
2541 (yas/template-file yas/editing-template)))))
2543 (when (y-or-n-p "[yas] Looks like a library or new snippet. Save to new file? ")
2544 (let* ((option (first (yas/guess-snippet-directories (yas/template-table yas/editing-template))))
2546 (yas/make-directory-maybe option))))
2548 (let ((default-file-name (or (and (yas/template-file yas/editing-template)
2549 (file-name-nondirectory (yas/template-file yas/editing-template)))
2550 (yas/template-name yas/editing-template))))
2551 (write-file (concat chosen "/"
2552 (read-from-minibuffer (format "File name to create in %s? " chosen)
2553 default-file-name)))
2554 (setf (yas/template-file yas/editing-template) buffer-file-name))))))
2557 (message "[yas] Snippet \"%s\" loaded for %s."
2558 (yas/template-name yas/editing-template)
2559 (yas/table-name (yas/template-table yas/editing-template))))
2562 (defun yas/tryout-snippet (&optional debug)
2563 "Test current buffers's snippet template in other buffer."
2565 (let* ((major-mode-and-parent (yas/compute-major-mode-and-parents buffer-file-name))
2566 (parsed (yas/parse-template))
2567 (test-mode (or (and (car major-mode-and-parent)
2568 (fboundp (car major-mode-and-parent))
2569 (car major-mode-and-parent))
2570 (first yas/guessed-modes)
2571 (intern (read-from-minibuffer "[yas] please input a mode: "))))
2572 (yas/current-template
2575 (yas/populate-template (yas/make-blank-template)
2576 :table nil ;; no tables for ephemeral snippets
2578 :content (second parsed)
2579 :name (third parsed)
2580 :expand-env (sixth parsed)))))
2581 (cond (yas/current-template
2582 (let ((buffer-name (format "*testing snippet: %s*" (yas/template-name yas/current-template))))
2583 (kill-buffer (get-buffer-create buffer-name))
2584 (switch-to-buffer (get-buffer-create buffer-name))
2585 (setq buffer-undo-list nil)
2586 (condition-case nil (funcall test-mode) (error nil))
2587 (yas/expand-snippet (yas/template-content yas/current-template)
2590 (yas/template-expand-env yas/current-template))
2592 (require 'yasnippet-debug nil t))
2593 (add-hook 'post-command-hook 'yas/debug-snippet-vars 't 'local))))
2595 (message "[yas] Cannot test snippet for unknown major mode")))))
2597 (defun yas/template-fine-group (template)
2598 (car (last (or (yas/template-group template)
2599 (yas/template-perm-group template)))))
2601 (defun yas/describe-tables (&optional choose)
2602 "Display snippets for each table."
2604 (let* ((by-name-hash (and choose
2605 (y-or-n-p "Show by namehash? ")))
2606 (buffer (get-buffer-create "*YASnippet tables*"))
2607 (active-tables (yas/get-snippet-tables))
2608 (remain-tables (let ((all))
2609 (maphash #'(lambda (k v)
2610 (unless (find v active-tables)
2614 (table-lists (list active-tables remain-tables))
2615 (original-buffer (current-buffer))
2617 (yas/condition-cache-timestamp (current-time)))
2618 (with-current-buffer buffer
2619 (setq buffer-read-only nil)
2621 (cond ((not by-name-hash)
2622 (insert "YASnippet tables: \n")
2623 (while (and table-lists
2625 (dolist (table (car table-lists))
2626 (yas/describe-pretty-table table original-buffer))
2627 (setq table-lists (cdr table-lists))
2629 (yas/create-snippet-xrefs)
2630 (display-buffer buffer)
2631 (setq continue (and choose (y-or-n-p "Show also non-active tables? ")))))
2632 (yas/create-snippet-xrefs)
2636 (insert "\n\nYASnippet tables by NAMEHASH: \n")
2637 (dolist (table (append active-tables remain-tables))
2638 (insert (format "\nSnippet table `%s':\n\n" (yas/table-name table)))
2640 (maphash #'(lambda (k v)
2642 (yas/table-hash table))
2644 (insert (format " key %s maps snippets: %s\n" key
2646 (maphash #'(lambda (k v)
2648 (gethash key (yas/table-hash table)))
2651 (setq buffer-read-only t))
2652 (display-buffer buffer)))
2654 (defun yas/describe-pretty-table (table &optional original-buffer)
2655 (insert (format "\nSnippet table `%s'"
2656 (yas/table-name table)))
2657 (if (yas/table-parents table)
2658 (insert (format " parents: %s\n"
2659 (mapcar #'yas/table-name
2660 (yas/table-parents table))))
2662 (insert (make-string 100 ?-) "\n")
2663 (insert "group state name key binding\n")
2664 (let ((groups-alist (list))
2666 (maphash #'(lambda (k v)
2667 (setq group (or (yas/template-fine-group v)
2669 (when (yas/template-name v)
2671 (aput 'groups-alist group (cons v (aget groups-alist group)))))
2672 (yas/table-uuidhash table))
2673 (dolist (group-and-templates groups-alist)
2674 (when (rest group-and-templates)
2675 (setq group (truncate-string-to-width (car group-and-templates) 25 0 ? "..."))
2676 (insert (make-string 100 ?-) "\n")
2677 (dolist (p (cdr group-and-templates))
2678 (let ((name (truncate-string-to-width (propertize (format "\\\\snippet `%s'" (yas/template-name p))
2682 (setq group (make-string (length group) ? ))))
2683 (condition-string (let ((condition (yas/template-condition p)))
2686 (with-current-buffer original-buffer
2687 (if (yas/eval-condition condition)
2692 (insert condition-string " ")
2694 (if (string-match "\\.\\.\\.$" name)
2698 (insert (truncate-string-to-width (or (yas/template-key p) "")
2700 (insert (truncate-string-to-width (key-description (yas/template-keybinding p))
2708 ;;; User convenience functions, for using in snippet definitions
2710 (defvar yas/modified-p nil
2711 "Non-nil if field has been modified by user or transformation.")
2713 (defvar yas/moving-away-p nil
2714 "Non-nil if user is about to exit field.")
2716 (defvar yas/text nil
2717 "Contains current field text.")
2719 (defun yas/substr (str pattern &optional subexp)
2720 "Search PATTERN in STR and return SUBEXPth match.
2722 If found, the content of subexp group SUBEXP (default 0) is
2723 returned, or else the original STR will be returned."
2724 (let ((grp (or subexp 0)))
2726 (if (string-match pattern str)
2727 (match-string-no-properties grp str)
2730 (defun yas/choose-value (possibilities)
2731 "Prompt for a string in the list POSSIBILITIES and return it."
2732 (unless (or yas/moving-away-p
2734 (some #'(lambda (fn)
2735 (funcall fn "Choose: " possibilities))
2736 yas/prompt-functions)))
2738 (defun yas/key-to-value (alist)
2739 "Prompt for a string in the list POSSIBILITIES and return it."
2740 (unless (or yas/moving-away-p
2742 (let ((key (read-key-sequence "")))
2744 (or (cdr (find key alist :key #'car :test #'string=))
2747 (defun yas/throw (text)
2748 "Throw a yas/exception with TEXT as the reason."
2749 (throw 'yas/exception (cons 'yas/exception text)))
2751 (defun yas/verify-value (possibilities)
2752 "Verify that the current field value is in POSSIBILITIES
2754 Otherwise throw exception."
2755 (when (and yas/moving-away-p (notany #'(lambda (pos) (string= pos yas/text)) possibilities))
2756 (yas/throw (format "[yas] field only allows %s" possibilities))))
2758 (defun yas/field-value (number)
2759 "Get the string for field with NUMBER.
2761 Use this in primary and mirror transformations to tget."
2762 (let* ((snippet (car (yas/snippets-at-point)))
2764 (yas/snippet-find-field snippet number))))
2766 (yas/field-text-for-display field))))
2769 "Return `yas/text' if that exists and is non-empty, else nil."
2771 (not (string= "" yas/text)))
2774 ;; (defun yas/selected-text ()
2775 ;; "Return `yas/selected-text' if that exists and is non-empty, else nil."
2776 ;; (if (and yas/selected-text
2777 ;; (not (string= "" yas/selected-text)))
2778 ;; yas/selected-text))
2780 (defun yas/get-field-once (number &optional transform-fn)
2781 (unless yas/modified-p
2783 (funcall transform-fn (yas/field-value number))
2784 (yas/field-value number))))
2786 (defun yas/default-from-field (number)
2787 (unless yas/modified-p
2788 (yas/field-value number)))
2790 (defun yas/inside-string ()
2791 (equal 'font-lock-string-face (get-char-property (1- (point)) 'face)))
2793 (defun yas/unimplemented (&optional missing-feature)
2794 (if yas/current-template
2795 (if (y-or-n-p (format "This snippet is unimplemented (missing %s) Visit the snippet definition? "
2798 (yas/visit-snippet-file-1 yas/current-template))
2799 (message "No implementation. Missing %s" (or missing-feature "something"))))
2802 ;;; Snippet expansion and field management
2804 (defvar yas/active-field-overlay nil
2805 "Overlays the currently active field.")
2807 (defvar yas/field-protection-overlays nil
2808 "Two overlays protect the current active field ")
2810 (defconst yas/prefix nil
2811 "A prefix argument for expansion direct from keybindings")
2813 (defvar yas/selected-text nil
2814 "The selected region deleted on the last snippet expansion.")
2816 (defvar yas/start-column nil
2817 "The column where the snippet expansion started.")
2819 (make-variable-buffer-local 'yas/active-field-overlay)
2820 (make-variable-buffer-local 'yas/field-protection-overlays)
2821 (put 'yas/active-field-overlay 'permanent-local t)
2822 (put 'yas/field-protection-overlays 'permanent-local t)
2824 (defstruct (yas/snippet (:constructor yas/make-snippet ()))
2830 (id (yas/snippet-next-id) :read-only t)
2831 (control-overlay nil)
2833 ;; stacked expansion: the `previous-active-field' slot saves the
2834 ;; active field where the child expansion took place
2835 previous-active-field
2838 (defstruct (yas/field (:constructor yas/make-field (number start end parent-field)))
2848 (defstruct (yas/mirror (:constructor yas/make-mirror (start end transform)))
2855 (defstruct (yas/exit (:constructor yas/make-exit (marker)))
2859 (defun yas/apply-transform (field-or-mirror field &optional empty-on-nil-p)
2860 "Calculate transformed string for FIELD-OR-MIRROR from FIELD.
2862 If there is no transform for ht field, return nil.
2864 If there is a transform but it returns nil, return the empty
2865 string iff EMPTY-ON-NIL-P is true."
2866 (let* ((yas/text (yas/field-text-for-display field))
2868 (yas/modified-p (yas/field-modified-p field))
2869 (yas/moving-away-p nil)
2870 (transform (if (yas/mirror-p field-or-mirror)
2871 (yas/mirror-transform field-or-mirror)
2872 (yas/field-transform field-or-mirror)))
2873 (start-point (if (yas/mirror-p field-or-mirror)
2874 (yas/mirror-start field-or-mirror)
2875 (yas/field-start field-or-mirror)))
2876 (transformed (and transform
2878 (goto-char start-point)
2879 (let ((ret (yas/eval-lisp transform)))
2880 (or ret (and empty-on-nil-p "")))))))
2883 (defsubst yas/replace-all (from to &optional text)
2884 "Replace all occurance from FROM to TO.
2886 With optional string TEXT do it in that string."
2888 (replace-regexp-in-string (regexp-quote from) to text t t)
2889 (goto-char (point-min))
2890 (while (search-forward from nil t)
2891 (replace-match to t t text))))
2893 (defun yas/snippet-find-field (snippet number)
2894 (find-if #'(lambda (field)
2895 (eq number (yas/field-number field)))
2896 (yas/snippet-fields snippet)))
2898 (defun yas/snippet-sort-fields (snippet)
2899 "Sort the fields of SNIPPET in navigation order."
2900 (setf (yas/snippet-fields snippet)
2901 (sort (yas/snippet-fields snippet)
2902 #'yas/snippet-field-compare)))
2904 (defun yas/snippet-field-compare (field1 field2)
2905 "Compare two fields. The field with a number is sorted first.
2906 If they both have a number, compare through the number. If neither
2907 have, compare through the field's start point"
2908 (let ((n1 (yas/field-number field1))
2909 (n2 (yas/field-number field2)))
2912 (or (zerop n2) (and (not (zerop n1))
2917 (< (yas/field-start field1)
2918 (yas/field-start field2))))))
2920 (defun yas/field-probably-deleted-p (snippet field)
2921 "Guess if SNIPPET's FIELD should be skipped."
2922 (and (zerop (- (yas/field-start field) (yas/field-end field)))
2923 (or (yas/field-parent-field field)
2924 (and (eq field (car (last (yas/snippet-fields snippet))))
2925 (= (yas/field-start field) (overlay-end (yas/snippet-control-overlay snippet)))))
2926 ;; the field numbered 0, just before the exit marker, should
2928 (not (zerop (yas/field-number field)))))
2930 (defun yas/snippets-at-point (&optional all-snippets)
2931 "Return a sorted list of snippets at point, most recently
2934 (remove nil (remove-duplicates (mapcar #'(lambda (ov)
2935 (overlay-get ov 'yas/snippet))
2937 (overlays-in (point-min) (point-max))
2938 (overlays-at (point))))))
2940 (<= (yas/snippet-id s2) (yas/snippet-id s1)))))
2942 (defun yas/next-field-or-maybe-expand ()
2943 "Try to expand a snippet at a key before point, otherwise
2944 delegate to `yas/next-field'."
2946 (if yas/triggers-in-field
2947 (let ((yas/fallback-behavior 'return-nil)
2948 (active-field (overlay-get yas/active-field-overlay 'yas/field)))
2950 (unless (yas/expand-from-trigger-key active-field)
2954 (defun yas/next-field (&optional arg)
2955 "Navigate to next field. If there's none, exit the snippet."
2959 (snippet (first (yas/snippets-at-point)))
2960 (active-field (overlay-get yas/active-field-overlay 'yas/field))
2961 (live-fields (remove-if #'(lambda (field)
2962 (and (not (eq field active-field))
2963 (yas/field-probably-deleted-p snippet field)))
2964 (yas/snippet-fields snippet)))
2965 (active-field-pos (position active-field live-fields))
2966 (target-pos (and active-field-pos (+ arg active-field-pos)))
2967 (target-field (nth target-pos live-fields)))
2968 ;; First check if we're moving out of a field with a transform
2970 (when (and active-field
2971 (yas/field-transform active-field))
2972 (let* ((yas/moving-away-p t)
2973 (yas/text (yas/field-text-for-display active-field))
2975 (yas/modified-p (yas/field-modified-p active-field)))
2976 ;; primary field transform: exit call to field-transform
2977 (yas/eval-lisp (yas/field-transform active-field))))
2978 ;; Now actually move...
2979 (cond ((>= target-pos (length live-fields))
2980 (yas/exit-snippet snippet))
2982 (yas/move-to-field snippet target-field))
2986 (defun yas/place-overlays (snippet field)
2987 "Correctly place overlays for SNIPPET's FIELD"
2988 (yas/make-move-field-protection-overlays snippet field)
2989 (yas/make-move-active-field-overlay snippet field))
2991 (defun yas/move-to-field (snippet field)
2992 "Update SNIPPET to move to field FIELD.
2994 Also create some protection overlays"
2995 (goto-char (yas/field-start field))
2996 (yas/place-overlays snippet field)
2997 (overlay-put yas/active-field-overlay 'yas/field field)
2998 (let ((number (yas/field-number field)))
2999 ;; check for the special ${0: ...} field
3000 (if (and number (zerop number))
3002 (set-mark (yas/field-end field))
3003 (setf (yas/snippet-force-exit snippet)
3004 (or (yas/field-transform field)
3006 ;; make this field active
3007 (setf (yas/snippet-active-field snippet) field)
3008 ;; primary field transform: first call to snippet transform
3009 (unless (yas/field-modified-p field)
3010 (if (yas/field-update-display field snippet)
3011 (let ((inhibit-modification-hooks t))
3012 (yas/update-mirrors snippet))
3013 (setf (yas/field-modified-p field) nil))))))
3015 (defun yas/prev-field ()
3016 "Navigate to prev field. If there's none, exit the snippet."
3018 (yas/next-field -1))
3020 (defun yas/abort-snippet (&optional snippet)
3022 (let ((snippet (or snippet
3023 (car (yas/snippets-at-point)))))
3025 (setf (yas/snippet-force-exit snippet) t))))
3027 (defun yas/exit-snippet (snippet)
3028 "Goto exit-marker of SNIPPET."
3030 (setf (yas/snippet-force-exit snippet) t)
3031 (goto-char (if (yas/snippet-exit snippet)
3032 (yas/exit-marker (yas/snippet-exit snippet))
3033 (overlay-end (yas/snippet-control-overlay snippet)))))
3035 (defun yas/exit-all-snippets ()
3036 "Exit all snippets."
3038 (mapc #'(lambda (snippet)
3039 (yas/exit-snippet snippet)
3040 (yas/check-commit-snippet))
3041 (yas/snippets-at-point)))
3044 ;;; Some low level snippet-routines
3046 (defun yas/commit-snippet (snippet)
3047 "Commit SNIPPET, but leave point as it is. This renders the
3048 snippet as ordinary text.
3050 Return a buffer position where the point should be placed if
3051 exiting the snippet.
3053 NO-HOOKS means don't run the `yas/after-exit-snippet-hook' hooks."
3055 (let ((control-overlay (yas/snippet-control-overlay snippet))
3059 ;; Save the end of the moribund snippet in case we need to revive it
3060 ;; its original expansion.
3062 (when (and control-overlay
3063 (overlay-buffer control-overlay))
3064 (setq yas/snippet-beg (overlay-start control-overlay))
3065 (setq yas/snippet-end (overlay-end control-overlay))
3066 (delete-overlay control-overlay))
3068 (let ((inhibit-modification-hooks t))
3069 (when yas/active-field-overlay
3070 (delete-overlay yas/active-field-overlay))
3071 (when yas/field-protection-overlays
3072 (mapc #'delete-overlay yas/field-protection-overlays)))
3074 ;; stacked expansion: if the original expansion took place from a
3075 ;; field, make sure we advance it here at least to
3076 ;; `yas/snippet-end'...
3078 (let ((previous-field (yas/snippet-previous-active-field snippet)))
3079 (when (and yas/snippet-end previous-field)
3080 (yas/advance-end-maybe previous-field yas/snippet-end)))
3082 ;; Convert all markers to points,
3084 (yas/markers-to-points snippet)
3086 ;; Take care of snippet revival
3088 (if yas/snippet-revival
3089 (push `(apply yas/snippet-revive ,yas/snippet-beg ,yas/snippet-end ,snippet)
3091 ;; Dismember the snippet... this is useful if we get called
3092 ;; again from `yas/take-care-of-redo'....
3093 (setf (yas/snippet-fields snippet) nil)))
3095 (message "[yas] snippet %s exited." (yas/snippet-id snippet)))
3097 (defun yas/check-commit-snippet ()
3098 "Checks if point exited the currently active field of the
3099 snippet, if so cleans up the whole snippet up."
3100 (let* ((snippets (yas/snippets-at-point 'all-snippets))
3101 (snippets-left snippets)
3102 (snippet-exit-transform))
3103 (dolist (snippet snippets)
3104 (let ((active-field (yas/snippet-active-field snippet)))
3105 (setq snippet-exit-transform (yas/snippet-force-exit snippet))
3106 (cond ((or snippet-exit-transform
3107 (not (and active-field (yas/field-contains-point-p active-field))))
3108 (setq snippets-left (delete snippet snippets-left))
3109 (setf (yas/snippet-force-exit snippet) nil)
3110 (yas/commit-snippet snippet))
3112 (or (not yas/active-field-overlay)
3113 (not (overlay-buffer yas/active-field-overlay))))
3115 ;; stacked expansion: this case is mainly for recent
3116 ;; snippet exits that place us back int the field of
3120 (yas/move-to-field snippet active-field)
3121 (yas/update-mirrors snippet)))
3124 (unless snippets-left
3125 (if snippet-exit-transform
3126 (yas/eval-lisp-no-saves snippet-exit-transform)
3127 (run-hooks 'yas/after-exit-snippet-hook)))))
3129 ;; Apropos markers-to-points:
3131 ;; This was found useful for performance reasons, so that an
3132 ;; excessive number of live markers aren't kept around in the
3133 ;; `buffer-undo-list'. However, in `markers-to-points', the
3134 ;; set-to-nil markers can't simply be discarded and replaced with
3135 ;; fresh ones in `points-to-markers'. The original marker that was
3136 ;; just set to nil has to be reused.
3138 ;; This shouldn't bring horrible problems with undo/redo, but it
3141 (defun yas/markers-to-points (snippet)
3142 "Convert all markers in SNIPPET to a cons (POINT . MARKER)
3143 where POINT is the original position of the marker and MARKER is
3144 the original marker object with the position set to nil."
3145 (dolist (field (yas/snippet-fields snippet))
3146 (let ((start (marker-position (yas/field-start field)))
3147 (end (marker-position (yas/field-end field))))
3148 (set-marker (yas/field-start field) nil)
3149 (set-marker (yas/field-end field) nil)
3150 (setf (yas/field-start field) (cons start (yas/field-start field)))
3151 (setf (yas/field-end field) (cons end (yas/field-end field))))
3152 (dolist (mirror (yas/field-mirrors field))
3153 (let ((start (marker-position (yas/mirror-start mirror)))
3154 (end (marker-position (yas/mirror-end mirror))))
3155 (set-marker (yas/mirror-start mirror) nil)
3156 (set-marker (yas/mirror-end mirror) nil)
3157 (setf (yas/mirror-start mirror) (cons start (yas/mirror-start mirror)))
3158 (setf (yas/mirror-end mirror) (cons end (yas/mirror-end mirror))))))
3159 (let ((snippet-exit (yas/snippet-exit snippet)))
3161 (let ((exit (marker-position (yas/exit-marker snippet-exit))))
3162 (set-marker (yas/exit-marker snippet-exit) nil)
3163 (setf (yas/exit-marker snippet-exit) (cons exit (yas/exit-marker snippet-exit)))))))
3165 (defun yas/points-to-markers (snippet)
3166 "Convert all cons (POINT . MARKER) in SNIPPET to markers. This
3167 is done by setting MARKER to POINT with `set-marker'."
3168 (dolist (field (yas/snippet-fields snippet))
3169 (setf (yas/field-start field) (set-marker (cdr (yas/field-start field))
3170 (car (yas/field-start field))))
3171 (setf (yas/field-end field) (set-marker (cdr (yas/field-end field))
3172 (car (yas/field-end field))))
3173 (dolist (mirror (yas/field-mirrors field))
3174 (setf (yas/mirror-start mirror) (set-marker (cdr (yas/mirror-start mirror))
3175 (car (yas/mirror-start mirror))))
3176 (setf (yas/mirror-end mirror) (set-marker (cdr (yas/mirror-end mirror))
3177 (car (yas/mirror-end mirror))))))
3178 (let ((snippet-exit (yas/snippet-exit snippet)))
3180 (setf (yas/exit-marker snippet-exit) (set-marker (cdr (yas/exit-marker snippet-exit))
3181 (car (yas/exit-marker snippet-exit)))))))
3183 (defun yas/field-contains-point-p (field &optional point)
3184 (let ((point (or point
3186 (and (>= point (yas/field-start field))
3187 (<= point (yas/field-end field)))))
3189 (defun yas/field-text-for-display (field)
3190 "Return the propertized display text for field FIELD. "
3191 (buffer-substring (yas/field-start field) (yas/field-end field)))
3193 (defun yas/undo-in-progress ()
3194 "True if some kind of undo is in progress"
3195 (or undo-in-progress
3196 (eq this-command 'undo)
3197 (eq this-command 'redo)))
3199 (defun yas/make-control-overlay (snippet start end)
3200 "Creates the control overlay that surrounds the snippet and
3202 (let ((overlay (make-overlay start
3207 (overlay-put overlay 'keymap yas/keymap)
3208 (overlay-put overlay 'yas/snippet snippet)
3211 (defun yas/skip-and-clear-or-delete-char (&optional field)
3212 "Clears unmodified field if at field start, skips to next tab.
3214 Otherwise deletes a character normally by calling `delete-char'."
3216 (let ((field (or field
3217 (and yas/active-field-overlay
3218 (overlay-buffer yas/active-field-overlay)
3219 (overlay-get yas/active-field-overlay 'yas/field)))))
3221 (not (yas/field-modified-p field))
3222 (eq (point) (marker-position (yas/field-start field))))
3223 (yas/skip-and-clear field)
3226 (call-interactively 'delete-char)))))
3228 (defun yas/skip-and-clear (field)
3229 "Deletes the region of FIELD and sets it modified state to t"
3230 ;; Just before skipping-and-clearing the field, mark its children
3231 ;; fields as modified, too. If the childen have mirrors-in-fields
3232 ;; this prevents them from updating erroneously (we're skipping and
3235 (yas/mark-this-and-children-modified field)
3236 (delete-region (yas/field-start field) (yas/field-end field)))
3238 (defun yas/mark-this-and-children-modified (field)
3239 (setf (yas/field-modified-p field) t)
3240 (let ((fom (yas/field-next field)))
3242 (yas/fom-parent-field fom))
3243 (when (and (eq (yas/fom-parent-field fom) field)
3245 (yas/mark-this-and-children-modified fom))
3246 (setq fom (yas/fom-next fom)))))
3248 (defun yas/make-move-active-field-overlay (snippet field)
3249 "Place the active field overlay in SNIPPET's FIELD.
3251 Move the overlay, or create it if it does not exit."
3252 (if (and yas/active-field-overlay
3253 (overlay-buffer yas/active-field-overlay))
3254 (move-overlay yas/active-field-overlay
3255 (yas/field-start field)
3256 (yas/field-end field))
3257 (setq yas/active-field-overlay
3258 (make-overlay (yas/field-start field)
3259 (yas/field-end field)
3261 (overlay-put yas/active-field-overlay 'priority 100)
3262 (overlay-put yas/active-field-overlay 'face 'yas/field-highlight-face)
3263 (overlay-put yas/active-field-overlay 'yas/snippet snippet)
3264 (overlay-put yas/active-field-overlay 'modification-hooks '(yas/on-field-overlay-modification))
3265 (overlay-put yas/active-field-overlay 'insert-in-front-hooks
3266 '(yas/on-field-overlay-modification))
3267 (overlay-put yas/active-field-overlay 'insert-behind-hooks
3268 '(yas/on-field-overlay-modification))))
3270 (defun yas/on-field-overlay-modification (overlay after? beg end &optional length)
3271 "Clears the field and updates mirrors, conditionally.
3273 Only clears the field if it hasn't been modified and it point it
3274 at field start. This hook doesn't do anything if an undo is in
3276 (unless (yas/undo-in-progress)
3277 (let* ((field (overlay-get overlay 'yas/field))
3278 (number (and field (yas/field-number field)))
3279 (snippet (overlay-get yas/active-field-overlay 'yas/snippet)))
3281 (yas/advance-end-maybe field (overlay-end overlay))
3282 (let ((saved-point (point)))
3283 (yas/field-update-display field (car (yas/snippets-at-point)))
3284 (goto-char saved-point))
3285 (yas/update-mirrors (car (yas/snippets-at-point))))
3287 (when (and (not after?)
3288 (not (yas/field-modified-p field))
3289 (eq (point) (if (markerp (yas/field-start field))
3290 (marker-position (yas/field-start field))
3291 (yas/field-start field))))
3292 (yas/skip-and-clear field))
3293 (setf (yas/field-modified-p field) t))))))
3295 ;;; Apropos protection overlays:
3297 ;; These exist for nasty users who will try to delete parts of the
3298 ;; snippet outside the active field. Actual protection happens in
3299 ;; `yas/on-protection-overlay-modification'.
3301 ;; Currently this signals an error which inhibits the command. For
3302 ;; commands that move point (like `kill-line'), point is restored in
3303 ;; the `yas/post-command-handler' using a global
3304 ;; `yas/protection-violation' variable.
3306 ;; Alternatively, I've experimented with an implementation that
3307 ;; commits the snippet before actually calling `this-command'
3308 ;; interactively, and then signals an eror, which is ignored. but
3309 ;; blocks all other million modification hooks. This presented some
3310 ;; problems with stacked expansion.
3313 (defun yas/make-move-field-protection-overlays (snippet field)
3314 "Place protection overlays surrounding SNIPPET's FIELD.
3316 Move the overlays, or create them if they do not exit."
3317 (let ((start (yas/field-start field))
3318 (end (yas/field-end field)))
3319 ;; First check if the (1+ end) is contained in the buffer,
3320 ;; otherwise we'll have to do a bit of cheating and silently
3321 ;; insert a newline. the `(1+ (buffer-size))' should prevent this
3322 ;; when using stacked expansion
3324 (when (< (buffer-size) end)
3326 (let ((inhibit-modification-hooks t))
3327 (goto-char (point-max))
3329 ;; go on to normal overlay creation/moving
3331 (cond ((and yas/field-protection-overlays
3332 (every #'overlay-buffer yas/field-protection-overlays))
3333 (move-overlay (first yas/field-protection-overlays) (1- start) start)
3334 (move-overlay (second yas/field-protection-overlays) end (1+ end)))
3336 (setq yas/field-protection-overlays
3337 (list (make-overlay (1- start) start nil t nil)
3338 (make-overlay end (1+ end) nil t nil)))
3339 (dolist (ov yas/field-protection-overlays)
3340 (overlay-put ov 'face 'yas/field-debug-face)
3341 (overlay-put ov 'yas/snippet snippet)
3342 ;; (overlay-put ov 'evaporate t)
3343 (overlay-put ov 'modification-hooks '(yas/on-protection-overlay-modification)))))))
3345 (defvar yas/protection-violation nil
3346 "When non-nil, signals attempts to erronesly exit or modify the snippet.
3348 Functions in the `post-command-hook', for example
3349 `yas/post-command-handler' can check it and reset its value to
3350 nil. The variables value is the point where the violation
3353 (defun yas/on-protection-overlay-modification (overlay after? beg end &optional length)
3354 "Signals a snippet violation, then issues error.
3356 The error should be ignored in `debug-ignored-errors'"
3357 (cond ((not (or after?
3358 (yas/undo-in-progress)))
3359 (setq yas/protection-violation (point))
3360 (error "Exit the snippet first!"))))
3362 (add-to-list 'debug-ignored-errors "^Exit the snippet first!$")
3365 ;;; Apropos stacked expansion:
3367 ;; the parent snippet does not run its fields modification hooks
3368 ;; (`yas/on-field-overlay-modification' and
3369 ;; `yas/on-protection-overlay-modification') while the child snippet
3370 ;; is active. This means, among other things, that the mirrors of the
3371 ;; parent snippet are not updated, this only happening when one exits
3372 ;; the child snippet.
3374 ;; Unfortunately, this also puts some ugly (and not fully-tested)
3375 ;; bits of code in `yas/expand-snippet' and
3376 ;; `yas/commit-snippet'. I've tried to mark them with "stacked
3379 ;; This was thought to be safer in in an undo/redo perpective, but
3380 ;; maybe the correct implementation is to make the globals
3381 ;; `yas/active-field-overlay' and `yas/field-protection-overlays' be
3382 ;; snippet-local and be active even while the child snippet is
3383 ;; running. This would mean a lot of overlay modification hooks
3384 ;; running, but if managed correctly (including overlay priorities)
3385 ;; they should account for all situations...
3388 (defun yas/expand-snippet (content &optional start end expand-env)
3389 "Expand snippet CONTENT at current point.
3391 Text between START and END will be deleted before inserting
3392 template. EXPAND-ENV is are let-style variable to value bindings
3393 considered when expanding the snippet."
3394 (run-hooks 'yas/before-expand-snippet-hook)
3396 ;; If a region is active, set `yas/selected-text'
3397 (setq yas/selected-text
3398 (when (region-active-p)
3399 (prog1 (buffer-substring-no-properties (region-beginning)
3401 (unless start (setq start (region-beginning))
3402 (unless end (setq end (region-end)))))))
3408 (let ((to-delete (and start end (buffer-substring-no-properties start end)))
3409 (start (or start (point)))
3410 (end (or end (point)))
3412 (setq yas/indent-original-column (current-column))
3413 ;; Delete the region to delete, this *does* get undo-recorded.
3415 (when (and to-delete
3417 (delete-region start end))
3419 (cond ((listp content)
3420 ;; x) This is a snippet-command
3422 (yas/eval-lisp-no-saves content))
3424 ;; x) This is a snippet-snippet :-)
3426 ;; Narrow the region down to the content, shoosh the
3427 ;; `buffer-undo-list', and create the snippet, the new
3428 ;; snippet updates its mirrors once, so we are left with
3429 ;; some plain text. The undo action for deleting this
3430 ;; plain text will get recorded at the end.
3432 ;; stacked expansion: also shoosh the overlay modification hooks
3434 (narrow-to-region start start)
3435 (let ((inhibit-modification-hooks t)
3436 (buffer-undo-list t))
3437 ;; snippet creation might evaluate users elisp, which
3438 ;; might generate errors, so we have to be ready to catch
3439 ;; them mostly to make the undo information
3441 (setq yas/start-column (save-restriction (widen) (current-column)))
3445 (eval `(let ,expand-env
3447 (yas/snippet-create (point-min) (point-max))))
3449 (yas/snippet-create (point-min) (point-max))))))
3451 ;; stacked-expansion: This checks for stacked expansion, save the
3452 ;; `yas/previous-active-field' and advance its boudary.
3454 (let ((existing-field (and yas/active-field-overlay
3455 (overlay-buffer yas/active-field-overlay)
3456 (overlay-get yas/active-field-overlay 'yas/field))))
3457 (when existing-field
3458 (setf (yas/snippet-previous-active-field snippet) existing-field)
3459 (yas/advance-end-maybe existing-field (overlay-end yas/active-field-overlay))))
3461 ;; Exit the snippet immediately if no fields
3463 (unless (yas/snippet-fields snippet)
3464 (yas/exit-snippet snippet))
3466 ;; Push two undo actions: the deletion of the inserted contents of
3467 ;; the new snippet (without the "key") followed by an apply of
3468 ;; `yas/take-care-of-redo' on the newly inserted snippet boundaries
3470 ;; A small exception, if `yas/also-auto-indent-first-line'
3471 ;; is t and `yas/indent' decides to indent the line to a
3472 ;; point before the actual expansion point, undo would be
3473 ;; messed up. We call the early point "newstart"". case,
3474 ;; and attempt to fix undo.
3476 (let ((newstart (overlay-start (yas/snippet-control-overlay snippet)))
3477 (end (overlay-end (yas/snippet-control-overlay snippet))))
3478 (when (< newstart start)
3479 (push (cons (make-string (- start newstart) ? ) newstart) buffer-undo-list))
3480 (push (cons newstart end) buffer-undo-list)
3481 (push `(apply yas/take-care-of-redo ,start ,end ,snippet)
3483 ;; Now, schedule a move to the first field
3485 (let ((first-field (car (yas/snippet-fields snippet))))
3487 (sit-for 0) ;; fix issue 125
3488 (yas/move-to-field snippet first-field)))
3489 (message "[yas] snippet expanded.")
3492 (defun yas/take-care-of-redo (beg end snippet)
3493 "Commits SNIPPET, which in turn pushes an undo action for
3496 Meant to exit in the `buffer-undo-list'."
3497 ;; slightly optimize: this action is only needed for snippets with
3498 ;; at least one field
3499 (when (yas/snippet-fields snippet)
3500 (yas/commit-snippet snippet)))
3502 (defun yas/snippet-revive (beg end snippet)
3503 "Revives the SNIPPET and creates a control overlay from BEG to
3506 BEG and END are, we hope, the original snippets boudaries. All
3507 the markers/points exiting existing inside SNIPPET should point
3508 to their correct locations *at the time the snippet is revived*.
3510 After revival, push the `yas/take-care-of-redo' in the
3512 ;; Reconvert all the points to markers
3514 (yas/points-to-markers snippet)
3515 ;; When at least one editable field existed in the zombie snippet,
3516 ;; try to revive the whole thing...
3518 (let ((target-field (or (yas/snippet-active-field snippet)
3519 (car (yas/snippet-fields snippet)))))
3521 (setf (yas/snippet-control-overlay snippet) (yas/make-control-overlay snippet beg end))
3522 (overlay-put (yas/snippet-control-overlay snippet) 'yas/snippet snippet)
3524 (yas/move-to-field snippet target-field)
3526 (push `(apply yas/take-care-of-redo ,beg ,end ,snippet)
3527 buffer-undo-list))))
3529 (defun yas/snippet-create (begin end)
3530 "Creates a snippet from an template inserted between BEGIN and END.
3532 Returns the newly created snippet."
3533 (let ((snippet (yas/make-snippet)))
3535 (yas/snippet-parse-create snippet)
3537 ;; Sort and link each field
3538 (yas/snippet-sort-fields snippet)
3540 ;; Create keymap overlay for snippet
3541 (setf (yas/snippet-control-overlay snippet)
3542 (yas/make-control-overlay snippet (point-min) (point-max)))
3545 (goto-char (point-max))
3550 ;;; Apropos adjacencies and "fom's":
3552 ;; Once the $-constructs bits like "$n" and "${:n" are deleted in the
3553 ;; recently expanded snippet, we might actually have many fields,
3554 ;; mirrors (and the snippet exit) in the very same position in the
3555 ;; buffer. Therefore we need to single-link the
3556 ;; fields-or-mirrors-or-exit, which I have called "fom", according to
3557 ;; their original positions in the buffer.
3559 ;; Then we have operation `yas/advance-end-maybe' and
3560 ;; `yas/advance-start-maybe', which conditionally push the starts and
3561 ;; ends of these foms down the chain.
3563 ;; This allows for like the printf with the magic ",":
3565 ;; printf ("${1:%s}\\n"${1:$(if (string-match "%" text) "," "\);")} \
3566 ;; $2${1:$(if (string-match "%" text) "\);" "")}$0
3568 (defun yas/fom-start (fom)
3569 (cond ((yas/field-p fom)
3570 (yas/field-start fom))
3572 (yas/mirror-start fom))
3574 (yas/exit-marker fom))))
3576 (defun yas/fom-end (fom)
3577 (cond ((yas/field-p fom)
3578 (yas/field-end fom))
3580 (yas/mirror-end fom))
3582 (yas/exit-marker fom))))
3584 (defun yas/fom-next (fom)
3585 (cond ((yas/field-p fom)
3586 (yas/field-next fom))
3588 (yas/mirror-next fom))
3590 (yas/exit-next fom))))
3592 (defun yas/fom-parent-field (fom)
3593 (cond ((yas/field-p fom)
3594 (yas/field-parent-field fom))
3596 (yas/mirror-parent-field fom))
3600 (defun yas/calculate-adjacencies (snippet)
3601 "Calculate adjacencies for fields or mirrors of SNIPPET.
3603 This is according to their relative positions in the buffer, and
3604 has to be called before the $-constructs are deleted."
3605 (flet ((yas/fom-set-next-fom (fom nextfom)
3606 (cond ((yas/field-p fom)
3607 (setf (yas/field-next fom) nextfom))
3609 (setf (yas/mirror-next fom) nextfom))
3611 (setf (yas/exit-next fom) nextfom))))
3612 (yas/compare-fom-begs (fom1 fom2)
3613 (if (= (yas/fom-start fom2) (yas/fom-start fom1))
3615 (>= (yas/fom-start fom2) (yas/fom-start fom1))))
3616 (yas/link-foms (fom1 fom2)
3617 (yas/fom-set-next-fom fom1 fom2)))
3618 ;; make some yas/field, yas/mirror and yas/exit soup
3620 (when (yas/snippet-exit snippet)
3621 (push (yas/snippet-exit snippet) soup))
3622 (dolist (field (yas/snippet-fields snippet))
3624 (dolist (mirror (yas/field-mirrors field))
3625 (push mirror soup)))
3628 #'yas/compare-fom-begs))
3630 (reduce #'yas/link-foms soup)))))
3632 (defun yas/calculate-mirrors-in-fields (snippet mirror)
3633 "Attempt to assign a parent field of SNIPPET to the mirror MIRROR.
3635 Use the tighest containing field if more than one field contains
3636 the mirror. Intended to be called *before* the dollar-regions are
3638 (let ((min (point-min))
3640 (dolist (field (yas/snippet-fields snippet))
3641 (when (and (<= (yas/field-start field) (yas/mirror-start mirror))
3642 (<= (yas/mirror-end mirror) (yas/field-end field))
3643 (< min (yas/field-start field))
3644 (< (yas/field-end field) max))
3645 (setq min (yas/field-start field)
3646 max (yas/field-end field))
3647 (setf (yas/mirror-parent-field mirror) field)))))
3649 (defun yas/advance-end-maybe (fom newend)
3650 "Maybe advance FOM's end to NEWEND if it needs it.
3654 * call `yas/advance-start-maybe' on FOM's next fom.
3656 * in case FOM is field call `yas/advance-end-maybe' on its parent
3659 Also, if FOM is an exit-marker, always call
3660 `yas/advance-start-maybe' on its next fom. This is beacuse
3661 exit-marker have identical start and end markers.
3664 (cond ((and fom (< (yas/fom-end fom) newend))
3665 (set-marker (yas/fom-end fom) newend)
3666 (yas/advance-start-maybe (yas/fom-next fom) newend)
3667 (let ((parent (yas/fom-parent-field fom)))
3669 (yas/advance-end-maybe parent newend))))
3671 (yas/advance-start-maybe (yas/fom-next fom) newend))))
3673 (defun yas/advance-start-maybe (fom newstart)
3674 "Maybe advance FOM's start to NEWSTART if it needs it.
3676 If it does, also call `yas/advance-end-maybe' on FOM."
3677 (when (and fom (< (yas/fom-start fom) newstart))
3678 (set-marker (yas/fom-start fom) newstart)
3679 (yas/advance-end-maybe fom newstart)))
3681 (defun yas/advance-end-of-parents-maybe (field newend)
3682 "Like `yas/advance-end-maybe' but for parents."
3684 (< (yas/field-end field) newend))
3685 (set-marker (yas/field-end field) newend)
3686 (yas/advance-end-of-parents-maybe (yas/field-parent-field field) newend)))
3688 (defvar yas/dollar-regions nil
3689 "When expanding the snippet the \"parse-create\" functions add
3690 cons cells to this var")
3692 (defun yas/snippet-parse-create (snippet)
3693 "Parse a recently inserted snippet template, creating all
3694 necessary fields, mirrors and exit points.
3696 Meant to be called in a narrowed buffer, does various passes"
3697 (let ((parse-start (point)))
3698 ;; Reset the yas/dollar-regions
3700 (setq yas/dollar-regions nil)
3701 ;; protect escaped quote, backquotes and backslashes
3703 (yas/protect-escapes nil '(?\\ ?` ?'))
3704 ;; replace all backquoted expressions
3706 (goto-char parse-start)
3707 (yas/replace-backquotes)
3708 ;; protect escapes again since previous steps might have generated
3709 ;; more characters needing escaping
3711 (goto-char parse-start)
3712 (yas/protect-escapes)
3713 ;; parse fields with {}
3715 (goto-char parse-start)
3716 (yas/field-parse-create snippet)
3717 ;; parse simple mirrors and fields
3719 (goto-char parse-start)
3720 (yas/simple-mirror-parse-create snippet)
3721 ;; parse mirror transforms
3723 (goto-char parse-start)
3724 (yas/transform-mirror-parse-create snippet)
3725 ;; calculate adjacencies of fields and mirrors
3727 (yas/calculate-adjacencies snippet)
3728 ;; Delete $-constructs
3730 (yas/delete-regions yas/dollar-regions)
3733 (goto-char parse-start)
3734 (yas/restore-escapes)
3735 ;; update mirrors for the first time
3737 (yas/update-mirrors snippet)
3738 ;; indent the best we can
3740 (goto-char parse-start)
3741 (yas/indent snippet)))
3743 (defun yas/indent-according-to-mode (snippet-markers)
3744 "Indent current line according to mode, preserving
3746 ;;; Apropos indenting problems....
3748 ;; `indent-according-to-mode' uses whatever `indent-line-function'
3749 ;; is available. Some implementations of these functions delete text
3750 ;; before they insert. If there happens to be a marker just after
3751 ;; the text being deleted, the insertion actually happens after the
3752 ;; marker, which misplaces it.
3754 ;; This would also happen if we had used overlays with the
3755 ;; `front-advance' property set to nil.
3757 ;; This is why I have these `trouble-markers', they are the ones at
3758 ;; they are the ones at the first non-whitespace char at the line
3759 ;; (i.e. at `yas/real-line-beginning'. After indentation takes place
3760 ;; we should be at the correct to restore them to. All other
3761 ;; non-trouble-markers have been *pushed* and don't need special
3764 (goto-char (yas/real-line-beginning))
3765 (let ((trouble-markers (remove-if-not #'(lambda (marker)
3771 (indent-according-to-mode)
3772 (error (message "[yas] warning: yas/indent-according-to-mode habing problems running %s" indent-line-function)
3774 (mapc #'(lambda (marker)
3775 (set-marker marker (point)))
3778 (defvar yas/indent-original-column nil)
3779 (defun yas/indent (snippet)
3780 (let ((snippet-markers (yas/collect-snippet-markers snippet)))
3781 ;; Look for those $>
3783 (while (re-search-forward "$>" nil t)
3784 (delete-region (match-beginning 0) (match-end 0))
3785 (when (not (eq yas/indent-line 'auto))
3786 (yas/indent-according-to-mode snippet-markers))))
3787 ;; Now do stuff for 'fixed and 'auto
3789 (cond ((eq yas/indent-line 'fixed)
3790 (while (and (zerop (forward-line))
3791 (zerop (current-column)))
3792 (indent-to-column yas/indent-original-column)))
3793 ((eq yas/indent-line 'auto)
3794 (let ((end (set-marker (make-marker) (point-max)))
3795 (indent-first-line-p yas/also-auto-indent-first-line))
3796 (while (and (zerop (if indent-first-line-p
3799 (setq indent-first-line-p nil))
3803 (yas/indent-according-to-mode snippet-markers))))
3807 (defun yas/collect-snippet-markers (snippet)
3808 "Make a list of all the markers used by SNIPPET."
3810 (dolist (field (yas/snippet-fields snippet))
3811 (push (yas/field-start field) markers)
3812 (push (yas/field-end field) markers)
3813 (dolist (mirror (yas/field-mirrors field))
3814 (push (yas/mirror-start mirror) markers)
3815 (push (yas/mirror-end mirror) markers)))
3816 (let ((snippet-exit (yas/snippet-exit snippet)))
3817 (when (and snippet-exit
3818 (marker-buffer (yas/exit-marker snippet-exit)))
3819 (push (yas/exit-marker snippet-exit) markers)))
3822 (defun yas/real-line-beginning ()
3823 (let ((c (char-after (line-beginning-position)))
3824 (n (line-beginning-position)))
3825 (while (or (eql c ?\ )
3828 (setq c (char-after n)))
3831 (defun yas/escape-string (escaped)
3832 (concat "YASESCAPE" (format "%d" escaped) "PROTECTGUARD"))
3834 (defun yas/protect-escapes (&optional text escaped)
3835 "Protect all escaped characters with their numeric ASCII value.
3837 With optional string TEXT do it in string instead of buffer."
3838 (let ((changed-text text)
3839 (text-provided-p text))
3840 (mapc #'(lambda (escaped)
3842 (yas/replace-all (concat "\\" (char-to-string escaped))
3843 (yas/escape-string escaped)
3844 (when text-provided-p changed-text))))
3845 (or escaped yas/escaped-characters))
3848 (defun yas/restore-escapes (&optional text escaped)
3849 "Restore all escaped characters from their numeric ASCII value.
3851 With optional string TEXT do it in string instead of the buffer."
3852 (let ((changed-text text)
3853 (text-provided-p text))
3854 (mapc #'(lambda (escaped)
3856 (yas/replace-all (yas/escape-string escaped)
3857 (char-to-string escaped)
3858 (when text-provided-p changed-text))))
3859 (or escaped yas/escaped-characters))
3862 (defun yas/replace-backquotes ()
3863 "Replace all the \"`(lisp-expression)`\"-style expression
3864 with their evaluated value"
3865 (while (re-search-forward yas/backquote-lisp-expression-regexp nil t)
3866 (let ((current-string (match-string 1)) transformed)
3867 (delete-region (match-beginning 0) (match-end 0))
3868 (setq transformed (yas/eval-lisp (yas/read-lisp (yas/restore-escapes current-string))))
3869 (goto-char (match-beginning 0))
3870 (when transformed (insert transformed)))))
3872 (defun yas/scan-sexps (from count)
3874 (with-syntax-table (standard-syntax-table)
3875 (scan-sexps from count))
3879 (defun yas/make-marker (pos)
3880 "Create a marker at POS with `nil' `marker-insertion-type'"
3881 (let ((marker (set-marker (make-marker) pos)))
3882 (set-marker-insertion-type marker nil)
3885 (defun yas/field-parse-create (snippet &optional parent-field)
3886 "Parse most field expressions, except for the simple one \"$n\".
3888 The following count as a field:
3890 * \"${n: text}\", for a numbered field with default text, as long as N is not 0;
3892 * \"${n: text$(expression)}, the same with a lisp expression;
3893 this is caught with the curiously named `yas/multi-dollar-lisp-expression-regexp'
3895 * the same as above but unnumbered, (no N:) and number is calculated automatically.
3897 When multiple expressions are found, only the last one counts."
3900 (while (re-search-forward yas/field-regexp nil t)
3901 (let* ((real-match-end-0 (yas/scan-sexps (1+ (match-beginning 0)) 1))
3902 (number (and (match-string-no-properties 1)
3903 (string-to-number (match-string-no-properties 1))))
3904 (brand-new-field (and real-match-end-0
3905 ;; break if on "$(" immediately
3906 ;; after the ":", this will be
3907 ;; caught as a mirror with
3909 (not (save-match-data
3910 (eq (string-match "$[ \t\n]*("
3911 (match-string-no-properties 2)) 0)))
3912 ;; allow ${0: some exit text}
3913 ;; (not (and number (zerop number)))
3914 (yas/make-field number
3915 (yas/make-marker (match-beginning 2))
3916 (yas/make-marker (1- real-match-end-0))
3918 (when brand-new-field
3919 (goto-char real-match-end-0)
3920 (push (cons (1- real-match-end-0) real-match-end-0)
3922 (push (cons (match-beginning 0) (match-beginning 2))
3924 (push brand-new-field (yas/snippet-fields snippet))
3927 (narrow-to-region (yas/field-start brand-new-field) (yas/field-end brand-new-field))
3928 (goto-char (point-min))
3929 (yas/field-parse-create snippet brand-new-field)))))))
3930 ;; if we entered from a parent field, now search for the
3931 ;; `yas/multi-dollar-lisp-expression-regexp'. THis is used for
3932 ;; primary field transformations
3936 (while (re-search-forward yas/multi-dollar-lisp-expression-regexp nil t)
3937 (let* ((real-match-end-1 (yas/scan-sexps (match-beginning 1) 1)))
3938 ;; commit the primary field transformation if:
3940 ;; 1. we don't find it in yas/dollar-regions (a subnested
3941 ;; field) might have already caught it.
3943 ;; 2. we really make sure we have either two '$' or some
3944 ;; text and a '$' after the colon ':'. This is a FIXME: work
3945 ;; my regular expressions and end these ugly hacks.
3947 (when (and real-match-end-1
3948 (not (member (cons (match-beginning 0)
3950 yas/dollar-regions))
3952 (char-before (1- (match-beginning 1))))))
3953 (let ((lisp-expression-string (buffer-substring-no-properties (match-beginning 1)
3955 (setf (yas/field-transform parent-field)
3956 (yas/read-lisp (yas/restore-escapes lisp-expression-string))))
3957 (push (cons (match-beginning 0) real-match-end-1)
3958 yas/dollar-regions)))))))
3960 (defun yas/transform-mirror-parse-create (snippet)
3961 "Parse the \"${n:$(lisp-expression)}\" mirror transformations."
3962 (while (re-search-forward yas/transform-mirror-regexp nil t)
3963 (let* ((real-match-end-0 (yas/scan-sexps (1+ (match-beginning 0)) 1))
3964 (number (string-to-number (match-string-no-properties 1)))
3966 (not (zerop number))
3967 (yas/snippet-find-field snippet number)))
3969 (and real-match-end-0
3971 (yas/make-mirror (yas/make-marker (match-beginning 0))
3972 (yas/make-marker (match-beginning 0))
3974 (yas/restore-escapes
3975 (buffer-substring-no-properties (match-beginning 2)
3976 (1- real-match-end-0))))))))
3977 (when brand-new-mirror
3978 (push brand-new-mirror
3979 (yas/field-mirrors field))
3980 (yas/calculate-mirrors-in-fields snippet brand-new-mirror)
3981 (push (cons (match-beginning 0) real-match-end-0) yas/dollar-regions)))))
3983 (defun yas/simple-mirror-parse-create (snippet)
3984 "Parse the simple \"$n\" fields/mirrors/exitmarkers."
3985 (while (re-search-forward yas/simple-mirror-regexp nil t)
3986 (let ((number (string-to-number (match-string-no-properties 1))))
3987 (cond ((zerop number)
3989 (setf (yas/snippet-exit snippet)
3990 (yas/make-exit (yas/make-marker (match-end 0))))
3992 (goto-char (match-beginning 0))
3993 (when yas/wrap-around-region
3994 (cond (yas/selected-text
3995 (insert yas/selected-text))
3996 ((and (eq yas/wrap-around-region 'cua)
3999 (insert (prog1 (get-register ?0)
4000 (set-register ?0 nil))))))
4001 (push (cons (point) (yas/exit-marker (yas/snippet-exit snippet)))
4002 yas/dollar-regions)))
4004 (let ((field (yas/snippet-find-field snippet number)))
4006 (let ((brand-new-mirror (yas/make-mirror
4007 (yas/make-marker (match-beginning 0))
4008 (yas/make-marker (match-beginning 0))
4010 (push brand-new-mirror
4011 (yas/field-mirrors field))
4012 (yas/calculate-mirrors-in-fields snippet brand-new-mirror))
4013 (push (yas/make-field number
4014 (yas/make-marker (match-beginning 0))
4015 (yas/make-marker (match-beginning 0))
4017 (yas/snippet-fields snippet))))
4018 (push (cons (match-beginning 0) (match-end 0))
4019 yas/dollar-regions))))))
4021 (defun yas/delete-regions (regions)
4022 "Sort disjuct REGIONS by start point, then delete from the back."
4023 (mapc #'(lambda (reg)
4024 (delete-region (car reg) (cdr reg)))
4027 (>= (car r1) (car r2))))))
4029 (defun yas/update-mirrors (snippet)
4030 "Updates all the mirrors of SNIPPET."
4032 (let* ((fields (copy-list (yas/snippet-fields snippet)))
4033 (field (car fields)))
4035 (dolist (mirror (yas/field-mirrors field))
4036 ;; stacked expansion: I added an `inhibit-modification-hooks'
4037 ;; here, for safety, may need to remove if we the mechanism is
4040 (let ((inhibit-modification-hooks t)
4041 (mirror-parent-field (yas/mirror-parent-field mirror)))
4042 ;; updatte this mirror
4044 (yas/mirror-update-display mirror field)
4045 ;; for mirrors-in-fields: schedule a possible
4046 ;; parent field for reupdting later on
4048 (when mirror-parent-field
4049 (add-to-list 'fields mirror-parent-field 'append #'eq))
4050 ;; `yas/place-overlays' is needed if the active field and
4051 ;; protected overlays have been changed because of insertions
4052 ;; in `yas/mirror-update-display'
4054 (when (eq field (yas/snippet-active-field snippet))
4055 (yas/place-overlays snippet field))))
4056 (setq fields (cdr fields))
4057 (setq field (car fields))))))
4059 (defun yas/mirror-update-display (mirror field)
4060 "Update MIRROR according to FIELD (and mirror transform)."
4062 (let* ((mirror-parent-field (yas/mirror-parent-field mirror))
4063 (reflection (and (not (and mirror-parent-field
4064 (yas/field-modified-p mirror-parent-field)))
4065 (or (yas/apply-transform mirror field 'empty-on-nil)
4066 (yas/field-text-for-display field)))))
4067 (when (and reflection
4068 (not (string= reflection (buffer-substring-no-properties (yas/mirror-start mirror)
4069 (yas/mirror-end mirror)))))
4070 (goto-char (yas/mirror-start mirror))
4072 (if (> (yas/mirror-end mirror) (point))
4073 (delete-region (point) (yas/mirror-end mirror))
4074 (set-marker (yas/mirror-end mirror) (point))
4075 (yas/advance-start-maybe (yas/mirror-next mirror) (point))
4076 ;; super-special advance
4077 (yas/advance-end-of-parents-maybe mirror-parent-field (point))))))
4079 (defun yas/field-update-display (field snippet)
4080 "Much like `yas/mirror-update-display', but for fields"
4081 (when (yas/field-transform field)
4082 (let ((inhibit-modification-hooks t)
4083 (transformed (and (not (eq (yas/field-number field) 0))
4084 (yas/apply-transform field field)))
4086 (when (and transformed
4087 (not (string= transformed (buffer-substring-no-properties (yas/field-start field)
4088 (yas/field-end field)))))
4089 (setf (yas/field-modified-p field) t)
4090 (goto-char (yas/field-start field))
4091 (insert transformed)
4092 (if (> (yas/field-end field) (point))
4093 (delete-region (point) (yas/field-end field))
4094 (set-marker (yas/field-end field) (point))
4095 (yas/advance-start-maybe (yas/field-next field) (point)))
4099 ;;; Post-command hooks:
4101 (defvar yas/post-command-runonce-actions nil
4102 "List of actions to run once `post-command-hook'.
4104 Each element of this list looks like (FN . ARGS) where FN is
4105 called with ARGS as its arguments after the currently executing
4108 After all actions have been run, this list is emptied, and after
4109 that the rest of `yas/post-command-handler' runs.")
4111 (defun yas/post-command-handler ()
4112 "Handles various yasnippet conditions after each command."
4113 (when yas/post-command-runonce-actions
4115 (mapc #'(lambda (fn-and-args)
4116 (apply (car fn-and-args)
4118 yas/post-command-runonce-actions)
4119 (error (message "[yas] problem running `yas/post-command-runonce-actions'!")))
4120 (setq yas/post-command-runonce-actions nil))
4121 (cond (yas/protection-violation
4122 (goto-char yas/protection-violation)
4123 (setq yas/protection-violation nil))
4124 ((eq 'undo this-command)
4126 ;; After undo revival the correct field is sometimes not
4127 ;; restored correctly, this condition handles that
4129 (let* ((snippet (car (yas/snippets-at-point)))
4130 (target-field (and snippet
4131 (find-if-not #'(lambda (field)
4132 (yas/field-probably-deleted-p snippet field))
4134 (cons (yas/snippet-active-field snippet)
4135 (yas/snippet-fields snippet)))))))
4137 (yas/move-to-field snippet target-field))))
4138 ((not (yas/undo-in-progress))
4139 ;; When not in an undo, check if we must commit the snippet
4140 ;; (user exited it).
4141 (yas/check-commit-snippet))))
4145 (put 'yas/expand 'function-documentation
4146 '(yas/expand-from-trigger-key-doc))
4147 (defun yas/expand-from-trigger-key-doc ()
4148 "A doc synthethizer for `yas/expand-from-trigger-key-doc'."
4149 (let ((fallback-description
4150 (cond ((eq yas/fallback-behavior 'call-other-command)
4151 (let* ((yas/minor-mode nil)
4152 (fallback (key-binding (read-kbd-macro yas/trigger-key))))
4154 (format " call command `%s'." (pp-to-string fallback)))
4156 ((eq yas/fallback-behavior 'return-nil)
4159 ", defer to `yas/fallback-behaviour' :-)"))))
4160 (concat "Expand a snippet before point. If no snippet
4161 expansion is possible,"
4162 fallback-description
4163 "\n\nOptional argument FIELD is for non-interactive use and is an
4164 object satisfying `yas/field-p' to restrict the expansion to.")))
4166 (put 'yas/expand-from-keymap 'function-documentation '(yas/expand-from-keymap-doc))
4167 (defun yas/expand-from-keymap-doc ()
4168 "A doc synthethizer for `yas/expand-from-keymap-doc'."
4169 (add-hook 'temp-buffer-show-hook 'yas/snippet-description-finish-runonce)
4170 (concat "Expand/run snippets from keymaps, possibly falling back to original binding.\n"
4171 (when (eq this-command 'describe-key)
4172 (let* ((vec (this-single-command-keys))
4173 (templates (mapcan #'(lambda (table)
4174 (yas/fetch table vec))
4175 (yas/get-snippet-tables)))
4176 (yas/direct-keymaps nil)
4177 (fallback (key-binding vec)))
4178 (concat "In this case, "
4180 (concat "these snippets are bound to this key:\n"
4181 (yas/template-pretty-list templates)
4182 "\n\nIf none of these expands, "))
4184 (format "fallback `%s' will be called." (pp-to-string fallback)))
4185 "no fallback keybinding is called."))))))
4187 (defun yas/template-pretty-list (templates)
4189 (yas/buffer-local-condition 'always))
4190 (dolist (plate templates)
4191 (setq acc (concat acc "\n*) "
4192 (propertize (concat "\\\\snippet `" (car plate) "'")
4193 'yasnippet (cdr plate)))))
4196 (define-button-type 'help-snippet-def
4197 :supertype 'help-xref
4198 'help-function (lambda (template) (yas/visit-snippet-file-1 template))
4199 'help-echo (purecopy "mouse-2, RET: find snippets's definition"))
4201 (defun yas/snippet-description-finish-runonce ()
4202 "Final adjustments for the help buffer when snippets are concerned."
4203 (yas/create-snippet-xrefs)
4204 (remove-hook 'temp-buffer-show-hook 'yas/snippet-description-finish-runonce))
4206 (defun yas/create-snippet-xrefs ()
4208 (goto-char (point-min))
4209 (while (search-forward-regexp "\\\\\\\\snippet[ \s\t]+`\\([^']+\\)'" nil t)
4210 (let ((template (get-text-property (match-beginning 1)
4213 (help-xref-button 1 'help-snippet-def template)
4214 (kill-region (match-end 1) (match-end 0))
4215 (kill-region (match-beginning 0) (match-beginning 1)))))))
4217 (defun yas/expand-uuid (mode-symbol uuid &optional start end expand-env)
4218 "Expand a snippet registered in MODE-SYMBOL's table with UUID.
4220 Remaining args as in `yas/expand-snippet'."
4221 (let* ((table (gethash mode-symbol yas/tables))
4222 (yas/current-template (and table
4223 (gethash uuid (yas/table-uuidhash table)))))
4224 (when yas/current-template
4225 (yas/expand-snippet (yas/template-content yas/current-template)))))
4229 ;; `locate-dominating-file' is added for compatibility in emacs < 23
4230 (unless (or (eq emacs-major-version 23)
4231 (fboundp 'locate-dominating-file))
4232 (defvar locate-dominating-stop-dir-regexp
4233 "\\`\\(?:[\\/][\\/][^\\/]+[\\/]\\|/\\(?:net\\|afs\\|\\.\\.\\.\\)/\\)\\'"
4234 "Regexp of directory names which stop the search in `locate-dominating-file'.
4235 Any directory whose name matches this regexp will be treated like
4236 a kind of root directory by `locate-dominating-file' which will stop its search
4237 when it bumps into it.
4238 The default regexp prevents fruitless and time-consuming attempts to find
4239 special files in directories in which filenames are interpreted as hostnames,
4240 or mount points potentially requiring authentication as a different user.")
4242 (defun locate-dominating-file (file name)
4243 "Look up the directory hierarchy from FILE for a file named NAME.
4244 Stop at the first parent directory containing a file NAME,
4245 and return the directory. Return nil if not found."
4246 ;; We used to use the above locate-dominating-files code, but the
4247 ;; directory-files call is very costly, so we're much better off doing
4248 ;; multiple calls using the code in here.
4250 ;; Represent /home/luser/foo as ~/foo so that we don't try to look for
4251 ;; `name' in /home or in /.
4252 (setq file (abbreviate-file-name file))
4255 ;; `user' is not initialized outside the loop because
4256 ;; `file' may not exist, so we may have to walk up part of the
4257 ;; hierarchy before we find the "initial UUID".
4260 (while (not (or root
4262 ;; FIXME: Disabled this heuristic because it is sometimes
4264 ;; As a heuristic, we stop looking up the hierarchy of
4265 ;; directories as soon as we find a directory belonging
4266 ;; to another user. This should save us from looking in
4267 ;; things like /net and /afs. This assumes that all the
4268 ;; files inside a project belong to the same user.
4269 ;; (let ((prev-user user))
4270 ;; (setq user (nth 2 (file-attributes file)))
4271 ;; (and prev-user (not (equal user prev-user))))
4272 (string-match locate-dominating-stop-dir-regexp file)))
4273 (setq try (file-exists-p (expand-file-name name file)))
4274 (cond (try (setq root file))
4275 ((equal file (setq prev-file file
4276 file (file-name-directory
4277 (directory-file-name file))))
4281 ;; `c-neutralize-syntax-in-CPP` sometimes fires "End of Buffer" error
4282 ;; (when it execute forward-char) and interrupt the after change
4283 ;; hook. Thus prevent the insert-behind hook of yasnippet to be
4284 ;; invoked. Here's a way to reproduce it:
4286 ;; # open a *new* Emacs.
4287 ;; # load yasnippet.
4288 ;; # open a *new* .cpp file.
4289 ;; # input "inc" and press TAB to expand the snippet.
4290 ;; # select the `#include <...>` snippet.
4291 ;; # type inside `<>`
4293 (defadvice c-neutralize-syntax-in-CPP
4294 (around yas-mp/c-neutralize-syntax-in-CPP activate)
4295 "Adviced `c-neutralize-syntax-in-CPP' to properly
4296 handle the end-of-buffer error fired in it by calling
4297 `forward-char' at the end of buffer."
4300 (error (message (error-message-string err)))))
4302 ;; disable c-electric-* serial command in YAS fields
4303 (add-hook 'c-mode-common-hook
4305 (dolist (k '(":" ">" ";" "<" "{" "}"))
4306 (define-key (symbol-value (make-local-variable 'yas/keymap))
4307 k 'self-insert-command))))
4309 (provide 'yasnippet)
4311 ;;; yasnippet.el ends here