1 ;;; yasnippet.el --- Yet another snippet extension for Emacs.
3 ;; Copyright (C) 2008-2012 Free Software Foundation, Inc.
4 ;; Authors: pluskid <pluskid@gmail.com>, João Távora <joaotavora@gmail.com>
6 ;; Package-version: 0.8.0
7 ;; X-URL: http://github.com/capitaomorte/yasnippet
8 ;; Keywords: convenience, emulation
9 ;; URL: http://github.com/capitaomorte/yasnippet
10 ;; EmacsWiki: YaSnippetMode
12 ;; This program is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; This program is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
27 ;; Basic steps to setup:
29 ;; (add-to-list 'load-path
30 ;; "~/path-to-yasnippet")
31 ;; (require 'yasnippet)
32 ;; (yas-global-mode 1)
35 ;; Interesting variables are:
39 ;; The directory where user-created snippets are to be
40 ;; stored. Can also be a list of directories. In that case,
41 ;; when used for bulk (re)loading of snippets (at startup or
42 ;; via `yas-reload-all'), directories appearing earlier in
43 ;; the list shadow other dir's snippets. Also, the first
44 ;; directory is taken as the default for storing the user's
47 ;; The deprecated `yas/root-directory' aliases this variable
48 ;; for backward-compatibility.
52 ;; A local variable that you can set in a hook to override
53 ;; snippet-lookup based on major mode. It is a symbol (or
54 ;; list of symbols) that correspond to subdirectories of
55 ;; `yas-snippet-dirs' and is used for deciding which
56 ;; snippets to consider for the active buffer.
58 ;; Deprecated `yas/mode-symbol' aliases this variable for
59 ;; backward-compatibility.
61 ;; Major commands are:
65 ;; Try to expand snippets before point. In `yas-minor-mode',
66 ;; this is bound to `yas-trigger-key' which you can customize.
68 ;; M-x yas-load-directory
70 ;; Prompts you for a directory hierarchy of snippets to load.
72 ;; M-x yas-insert-snippet
74 ;; Prompts you for possible snippet expansion if that is
75 ;; possible according to buffer-local and snippet-local
76 ;; expansion conditions. With prefix argument, ignore these
79 ;; M-x yas-visit-snippet-file
81 ;; Prompts you for possible snippet expansions like
82 ;; `yas-insert-snippet', but instead of expanding it, takes
83 ;; you directly to the snippet definition's file, if it
86 ;; M-x yas-new-snippet
88 ;; Lets you create a new snippet file in the correct
89 ;; subdirectory of `yas-snippet-dirs', according to the
92 ;; M-x yas-load-snippet-buffer
94 ;; When editing a snippet, this loads the snippet. This is
95 ;; bound to "C-c C-c" while in the `snippet-mode' editing
98 ;; M-x yas-tryout-snippet
100 ;; When editing a snippet, this opens a new empty buffer,
101 ;; sets it to the appropriate major mode and inserts the
102 ;; snippet there, so you can see what it looks like. This is
103 ;; bound to "C-c C-t" while in `snippet-mode'.
105 ;; M-x yas-describe-tables
107 ;; Lists known snippets in a separate buffer. User is
108 ;; prompted as to whether only the currently active tables
109 ;; are to be displayed, or all the tables for all major
112 ;; The `dropdown-list.el' extension is bundled with YASnippet, you
113 ;; can optionally use it the preferred "prompting method", putting in
114 ;; your .emacs file, for example:
116 ;; (require 'dropdown-list)
117 ;; (setq yas-prompt-functions '(yas-dropdown-prompt
119 ;; yas-completing-prompt))
121 ;; Also check out the customization group
123 ;; M-x customize-group RET yasnippet RET
125 ;; If you use the customization group to set variables
126 ;; `yas-snippet-dirs' or `yas-global-mode', make sure the path to
127 ;; "yasnippet.el" is present in the `load-path' *before* the
128 ;; `custom-set-variables' is executed in your .emacs file.
130 ;; For more information and detailed usage, refer to the project page:
131 ;; http://github.com/capitaomorte/yasnippet
140 ;;; User customizable variables
142 (defgroup yasnippet nil
143 "Yet Another Snippet extension"
146 (defvar yas--load-file-name load-file-name
147 "Store the filename that yasnippet.el was originally loaded from.")
149 (defcustom yas-snippet-dirs (remove nil
150 (list "~/.emacs.d/snippets"
151 (when yas--load-file-name
152 (concat (file-name-directory yas--load-file-name) "snippets"))))
153 "Directory or list of snippet dirs for each major mode.
155 The directory where user-created snippets are to be stored. Can
156 also be a list of directories. In that case, when used for
157 bulk (re)loading of snippets (at startup or via
158 `yas-reload-all'), directories appearing earlier in the list
159 shadow other dir's snippets. Also, the first directory is taken
160 as the default for storing the user's new snippets."
161 :type '(choice (string :tag "Single directory (string)")
162 (repeat :args (string) :tag "List of directories (strings)"))
165 :set #'(lambda (symbol new)
166 (let ((old (and (boundp symbol)
167 (symbol-value symbol))))
168 (set-default symbol new)
169 (unless (or (not (fboundp 'yas-reload-all))
173 (defun yas-snippet-dirs ()
174 "Returns `yas-snippet-dirs' (which see) as a list."
175 (if (listp yas-snippet-dirs) yas-snippet-dirs (list yas-snippet-dirs)))
177 (defvaralias 'yas/root-directory 'yas-snippet-dirs)
179 (defcustom yas-prompt-functions '(yas-x-prompt
181 yas-completing-prompt
184 "Functions to prompt for keys, templates, etc interactively.
186 These functions are called with the following arguments:
188 - PROMPT: A string to prompt the user
190 - CHOICES: a list of strings or objects.
192 - optional DISPLAY-FN : A function that, when applied to each of
193 the objects in CHOICES will return a string.
195 The return value of any function you put here should be one of
196 the objects in CHOICES, properly formatted with DISPLAY-FN (if
199 - To signal that your particular style of prompting is
200 unavailable at the moment, you can also have the function return
203 - To signal that the user quit the prompting process, you can
206 (signal 'quit \"user quit!\")."
207 :type '(repeat function)
210 (defcustom yas-indent-line 'auto
211 "Controls indenting applied to a recent snippet expansion.
213 The following values are possible:
215 - `fixed' Indent the snippet to the current column;
217 - `auto' Indent each line of the snippet with `indent-according-to-mode'
219 Every other value means don't apply any snippet-side indentation
220 after expansion (the manual per-line \"$>\" indentation still
222 :type '(choice (const :tag "Nothing" nothing)
223 (const :tag "Fixed" fixed)
224 (const :tag "Auto" auto))
227 (defcustom yas-also-auto-indent-first-line nil
228 "Non-nil means also auto indent first line according to mode.
230 Naturally this is only valid when `yas-indent-line' is `auto'"
234 (defcustom yas-snippet-revival t
235 "Non-nil means re-activate snippet fields after undo/redo."
239 (defcustom yas-trigger-key "<tab>"
240 "The key bound to `yas-expand' when `yas-minor-mode' is active.
242 Value is a string that is converted to the internal Emacs key
243 representation using `read-kbd-macro'."
246 :set #'(lambda (symbol key)
247 (let ((old (and (boundp symbol)
248 (symbol-value symbol))))
249 (set-default symbol key)
250 ;; On very first loading of this defcustom,
251 ;; `yas-trigger-key' is *not* loaded.
252 (if (fboundp 'yas--trigger-key-reload)
253 (yas--trigger-key-reload old)))))
255 (defcustom yas-next-field-key '("TAB" "<tab>")
256 "The key to navigate to next field when a snippet is active.
258 Value is a string that is converted to the internal Emacs key
259 representation using `read-kbd-macro'.
261 Can also be a list of strings."
262 :type '(choice (string :tag "String")
263 (repeat :args (string) :tag "List of strings"))
265 :set #'(lambda (symbol val)
266 (set-default symbol val)
267 (if (fboundp 'yas--init-yas-in-snippet-keymap)
268 (yas--init-yas-in-snippet-keymap))))
271 (defcustom yas-prev-field-key '("<backtab>" "<S-tab>")
272 "The key to navigate to previous field when a snippet is active.
274 Value is a string that is converted to the internal Emacs key
275 representation using `read-kbd-macro'.
277 Can also be a list of strings."
278 :type '(choice (string :tag "String")
279 (repeat :args (string) :tag "List of strings"))
281 :set #'(lambda (symbol val)
282 (set-default symbol val)
283 (if (fboundp 'yas--init-yas-in-snippet-keymap)
284 (yas--init-yas-in-snippet-keymap))))
286 (defcustom yas-skip-and-clear-key '("C-d" "<delete>" "<deletechar>")
287 "The key to clear the currently active field.
289 Value is a string that is converted to the internal Emacs key
290 representation using `read-kbd-macro'.
292 Can also be a list of strings."
293 :type '(choice (string :tag "String")
294 (repeat :args (string) :tag "List of strings"))
296 :set #'(lambda (symbol val)
297 (set-default symbol val)
298 (if (fboundp 'yas--init-yas-in-snippet-keymap)
299 (yas--init-yas-in-snippet-keymap))))
301 (defcustom yas-triggers-in-field nil
302 "If non-nil, `yas-next-field-key' can trigger stacked expansions.
304 Otherwise, `yas-next-field-key' just tries to move on to the next
309 (defcustom yas-fallback-behavior 'call-other-command
310 "How to act when `yas-trigger-key' does *not* expand a snippet.
312 - `call-other-command' means try to temporarily disable YASnippet
313 and call the next command bound to `yas-trigger-key'.
315 - nil or the symbol `return-nil' mean do nothing. (and
316 `yas-expand' returns nil)
318 - A Lisp form (apply COMMAND . ARGS) means interactively call
319 COMMAND, if ARGS is non-nil, call COMMAND non-interactively
320 with ARGS as arguments."
321 :type '(choice (const :tag "Call previous command" call-other-command)
322 (const :tag "Do nothing" return-nil))
325 (defcustom yas-choose-keys-first nil
326 "If non-nil, prompt for snippet key first, then for template.
328 Otherwise prompts for all possible snippet names.
330 This affects `yas-insert-snippet' and `yas-visit-snippet-file'."
334 (defcustom yas-choose-tables-first nil
335 "If non-nil, and multiple eligible snippet tables, prompts user for tables first.
337 Otherwise, user chooses between the merging together of all
340 This affects `yas-insert-snippet', `yas-visit-snippet-file'"
344 (defcustom yas-use-menu 'abbreviate
345 "Display a YASnippet menu in the menu bar.
347 When non-nil, submenus for each snippet table will be listed
348 under the menu \"Yasnippet\".
350 - If set to `abbreviate', only the current major-mode
351 menu and the modes set in `yas-extra-modes' are listed.
353 - If set to `full', every submenu is listed
355 - It set to nil, don't display a menu at all (this requires a
356 `yas-reload-all' call if the menu is already visible).
358 Any other non-nil value, every submenu is listed."
359 :type '(choice (const :tag "Full" full)
360 (const :tag "Abbreviate" abbreviate)
361 (const :tag "No menu" nil))
364 (defcustom yas-trigger-symbol (if (eq window-system 'mac)
365 (char-to-string ?\x21E5) ;; little ->| sign
367 "The text that will be used in menu to represent the trigger."
371 (defcustom yas-wrap-around-region nil
372 "If non-nil, snippet expansion wraps around selected region.
374 The wrapping occurs just before the snippet's exit marker. This
375 can be overridden on a per-snippet basis."
379 (defcustom yas-good-grace t
380 "If non-nil, don't raise errors in inline elisp evaluation.
382 An error string \"[yas] error\" is returned instead."
386 (defcustom yas-visit-from-menu nil
387 "If non-nil visit snippets's files from menu, instead of expanding them.
389 This can only work when snippets are loaded from files."
393 (defcustom yas-expand-only-for-last-commands nil
394 "List of `last-command' values to restrict tab-triggering to, or nil.
396 Leave this set at nil (the default) to be able to trigger an
397 expansion simply by placing the cursor after a valid tab trigger,
398 using whichever commands.
400 Optionally, set this to something like '(self-insert-command) if
401 you to wish restrict expansion to only happen when the last
402 letter of the snippet tab trigger was typed immediately before
403 the trigger key itself."
404 :type '(repeat function)
407 ;; Only two faces, and one of them shouldn't even be used...
409 (defface yas-field-highlight-face
410 '((t (:inherit 'region)))
411 "The face used to highlight the currently active field of a snippet"
414 (defface yas--field-debug-face
416 "The face used for debugging some overlays normally hidden"
420 ;;; User can also customize the next defvars
422 (defun yas--define-some-keys (keys keymap definition)
423 "Bind KEYS to DEFINITION in KEYMAP, read with `read-kbd-macro'."
424 (let ((keys (or (and (listp keys) keys)
427 (define-key keymap (read-kbd-macro key) definition))))
429 (defun yas--init-yas-in-snippet-keymap ()
430 "Set the value of `yas-keymap'."
432 (let ((map (make-sparse-keymap)))
433 (mapc #'(lambda (binding)
434 (yas--define-some-keys (car binding) map (cdr binding)))
435 `((,yas-next-field-key . yas-next-field-or-maybe-expand)
436 (,yas-prev-field-key . yas-prev-field)
437 ("C-g" . yas-abort-snippet)
438 (,yas-skip-and-clear-key . yas-skip-and-clear-or-delete-char)))
441 (defvar yas-keymap (yas--init-yas-in-snippet-keymap)
442 "The keymap active while a snippet expansion is in progress.")
444 (defvar yas-key-syntaxes (list "w" "w_" "w_." "w_.()" "^ ")
445 "List of character syntaxes used to find a trigger key before point.
446 The list is tried in the order while scanning characters
447 backwards from point. For example, if the list is '(\"w\" \"w_\")
448 first look for trigger keys which are composed exclusively of
449 \"word\"-syntax characters, and then, if that fails, look for
450 keys which are either of \"word\" or \"symbol\"
451 syntax. Triggering after
455 will, according to the \"w\" element first try \"bar\". If that
456 isn't a trigger key, \"foo-bar\" is tried, respecting a second
459 (defvar yas-after-exit-snippet-hook
461 "Hooks to run after a snippet exited.
463 The hooks will be run in an environment where some variables bound to
466 `yas-snippet-beg' : The beginning of the region of the snippet.
468 `yas-snippet-end' : Similar to beg.
470 Attention: These hooks are not run when exiting nested/stacked snippet expansion!")
472 (defvar yas-before-expand-snippet-hook
474 "Hooks to run just before expanding a snippet.")
476 (defvar yas-buffer-local-condition
477 '(if (and (or (fourth (syntax-ppss))
478 (fifth (syntax-ppss)))
479 (eq (symbol-function this-command) 'yas-expand-from-trigger-key))
480 '(require-snippet-condition . force-in-comment)
482 "Snippet expanding condition.
484 This variable is a Lisp form which is evaluated every time a
485 snippet expansion is attempted:
487 * If it evaluates to nil, no snippets can be expanded.
489 * If it evaluates to the a cons (require-snippet-condition
492 * Snippets bearing no \"# condition:\" directive are not
495 * Snippets bearing conditions that evaluate to nil (or
496 produce an error) won't be considered.
498 * If the snippet has a condition that evaluates to non-nil
501 * If REQUIREMENT is t, the snippet is considered
503 * If REQUIREMENT is `eq' RESULT, the snippet is
506 * Otherwise, the snippet is not considered.
508 * If it evaluates to the symbol 'always, all snippets are
509 considered for expansion, regardless of any conditions.
511 * If it evaluates to t or some other non-nil value
513 * Snippet bearing no conditions, or conditions that
514 evaluate to non-nil, are considered for expansion.
516 * Otherwise, the snippet is not considered.
518 Here's an example preventing snippets from being expanded from
519 inside comments, in `python-mode' only, with the exception of
520 snippets returning the symbol 'force-in-comment in their
523 (add-hook 'python-mode-hook
525 (setq yas-buffer-local-condition
526 '(if (python-in-string/comment)
527 '(require-snippet-condition . force-in-comment)
530 The default value is similar, it filters out potential snippet
531 expansions inside comments and string literals, unless the
532 snippet itself contains a condition that returns the symbol
533 `force-in-comment'.")
536 ;;; Internal variables
538 (defvar yas--version "0.8.0 (beta)")
540 (defvar yas--menu-table (make-hash-table)
541 "A hash table of MAJOR-MODE symbols to menu keymaps.")
543 (defvar yas--known-modes
544 '(ruby-mode rst-mode markdown-mode)
545 "A list of mode which is well known but not part of Emacs.")
547 (defvar yas--escaped-characters
548 '(?\\ ?` ?\" ?' ?$ ?} ?{ ?\( ?\))
549 "List of characters which *might* need to be escaped.")
551 (defconst yas--field-regexp
552 "${\\([0-9]+:\\)?\\([^}]*\\)}"
553 "A regexp to *almost* recognize a field.")
555 (defconst yas--multi-dollar-lisp-expression-regexp
556 "$+[ \t\n]*\\(([^)]*)\\)"
557 "A regexp to *almost* recognize a \"$(...)\" expression.")
559 (defconst yas--backquote-lisp-expression-regexp
561 "A regexp to recognize a \"`lisp-expression`\" expression." )
563 (defconst yas--transform-mirror-regexp
564 "${\\(?:\\([0-9]+\\):\\)?$\\([ \t\n]*([^}]*\\)"
565 "A regexp to *almost* recognize a mirror with a transform.")
567 (defconst yas--simple-mirror-regexp
569 "A regexp to recognize a simple mirror.")
571 (defvar yas--snippet-id-seed 0
572 "Contains the next id for a snippet.")
574 (defun yas--snippet-next-id ()
575 (let ((id yas--snippet-id-seed))
576 (incf yas--snippet-id-seed)
582 ;; XXX: `last-buffer-undo-list' is somehow needed in Carbon Emacs for MacOSX
583 (defvar last-buffer-undo-list nil)
585 (defvar yas--minor-mode-menu nil
586 "Holds the YASnippet menu.")
588 (defun yas--init-minor-keymap ()
589 "Set up the `yas-minor-mode' keymap."
590 (let ((map (make-sparse-keymap)))
592 (easy-menu-define yas--minor-mode-menu
594 "Menu used when `yas-minor-mode' is active."
597 ["Expand trigger" yas-expand
598 :help "Possibly expand tab trigger before point"]
599 ["Insert at point..." yas-insert-snippet
600 :help "Prompt for an expandable snippet and expand it at point"]
601 ["New snippet..." yas-new-snippet
602 :help "Create a new snippet in an appropriate directory"]
603 ["Visit snippet file..." yas-visit-snippet-file
604 :help "Prompt for an expandable snippet and find its file"]
606 ("Snippet menu behaviour"
607 ["Visit snippets" (setq yas-visit-from-menu t)
608 :help "Visit snippets from the menu"
609 :active t :style radio :selected yas-visit-from-menu]
610 ["Expand snippets" (setq yas-visit-from-menu nil)
611 :help "Expand snippets from the menu"
612 :active t :style radio :selected (not yas-visit-from-menu)]
614 ["Show all known modes" (setq yas-use-menu 'full)
615 :help "Show one snippet submenu for each loaded table"
616 :active t :style radio :selected (eq yas-use-menu 'full)]
617 ["Abbreviate according to current mode" (setq yas-use-menu 'abbreviate)
618 :help "Show only snippet submenus for the current active modes"
619 :active t :style radio :selected (eq yas-use-menu 'abbreviate)])
621 ["Auto" (setq yas-indent-line 'auto)
622 :help "Indent each line of the snippet with `indent-according-to-mode'"
623 :active t :style radio :selected (eq yas-indent-line 'auto)]
624 ["Fixed" (setq yas-indent-line 'fixed)
625 :help "Indent the snippet to the current column"
626 :active t :style radio :selected (eq yas-indent-line 'fixed)]
627 ["None" (setq yas-indent-line 'none)
628 :help "Don't apply any particular snippet indentation after expansion"
629 :active t :style radio :selected (not (member yas-indent-line '(fixed auto)))]
631 ["Also auto indent first line" (setq yas-also-auto-indent-first-line
632 (not yas-also-auto-indent-first-line))
633 :help "When auto-indenting also, auto indent the first line menu"
634 :active (eq yas-indent-line 'auto)
635 :style toggle :selected yas-also-auto-indent-first-line]
638 ["System X-widget" (setq yas-prompt-functions
640 (remove 'yas-x-prompt
641 yas-prompt-functions)))
642 :help "Use your windowing system's (gtk, mac, windows, etc...) default menu"
643 :active t :style radio :selected (eq (car yas-prompt-functions)
645 ["Dropdown-list" (setq yas-prompt-functions
646 (cons 'yas-dropdown-prompt
647 (remove 'yas-dropdown-prompt
648 yas-prompt-functions)))
649 :help "Use a special dropdown list"
650 :active t :style radio :selected (eq (car yas-prompt-functions)
651 'yas-dropdown-prompt)]
652 ["Ido" (setq yas-prompt-functions
653 (cons 'yas-ido-prompt
654 (remove 'yas-ido-prompt
655 yas-prompt-functions)))
656 :help "Use an ido-style minibuffer prompt"
657 :active t :style radio :selected (eq (car yas-prompt-functions)
659 ["Completing read" (setq yas-prompt-functions
660 (cons 'yas-completing-prompt
661 (remove 'yas-completing-prompt
662 yas-prompt-functions)))
663 :help "Use a normal minibuffer prompt"
664 :active t :style radio :selected (eq (car yas-prompt-functions)
665 'yas-completing-prompt)]
668 ["Wrap region in exit marker"
669 (setq yas-wrap-around-region
670 (not yas-wrap-around-region))
671 :help "If non-nil automatically wrap the selected text in the $0 snippet exit"
672 :style toggle :selected yas-wrap-around-region]
673 ["Allow stacked expansions "
674 (setq yas-triggers-in-field
675 (not yas-triggers-in-field))
676 :help "If non-nil allow snippets to be triggered inside other snippet fields"
677 :style toggle :selected yas-triggers-in-field]
678 ["Revive snippets on undo "
679 (setq yas-snippet-revival
680 (not yas-snippet-revival))
681 :help "If non-nil allow snippets to become active again after undo"
682 :style toggle :selected yas-snippet-revival]
685 (not yas-good-grace))
686 :help "If non-nil don't raise errors in bad embedded elisp in snippets"
687 :style toggle :selected yas-good-grace]
690 ["Load snippets..." yas-load-directory
691 :help "Load snippets from a specific directory"]
692 ["Reload everything" yas-reload-all
693 :help "Cleanup stuff, reload snippets, rebuild menus"]
695 :help "Display some information about YASnippet"])))
697 ;; Now for the stuff that has direct keybindings
699 (define-key map "\C-c&\C-s" 'yas-insert-snippet)
700 (define-key map "\C-c&\C-n" 'yas-new-snippet)
701 (define-key map "\C-c&\C-v" 'yas-visit-snippet-file)
704 (defvar yas-minor-mode-map (yas--init-minor-keymap)
705 "The keymap used when `yas-minor-mode' is active.")
707 (defun yas--trigger-key-reload (&optional unbind-key)
708 "Rebind `yas-expand' to the new value of `yas-trigger-key'.
710 With optional UNBIND-KEY, try to unbind that key from
711 `yas-minor-mode-map'."
712 (when (and unbind-key
714 (not (string= unbind-key "")))
715 (define-key yas-minor-mode-map (read-kbd-macro unbind-key) nil))
716 (when (and yas-trigger-key
717 (stringp yas-trigger-key)
718 (not (string= yas-trigger-key "")))
719 (define-key yas-minor-mode-map (read-kbd-macro yas-trigger-key) 'yas-expand)))
721 (defvar yas--tables (make-hash-table)
722 "A hash table of mode symbols to `yas--table' objects.")
724 (defvar yas--parents (make-hash-table)
725 "A hash table of mode symbols do lists of direct parent mode symbols.
727 This list is populated when reading the \".yas-parents\" files
728 found when traversing snippet directories with
729 `yas-load-directory'.
731 There might be additional parenting information stored in the
732 `derived-mode-parent' property of some mode symbols, but that is
735 (defvar yas--direct-keymaps (list)
736 "Keymap alist supporting direct snippet keybindings.
738 This variable is placed in `emulation-mode-map-alists'.
740 Its elements looks like (TABLE-NAME . KEYMAP). They're
741 instantiated on `yas-reload-all' but KEYMAP is added to only when
742 loading snippets. `yas--direct-TABLE-NAME' is then a variable set
743 buffer-locally when entering `yas-minor-mode'. KEYMAP binds all
744 defined direct keybindings to the command
745 `yas-expand-from-keymap' which then which snippet to expand.")
747 (defun yas-direct-keymaps-reload ()
748 "Force reload the direct keybinding for active snippet tables."
750 (setq yas--direct-keymaps nil)
751 (maphash #'(lambda (name table)
752 (push (cons (intern (format "yas--direct-%s" name))
753 (yas--table-direct-keymap table))
754 yas--direct-keymaps))
757 (defun yas--modes-to-activate ()
758 "Compute list of mode symbols that are active for `yas-expand'
760 (let ((modes-to-activate (list major-mode))
762 (while (setq mode (get mode 'derived-mode-parent))
763 (push mode modes-to-activate))
764 (dolist (mode (yas-extra-modes))
765 (push mode modes-to-activate))
767 (append modes-to-activate
768 (mapcan #'(lambda (mode)
769 (yas--all-parents mode))
770 modes-to-activate)))))
772 (defvar yas-minor-mode-hook nil
773 "Hook run when `yas-minor-mode' is turned on.")
776 (define-minor-mode yas-minor-mode
777 "Toggle YASnippet mode.
779 When YASnippet mode is enabled, the `yas-trigger-key' key expands
780 snippets of code depending on the major mode.
782 With no argument, this command toggles the mode.
783 positive prefix argument turns on the mode.
784 Negative prefix argument turns off the mode.
786 You can customize the key through `yas-trigger-key'.
789 \\{yas-minor-mode-map}"
791 ;; The indicator for the mode line.
794 (cond (yas-minor-mode
795 ;; Reload the trigger key
797 (yas--trigger-key-reload)
798 ;; Install the direct keymaps in `emulation-mode-map-alists'
799 ;; (we use `add-hook' even though it's not technically a hook,
800 ;; but it works). Then define variables named after modes to
801 ;; index `yas--direct-keymaps'.
803 ;; Also install the post-command-hook.
805 (add-hook 'emulation-mode-map-alists 'yas--direct-keymaps)
806 (add-hook 'post-command-hook 'yas--post-command-handler nil t)
807 ;; Set the `yas--direct-%s' vars for direct keymap expansion
809 (dolist (mode (yas--modes-to-activate))
810 (let ((name (intern (format "yas--direct-%s" mode))))
811 (set-default name nil)
812 (set (make-local-variable name) t)))
815 (yas--load-pending-jits))
817 ;; Uninstall the direct keymaps and the post-command hook
819 (remove-hook 'post-command-hook 'yas--post-command-handler t)
820 (remove-hook 'emulation-mode-map-alists 'yas--direct-keymaps))))
822 (defvar yas--dont-activate '(minibufferp)
823 "If non-nil don't let `yas-minor-mode-on' active yas for this buffer.
825 If a function, then its result is used.
827 If a list of functions, then all functions must return nil to
828 activate yas for this buffer.
830 `yas-minor-mode-on' is usually called by `yas-global-mode' so
831 this effectively lets you define exceptions to the \"global\"
832 behaviour. Can also be a function of zero arguments.")
833 (make-variable-buffer-local 'yas--dont-activate)
835 (defun yas-minor-mode-on ()
836 "Turn on YASnippet minor mode.
838 Do this unless `yas--dont-activate' is truish."
840 (unless (cond ((functionp yas--dont-activate)
841 (funcall yas--dont-activate))
842 ((consp yas--dont-activate)
843 (some #'funcall yas--dont-activate))
844 (yas--dont-activate))
845 ;; Load all snippets definitions unless we still don't have a
846 ;; root-directory or some snippets have already been loaded.
851 (define-globalized-minor-mode yas-global-mode yas-minor-mode yas-minor-mode-on
855 (defun yas--global-mode-reload-with-jit-maybe ()
856 "Run `yas-reload-all' when `yas-global-mode' is on."
857 (when yas-global-mode (yas-reload-all)))
859 (add-hook 'yas-global-mode-hook 'yas--global-mode-reload-with-jit-maybe)
861 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
864 (defvar yas--font-lock-keywords
865 (append '(("^#.*$" . font-lock-comment-face))
866 lisp-font-lock-keywords
867 lisp-font-lock-keywords-1
868 lisp-font-lock-keywords-2
870 (0 font-lock-keyword-face)
871 (1 font-lock-string-face t))
873 (0 font-lock-keyword-face)
874 (1 font-lock-warning-face t))
875 ("${" font-lock-keyword-face)
876 ("$[0-9]+?" font-lock-preprocessor-face)
877 ("\\(\\$(\\)" 1 font-lock-preprocessor-face)
879 (0 font-lock-keyword-face)))))
881 (defun yas--init-major-keymap ()
882 "Setup YASnippet major-mode keymap."
883 (let ((map (make-sparse-keymap)))
884 (easy-menu-define nil
886 "Menu used when snippet-mode is active."
888 (mapcar #'(lambda (ent)
890 (define-key map (third ent) (second ent)))
891 (vector (first ent) (second ent) t))
893 (list "Load this snippet" 'yas-load-snippet-buffer "\C-c\C-c")
894 (list "Try out this snippet" 'yas-tryout-snippet "\C-c\C-t")))))
897 (defvar snippet-mode-map
898 (yas--init-major-keymap)
899 "The keymap used when `snippet-mode' is active.")
902 (define-derived-mode snippet-mode text-mode "Snippet"
903 "A mode for editing yasnippets"
904 (setq font-lock-defaults '(yas--font-lock-keywords))
905 (set (make-local-variable 'require-final-newline) nil)
906 (set (make-local-variable 'comment-start) "#")
907 (set (make-local-variable 'comment-start-skip) "#+[\t ]*"))
911 ;;; Internal structs for template management
913 (defstruct (yas--template (:constructor yas--make-blank-template))
914 "A template for a snippet."
924 group ;; as dictated by the #group: directive or .yas-make-groups
925 perm-group ;; as dictated by `yas-define-menu'
929 (defun yas--populate-template (template &rest args)
930 "Helper function to populate TEMPLATE with properties."
934 (position (intern (substring (symbol-name (car args)) 1))
935 (mapcar #'car (get 'yas--template 'cl-struct-slots)))
937 (setq args (cddr args)))
940 (defstruct (yas--table (:constructor yas--make-snippet-table (name)))
941 "A table to store snippets for a particular mode.
943 Has the following fields:
947 A symbol name normally corresponding to a major mode, but can
948 also be a pseudo major-mode to be referenced in
949 `yas-extra-modes', for example.
953 A hash table (KEY . NAMEHASH), known as the \"keyhash\". KEY is
954 a string or a vector, where the former is the snippet's trigger
955 and the latter means it's a direct keybinding. NAMEHASH is yet
956 another hash of (NAME . TEMPLATE) where NAME is the snippet's
957 name and TEMPLATE is a `yas--template' object.
959 `yas--table-direct-keymap'
961 A keymap for the snippets in this table that have direct
962 keybindings. This is kept in sync with the keyhash, i.e., all
963 the elements of the keyhash that are vectors appear here as
964 bindings to `yas-expand-from-keymap'.
966 `yas--table-uuidhash'
968 A hash table mapping snippets uuid's to the same `yas--template'
969 objects. A snippet uuid defaults to the snippet's name.
972 (hash (make-hash-table :test 'equal))
973 (uuidhash (make-hash-table :test 'equal))
975 (direct-keymap (make-sparse-keymap)))
977 (defun yas--get-template-by-uuid (mode uuid)
978 "Find the snippet template in MODE by its UUID."
979 (let* ((table (gethash mode yas--tables mode)))
981 (gethash uuid (yas--table-uuidhash table)))))
983 ;; Apropos storing/updating in TABLE, this works in two steps:
985 ;; 1. `yas--remove-template-by-uuid' removes any
986 ;; keyhash-namehash-template mappings from TABLE, grabbing the
987 ;; snippet by its uuid. Also removes mappings from TABLE's
988 ;; `yas--table-direct-keymap' (FIXME: and should probably take care
989 ;; of potentially stale menu bindings right?.)
991 ;; 2. `yas--add-template' adds this all over again.
993 ;; Create a new or add to an existing keyhash-namehash mapping.
995 ;; For reference on understanding this, consider three snippet
998 ;; A: # name: The Foo
1000 ;; # binding: C-c M-l
1002 ;; B: # name: Mrs Foo
1005 ;; C: # name: The Bar
1006 ;; # binding: C-c M-l
1011 ;; keyhash namehashes(3) yas--template structs(4)
1012 ;; -----------------------------------------------------
1015 ;; "foo" ---> "The Foo" ---> [yas--template A] |
1016 ;; "Mrs Foo" ---> [yas--template B] |
1018 ;; [C-c M-l] ---> "The Foo" -------------------------/
1019 ;; "The Bar" ---> [yas--template C]
1021 ;; "baz" ---> "Baz" ---> [yas--template D]
1023 ;; Additionally, since uuid defaults to the name, we have a
1024 ;; `yas--table-uuidhash' for TABLE
1026 ;; uuidhash yas--template structs
1027 ;; -------------------------------
1028 ;; "The Foo" ---> [yas--template A]
1029 ;; "Mrs Foo" ---> [yas--template B]
1030 ;; "The Bar" ---> [yas--template C]
1031 ;; "Baz" ---> [yas--template D]
1033 ;; FIXME: the more I look at this data-structure the more I think I'm
1034 ;; stupid. There has to be an easier way (but beware lots of code
1035 ;; depends on this).
1037 (defun yas--remove-template-by-uuid (table uuid)
1038 "Remove from TABLE a template identified by UUID."
1039 (let ((template (gethash uuid (yas--table-uuidhash table))))
1041 (let* ((name (yas--template-name template))
1043 ;; Remove the name from each of the targeted namehashes
1045 (maphash #'(lambda (k v)
1046 (let ((template (gethash name v)))
1048 (eq uuid (yas--template-uuid template)))
1050 (when (zerop (hash-table-count v))
1051 (push k empty-keys)))))
1052 (yas--table-hash table))
1053 ;; Remove the namehash themselves if they've become empty
1055 (dolist (key empty-keys)
1057 (define-key (yas--table-direct-keymap table) key nil))
1058 (remhash key (yas--table-hash table)))
1060 ;; Finally, remove the uuid from the uuidhash
1062 (remhash uuid (yas--table-uuidhash table))))))
1064 (defun yas--add-template (table template)
1065 "Store in TABLE the snippet template TEMPLATE.
1067 KEY can be a string (trigger key) of a vector (direct
1069 (let ((name (yas--template-name template))
1070 (key (yas--template-key template))
1071 (keybinding (yas--template-keybinding template))
1072 (menu-binding-pair (yas--template-menu-binding-pair-get-create template)))
1073 (dolist (k (remove nil (list key keybinding)))
1077 (yas--table-hash table))
1079 (make-hash-table :test 'equal)
1080 (yas--table-hash table))))
1082 (define-key (yas--table-direct-keymap table) k 'yas-expand-from-keymap)))
1084 ;; Update TABLE's `yas--table-uuidhash'
1085 (puthash (yas--template-uuid template)
1087 (yas--table-uuidhash table))))
1089 (defun yas--update-template (table template)
1090 "Add or update TEMPLATE in TABLE.
1092 Also takes care of adding and updating to the associated menu."
1093 ;; Remove from table by uuid
1095 (yas--remove-template-by-uuid table (yas--template-uuid template))
1096 ;; Add to table again
1098 (yas--add-template table template)
1099 ;; Take care of the menu
1102 (yas--update-template-menu table template)))
1104 (defun yas--update-template-menu (table template)
1105 "Update every menu-related for TEMPLATE."
1106 (let ((menu-binding-pair (yas--template-menu-binding-pair-get-create template))
1107 (key (yas--template-key template))
1108 (keybinding (yas--template-keybinding template)))
1109 ;; The snippet might have changed name or keys, so update
1110 ;; user-visible strings
1112 (unless (eq (cdr menu-binding-pair) :none)
1113 ;; the menu item name
1115 (setf (cadar menu-binding-pair) (yas--template-name template))
1116 ;; the :keys information (also visible to the user)
1117 (setf (getf (cdr (car menu-binding-pair)) :keys)
1118 (or (and keybinding (key-description keybinding))
1119 (and key (concat key yas-trigger-symbol))))))
1120 (unless (yas--template-menu-managed-by-yas-define-menu template)
1122 (yas--menu-keymap-get-create (yas--table-mode table)
1123 (mapcar #'yas--table-mode
1124 (yas--table-parents table))))
1125 (group (yas--template-group template)))
1126 ;; Remove from menu keymap
1128 (assert menu-keymap)
1129 (yas--delete-from-keymap menu-keymap (yas--template-uuid template))
1131 ;; Add necessary subgroups as necessary.
1133 (dolist (subgroup group)
1134 (let ((subgroup-keymap (lookup-key menu-keymap (vector (make-symbol subgroup)))))
1135 (unless (and subgroup-keymap
1136 (keymapp subgroup-keymap))
1137 (setq subgroup-keymap (make-sparse-keymap))
1138 (define-key menu-keymap (vector (make-symbol subgroup))
1139 `(menu-item ,subgroup ,subgroup-keymap)))
1140 (setq menu-keymap subgroup-keymap)))
1142 ;; Add this entry to the keymap
1144 (define-key menu-keymap
1145 (vector (make-symbol (yas--template-uuid template)))
1146 (car (yas--template-menu-binding-pair template))))))
1148 (defun yas--namehash-templates-alist (namehash)
1149 "Return NAMEHASH as an alist."
1151 (maphash #'(lambda (k v)
1152 (push (cons k v) alist))
1156 (defun yas--fetch (table key)
1157 "Fetch templates in TABLE by KEY.
1159 Return a list of cons (NAME . TEMPLATE) where NAME is a
1160 string and TEMPLATE is a `yas--template' structure."
1161 (let* ((keyhash (yas--table-hash table))
1162 (namehash (and keyhash (gethash key keyhash))))
1164 (yas--filter-templates-by-condition (yas--namehash-templates-alist namehash)))))
1167 ;;; Filtering/condition logic
1169 (defun yas--eval-condition (condition)
1176 (yas--message 1 "Error in condition evaluation: %s" (error-message-string err))
1180 (defun yas--filter-templates-by-condition (templates)
1181 "Filter the templates using the applicable condition.
1183 TEMPLATES is a list of cons (NAME . TEMPLATE) where NAME is a
1184 string and TEMPLATE is a `yas--template' structure.
1186 This function implements the rules described in
1187 `yas-buffer-local-condition'. See that variables documentation."
1188 (let ((requirement (yas--require-template-specific-condition-p)))
1189 (if (eq requirement 'always)
1191 (remove-if-not #'(lambda (pair)
1192 (yas--template-can-expand-p
1193 (yas--template-condition (cdr pair)) requirement))
1196 (defun yas--require-template-specific-condition-p ()
1197 "Decides if this buffer requests/requires snippet-specific
1198 conditions to filter out potential expansions."
1199 (if (eq 'always yas-buffer-local-condition)
1201 (let ((local-condition (or (and (consp yas-buffer-local-condition)
1202 (yas--eval-condition yas-buffer-local-condition))
1203 yas-buffer-local-condition)))
1204 (when local-condition
1205 (if (eq local-condition t)
1207 (and (consp local-condition)
1208 (eq 'require-snippet-condition (car local-condition))
1209 (symbolp (cdr local-condition))
1210 (cdr local-condition)))))))
1212 (defun yas--template-can-expand-p (condition requirement)
1213 "Evaluates CONDITION and REQUIREMENT and returns a boolean."
1214 (let* ((result (or (null condition)
1215 (yas--eval-condition condition))))
1216 (cond ((eq requirement t)
1219 (eq requirement result)))))
1221 (defun yas--all-parents (mode)
1222 "Returns a list of all parent modes of MODE."
1223 (let ((parents (gethash mode yas--parents)))
1225 (mapcan #'yas--all-parents parents))))
1227 (defun yas--table-templates (table)
1230 (maphash #'(lambda (key namehash)
1231 (maphash #'(lambda (name template)
1232 (push (cons name template) acc))
1234 (yas--table-hash table))
1235 (yas--filter-templates-by-condition acc))))
1237 (defun yas--current-key ()
1238 "Get the key under current position. A key is used to find
1239 the template of a snippet in the current snippet-table."
1240 (let ((start (point))
1242 (syntaxes yas-key-syntaxes)
1246 (while (and (not done) syntaxes)
1247 (setq syntax (car syntaxes))
1248 (setq syntaxes (cdr syntaxes))
1250 (skip-syntax-backward syntax)
1251 (setq start (point)))
1253 (mapcan #'(lambda (table)
1254 (yas--fetch table (buffer-substring-no-properties start end)))
1255 (yas--get-snippet-tables)))
1264 (defun yas--table-all-keys (table)
1265 "Get trigger keys of all active snippets in TABLE."
1267 (maphash #'(lambda (key namehash)
1268 (when (yas--filter-templates-by-condition (yas--namehash-templates-alist namehash))
1270 (yas--table-hash table))
1273 (defun yas--table-mode (table)
1274 (intern (yas--table-name table)))
1277 ;;; Internal functions:
1279 (defun yas--real-mode? (mode)
1280 "Try to find out if MODE is a real mode.
1282 The MODE bound to a function (like `c-mode') is considered real
1283 mode. Other well known mode like `ruby-mode' which is not part of
1284 Emacs might not bound to a function until it is loaded. So
1285 yasnippet keeps a list of modes like this to help the judgment."
1287 (find mode yas--known-modes)))
1289 (defun yas--eval-lisp (form)
1290 "Evaluate FORM and convert the result to string."
1291 (let ((retval (catch 'yas--exception
1297 (let ((result (eval form)))
1299 (format "%s" result))))))
1300 (error (if yas-good-grace
1301 (yas--format "elisp error! %s" (error-message-string err))
1302 (error (yas--format "elisp error: %s"
1303 (error-message-string err)))))))))
1304 (when (and (consp retval)
1305 (eq 'yas--exception (car retval)))
1306 (error (cdr retval)))
1309 (defun yas--eval-lisp-no-saves (form)
1312 (error (if yas-good-grace
1313 (yas--format "elisp error! %s" (error-message-string err))
1314 (error (yas--format "elisp error: %s"
1315 (error-message-string err)))))))
1317 (defun yas--read-lisp (string &optional nil-on-error)
1318 "Read STRING as a elisp expression and return it.
1320 In case STRING in an invalid expression and NIL-ON-ERROR is nil,
1321 return an expression that when evaluated will issue an error."
1324 (error (and (not nil-on-error)
1325 `(error (error-message-string ,err))))))
1327 (defun yas--read-keybinding (keybinding)
1328 "Read KEYBINDING as a snippet keybinding, return a vector."
1329 (when (and keybinding
1330 (not (string-match "keybinding" keybinding)))
1332 (let ((res (or (and (string-match "^\\[.*\\]$" keybinding)
1334 (read-kbd-macro keybinding 'need-vector))))
1337 (yas--message 3 "warning: keybinding \"%s\" invalid since %s."
1338 keybinding (error-message-string err))
1341 (defvar yas-extra-modes nil
1342 "If non-nil, also lookup snippets for this/these modes.
1344 Can be a symbol or a list of symbols.
1346 This variable probably makes more sense as buffer-local, so
1347 ensure your use `make-local-variable' when you set it.")
1348 (defun yas-extra-modes ()
1349 (if (listp yas-extra-modes) yas-extra-modes (list yas-extra-modes)))
1350 (defvaralias 'yas/mode-symbol 'yas-extra-modes)
1352 (defun yas--table-get-create (mode)
1353 "Get or create the snippet table corresponding to MODE."
1354 (let ((table (gethash mode
1357 (setq table (yas--make-snippet-table (symbol-name mode)))
1358 (puthash mode table yas--tables)
1359 (push (cons (intern (format "yas--direct-%s" mode))
1360 (yas--table-direct-keymap table))
1361 yas--direct-keymaps))
1364 (defun yas--get-snippet-tables ()
1365 "Get snippet tables for current buffer.
1367 Return a list of `yas--table' objects. The list of modes to
1368 consider is returned by `yas--modes-to-activate'"
1370 (mapcar #'(lambda (mode-name)
1371 (gethash mode-name yas--tables))
1372 (yas--modes-to-activate))))
1374 (defun yas--menu-keymap-get-create (mode &optional parents)
1375 "Get or create the menu keymap for MODE and its PARENTS.
1377 This may very well create a plethora of menu keymaps and arrange
1378 them all in `yas--menu-table'"
1379 (let* ((menu-keymap (or (gethash mode yas--menu-table)
1380 (puthash mode (make-sparse-keymap) yas--menu-table))))
1381 (mapc #'yas--menu-keymap-get-create parents)
1382 (define-key yas--minor-mode-menu (vector mode)
1383 `(menu-item ,(symbol-name mode) ,menu-keymap
1384 :visible (yas--show-menu-p ',mode)))
1387 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1388 ;;; Template-related and snippet loading functions
1390 (defun yas--parse-template (&optional file)
1391 "Parse the template in the current buffer.
1393 Optional FILE is the absolute file name of the file being
1396 Optional GROUP is the group where the template is to go,
1397 otherwise we attempt to calculate it from FILE.
1399 Return a snippet-definition, i.e. a list
1401 (KEY TEMPLATE NAME CONDITION GROUP VARS FILE KEYBINDING UUID)
1403 If the buffer contains a line of \"# --\" then the contents above
1404 this line are ignored. Directives can set most of these with the syntax:
1406 # directive-name : directive-value
1408 Here's a list of currently recognized directives:
1419 (goto-char (point-min))
1420 (let* ((type 'snippet)
1422 (file-name-nondirectory file)))
1428 (yas--calculate-group file)))
1432 (if (re-search-forward "^# --\n" nil t)
1433 (progn (setq template
1434 (buffer-substring-no-properties (point)
1436 (setq bound (point))
1437 (goto-char (point-min))
1438 (while (re-search-forward "^# *\\([^ ]+?\\) *: *\\(.*\\)$" bound t)
1439 (when (string= "uuid" (match-string-no-properties 1))
1440 (setq uuid (match-string-no-properties 2)))
1441 (when (string= "type" (match-string-no-properties 1))
1442 (setq type (if (string= "command" (match-string-no-properties 2))
1445 (when (string= "key" (match-string-no-properties 1))
1446 (setq key (match-string-no-properties 2)))
1447 (when (string= "name" (match-string-no-properties 1))
1448 (setq name (match-string-no-properties 2)))
1449 (when (string= "condition" (match-string-no-properties 1))
1450 (setq condition (yas--read-lisp (match-string-no-properties 2))))
1451 (when (string= "group" (match-string-no-properties 1))
1452 (setq group (match-string-no-properties 2)))
1453 (when (string= "expand-env" (match-string-no-properties 1))
1454 (setq expand-env (yas--read-lisp (match-string-no-properties 2)
1456 (when (string= "binding" (match-string-no-properties 1))
1457 (setq binding (match-string-no-properties 2)))))
1459 (buffer-substring-no-properties (point-min) (point-max))))
1460 (unless (or key binding)
1461 (setq key (and file (file-name-nondirectory file))))
1462 (when (eq type 'command)
1463 (setq template (yas--read-lisp (concat "(progn" template ")"))))
1465 (setq group (split-string group "\\.")))
1466 (list key template name condition group expand-env file binding uuid)))
1468 (defun yas--calculate-group (file)
1469 "Calculate the group for snippet file path FILE."
1470 (let* ((dominating-dir (locate-dominating-file file
1471 ".yas-make-groups"))
1472 (extra-path (and dominating-dir
1473 (replace-regexp-in-string (concat "^"
1474 (expand-file-name dominating-dir))
1476 (expand-file-name file))))
1477 (extra-dir (and extra-path
1478 (file-name-directory extra-path)))
1479 (group (and extra-dir
1480 (replace-regexp-in-string "/"
1482 (directory-file-name extra-dir)))))
1485 (defun yas--subdirs (directory &optional filep)
1486 "Return subdirs or files of DIRECTORY according to FILEP."
1487 (remove-if (lambda (file)
1488 (or (string-match "^\\."
1489 (file-name-nondirectory file))
1490 (string-match "^#.*#$"
1491 (file-name-nondirectory file))
1493 (file-name-nondirectory file))
1495 (file-directory-p file)
1496 (not (file-directory-p file)))))
1497 (directory-files directory t)))
1499 (defun yas--make-menu-binding (template)
1500 (let ((mode (yas--table-mode (yas--template-table template))))
1501 `(lambda () (interactive) (yas--expand-or-visit-from-menu ',mode ,(yas--template-uuid template)))))
1503 (defun yas--expand-or-visit-from-menu (mode uuid)
1504 (let* ((table (yas--table-get-create mode))
1505 (yas--current-template (and table
1506 (gethash uuid (yas--table-uuidhash table)))))
1507 (when yas--current-template
1508 (if yas-visit-from-menu
1509 (yas--visit-snippet-file-1 yas--current-template)
1510 (let ((where (if (region-active-p)
1511 (cons (region-beginning) (region-end))
1512 (cons (point) (point)))))
1513 (yas-expand-snippet (yas--template-content yas--current-template)
1516 (yas--template-expand-env yas--current-template)))))))
1518 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1519 ;; Popping up for keys and templates
1521 (defvar yas--x-pretty-prompt-templates nil
1522 "If non-nil, attempt to prompt for templates like TextMate.")
1525 (defun yas--prompt-for-template (templates &optional prompt)
1526 "Interactively choose a template from the list TEMPLATES.
1528 TEMPLATES is a list of `yas--template'.
1530 Optional PROMPT sets the prompt to use."
1533 (sort templates #'(lambda (t1 t2)
1534 (< (length (yas--template-name t1))
1535 (length (yas--template-name t2))))))
1536 (if yas--x-pretty-prompt-templates
1537 (yas--x-pretty-prompt-templates "Choose a snippet" templates)
1538 (some #'(lambda (fn)
1539 (funcall fn (or prompt "Choose a snippet: ")
1541 #'yas--template-name))
1542 yas-prompt-functions))))
1544 (defun yas--prompt-for-keys (keys &optional prompt)
1545 "Interactively choose a template key from the list KEYS.
1547 Optional PROMPT sets the prompt to use."
1549 (some #'(lambda (fn)
1550 (funcall fn (or prompt "Choose a snippet key: ") keys))
1551 yas-prompt-functions)))
1553 (defun yas--prompt-for-table (tables &optional prompt)
1554 "Interactively choose a table from the list TABLES.
1556 Optional PROMPT sets the prompt to use."
1558 (some #'(lambda (fn)
1559 (funcall fn (or prompt "Choose a snippet table: ")
1562 yas-prompt-functions)))
1564 (defun yas-x-prompt (prompt choices &optional display-fn)
1565 "Display choices in a x-window prompt."
1566 ;; FIXME: HACK: if we notice that one of the objects in choices is
1567 ;; actually a `yas--template', defer to `yas--x-prompt-pretty-templates'
1569 ;; This would be better implemented by passing CHOICES as a
1570 ;; structured tree rather than a list. Modifications would go as far
1571 ;; up as `yas--all-templates' I think.
1573 (when (and window-system choices)
1575 (let (menu d) ;; d for display
1577 (setq d (or (and display-fn (funcall display-fn c))
1580 (push (cons (concat " " d) c) menu))
1582 (push (car d) menu))))
1583 (setq menu (list prompt (push "title" menu)))
1584 (x-popup-menu (if (fboundp 'posn-at-point)
1585 (let ((x-y (posn-x-y (posn-at-point (point)))))
1586 (list (list (+ (car x-y) 10)
1594 (defun yas--x-pretty-prompt-templates (prompt templates)
1595 "Display TEMPLATES, grouping neatly by table name."
1596 (let ((organized (make-hash-table :test #'equal))
1600 (dolist (tl templates)
1601 (puthash (yas--template-table tl)
1603 (gethash (yas--template-table tl) organized))
1605 (setq more-than-one-table (> (hash-table-count organized) 1))
1606 (setq prefix (if more-than-one-table
1608 (if more-than-one-table
1609 (maphash #'(lambda (table templates)
1610 (push (yas--table-name table) menu)
1611 (dolist (tl templates)
1612 (push (cons (concat prefix (yas--template-name tl)) tl) menu))) organized)
1613 (setq menu (mapcar #'(lambda (tl) (cons (concat prefix (yas--template-name tl)) tl)) templates)))
1615 (setq menu (nreverse menu))
1616 (or (x-popup-menu (if (fboundp 'posn-at-point)
1617 (let ((x-y (posn-x-y (posn-at-point (point)))))
1618 (list (list (+ (car x-y) 10)
1622 (list prompt (push "title" menu)))
1625 (defun yas-ido-prompt (prompt choices &optional display-fn)
1626 (when (and (fboundp 'ido-completing-read)
1627 (or (>= emacs-major-version 24)
1629 (yas-completing-prompt prompt choices display-fn #'ido-completing-read)))
1631 (eval-when-compile (require 'dropdown-list nil t))
1632 (defun yas-dropdown-prompt (prompt choices &optional display-fn)
1633 (when (featurep 'dropdown-list)
1634 (let (formatted-choices
1638 (dolist (choice choices)
1639 (setq d (or (and display-fn (funcall display-fn choice))
1642 (push d formatted-choices)
1643 (push choice filtered-choices)))
1645 (setq n (and formatted-choices (dropdown-list formatted-choices)))
1647 (nth n filtered-choices)
1650 (defun yas-completing-prompt (prompt choices &optional display-fn completion-fn)
1651 (let (formatted-choices
1655 (completion-fn (or completion-fn
1656 #'completing-read)))
1657 (dolist (choice choices)
1658 (setq d (or (and display-fn (funcall display-fn choice))
1661 (push d formatted-choices)
1662 (push choice filtered-choices)))
1663 (setq chosen (and formatted-choices
1664 (funcall completion-fn prompt
1670 (let ((position (or (and chosen
1671 (position chosen formatted-choices :test #'string=))
1673 (nth position filtered-choices))))
1675 (defun yas-no-prompt (prompt choices &optional display-fn)
1678 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1679 ;; Loading snippets from files
1681 (defun yas--load-yas-setup-file (file)
1682 (load file 'noerror))
1684 (defun yas-load-directory (top-level-dir &optional use-jit)
1685 "Load snippets in directory hierarchy TOP-LEVEL-DIR.
1687 Below TOP-LEVEL-DIR each directory should be a mode name.
1689 Optional USE-JIT use jit-loading of snippets."
1690 (interactive "DSelect the root directory: ")
1691 (unless yas-snippet-dirs
1692 (setq yas-snippet-dirs top-level-dir))
1693 (dolist (dir (yas--subdirs top-level-dir))
1694 (let* ((major-mode-and-parents (yas--compute-major-mode-and-parents
1695 (concat dir "/dummy")))
1696 (mode-sym (car major-mode-and-parents))
1697 (parents (cdr major-mode-and-parents)))
1698 ;; Attention: The parents and the menus are already defined
1699 ;; here, even if the snippets are later jit-loaded.
1701 ;; * We need to know the parents at this point since entering a
1702 ;; given mode should jit load for its parents
1703 ;; immediately. This could be reviewed, the parents could be
1704 ;; discovered just-in-time-as well
1706 ;; * We need to create the menus here to support the `full'
1707 ;; option to `yas-use-menu' (all known snippet menus are shown to the user)
1709 (yas--define-parents mode-sym parents)
1710 (yas--menu-keymap-get-create mode-sym)
1711 (let ((form `(yas--load-directory-1 ,dir
1715 (yas--schedule-jit mode-sym form)
1717 (when (interactive-p)
1718 (yas--message 3 "Loaded snippets from %s." top-level-dir)))
1720 (defun yas--load-directory-1 (directory mode-sym parents &optional no-compiled-snippets)
1721 "Recursively load snippet templates from DIRECTORY."
1722 (unless (file-exists-p (concat directory "/" ".yas-skip"))
1723 (if (and (not no-compiled-snippets)
1724 (progn (yas--message 2 "Loading compiled snippets from %s" directory) t)
1725 (load (expand-file-name ".yas-compiled-snippets" directory) 'noerror (<= yas-verbosity 3)))
1726 (yas--message 2 "Loading snippet files from %s" directory)
1727 (yas--load-directory-2 directory mode-sym))))
1729 (defun yas--load-directory-2 (directory mode-sym)
1730 ;; Load .yas-setup.el files wherever we find them
1732 (yas--load-yas-setup-file (expand-file-name ".yas-setup" directory))
1733 (let* ((default-directory directory)
1735 ;; load the snippet files
1738 (dolist (file (yas--subdirs directory 'no-subdirs-just-files))
1739 (when (file-readable-p file)
1740 (insert-file-contents file nil nil nil t)
1741 (push (yas--parse-template file)
1744 (yas-define-snippets mode-sym
1746 ;; now recurse to a lower level
1748 (dolist (subdir (yas--subdirs directory))
1749 (yas--load-directory-2 subdir
1752 (defun yas--load-snippet-dirs (&optional nojit)
1753 "Reload the directories listed in `yas-snippet-dirs' or
1754 prompt the user to select one."
1756 (if yas-snippet-dirs
1757 (dolist (directory (reverse (yas-snippet-dirs)))
1758 (cond ((file-directory-p directory)
1759 (yas-load-directory directory (not nojit))
1761 (yas--message 3 "Loaded %s" directory)
1762 (yas--message 3 "Prepared just-in-time loading for %s" directory)))
1764 (push (yas--message 0 "Check your `yas-snippet-dirs': %s is not a directory" directory) errors))))
1765 (call-interactively 'yas-load-directory))
1768 (defun yas-reload-all (&optional interactive)
1769 "Reload all snippets and rebuild the YASnippet menu.
1771 When called interactively force immediate reload of all known
1772 snippets under `yas-snippet-dirs', otherwise use just-in-time
1777 (snippet-editing-buffers
1778 (remove-if-not #'(lambda (buffer)
1779 (with-current-buffer buffer yas--editing-template))
1781 ;; Warn if there are buffers visiting snippets, since reloading will break
1782 ;; any on-line editing of those buffers.
1784 (when snippet-editing-buffers
1786 (if (y-or-n-p "Some buffers editing live snippets, close them and proceed with reload? ")
1787 (mapc #'kill-buffer snippet-editing-buffers)
1788 (yas--message 1 "Aborted reload...")
1790 ;; in a non-interactive use, at least set
1791 ;; `yas--editing-template' to nil, make it guess it next time around
1792 (mapc #'(lambda (buffer) (setq yas--editing-template nil)) (buffer-list))))
1794 ;; Empty all snippet tables, parenting info and all menu tables
1796 (setq yas--tables (make-hash-table))
1797 (setq yas--parents (make-hash-table))
1798 (setq yas--menu-table (make-hash-table))
1800 ;; Cancel all pending 'yas--scheduled-jit-loads'
1802 (setq yas--scheduled-jit-loads (make-hash-table))
1804 ;; Init the `yas-minor-mode-map', taking care not to break the
1807 (setcdr yas-minor-mode-map (cdr (yas--init-minor-keymap)))
1809 ;; Reload the directories listed in `yas-snippet-dirs' or prompt
1810 ;; the user to select one.
1812 (setq errors (yas--load-snippet-dirs interactive))
1813 ;; Reload the direct keybindings
1815 (yas-direct-keymaps-reload)
1816 ;; Reload the trigger-key (shouldn't be needed, but see issue #237)
1818 (yas--trigger-key-reload)
1820 (yas--message 3 "Reloaded everything%s...%s."
1821 (if interactive "" " (snippets will load just-in-time)")
1822 (if errors " (some errors, check *Messages*)" "")))))
1824 (defun yas--load-pending-jits ()
1825 (when yas-minor-mode
1826 (dolist (mode (yas--modes-to-activate))
1827 (let ((forms (reverse (gethash mode yas--scheduled-jit-loads))))
1828 ;; must reverse to maintain coherence with `yas-snippet-dirs'
1829 (dolist (form forms)
1830 (yas--message 3 "Loading for `%s', just-in-time: %s!" mode form)
1832 (remhash mode yas--scheduled-jit-loads)))))
1834 ;; (when (<= emacs-major-version 22)
1835 ;; (add-hook 'after-change-major-mode-hook 'yas--load-pending-jits))
1837 (defun yas--quote-string (string)
1838 "Escape and quote STRING.
1839 foo\"bar\\! -> \"foo\\\"bar\\\\!\""
1841 (replace-regexp-in-string "[\\\"]"
1846 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1847 ;;; Snippet compilation function
1849 (defun yas--initialize ()
1850 "For backward compatibility, enable `yas-minor-mode' globally."
1851 (yas-global-mode 1))
1853 (defun yas-compile-directory (top-level-dir)
1854 "Create .yas-compiled-snippets.el files under subdirs of TOP-LEVEL-DIR.
1856 This works by stubbing a few functions, then calling
1857 `yas-load-directory'."
1858 (interactive "DTop level snippet directory?")
1859 (flet ((yas--load-yas-setup-file
1861 (let ((elfile (concat file ".el")))
1862 (when (file-exists-p elfile)
1863 (insert ";;; .yas-setup.el support file if any:\n;;;\n")
1864 (insert-file-contents elfile)
1867 (yas-define-snippets
1869 (insert ";;; Snippet definitions:\n;;;\n")
1870 (let ((literal-snippets (list))
1872 (dolist (snippet snippets)
1873 (let ((key (first snippet))
1874 (template-content (second snippet))
1875 (name (third snippet))
1876 (condition (fourth snippet))
1877 (group (fifth snippet))
1878 (expand-env (sixth snippet))
1879 (file nil) ;; (seventh snippet)) ;; omit on purpose
1880 (binding (eighth snippet))
1881 (uuid (ninth snippet)))
1892 (insert (pp-to-string `(yas-define-snippets ',mode ',literal-snippets)))
1894 (yas--load-directory-1
1895 (dir mode parents &rest ignore)
1896 (let ((output-file (concat (file-name-as-directory dir) ".yas-compiled-snippets.el")))
1897 (with-temp-file output-file
1898 (insert (format ";;; Compiled snippets and support files for `%s'\n" mode))
1899 (yas--load-directory-2 dir mode)
1900 (insert (format ";;; Do not edit! File generated at %s\n" (current-time-string)))))))
1901 (yas-load-directory top-level-dir nil)))
1903 (defun yas-recompile-all ()
1904 "Compile every dir in `yas-snippet-dirs'."
1906 (mapc #'yas-compile-directory (yas-snippet-dirs)))
1912 (defvar yas--scheduled-jit-loads (make-hash-table)
1913 "Alist of mode-symbols to forms to be evaled when `yas-minor-mode' kicks in.")
1915 (defun yas--schedule-jit (mode form)
1918 (gethash mode yas--scheduled-jit-loads))
1919 yas--scheduled-jit-loads))
1922 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1923 ;;; Some user level functions
1928 (message (concat "yasnippet (version "
1930 ") -- pluskid <pluskid@gmail.com>/joaotavora <joaotavora@gmail.com>")))
1932 (defun yas--define-parents (mode parents)
1933 "Add PARENTS to the list of MODE's parents."
1934 (puthash mode (remove-duplicates
1936 (gethash mode yas--parents)))
1939 (defun yas-define-snippets (mode snippets)
1940 "Define SNIPPETS for MODE.
1942 SNIPPETS is a list of snippet definitions, each taking the
1945 (KEY TEMPLATE NAME CONDITION GROUP EXPAND-ENV FILE KEYBINDING UUID)
1947 Within these, only KEY and TEMPLATE are actually mandatory.
1949 TEMPLATE might be a lisp form or a string, depending on whether
1950 this is a snippet or a snippet-command.
1952 CONDITION, EXPAND-ENV and KEYBINDING are lisp forms, they have
1953 been `yas--read-lisp'-ed and will eventually be
1954 `yas--eval-lisp'-ed.
1956 The remaining elements are strings.
1958 FILE is probably of very little use if you're programatically
1961 UUID is the snippets \"unique-id\". Loading a second snippet file
1962 with the same uuid replaced the previous snippet.
1964 You can use `yas--parse-template' to return such lists based on
1965 the current buffers contents."
1966 (let ((snippet-table (yas--table-get-create mode))
1968 (dolist (snippet snippets)
1969 (setq template (yas-define-snippets-1 snippet
1973 (defun yas-define-snippets-1 (snippet snippet-table)
1974 "Helper for `yas-define-snippets'."
1975 ;; X) Calculate some more defaults on the values returned by
1976 ;; `yas--parse-template'.
1978 (let* ((file (seventh snippet))
1980 (name (or (third snippet)
1982 (file-name-directory file))))
1983 (condition (fourth snippet))
1984 (group (fifth snippet))
1985 (keybinding (yas--read-keybinding (eighth snippet)))
1986 (uuid (or (ninth snippet)
1988 (template (or (gethash uuid (yas--table-uuidhash snippet-table))
1989 (yas--make-blank-template))))
1990 ;; X) populate the template object
1992 (yas--populate-template template
1993 :table snippet-table
1995 :content (second snippet)
1998 :condition condition
1999 :expand-env (sixth snippet)
2000 :file (seventh snippet)
2001 :keybinding keybinding
2003 ;; X) Update this template in the appropriate table. This step
2004 ;; also will take care of adding the key indicators in the
2005 ;; templates menu entry, if any
2007 (yas--update-template snippet-table template)
2008 ;; X) Return the template
2014 ;;; Apropos snippet menu:
2016 ;; The snippet menu keymaps are store by mode in hash table called
2017 ;; `yas--menu-table'. They are linked to the main menu in
2018 ;; `yas--menu-keymap-get-create' and are initially created empty,
2019 ;; reflecting the table hierarchy.
2021 ;; They can be populated in two mutually exclusive ways: (1) by
2022 ;; reading `yas--template-group', which in turn is populated by the "#
2023 ;; group:" directives of the snippets or the ".yas-make-groups" file
2024 ;; or (2) by using a separate `yas-define-menu' call, which declares a
2025 ;; menu structure based on snippets uuids.
2027 ;; Both situations are handled in `yas--update-template-menu', which
2028 ;; uses the predicate `yas--template-menu-managed-by-yas-define-menu'
2029 ;; that can tell between the two situations.
2033 ;; * if `yas-define-menu' is used it must run before
2034 ;; `yas-define-snippets' and the UUIDS must match, otherwise we get
2035 ;; duplicate entries. The `yas--template' objects are created in
2036 ;; `yas-define-menu', holding nothing but the menu entry,
2037 ;; represented by a pair of ((menu-item NAME :keys KEYS) TYPE) and
2038 ;; stored in `yas--template-menu-binding-pair'. The (menu-item ...)
2039 ;; part is then stored in the menu keymap itself which make the item
2040 ;; appear to the user. These limitations could probably be revised.
2042 ;; * The `yas--template-perm-group' slot is only used in
2043 ;; `yas-describe-tables'.
2045 (defun yas--template-menu-binding-pair-get-create (template &optional type)
2046 "Get TEMPLATE's menu binding or assign it a new one.
2048 TYPE may be `:stay', signaling this menu binding should be
2049 static in the menu."
2050 (or (yas--template-menu-binding-pair template)
2051 (let ((key (yas--template-key template))
2052 (keybinding (yas--template-keybinding template)))
2053 (setf (yas--template-menu-binding-pair template)
2054 (cons `(menu-item ,(or (yas--template-name template)
2055 (yas--template-uuid template))
2056 ,(yas--make-menu-binding template)
2059 (defun yas--template-menu-managed-by-yas-define-menu (template)
2060 "Non-nil if TEMPLATE's menu entry was included in a `yas-define-menu' call."
2061 (cdr (yas--template-menu-binding-pair template)))
2064 (defun yas--show-menu-p (mode)
2065 (cond ((eq yas-use-menu 'abbreviate)
2067 (mapcar #'(lambda (table)
2068 (yas--table-mode table))
2069 (yas--get-snippet-tables))))
2070 ((eq yas-use-menu 'full)
2072 ((eq yas-use-menu t)
2075 (defun yas--delete-from-keymap (keymap uuid)
2076 "Recursively delete items with UUID from KEYMAP and its submenus."
2078 ;; XXX: This used to skip any submenus named \"parent mode\"
2080 ;; First of all, recursively enter submenus, i.e. the tree is
2081 ;; searched depth first so that stale submenus can be found in the
2084 (mapc #'(lambda (item)
2085 (when (and (listp (cdr item))
2086 (keymapp (third (cdr item))))
2087 (yas--delete-from-keymap (third (cdr item)) uuid)))
2089 ;; Set the uuid entry to nil
2091 (define-key keymap (vector (make-symbol uuid)) nil)
2092 ;; Destructively modify keymap
2094 (setcdr keymap (delete-if #'(lambda (item)
2095 (or (null (cdr item))
2096 (and (keymapp (third (cdr item)))
2097 (null (cdr (third (cdr item)))))))
2100 (defun yas-define-menu (mode menu &optional omit-items)
2101 "Define a snippet menu for MODE according to MENU, omitting OMIT-ITEMS.
2103 MENU is a list, its elements can be:
2105 - (yas-item UUID) : Creates an entry the snippet identified with
2106 UUID. The menu entry for a snippet thus identified is
2107 permanent, i.e. it will never move (be reordered) in the menu.
2109 - (yas-separator) : Creates a separator
2111 - (yas-submenu NAME SUBMENU) : Creates a submenu with NAME,
2112 SUBMENU has the same form as MENU. NAME is also added to the
2113 list of groups of the snippets defined thereafter.
2115 OMIT-ITEMS is a list of snippet uuid's that will always be
2116 omitted from MODE's menu, even if they're manually loaded.
2118 This function does nothing if `yas-use-menu' is nil."
2120 (let* ((table (yas--table-get-create mode))
2121 (hash (yas--table-uuidhash table)))
2122 (yas--define-menu-1 table
2123 (yas--menu-keymap-get-create mode)
2126 (dolist (uuid omit-items)
2127 (let ((template (or (gethash uuid hash)
2128 (yas--populate-template (puthash uuid
2129 (yas--make-blank-template)
2133 (setf (yas--template-menu-binding-pair template) (cons nil :none)))))))
2135 (defun yas--define-menu-1 (table menu-keymap menu uuidhash &optional group-list)
2136 "Helper for `yas-define-menu'."
2137 (dolist (e (reverse menu))
2138 (cond ((eq (first e) 'yas-item)
2139 (let ((template (or (gethash (second e) uuidhash)
2140 (yas--populate-template (puthash (second e)
2141 (yas--make-blank-template)
2144 :perm-group group-list
2145 :uuid (second e)))))
2146 (define-key menu-keymap (vector (gensym))
2147 (car (yas--template-menu-binding-pair-get-create template :stay)))))
2148 ((eq (first e) 'yas-submenu)
2149 (let ((subkeymap (make-sparse-keymap)))
2150 (define-key menu-keymap (vector (gensym))
2151 `(menu-item ,(second e) ,subkeymap))
2152 (yas--define-menu-1 table
2156 (append group-list (list (second e))))))
2157 ((eq (first e) 'yas-separator)
2158 (define-key menu-keymap (vector (gensym))
2159 '(menu-item "----")))
2161 (yas--message 3 "Don't know anything about menu entry %s" (first e))))))
2163 (defun yas--define (mode key template &optional name condition group)
2164 "Define a snippet. Expanding KEY into TEMPLATE.
2166 NAME is a description to this template. Also update the menu if
2167 `yas-use-menu' is t. CONDITION is the condition attached to
2168 this snippet. If you attach a condition to a snippet, then it
2169 will only be expanded when the condition evaluated to non-nil."
2170 (yas-define-snippets mode
2171 (list (list key template name condition group))))
2173 (defun yas-hippie-try-expand (first-time?)
2174 "Integrate with hippie expand.
2176 Just put this function in `hippie-expand-try-functions-list'."
2177 (when yas-minor-mode
2178 (if (not first-time?)
2179 (let ((yas-fallback-behavior 'return-nil))
2185 ;;; Apropos condition-cache:
2190 (defvar yas--condition-cache-timestamp nil)
2191 (defmacro yas-define-condition-cache (func doc &rest body)
2192 "Define a function FUNC with doc DOC and body BODY, BODY is
2193 executed at most once every snippet expansion attempt, to check
2194 expansion conditions.
2196 It doesn't make any sense to call FUNC programatically."
2197 `(defun ,func () ,(if (and doc
2200 "\n\nFor use in snippets' conditions. Within each
2201 snippet-expansion routine like `yas-expand', computes actual
2202 value for the first time then always returns a cached value.")
2203 (setq body (cons doc body))
2205 (let ((timestamp-and-value (get ',func 'yas--condition-cache)))
2206 (if (equal (car timestamp-and-value) yas--condition-cache-timestamp)
2207 (cdr timestamp-and-value)
2208 (let ((new-value (progn
2211 (put ',func 'yas--condition-cache (cons yas--condition-cache-timestamp new-value))
2214 (defalias 'yas-expand 'yas-expand-from-trigger-key)
2215 (defun yas-expand-from-trigger-key (&optional field)
2216 "Expand a snippet before point.
2218 If no snippet expansion is possible, fall back to the behaviour
2219 defined in `yas-fallback-behavior'.
2221 Optional argument FIELD is for non-interactive use and is an
2222 object satisfying `yas--field-p' to restrict the expansion to."
2224 (setq yas--condition-cache-timestamp (current-time))
2225 (let (templates-and-pos)
2226 (unless (and yas-expand-only-for-last-commands
2227 (not (member last-command yas-expand-only-for-last-commands)))
2228 (setq templates-and-pos (if field
2230 (narrow-to-region (yas--field-start field)
2231 (yas--field-end field))
2233 (yas--current-key))))
2234 (if (and templates-and-pos
2235 (first templates-and-pos))
2236 (yas--expand-or-prompt-for-template (first templates-and-pos)
2237 (second templates-and-pos)
2238 (third templates-and-pos))
2239 (yas--fallback 'trigger-key))))
2241 (defun yas-expand-from-keymap ()
2242 "Directly expand some snippets, searching `yas--direct-keymaps'.
2244 If expansion fails, execute the previous binding for this key"
2246 (setq yas--condition-cache-timestamp (current-time))
2247 (let* ((yas--prefix current-prefix-arg)
2248 (vec (subseq (this-command-keys-vector) (if current-prefix-arg
2249 universal-argument-num-events
2251 (templates (mapcan #'(lambda (table)
2252 (yas--fetch table vec))
2253 (yas--get-snippet-tables))))
2255 (yas--expand-or-prompt-for-template templates)
2256 (let ((yas-fallback-behavior 'call-other-command))
2259 (defun yas--expand-or-prompt-for-template (templates &optional start end)
2260 "Expand one of TEMPLATES from START to END.
2262 Prompt the user if TEMPLATES has more than one element, else
2263 expand immediately. Common gateway for
2264 `yas-expand-from-trigger-key' and `yas-expand-from-keymap'."
2265 (let ((yas--current-template (or (and (rest templates) ;; more than one
2266 (yas--prompt-for-template (mapcar #'cdr templates)))
2268 (when yas--current-template
2269 (yas-expand-snippet (yas--template-content yas--current-template)
2272 (yas--template-expand-env yas--current-template)))))
2274 (defun yas--trigger-key-for-fallback ()
2275 ;; When `yas-trigger-key' is <tab> it correctly overrides
2276 ;; org-mode's <tab>, for example and searching for fallbacks
2277 ;; correctly returns `org-cycle'. However, most other modes bind
2278 ;; "TAB" (which is translated from <tab>), and calling
2279 ;; (key-binding "TAB") does not place return that command into
2280 ;; our command-2 local. So we cheat.
2282 (if (string= yas-trigger-key "<tab>")
2286 (defun yas--fallback (&optional from-trigger-key-p)
2287 "Fallback after expansion has failed.
2289 Common gateway for `yas-expand-from-trigger-key' and
2290 `yas-expand-from-keymap'."
2291 (cond ((eq yas-fallback-behavior 'return-nil)
2294 ((eq yas-fallback-behavior 'call-other-command)
2295 (let* ((yas-minor-mode nil)
2296 (yas--direct-keymaps nil)
2297 (yas-trigger-key (yas--trigger-key-for-fallback))
2298 (keys-1 (this-command-keys-vector))
2299 (keys-2 (and yas-trigger-key
2301 (stringp yas-trigger-key)
2302 (read-kbd-macro yas-trigger-key)))
2303 (command-1 (and keys-1 (key-binding keys-1)))
2304 (command-2 (and keys-2 (key-binding keys-2)))
2305 ;; An (ugly) safety: prevents infinite recursion of
2306 ;; yas-expand* calls.
2307 (command (or (and (symbolp command-1)
2308 (not (string-match "yas-expand" (symbol-name command-1)))
2310 (and (symbolp command-2)
2312 (when (and (commandp command)
2313 (not (string-match "yas-expand" (symbol-name command))))
2314 (setq this-command command)
2315 (call-interactively command))))
2316 ((and (listp yas-fallback-behavior)
2317 (cdr yas-fallback-behavior)
2318 (eq 'apply (car yas-fallback-behavior)))
2319 (if (cddr yas-fallback-behavior)
2320 (apply (cadr yas-fallback-behavior)
2321 (cddr yas-fallback-behavior))
2322 (when (commandp (cadr yas-fallback-behavior))
2323 (setq this-command (cadr yas-fallback-behavior))
2324 (call-interactively (cadr yas-fallback-behavior)))))
2326 ;; also return nil if all the other fallbacks have failed
2331 ;;; Utils for snippet development:
2333 (defun yas--all-templates (tables)
2334 "Get `yas--template' objects in TABLES, applicable for buffer and point.
2336 Honours `yas-choose-tables-first', `yas-choose-keys-first' and
2337 `yas-buffer-local-condition'"
2338 (when yas-choose-tables-first
2339 (setq tables (list (yas--prompt-for-table tables))))
2341 (if yas-choose-keys-first
2342 (let ((key (yas--prompt-for-keys
2343 (mapcan #'yas--table-all-keys tables))))
2345 (mapcan #'(lambda (table)
2346 (yas--fetch table key))
2348 (remove-duplicates (mapcan #'yas--table-templates tables)
2351 (defun yas-insert-snippet (&optional no-condition)
2352 "Choose a snippet to expand, pop-up a list of choices according
2353 to `yas--prompt-function'.
2355 With prefix argument NO-CONDITION, bypass filtering of snippets
2358 (setq yas--condition-cache-timestamp (current-time))
2359 (let* ((yas-buffer-local-condition (or (and no-condition
2361 yas-buffer-local-condition))
2362 (templates (yas--all-templates (yas--get-snippet-tables)))
2363 (yas--current-template (and templates
2364 (or (and (rest templates) ;; more than one template for same key
2365 (yas--prompt-for-template templates))
2367 (where (if (region-active-p)
2368 (cons (region-beginning) (region-end))
2369 (cons (point) (point)))))
2370 (if yas--current-template
2371 (yas-expand-snippet (yas--template-content yas--current-template)
2374 (yas--template-expand-env yas--current-template))
2375 (yas--message 3 "No snippets can be inserted here!"))))
2377 (defun yas-visit-snippet-file ()
2378 "Choose a snippet to edit, selection like `yas-insert-snippet'.
2380 Only success if selected snippet was loaded from a file. Put the
2381 visited file in `snippet-mode'."
2383 (let* ((yas-buffer-local-condition 'always)
2384 (templates (yas--all-templates (yas--get-snippet-tables)))
2385 (yas-prompt-functions '(yas-ido-prompt yas-completing-prompt))
2386 (template (and templates
2387 (or (yas--prompt-for-template templates
2388 "Choose a snippet template to edit: ")
2392 (yas--visit-snippet-file-1 template)
2393 (message "No snippets tables active!"))))
2395 (defun yas--visit-snippet-file-1 (template)
2396 "Helper for `yas-visit-snippet-file'."
2397 (let ((file (yas--template-file template)))
2398 (cond ((and file (file-readable-p file))
2399 (find-file-other-window file)
2401 (set (make-local-variable 'yas--editing-template) template))
2403 (message "Original file %s no longer exists!" file))
2405 (switch-to-buffer (format "*%s*"(yas--template-name template)))
2406 (let ((type 'snippet))
2407 (when (listp (yas--template-content template))
2408 (insert (format "# type: command\n"))
2409 (setq type 'command))
2410 (insert (format "# key: %s\n" (yas--template-key template)))
2411 (insert (format "# name: %s\n" (yas--template-name template)))
2412 (when (yas--template-keybinding template)
2413 (insert (format "# binding: %s\n" (yas--template-keybinding template))))
2414 (when (yas--template-expand-env template)
2415 (insert (format "# expand-env: %s\n" (yas--template-expand-env template))))
2416 (when (yas--template-condition template)
2417 (insert (format "# condition: %s\n" (yas--template-condition template))))
2419 (insert (if (eq type 'command)
2420 (pp-to-string (yas--template-content template))
2421 (yas--template-content template))))
2423 (set (make-local-variable 'yas--editing-template) template)))))
2425 (defun yas--guess-snippet-directories-1 (table)
2426 "Guesses possible snippet subdirectories for TABLE."
2427 (cons (yas--table-name table)
2428 (mapcan #'(lambda (parent)
2429 (yas--guess-snippet-directories-1
2431 (yas--table-parents table))))
2433 (defun yas--guess-snippet-directories (&optional table)
2434 "Try to guess suitable directories based on the current active
2435 tables (or optional TABLE).
2437 Returns a list of elements (TABLE . DIRS) where TABLE is a
2438 `yas--table' object and DIRS is a list of all possible directories
2439 where snippets of table might exist."
2440 (let ((main-dir (replace-regexp-in-string
2442 (or (first (or (yas-snippet-dirs)
2443 (setq yas-snippet-dirs '("~/.emacs.d/snippets")))))))
2444 (tables (or (and table
2446 (yas--get-snippet-tables))))
2447 ;; HACK! the snippet table created here is actually registered!
2449 (unless (or table (gethash major-mode yas--tables))
2450 (push (yas--table-get-create major-mode)
2453 (mapcar #'(lambda (table)
2455 (mapcar #'(lambda (subdir)
2456 (concat main-dir "/" subdir))
2457 (yas--guess-snippet-directories-1 table))))
2460 (defun yas--make-directory-maybe (table-and-dirs &optional main-table-string)
2461 "Returns a dir inside TABLE-AND-DIRS, prompts for creation if none exists."
2462 (or (some #'(lambda (dir) (when (file-directory-p dir) dir)) (cdr table-and-dirs))
2463 (let ((candidate (first (cdr table-and-dirs))))
2464 (unless (file-writable-p (file-name-directory candidate))
2465 (error (yas--format "%s is not writable." candidate)))
2466 (if (y-or-n-p (format "Guessed directory (%s) for%s%s table \"%s\" does not exist! Create? "
2468 (if (gethash (yas--table-mode (car table-and-dirs))
2472 (or main-table-string
2474 (yas--table-name (car table-and-dirs))))
2476 (make-directory candidate 'also-make-parents)
2477 ;; create the .yas-parents file here...
2480 (defun yas-new-snippet (&optional no-template)
2481 "Pops a new buffer for writing a snippet.
2483 Expands a snippet-writing snippet, unless the optional prefix arg
2484 NO-TEMPLATE is non-nil."
2486 (let ((guessed-directories (yas--guess-snippet-directories)))
2488 (switch-to-buffer "*new snippet*")
2490 (kill-all-local-variables)
2493 (set (make-local-variable 'yas--guessed-modes) (mapcar #'(lambda (d)
2494 (yas--table-mode (car d)))
2495 guessed-directories))
2496 (unless no-template (yas-expand-snippet "\
2497 # -*- mode: snippet -*-
2499 # key: ${2:${1:$(replace-regexp-in-string \"\\\\\\\\(\\\\\\\\w+\\\\\\\\).*\" \"\\\\\\\\1\" yas-text)}}${3:
2500 # binding: ${4:direct-keybinding}}${5:
2501 # expand-env: ((${6:some-var} ${7:some-value}))}${8:
2506 (defun yas--compute-major-mode-and-parents (file)
2507 "Given FILE, find the nearest snippet directory for a given mode.
2509 Returns a list (MODE-SYM PARENTS), the mode's symbol and a list
2510 representing one or more of the mode's parents.
2512 Note that MODE-SYM need not be the symbol of a real major mode,
2513 neither do the elements of PARENTS."
2514 (let* ((file-dir (and file
2515 (directory-file-name (or (some #'(lambda (special)
2516 (locate-dominating-file file special))
2520 (directory-file-name (file-name-directory file))))))
2521 (parents-file-name (concat file-dir "/.yas-parents"))
2522 (major-mode-name (and file-dir
2523 (file-name-nondirectory file-dir)))
2524 (major-mode-sym (or (and major-mode-name
2525 (intern major-mode-name))))
2526 (parents (when (file-readable-p parents-file-name)
2530 (insert-file-contents parents-file-name)
2531 (buffer-substring-no-properties (point-min)
2533 (when major-mode-sym
2534 (cons major-mode-sym parents))))
2536 (defvar yas--editing-template nil
2537 "Supporting variable for `yas-load-snippet-buffer' and `yas--visit-snippet'.")
2539 (defvar yas--current-template nil
2540 "Holds the current template being expanded into a snippet.")
2542 (defvar yas--guessed-modes nil
2543 "List of guessed modes supporting `yas-load-snippet-buffer'.")
2545 (defun yas--read-table ()
2546 "Ask user for a snippet table, help with some guessing."
2547 (let ((prompt (if (and (featurep 'ido)
2549 'ido-completing-read 'completing-read)))
2550 (unless yas--guessed-modes
2551 (set (make-local-variable 'yas--guessed-modes)
2552 (or (yas--compute-major-mode-and-parents buffer-file-name))))
2554 (funcall prompt (format "Choose or enter a table (yas guesses %s): "
2555 (if yas--guessed-modes
2556 (first yas--guessed-modes)
2558 (mapcar #'symbol-name yas--guessed-modes)
2563 (if (first yas--guessed-modes)
2564 (symbol-name (first yas--guessed-modes)))))))
2566 (defun yas-load-snippet-buffer (table &optional interactive)
2567 "Parse and load current buffer's snippet definition into TABLE.
2569 TABLE is a symbol naming a passed to `yas--table-get-create'.
2571 When called interactively, prompt for the table name and
2572 whether (and where) to save the snippet, then quit the window."
2573 (interactive (list (yas--read-table) t))
2575 ;; We have `yas--editing-template', this buffer's content comes from a
2576 ;; template which is already loaded and neatly positioned,...
2578 (yas--editing-template
2579 (yas-define-snippets-1 (yas--parse-template (yas--template-file yas--editing-template))
2580 (yas--template-table yas--editing-template)))
2581 ;; Try to use `yas--guessed-modes'. If we don't have that use the
2582 ;; value from `yas--compute-major-mode-and-parents'
2585 (unless yas--guessed-modes
2586 (set (make-local-variable 'yas--guessed-modes) (or (yas--compute-major-mode-and-parents buffer-file-name))))
2587 (let* ((table (yas--table-get-create table)))
2588 (set (make-local-variable 'yas--editing-template)
2589 (yas-define-snippets-1 (yas--parse-template buffer-file-name)
2592 (when (and interactive
2594 ;; Only offer to save this if it looks like a library or new
2595 ;; snippet (loaded from elisp, from a dir in `yas-snippet-dirs'
2596 ;; which is not the first, or from an unwritable file)
2598 (not (yas--template-file yas--editing-template))
2599 (not (file-writable-p (yas--template-file yas--editing-template)))
2600 (and (listp yas-snippet-dirs)
2601 (second yas-snippet-dirs)
2602 (not (string-match (expand-file-name (first yas-snippet-dirs))
2603 (yas--template-file yas--editing-template)))))
2604 (y-or-n-p (yas--format "Looks like a library or new snippet. Save to new file? ")))
2605 (let* ((option (first (yas--guess-snippet-directories (yas--template-table yas--editing-template))))
2607 (yas--make-directory-maybe option))))
2609 (let ((default-file-name (or (and (yas--template-file yas--editing-template)
2610 (file-name-nondirectory (yas--template-file yas--editing-template)))
2611 (yas--template-name yas--editing-template))))
2612 (write-file (concat chosen "/"
2613 (read-from-minibuffer (format "File name to create in %s? " chosen)
2614 default-file-name)))
2615 (setf (yas--template-file yas--editing-template) buffer-file-name)))))
2617 (yas--message 3 "Snippet \"%s\" loaded for %s."
2618 (yas--template-name yas--editing-template)
2619 (yas--table-name (yas--template-table yas--editing-template)))
2620 (quit-window interactive)))
2622 (defun yas-tryout-snippet (&optional debug)
2623 "Test current buffer's snippet template in other buffer."
2625 (let* ((major-mode-and-parent (yas--compute-major-mode-and-parents buffer-file-name))
2626 (parsed (yas--parse-template))
2627 (test-mode (or (and (car major-mode-and-parent)
2628 (fboundp (car major-mode-and-parent))
2629 (car major-mode-and-parent))
2630 (first yas--guessed-modes)
2631 (intern (read-from-minibuffer (yas--format "Please input a mode: ")))))
2632 (yas--current-template
2635 (yas--populate-template (yas--make-blank-template)
2636 :table nil ;; no tables for ephemeral snippets
2638 :content (second parsed)
2639 :name (third parsed)
2640 :expand-env (sixth parsed)))))
2641 (cond (yas--current-template
2642 (let ((buffer-name (format "*testing snippet: %s*" (yas--template-name yas--current-template))))
2643 (kill-buffer (get-buffer-create buffer-name))
2644 (switch-to-buffer (get-buffer-create buffer-name))
2645 (setq buffer-undo-list nil)
2646 (condition-case nil (funcall test-mode) (error nil))
2648 (setq buffer-read-only nil)
2649 (yas-expand-snippet (yas--template-content yas--current-template)
2652 (yas--template-expand-env yas--current-template))
2654 (require 'yasnippet-debug nil t))
2655 (add-hook 'post-command-hook 'yas-debug-snippet-vars nil t))))
2657 (yas--message 3 "Cannot test snippet for unknown major mode")))))
2659 (defun yas-active-keys ()
2660 "Return all active trigger keys for current buffer and point."
2661 (remove-duplicates (mapcan #'yas--table-all-keys (yas--get-snippet-tables))
2664 (defun yas--template-fine-group (template)
2665 (car (last (or (yas--template-group template)
2666 (yas--template-perm-group template)))))
2668 (defun yas-describe-tables (&optional choose)
2669 "Display snippets for each table."
2671 (let* ((by-name-hash (and choose
2672 (y-or-n-p "Show by namehash? ")))
2673 (buffer (get-buffer-create "*YASnippet tables*"))
2674 (active-tables (yas--get-snippet-tables))
2675 (remain-tables (let ((all))
2676 (maphash #'(lambda (k v)
2677 (unless (find v active-tables)
2681 (table-lists (list active-tables remain-tables))
2682 (original-buffer (current-buffer))
2684 (yas--condition-cache-timestamp (current-time)))
2685 (with-current-buffer buffer
2686 (setq buffer-read-only nil)
2688 (cond ((not by-name-hash)
2689 (insert "YASnippet tables: \n")
2690 (while (and table-lists
2692 (dolist (table (car table-lists))
2693 (yas--describe-pretty-table table original-buffer))
2694 (setq table-lists (cdr table-lists))
2696 (yas--create-snippet-xrefs)
2697 (display-buffer buffer)
2698 (setq continue (and choose (y-or-n-p "Show also non-active tables? ")))))
2699 (yas--create-snippet-xrefs)
2703 (insert "\n\nYASnippet tables by NAMEHASH: \n")
2704 (dolist (table (append active-tables remain-tables))
2705 (insert (format "\nSnippet table `%s':\n\n" (yas--table-name table)))
2707 (maphash #'(lambda (k v)
2709 (yas--table-hash table))
2711 (insert (format " key %s maps snippets: %s\n" key
2713 (maphash #'(lambda (k v)
2715 (gethash key (yas--table-hash table)))
2718 (setq buffer-read-only t))
2719 (display-buffer buffer)))
2721 (defun yas--describe-pretty-table (table &optional original-buffer)
2722 (insert (format "\nSnippet table `%s'"
2723 (yas--table-name table)))
2724 (if (yas--table-parents table)
2725 (insert (format " parents: %s\n"
2726 (mapcar #'yas--table-name
2727 (yas--table-parents table))))
2729 (insert (make-string 100 ?-) "\n")
2730 (insert "group state name key binding\n")
2731 (let ((groups-hash (make-hash-table :test #'equal)))
2732 (maphash #'(lambda (k v)
2733 (let ((group (or (yas--template-fine-group v)
2735 (when (yas--template-name v)
2737 (cons v (gethash group groups-hash))
2739 (yas--table-uuidhash table))
2741 #'(lambda (group templates)
2742 (setq group (truncate-string-to-width group 25 0 ? "..."))
2743 (insert (make-string 100 ?-) "\n")
2744 (dolist (p templates)
2745 (let ((name (truncate-string-to-width (propertize (format "\\\\snippet `%s'" (yas--template-name p))
2749 (setq group (make-string (length group) ? ))))
2750 (condition-string (let ((condition (yas--template-condition p)))
2753 (with-current-buffer original-buffer
2754 (if (yas--eval-condition condition)
2759 (insert condition-string " ")
2761 (if (string-match "\\.\\.\\.$" name)
2765 (insert (truncate-string-to-width (or (yas--template-key p) "")
2767 (insert (truncate-string-to-width (key-description (yas--template-keybinding p))
2774 ;;; User convenience functions, for using in snippet definitions
2776 (defvar yas-modified-p nil
2777 "Non-nil if field has been modified by user or transformation.")
2779 (defvar yas-moving-away-p nil
2780 "Non-nil if user is about to exit field.")
2782 (defvar yas-text nil
2783 "Contains current field text.")
2785 (defun yas-substr (str pattern &optional subexp)
2786 "Search PATTERN in STR and return SUBEXPth match.
2788 If found, the content of subexp group SUBEXP (default 0) is
2789 returned, or else the original STR will be returned."
2790 (let ((grp (or subexp 0)))
2792 (if (string-match pattern str)
2793 (match-string-no-properties grp str)
2796 (defun yas-choose-value (&rest possibilities)
2797 "Prompt for a string in POSSIBILITIES and return it.
2799 The last element of POSSIBILITIES may be a list of strings."
2800 (unless (or yas-moving-away-p
2802 (setq possibilities (nreverse possibilities))
2803 (setq possibilities (if (listp (car possibilities))
2804 (append (reverse (car possibilities)) (rest possibilities))
2806 (some #'(lambda (fn)
2807 (funcall fn "Choose: " possibilities))
2808 yas-prompt-functions)))
2810 (defun yas-key-to-value (alist)
2811 (unless (or yas-moving-away-p
2813 (let ((key (read-key-sequence "")))
2815 (or (cdr (find key alist :key #'car :test #'string=))
2818 (defun yas-throw (text)
2819 "Throw a yas--exception with TEXT as the reason."
2820 (throw 'yas--exception (cons 'yas--exception text)))
2822 (defun yas-verify-value (possibilities)
2823 "Verify that the current field value is in POSSIBILITIES.
2825 Otherwise throw exception."
2826 (when (and yas-moving-away-p (notany #'(lambda (pos) (string= pos yas-text)) possibilities))
2827 (yas-throw (yas--format "Field only allows %s" possibilities))))
2829 (defun yas-field-value (number)
2830 "Get the string for field with NUMBER.
2832 Use this in primary and mirror transformations to tget."
2833 (let* ((snippet (car (yas--snippets-at-point)))
2835 (yas--snippet-find-field snippet number))))
2837 (yas--field-text-for-display field))))
2840 "Return `yas-text' if that exists and is non-empty, else nil."
2842 (not (string= "" yas-text)))
2845 (defun yas-selected-text ()
2846 "Return `yas-selected-text' if that exists and is non-empty, else nil."
2847 (if (and yas-selected-text
2848 (not (string= "" yas-selected-text)))
2851 (defun yas--get-field-once (number &optional transform-fn)
2852 (unless yas-modified-p
2854 (funcall transform-fn (yas-field-value number))
2855 (yas-field-value number))))
2857 (defun yas-default-from-field (number)
2858 (unless yas-modified-p
2859 (yas-field-value number)))
2861 (defun yas-inside-string ()
2862 "Return non-nil if the point is inside a string according to font-lock."
2863 (equal 'font-lock-string-face (get-char-property (1- (point)) 'face)))
2865 (defun yas-unimplemented (&optional missing-feature)
2866 (if yas--current-template
2867 (if (y-or-n-p (format "This snippet is unimplemented (missing %s) Visit the snippet definition? "
2870 (yas--visit-snippet-file-1 yas--current-template))
2871 (message "No implementation. Missing %s" (or missing-feature "something"))))
2874 ;;; Snippet expansion and field management
2876 (defvar yas--active-field-overlay nil
2877 "Overlays the currently active field.")
2879 (defvar yas--field-protection-overlays nil
2880 "Two overlays protect the current active field.")
2882 (defconst yas--prefix nil
2883 "A prefix argument for expansion direct from keybindings.")
2885 (defvar yas-selected-text nil
2886 "The selected region deleted on the last snippet expansion.")
2888 (defvar yas--start-column nil
2889 "The column where the snippet expansion started.")
2891 (make-variable-buffer-local 'yas--active-field-overlay)
2892 (make-variable-buffer-local 'yas--field-protection-overlays)
2893 (put 'yas--active-field-overlay 'permanent-local t)
2894 (put 'yas--field-protection-overlays 'permanent-local t)
2896 (defstruct (yas--snippet (:constructor yas--make-snippet ()))
2902 (id (yas--snippet-next-id) :read-only t)
2903 (control-overlay nil)
2905 ;; stacked expansion: the `previous-active-field' slot saves the
2906 ;; active field where the child expansion took place
2907 previous-active-field
2910 (defstruct (yas--field (:constructor yas--make-field (number start end parent-field)))
2920 (defstruct (yas--mirror (:constructor yas--make-mirror (start end transform)))
2927 (defstruct (yas--exit (:constructor yas--make-exit (marker)))
2931 (defun yas--apply-transform (field-or-mirror field &optional empty-on-nil-p)
2932 "Calculate transformed string for FIELD-OR-MIRROR from FIELD.
2934 If there is no transform for ht field, return nil.
2936 If there is a transform but it returns nil, return the empty
2937 string iff EMPTY-ON-NIL-P is true."
2938 (let* ((yas-text (yas--field-text-for-display field))
2940 (yas-modified-p (yas--field-modified-p field))
2941 (yas-moving-away-p nil)
2942 (transform (if (yas--mirror-p field-or-mirror)
2943 (yas--mirror-transform field-or-mirror)
2944 (yas--field-transform field-or-mirror)))
2945 (start-point (if (yas--mirror-p field-or-mirror)
2946 (yas--mirror-start field-or-mirror)
2947 (yas--field-start field-or-mirror)))
2948 (transformed (and transform
2950 (goto-char start-point)
2951 (let ((ret (yas--eval-lisp transform)))
2952 (or ret (and empty-on-nil-p "")))))))
2955 (defsubst yas--replace-all (from to &optional text)
2956 "Replace all occurrences from FROM to TO.
2958 With optional string TEXT do it in that string."
2960 (replace-regexp-in-string (regexp-quote from) to text t t)
2961 (goto-char (point-min))
2962 (while (search-forward from nil t)
2963 (replace-match to t t text))))
2965 (defun yas--snippet-find-field (snippet number)
2966 (find-if #'(lambda (field)
2967 (eq number (yas--field-number field)))
2968 (yas--snippet-fields snippet)))
2970 (defun yas--snippet-sort-fields (snippet)
2971 "Sort the fields of SNIPPET in navigation order."
2972 (setf (yas--snippet-fields snippet)
2973 (sort (yas--snippet-fields snippet)
2974 #'yas--snippet-field-compare)))
2976 (defun yas--snippet-field-compare (field1 field2)
2977 "Compare FIELD1 and FIELD2.
2979 The field with a number is sorted first. If they both have a
2980 number, compare through the number. If neither have, compare
2981 through the field's start point"
2982 (let ((n1 (yas--field-number field1))
2983 (n2 (yas--field-number field2)))
2986 (or (zerop n2) (and (not (zerop n1))
2991 (< (yas--field-start field1)
2992 (yas--field-start field2))))))
2994 (defun yas--field-probably-deleted-p (snippet field)
2995 "Guess if SNIPPET's FIELD should be skipped."
2997 ;; field must be zero length
2999 (zerop (- (yas--field-start field) (yas--field-end field)))
3002 ;; 1) is a nested field and it's been modified
3004 (and (yas--field-parent-field field)
3005 (yas--field-modified-p field))
3006 ;; 2) ends just before the snippet end
3008 (and (eq field (car (last (yas--snippet-fields snippet))))
3009 (= (yas--field-start field) (overlay-end (yas--snippet-control-overlay snippet)))))
3010 ;; the field numbered 0, just before the exit marker, should
3013 (not (zerop (yas--field-number field)))))
3015 (defun yas--snippets-at-point (&optional all-snippets)
3016 "Return a sorted list of snippets at point.
3018 The most recently-inserted snippets are returned first."
3020 (remove nil (remove-duplicates (mapcar #'(lambda (ov)
3021 (overlay-get ov 'yas--snippet))
3023 (overlays-in (point-min) (point-max))
3024 (nconc (overlays-at (point)) (overlays-at (1- (point))))))))
3026 (<= (yas--snippet-id s2) (yas--snippet-id s1)))))
3028 (defun yas-next-field-or-maybe-expand ()
3029 "Try to expand a snippet at a key before point.
3031 Otherwise delegate to `yas-next-field'."
3033 (if yas-triggers-in-field
3034 (let ((yas-fallback-behavior 'return-nil)
3035 (active-field (overlay-get yas--active-field-overlay 'yas--field)))
3037 (unless (yas-expand-from-trigger-key active-field)
3041 (defun yas-next-field (&optional arg)
3042 "Navigate to the ARGth next field.
3044 If there's none, exit the snippet."
3048 (snippet (first (yas--snippets-at-point)))
3049 (active-field (overlay-get yas--active-field-overlay 'yas--field))
3050 (live-fields (remove-if #'(lambda (field)
3051 (and (not (eq field active-field))
3052 (yas--field-probably-deleted-p snippet field)))
3053 (yas--snippet-fields snippet)))
3054 (active-field-pos (position active-field live-fields))
3055 (target-pos (and active-field-pos (+ arg active-field-pos)))
3056 (target-field (and target-pos (nth target-pos live-fields))))
3057 ;; First check if we're moving out of a field with a transform
3059 (when (and active-field
3060 (yas--field-transform active-field))
3061 (let* ((yas-moving-away-p t)
3062 (yas-text (yas--field-text-for-display active-field))
3064 (yas-modified-p (yas--field-modified-p active-field)))
3065 ;; primary field transform: exit call to field-transform
3066 (yas--eval-lisp (yas--field-transform active-field))))
3067 ;; Now actually move...
3068 (cond ((and target-pos (>= target-pos (length live-fields)))
3069 (yas-exit-snippet snippet))
3071 (yas--move-to-field snippet target-field))
3075 (defun yas--place-overlays (snippet field)
3076 "Correctly place overlays for SNIPPET's FIELD."
3077 (yas--make-move-field-protection-overlays snippet field)
3078 (yas--make-move-active-field-overlay snippet field))
3080 (defun yas--move-to-field (snippet field)
3081 "Update SNIPPET to move to field FIELD.
3083 Also create some protection overlays"
3084 (goto-char (yas--field-start field))
3085 (yas--place-overlays snippet field)
3086 (overlay-put yas--active-field-overlay 'yas--field field)
3087 (let ((number (yas--field-number field)))
3088 ;; check for the special ${0: ...} field
3089 (if (and number (zerop number))
3091 (set-mark (yas--field-end field))
3092 (setf (yas--snippet-force-exit snippet)
3093 (or (yas--field-transform field)
3095 ;; make this field active
3096 (setf (yas--snippet-active-field snippet) field)
3097 ;; primary field transform: first call to snippet transform
3098 (unless (yas--field-modified-p field)
3099 (if (yas--field-update-display field snippet)
3100 (yas--update-mirrors snippet)
3101 (setf (yas--field-modified-p field) nil))))))
3103 (defun yas-prev-field ()
3104 "Navigate to prev field. If there's none, exit the snippet."
3106 (yas-next-field -1))
3108 (defun yas-abort-snippet (&optional snippet)
3110 (let ((snippet (or snippet
3111 (car (yas--snippets-at-point)))))
3113 (setf (yas--snippet-force-exit snippet) t))))
3115 (defun yas-exit-snippet (snippet)
3116 "Goto exit-marker of SNIPPET."
3117 (interactive (list (first (yas--snippets-at-point))))
3119 (setf (yas--snippet-force-exit snippet) t)
3120 (goto-char (if (yas--snippet-exit snippet)
3121 (yas--exit-marker (yas--snippet-exit snippet))
3122 (overlay-end (yas--snippet-control-overlay snippet))))))
3124 (defun yas-exit-all-snippets ()
3125 "Exit all snippets."
3127 (mapc #'(lambda (snippet)
3128 (yas-exit-snippet snippet)
3129 (yas--check-commit-snippet))
3130 (yas--snippets-at-point 'all-snippets)))
3133 ;;; Some low level snippet-routines:
3135 (defmacro yas--inhibit-overlay-hooks (&rest body)
3136 "Run BODY with `yas--inhibit-overlay-hooks' set to t."
3137 (declare (indent 0))
3138 `(let ((yas--inhibit-overlay-hooks t))
3141 (defvar yas-snippet-beg nil "Beginning position of the last snippet committed.")
3142 (defvar yas-snippet-end nil "End position of the last snippet committed.")
3144 (defun yas--commit-snippet (snippet)
3145 "Commit SNIPPET, but leave point as it is.
3147 This renders the snippet as ordinary text."
3149 (let ((control-overlay (yas--snippet-control-overlay snippet)))
3151 ;; Save the end of the moribund snippet in case we need to revive it
3152 ;; its original expansion.
3154 (when (and control-overlay
3155 (overlay-buffer control-overlay))
3156 (setq yas-snippet-beg (overlay-start control-overlay))
3157 (setq yas-snippet-end (overlay-end control-overlay))
3158 (delete-overlay control-overlay))
3160 (yas--inhibit-overlay-hooks
3161 (when yas--active-field-overlay
3162 (delete-overlay yas--active-field-overlay))
3163 (when yas--field-protection-overlays
3164 (mapc #'delete-overlay yas--field-protection-overlays)))
3166 ;; stacked expansion: if the original expansion took place from a
3167 ;; field, make sure we advance it here at least to
3168 ;; `yas-snippet-end'...
3170 (let ((previous-field (yas--snippet-previous-active-field snippet)))
3171 (when (and yas-snippet-end previous-field)
3172 (yas--advance-end-maybe previous-field yas-snippet-end)))
3174 ;; Convert all markers to points,
3176 (yas--markers-to-points snippet)
3178 ;; Take care of snippet revival
3180 (if yas-snippet-revival
3181 (push `(apply yas--snippet-revive ,yas-snippet-beg ,yas-snippet-end ,snippet)
3183 ;; Dismember the snippet... this is useful if we get called
3184 ;; again from `yas--take-care-of-redo'....
3185 (setf (yas--snippet-fields snippet) nil)))
3187 (yas--message 3 "Snippet %s exited." (yas--snippet-id snippet)))
3189 (defun yas--safely-run-hooks (hook-var)
3190 (condition-case error
3191 (run-hooks hook-var)
3193 (yas--message 3 "%s error: %s" hook-var (error-message-string error)))))
3196 (defun yas--check-commit-snippet ()
3197 "Checks if point exited the currently active field of the snippet.
3199 If so cleans up the whole snippet up."
3200 (let* ((snippets (yas--snippets-at-point 'all-snippets))
3201 (snippets-left snippets)
3202 (snippet-exit-transform))
3203 (dolist (snippet snippets)
3204 (let ((active-field (yas--snippet-active-field snippet)))
3205 (setq snippet-exit-transform (yas--snippet-force-exit snippet))
3206 (cond ((or snippet-exit-transform
3207 (not (and active-field (yas--field-contains-point-p active-field))))
3208 (setq snippets-left (delete snippet snippets-left))
3209 (setf (yas--snippet-force-exit snippet) nil)
3210 (yas--commit-snippet snippet))
3212 (or (not yas--active-field-overlay)
3213 (not (overlay-buffer yas--active-field-overlay))))
3215 ;; stacked expansion: this case is mainly for recent
3216 ;; snippet exits that place us back int the field of
3220 (yas--move-to-field snippet active-field)
3221 (yas--update-mirrors snippet)))
3224 (unless (or (null snippets) snippets-left)
3225 (if snippet-exit-transform
3226 (yas--eval-lisp-no-saves snippet-exit-transform))
3227 (yas--safely-run-hooks 'yas-after-exit-snippet-hook))))
3229 ;; Apropos markers-to-points:
3231 ;; This was found useful for performance reasons, so that an
3232 ;; excessive number of live markers aren't kept around in the
3233 ;; `buffer-undo-list'. However, in `markers-to-points', the
3234 ;; set-to-nil markers can't simply be discarded and replaced with
3235 ;; fresh ones in `points-to-markers'. The original marker that was
3236 ;; just set to nil has to be reused.
3238 ;; This shouldn't bring horrible problems with undo/redo, but it
3241 (defun yas--markers-to-points (snippet)
3242 "Convert all markers in SNIPPET to a cons (POINT . MARKER)
3243 where POINT is the original position of the marker and MARKER is
3244 the original marker object with the position set to nil."
3245 (dolist (field (yas--snippet-fields snippet))
3246 (let ((start (marker-position (yas--field-start field)))
3247 (end (marker-position (yas--field-end field))))
3248 (set-marker (yas--field-start field) nil)
3249 (set-marker (yas--field-end field) nil)
3250 (setf (yas--field-start field) (cons start (yas--field-start field)))
3251 (setf (yas--field-end field) (cons end (yas--field-end field))))
3252 (dolist (mirror (yas--field-mirrors field))
3253 (let ((start (marker-position (yas--mirror-start mirror)))
3254 (end (marker-position (yas--mirror-end mirror))))
3255 (set-marker (yas--mirror-start mirror) nil)
3256 (set-marker (yas--mirror-end mirror) nil)
3257 (setf (yas--mirror-start mirror) (cons start (yas--mirror-start mirror)))
3258 (setf (yas--mirror-end mirror) (cons end (yas--mirror-end mirror))))))
3259 (let ((snippet-exit (yas--snippet-exit snippet)))
3261 (let ((exit (marker-position (yas--exit-marker snippet-exit))))
3262 (set-marker (yas--exit-marker snippet-exit) nil)
3263 (setf (yas--exit-marker snippet-exit) (cons exit (yas--exit-marker snippet-exit)))))))
3265 (defun yas--points-to-markers (snippet)
3266 "Convert all cons (POINT . MARKER) in SNIPPET to markers.
3268 This is done by setting MARKER to POINT with `set-marker'."
3269 (dolist (field (yas--snippet-fields snippet))
3270 (setf (yas--field-start field) (set-marker (cdr (yas--field-start field))
3271 (car (yas--field-start field))))
3272 (setf (yas--field-end field) (set-marker (cdr (yas--field-end field))
3273 (car (yas--field-end field))))
3274 (dolist (mirror (yas--field-mirrors field))
3275 (setf (yas--mirror-start mirror) (set-marker (cdr (yas--mirror-start mirror))
3276 (car (yas--mirror-start mirror))))
3277 (setf (yas--mirror-end mirror) (set-marker (cdr (yas--mirror-end mirror))
3278 (car (yas--mirror-end mirror))))))
3279 (let ((snippet-exit (yas--snippet-exit snippet)))
3281 (setf (yas--exit-marker snippet-exit) (set-marker (cdr (yas--exit-marker snippet-exit))
3282 (car (yas--exit-marker snippet-exit)))))))
3284 (defun yas--field-contains-point-p (field &optional point)
3285 (let ((point (or point
3287 (and (>= point (yas--field-start field))
3288 (<= point (yas--field-end field)))))
3290 (defun yas--field-text-for-display (field)
3291 "Return the propertized display text for field FIELD."
3292 (buffer-substring (yas--field-start field) (yas--field-end field)))
3294 (defun yas--undo-in-progress ()
3295 "True if some kind of undo is in progress."
3296 (or undo-in-progress
3297 (eq this-command 'undo)
3298 (eq this-command 'redo)))
3300 (defun yas--make-control-overlay (snippet start end)
3301 "Creates the control overlay that surrounds the snippet and
3303 (let ((overlay (make-overlay start
3308 (overlay-put overlay 'keymap yas-keymap)
3309 (overlay-put overlay 'priority 100)
3310 (overlay-put overlay 'yas--snippet snippet)
3313 (defun yas-skip-and-clear-or-delete-char (&optional field)
3314 "Clears unmodified field if at field start, skips to next tab.
3316 Otherwise deletes a character normally by calling `delete-char'."
3318 (let ((field (or field
3319 (and yas--active-field-overlay
3320 (overlay-buffer yas--active-field-overlay)
3321 (overlay-get yas--active-field-overlay 'yas--field)))))
3323 (not (yas--field-modified-p field))
3324 (eq (point) (marker-position (yas--field-start field))))
3325 (yas--skip-and-clear field)
3328 (call-interactively 'delete-char)))))
3330 (defun yas--skip-and-clear (field)
3331 "Deletes the region of FIELD and sets it's modified state to t."
3332 ;; Just before skipping-and-clearing the field, mark its children
3333 ;; fields as modified, too. If the children have mirrors-in-fields
3334 ;; this prevents them from updating erroneously (we're skipping and
3337 (yas--mark-this-and-children-modified field)
3338 (delete-region (yas--field-start field) (yas--field-end field)))
3340 (defun yas--mark-this-and-children-modified (field)
3341 (setf (yas--field-modified-p field) t)
3342 (let ((fom (yas--field-next field)))
3344 (yas--fom-parent-field fom))
3345 (when (and (eq (yas--fom-parent-field fom) field)
3347 (yas--mark-this-and-children-modified fom))
3348 (setq fom (yas--fom-next fom)))))
3350 (defun yas--make-move-active-field-overlay (snippet field)
3351 "Place the active field overlay in SNIPPET's FIELD.
3353 Move the overlay, or create it if it does not exit."
3354 (if (and yas--active-field-overlay
3355 (overlay-buffer yas--active-field-overlay))
3356 (move-overlay yas--active-field-overlay
3357 (yas--field-start field)
3358 (yas--field-end field))
3359 (setq yas--active-field-overlay
3360 (make-overlay (yas--field-start field)
3361 (yas--field-end field)
3363 (overlay-put yas--active-field-overlay 'priority 100)
3364 (overlay-put yas--active-field-overlay 'face 'yas-field-highlight-face)
3365 (overlay-put yas--active-field-overlay 'yas--snippet snippet)
3366 (overlay-put yas--active-field-overlay 'modification-hooks '(yas--on-field-overlay-modification))
3367 (overlay-put yas--active-field-overlay 'insert-in-front-hooks
3368 '(yas--on-field-overlay-modification))
3369 (overlay-put yas--active-field-overlay 'insert-behind-hooks
3370 '(yas--on-field-overlay-modification))))
3372 (defvar yas--inhibit-overlay-hooks nil
3373 "Bind this temporarily to non-nil to prevent running `yas--on-*-modification'.")
3375 (defun yas--on-field-overlay-modification (overlay after? beg end &optional length)
3376 "Clears the field and updates mirrors, conditionally.
3378 Only clears the field if it hasn't been modified and it point it
3379 at field start. This hook doesn't do anything if an undo is in
3381 (unless (or yas--inhibit-overlay-hooks
3382 (yas--undo-in-progress))
3383 (let* ((field (overlay-get overlay 'yas--field))
3384 (number (and field (yas--field-number field)))
3385 (snippet (overlay-get yas--active-field-overlay 'yas--snippet)))
3387 (yas--advance-end-maybe field (overlay-end overlay))
3389 (yas--field-update-display field snippet))
3390 (yas--update-mirrors snippet))
3392 (when (and (not after?)
3393 (not (yas--field-modified-p field))
3394 (eq (point) (if (markerp (yas--field-start field))
3395 (marker-position (yas--field-start field))
3396 (yas--field-start field))))
3397 (yas--skip-and-clear field))
3398 (setf (yas--field-modified-p field) t))))))
3400 ;;; Apropos protection overlays:
3402 ;; These exist for nasty users who will try to delete parts of the
3403 ;; snippet outside the active field. Actual protection happens in
3404 ;; `yas--on-protection-overlay-modification'.
3406 ;; Currently this signals an error which inhibits the command. For
3407 ;; commands that move point (like `kill-line'), point is restored in
3408 ;; the `yas--post-command-handler' using a global
3409 ;; `yas--protection-violation' variable.
3411 ;; Alternatively, I've experimented with an implementation that
3412 ;; commits the snippet before actually calling `this-command'
3413 ;; interactively, and then signals an error, which is ignored. but
3414 ;; blocks all other million modification hooks. This presented some
3415 ;; problems with stacked expansion.
3417 (defun yas--make-move-field-protection-overlays (snippet field)
3418 "Place protection overlays surrounding SNIPPET's FIELD.
3420 Move the overlays, or create them if they do not exit."
3421 (let ((start (yas--field-start field))
3422 (end (yas--field-end field)))
3423 ;; First check if the (1+ end) is contained in the buffer,
3424 ;; otherwise we'll have to do a bit of cheating and silently
3425 ;; insert a newline. the `(1+ (buffer-size))' should prevent this
3426 ;; when using stacked expansion
3428 (when (< (buffer-size) end)
3430 (yas--inhibit-overlay-hooks
3431 (goto-char (point-max))
3433 ;; go on to normal overlay creation/moving
3435 (cond ((and yas--field-protection-overlays
3436 (every #'overlay-buffer yas--field-protection-overlays))
3437 (move-overlay (first yas--field-protection-overlays) (1- start) start)
3438 (move-overlay (second yas--field-protection-overlays) end (1+ end)))
3440 (setq yas--field-protection-overlays
3441 (list (make-overlay (1- start) start nil t nil)
3442 (make-overlay end (1+ end) nil t nil)))
3443 (dolist (ov yas--field-protection-overlays)
3444 (overlay-put ov 'face 'yas--field-debug-face)
3445 (overlay-put ov 'yas--snippet snippet)
3446 ;; (overlay-put ov 'evaporate t)
3447 (overlay-put ov 'modification-hooks '(yas--on-protection-overlay-modification)))))))
3449 (defvar yas--protection-violation nil
3450 "When non-nil, signals attempts to erroneously exit or modify the snippet.
3452 Functions in the `post-command-hook', for example
3453 `yas--post-command-handler' can check it and reset its value to
3454 nil. The variables value is the point where the violation
3457 (defun yas--on-protection-overlay-modification (overlay after? beg end &optional length)
3458 "Signals a snippet violation, then issues error.
3460 The error should be ignored in `debug-ignored-errors'"
3461 (unless yas--inhibit-overlay-hooks
3462 (cond ((not (or after?
3463 (yas--undo-in-progress)))
3464 (setq yas--protection-violation (point))
3465 (error "Exit the snippet first!")))))
3467 (add-to-list 'debug-ignored-errors "^Exit the snippet first!$")
3470 ;; Snippet expansion and "stacked" expansion:
3472 ;; Stacked expansion is when you try to expand a snippet when already
3473 ;; inside a snippet expansion.
3475 ;; The parent snippet does not run its fields modification hooks
3476 ;; (`yas--on-field-overlay-modification' and
3477 ;; `yas--on-protection-overlay-modification') while the child snippet
3478 ;; is active. This means, among other things, that the mirrors of the
3479 ;; parent snippet are not updated, this only happening when one exits
3480 ;; the child snippet.
3482 ;; Unfortunately, this also puts some ugly (and not fully-tested)
3483 ;; bits of code in `yas-expand-snippet' and
3484 ;; `yas--commit-snippet'. I've tried to mark them with "stacked
3487 ;; This was thought to be safer in an undo/redo perspective, but
3488 ;; maybe the correct implementation is to make the globals
3489 ;; `yas--active-field-overlay' and `yas--field-protection-overlays' be
3490 ;; snippet-local and be active even while the child snippet is
3491 ;; running. This would mean a lot of overlay modification hooks
3492 ;; running, but if managed correctly (including overlay priorities)
3493 ;; they should account for all situations...
3495 (defun yas-expand-snippet (content &optional start end expand-env)
3496 "Expand snippet CONTENT at current point.
3498 Text between START and END will be deleted before inserting
3499 template. EXPAND-ENV is are let-style variable to value bindings
3500 considered when expanding the snippet."
3501 (run-hooks 'yas-before-expand-snippet-hook)
3504 (let* ((yas-selected-text (or yas-selected-text
3505 (and (region-active-p)
3506 (buffer-substring-no-properties (region-beginning)
3509 (and (region-active-p)
3513 (and (region-active-p)
3516 (to-delete (and start
3518 (buffer-substring-no-properties start end)))
3521 (setq yas--indent-original-column (current-column))
3522 ;; Delete the region to delete, this *does* get undo-recorded.
3524 (when (and to-delete
3526 (delete-region start end))
3528 (cond ((listp content)
3529 ;; x) This is a snippet-command
3531 (yas--eval-lisp-no-saves content))
3533 ;; x) This is a snippet-snippet :-)
3535 ;; Narrow the region down to the content, shoosh the
3536 ;; `buffer-undo-list', and create the snippet, the new
3537 ;; snippet updates its mirrors once, so we are left with
3538 ;; some plain text. The undo action for deleting this
3539 ;; plain text will get recorded at the end.
3541 ;; stacked expansion: also shoosh the overlay modification hooks
3543 (narrow-to-region start start)
3544 (let ((buffer-undo-list t))
3545 ;; snippet creation might evaluate users elisp, which
3546 ;; might generate errors, so we have to be ready to catch
3547 ;; them mostly to make the undo information
3549 (setq yas--start-column (save-restriction (widen) (current-column)))
3550 (yas--inhibit-overlay-hooks
3553 (eval `(let* ,expand-env
3555 (yas--snippet-create (point-min) (point-max))))
3557 (yas--snippet-create (point-min) (point-max)))))))
3559 ;; stacked-expansion: This checks for stacked expansion, save the
3560 ;; `yas--previous-active-field' and advance its boundary.
3562 (let ((existing-field (and yas--active-field-overlay
3563 (overlay-buffer yas--active-field-overlay)
3564 (overlay-get yas--active-field-overlay 'yas--field))))
3565 (when existing-field
3566 (setf (yas--snippet-previous-active-field snippet) existing-field)
3567 (yas--advance-end-maybe existing-field (overlay-end yas--active-field-overlay))))
3569 ;; Exit the snippet immediately if no fields
3571 (unless (yas--snippet-fields snippet)
3572 (yas-exit-snippet snippet))
3574 ;; Push two undo actions: the deletion of the inserted contents of
3575 ;; the new snippet (without the "key") followed by an apply of
3576 ;; `yas--take-care-of-redo' on the newly inserted snippet boundaries
3578 ;; A small exception, if `yas-also-auto-indent-first-line'
3579 ;; is t and `yas--indent' decides to indent the line to a
3580 ;; point before the actual expansion point, undo would be
3581 ;; messed up. We call the early point "newstart"". case,
3582 ;; and attempt to fix undo.
3584 (let ((newstart (overlay-start (yas--snippet-control-overlay snippet)))
3585 (end (overlay-end (yas--snippet-control-overlay snippet))))
3586 (when (< newstart start)
3587 (push (cons (make-string (- start newstart) ? ) newstart) buffer-undo-list))
3588 (push (cons newstart end) buffer-undo-list)
3589 (push `(apply yas--take-care-of-redo ,start ,end ,snippet)
3591 ;; Now, schedule a move to the first field
3593 (let ((first-field (car (yas--snippet-fields snippet))))
3595 (sit-for 0) ;; fix issue 125
3596 (yas--move-to-field snippet first-field)))
3597 (yas--message 3 "snippet expanded.")
3600 (defun yas--take-care-of-redo (beg end snippet)
3601 "Commits SNIPPET, which in turn pushes an undo action for reviving it.
3603 Meant to exit in the `buffer-undo-list'."
3604 ;; slightly optimize: this action is only needed for snippets with
3605 ;; at least one field
3606 (when (yas--snippet-fields snippet)
3607 (yas--commit-snippet snippet)))
3609 (defun yas--snippet-revive (beg end snippet)
3610 "Revives SNIPPET and creates a control overlay from BEG to END.
3612 BEG and END are, we hope, the original snippets boundaries. All
3613 the markers/points exiting existing inside SNIPPET should point
3614 to their correct locations *at the time the snippet is revived*.
3616 After revival, push the `yas--take-care-of-redo' in the
3618 ;; Reconvert all the points to markers
3620 (yas--points-to-markers snippet)
3621 ;; When at least one editable field existed in the zombie snippet,
3622 ;; try to revive the whole thing...
3624 (let ((target-field (or (yas--snippet-active-field snippet)
3625 (car (yas--snippet-fields snippet)))))
3627 (setf (yas--snippet-control-overlay snippet) (yas--make-control-overlay snippet beg end))
3628 (overlay-put (yas--snippet-control-overlay snippet) 'yas--snippet snippet)
3630 (yas--move-to-field snippet target-field)
3632 (push `(apply yas--take-care-of-redo ,beg ,end ,snippet)
3633 buffer-undo-list))))
3635 (defun yas--snippet-create (begin end)
3636 "Creates a snippet from an template inserted between BEGIN and END.
3638 Returns the newly created snippet."
3639 (let ((snippet (yas--make-snippet)))
3641 (yas--snippet-parse-create snippet)
3643 ;; Sort and link each field
3644 (yas--snippet-sort-fields snippet)
3646 ;; Create keymap overlay for snippet
3647 (setf (yas--snippet-control-overlay snippet)
3648 (yas--make-control-overlay snippet (point-min) (point-max)))
3651 (goto-char (point-max))
3656 ;;; Apropos adjacencies and "fom's":
3658 ;; Once the $-constructs bits like "$n" and "${:n" are deleted in the
3659 ;; recently expanded snippet, we might actually have many fields,
3660 ;; mirrors (and the snippet exit) in the very same position in the
3661 ;; buffer. Therefore we need to single-link the
3662 ;; fields-or-mirrors-or-exit (which I have abbreviated to "fom")
3663 ;; according to their original positions in the buffer.
3665 ;; Then we have operation `yas--advance-end-maybe' and
3666 ;; `yas--advance-start-maybe', which conditionally push the starts and
3667 ;; ends of these foms down the chain.
3669 ;; This allows for like the printf with the magic ",":
3671 ;; printf ("${1:%s}\\n"${1:$(if (string-match "%" text) "," "\);")} \
3672 ;; $2${1:$(if (string-match "%" text) "\);" "")}$0
3674 (defun yas--fom-start (fom)
3675 (cond ((yas--field-p fom)
3676 (yas--field-start fom))
3677 ((yas--mirror-p fom)
3678 (yas--mirror-start fom))
3680 (yas--exit-marker fom))))
3682 (defun yas--fom-end (fom)
3683 (cond ((yas--field-p fom)
3684 (yas--field-end fom))
3685 ((yas--mirror-p fom)
3686 (yas--mirror-end fom))
3688 (yas--exit-marker fom))))
3690 (defun yas--fom-next (fom)
3691 (cond ((yas--field-p fom)
3692 (yas--field-next fom))
3693 ((yas--mirror-p fom)
3694 (yas--mirror-next fom))
3696 (yas--exit-next fom))))
3698 (defun yas--fom-parent-field (fom)
3699 (cond ((yas--field-p fom)
3700 (yas--field-parent-field fom))
3701 ((yas--mirror-p fom)
3702 (yas--mirror-parent-field fom))
3706 (defun yas--calculate-adjacencies (snippet)
3707 "Calculate adjacencies for fields or mirrors of SNIPPET.
3709 This is according to their relative positions in the buffer, and
3710 has to be called before the $-constructs are deleted."
3711 (flet ((yas--fom-set-next-fom (fom nextfom)
3712 (cond ((yas--field-p fom)
3713 (setf (yas--field-next fom) nextfom))
3714 ((yas--mirror-p fom)
3715 (setf (yas--mirror-next fom) nextfom))
3717 (setf (yas--exit-next fom) nextfom))))
3718 (yas--compare-fom-begs (fom1 fom2)
3719 (if (= (yas--fom-start fom2) (yas--fom-start fom1))
3720 (yas--mirror-p fom2)
3721 (>= (yas--fom-start fom2) (yas--fom-start fom1))))
3722 (yas--link-foms (fom1 fom2)
3723 (yas--fom-set-next-fom fom1 fom2)))
3724 ;; make some yas--field, yas--mirror and yas--exit soup
3726 (when (yas--snippet-exit snippet)
3727 (push (yas--snippet-exit snippet) soup))
3728 (dolist (field (yas--snippet-fields snippet))
3730 (dolist (mirror (yas--field-mirrors field))
3731 (push mirror soup)))
3734 #'yas--compare-fom-begs))
3736 (reduce #'yas--link-foms soup)))))
3738 (defun yas--calculate-mirrors-in-fields (snippet mirror)
3739 "Attempt to assign a parent field of SNIPPET to the mirror MIRROR.
3741 Use the tightest containing field if more than one field contains
3742 the mirror. Intended to be called *before* the dollar-regions are
3744 (let ((min (point-min))
3746 (dolist (field (yas--snippet-fields snippet))
3747 (when (and (<= (yas--field-start field) (yas--mirror-start mirror))
3748 (<= (yas--mirror-end mirror) (yas--field-end field))
3749 (< min (yas--field-start field))
3750 (< (yas--field-end field) max))
3751 (setq min (yas--field-start field)
3752 max (yas--field-end field))
3753 (setf (yas--mirror-parent-field mirror) field)))))
3755 (defun yas--advance-end-maybe (fom newend)
3756 "Maybe advance FOM's end to NEWEND if it needs it.
3760 * call `yas--advance-start-maybe' on FOM's next fom.
3762 * in case FOM is field call `yas--advance-end-maybe' on its parent
3765 Also, if FOM is an exit-marker, always call
3766 `yas--advance-start-maybe' on its next fom. This is because
3767 exit-marker have identical start and end markers."
3768 (cond ((and fom (< (yas--fom-end fom) newend))
3769 (set-marker (yas--fom-end fom) newend)
3770 (yas--advance-start-maybe (yas--fom-next fom) newend)
3771 (yas--advance-end-of-parents-maybe (yas--fom-parent-field fom) newend))
3773 (yas--advance-start-maybe (yas--fom-next fom) newend))))
3775 (defun yas--advance-start-maybe (fom newstart)
3776 "Maybe advance FOM's start to NEWSTART if it needs it.
3778 If it does, also call `yas--advance-end-maybe' on FOM."
3779 (when (and fom (< (yas--fom-start fom) newstart))
3780 (set-marker (yas--fom-start fom) newstart)
3781 (yas--advance-end-maybe fom newstart)))
3783 (defun yas--advance-end-of-parents-maybe (field newend)
3784 "Like `yas--advance-end-maybe' but for parent fields.
3786 Only works for fields and doesn't care about the start of the
3787 next FOM. Works its way up recursively for parents of parents."
3789 (< (yas--field-end field) newend))
3790 (set-marker (yas--field-end field) newend)
3791 (yas--advance-end-of-parents-maybe (yas--field-parent-field field) newend)))
3793 (defvar yas--dollar-regions nil
3794 "When expanding the snippet the \"parse-create\" functions add
3795 cons cells to this var.")
3797 (defvar yas--backquote-markers-and-strings nil
3798 "List of (MARKER . STRING) marking where the values from
3799 backquoted lisp expressions should be inserted at the end of
3802 (defun yas--snippet-parse-create (snippet)
3803 "Parse a recently inserted snippet template, creating all
3804 necessary fields, mirrors and exit points.
3806 Meant to be called in a narrowed buffer, does various passes"
3807 (let ((parse-start (point)))
3808 ;; Reset the yas--dollar-regions
3810 (setq yas--dollar-regions nil)
3811 ;; protect just the backquotes
3813 (yas--protect-escapes nil '(?`))
3814 ;; replace all backquoted expressions
3816 (goto-char parse-start)
3817 (yas--save-backquotes)
3818 ;; protect escaped characters
3820 (yas--protect-escapes)
3821 ;; parse fields with {}
3823 (goto-char parse-start)
3824 (yas--field-parse-create snippet)
3825 ;; parse simple mirrors and fields
3827 (goto-char parse-start)
3828 (yas--simple-mirror-parse-create snippet)
3829 ;; parse mirror transforms
3831 (goto-char parse-start)
3832 (yas--transform-mirror-parse-create snippet)
3833 ;; calculate adjacencies of fields and mirrors
3835 (yas--calculate-adjacencies snippet)
3836 ;; Delete $-constructs
3838 (yas--delete-regions yas--dollar-regions)
3839 ;; restore backquoted expression values
3841 (yas--restore-backquotes)
3844 (goto-char parse-start)
3845 (yas--restore-escapes)
3846 ;; update mirrors for the first time
3848 (yas--update-mirrors snippet)
3849 ;; indent the best we can
3851 (goto-char parse-start)
3852 (yas--indent snippet)))
3854 (defun yas--indent-according-to-mode (snippet-markers)
3855 "Indent current line according to mode, preserving SNIPPET-MARKERS."
3856 ;;; Apropos indenting problems....
3858 ;; `indent-according-to-mode' uses whatever `indent-line-function'
3859 ;; is available. Some implementations of these functions delete text
3860 ;; before they insert. If there happens to be a marker just after
3861 ;; the text being deleted, the insertion actually happens after the
3862 ;; marker, which misplaces it.
3864 ;; This would also happen if we had used overlays with the
3865 ;; `front-advance' property set to nil.
3867 ;; This is why I have these `trouble-markers', they are the ones at
3868 ;; they are the ones at the first non-whitespace char at the line
3869 ;; (i.e. at `yas--real-line-beginning'. After indentation takes place
3870 ;; we should be at the correct to restore them to. All other
3871 ;; non-trouble-markers have been *pushed* and don't need special
3874 (goto-char (yas--real-line-beginning))
3875 (let ((trouble-markers (remove-if-not #'(lambda (marker)
3881 (indent-according-to-mode)
3882 (error (yas--message 3 "Warning: `yas--indent-according-to-mode' having problems running %s" indent-line-function)
3884 (mapc #'(lambda (marker)
3885 (set-marker marker (point)))
3888 (defvar yas--indent-original-column nil)
3889 (defun yas--indent (snippet)
3890 (let ((snippet-markers (yas--collect-snippet-markers snippet)))
3891 ;; Look for those $>
3893 (while (re-search-forward "$>" nil t)
3894 (delete-region (match-beginning 0) (match-end 0))
3895 (when (not (eq yas-indent-line 'auto))
3896 (yas--indent-according-to-mode snippet-markers))))
3897 ;; Now do stuff for 'fixed and 'auto
3899 (cond ((eq yas-indent-line 'fixed)
3900 (while (and (zerop (forward-line))
3901 (zerop (current-column)))
3902 (indent-to-column yas--indent-original-column)))
3903 ((eq yas-indent-line 'auto)
3904 (let ((end (set-marker (make-marker) (point-max)))
3905 (indent-first-line-p yas-also-auto-indent-first-line))
3906 (while (and (zerop (if indent-first-line-p
3909 (setq indent-first-line-p nil))
3913 (yas--indent-according-to-mode snippet-markers))))
3917 (defun yas--collect-snippet-markers (snippet)
3918 "Make a list of all the markers used by SNIPPET."
3920 (dolist (field (yas--snippet-fields snippet))
3921 (push (yas--field-start field) markers)
3922 (push (yas--field-end field) markers)
3923 (dolist (mirror (yas--field-mirrors field))
3924 (push (yas--mirror-start mirror) markers)
3925 (push (yas--mirror-end mirror) markers)))
3926 (let ((snippet-exit (yas--snippet-exit snippet)))
3927 (when (and snippet-exit
3928 (marker-buffer (yas--exit-marker snippet-exit)))
3929 (push (yas--exit-marker snippet-exit) markers)))
3932 (defun yas--real-line-beginning ()
3933 (let ((c (char-after (line-beginning-position)))
3934 (n (line-beginning-position)))
3935 (while (or (eql c ?\ )
3938 (setq c (char-after n)))
3941 (defun yas--escape-string (escaped)
3942 (concat "YASESCAPE" (format "%d" escaped) "PROTECTGUARD"))
3944 (defun yas--protect-escapes (&optional text escaped)
3945 "Protect all escaped characters with their numeric ASCII value.
3947 With optional string TEXT do it in string instead of buffer."
3948 (let ((changed-text text)
3949 (text-provided-p text))
3950 (mapc #'(lambda (escaped)
3952 (yas--replace-all (concat "\\" (char-to-string escaped))
3953 (yas--escape-string escaped)
3954 (when text-provided-p changed-text))))
3955 (or escaped yas--escaped-characters))
3958 (defun yas--restore-escapes (&optional text escaped)
3959 "Restore all escaped characters from their numeric ASCII value.
3961 With optional string TEXT do it in string instead of the buffer."
3962 (let ((changed-text text)
3963 (text-provided-p text))
3964 (mapc #'(lambda (escaped)
3966 (yas--replace-all (yas--escape-string escaped)
3967 (char-to-string escaped)
3968 (when text-provided-p changed-text))))
3969 (or escaped yas--escaped-characters))
3972 (defun yas--save-backquotes ()
3973 "Save all the \"`(lisp-expression)`\"-style expressions
3974 with their evaluated value into `yas--backquote-markers-and-strings'."
3975 (while (re-search-forward yas--backquote-lisp-expression-regexp nil t)
3976 (let ((current-string (match-string-no-properties 1)) transformed)
3977 (delete-region (match-beginning 0) (match-end 0))
3978 (setq transformed (yas--eval-lisp (yas--read-lisp (yas--restore-escapes current-string '(?`)))))
3979 (goto-char (match-beginning 0))
3981 (let ((marker (make-marker)))
3982 (insert "Y") ;; quite horrendous, I love it :)
3983 (set-marker marker (point))
3985 (push (cons marker transformed) yas--backquote-markers-and-strings))))))
3987 (defun yas--restore-backquotes ()
3988 "Replace markers in `yas--backquote-markers-and-strings' with their values."
3989 (while yas--backquote-markers-and-strings
3990 (let* ((marker-and-string (pop yas--backquote-markers-and-strings))
3991 (marker (car marker-and-string))
3992 (string (cdr marker-and-string)))
3998 (set-marker marker nil)))))
4000 (defun yas--scan-sexps (from count)
4002 (with-syntax-table (standard-syntax-table)
4003 (scan-sexps from count))
4007 (defun yas--make-marker (pos)
4008 "Create a marker at POS with nil `marker-insertion-type'."
4009 (let ((marker (set-marker (make-marker) pos)))
4010 (set-marker-insertion-type marker nil)
4013 (defun yas--field-parse-create (snippet &optional parent-field)
4014 "Parse most field expressions in SNIPPET, except for the simple one \"$n\".
4016 The following count as a field:
4018 * \"${n: text}\", for a numbered field with default text, as long as N is not 0;
4020 * \"${n: text$(expression)}, the same with a lisp expression;
4021 this is caught with the curiously named `yas--multi-dollar-lisp-expression-regexp'
4023 * the same as above but unnumbered, (no N:) and number is calculated automatically.
4025 When multiple expressions are found, only the last one counts."
4028 (while (re-search-forward yas--field-regexp nil t)
4029 (let* ((real-match-end-0 (yas--scan-sexps (1+ (match-beginning 0)) 1))
4030 (number (and (match-string-no-properties 1)
4031 (string-to-number (match-string-no-properties 1))))
4032 (brand-new-field (and real-match-end-0
4033 ;; break if on "$(" immediately
4034 ;; after the ":", this will be
4035 ;; caught as a mirror with
4037 (not (save-match-data
4038 (eq (string-match "$[ \t\n]*("
4039 (match-string-no-properties 2)) 0)))
4040 ;; allow ${0: some exit text}
4041 ;; (not (and number (zerop number)))
4042 (yas--make-field number
4043 (yas--make-marker (match-beginning 2))
4044 (yas--make-marker (1- real-match-end-0))
4046 (when brand-new-field
4047 (goto-char real-match-end-0)
4048 (push (cons (1- real-match-end-0) real-match-end-0)
4049 yas--dollar-regions)
4050 (push (cons (match-beginning 0) (match-beginning 2))
4051 yas--dollar-regions)
4052 (push brand-new-field (yas--snippet-fields snippet))
4055 (narrow-to-region (yas--field-start brand-new-field) (yas--field-end brand-new-field))
4056 (goto-char (point-min))
4057 (yas--field-parse-create snippet brand-new-field)))))))
4058 ;; if we entered from a parent field, now search for the
4059 ;; `yas--multi-dollar-lisp-expression-regexp'. This is used for
4060 ;; primary field transformations
4064 (while (re-search-forward yas--multi-dollar-lisp-expression-regexp nil t)
4065 (let* ((real-match-end-1 (yas--scan-sexps (match-beginning 1) 1)))
4066 ;; commit the primary field transformation if:
4068 ;; 1. we don't find it in yas--dollar-regions (a subnested
4069 ;; field) might have already caught it.
4071 ;; 2. we really make sure we have either two '$' or some
4072 ;; text and a '$' after the colon ':'. This is a FIXME: work
4073 ;; my regular expressions and end these ugly hacks.
4075 (when (and real-match-end-1
4076 (not (member (cons (match-beginning 0)
4078 yas--dollar-regions))
4080 (char-before (1- (match-beginning 1))))))
4081 (let ((lisp-expression-string (buffer-substring-no-properties (match-beginning 1)
4083 (setf (yas--field-transform parent-field)
4084 (yas--read-lisp (yas--restore-escapes lisp-expression-string))))
4085 (push (cons (match-beginning 0) real-match-end-1)
4086 yas--dollar-regions)))))))
4088 (defun yas--transform-mirror-parse-create (snippet)
4089 "Parse the \"${n:$(lisp-expression)}\" mirror transformations in SNIPPET."
4090 (while (re-search-forward yas--transform-mirror-regexp nil t)
4091 (let* ((real-match-end-0 (yas--scan-sexps (1+ (match-beginning 0)) 1))
4092 (number (string-to-number (match-string-no-properties 1)))
4094 (not (zerop number))
4095 (yas--snippet-find-field snippet number)))
4097 (and real-match-end-0
4099 (yas--make-mirror (yas--make-marker (match-beginning 0))
4100 (yas--make-marker (match-beginning 0))
4102 (yas--restore-escapes
4103 (buffer-substring-no-properties (match-beginning 2)
4104 (1- real-match-end-0))))))))
4105 (when brand-new-mirror
4106 (push brand-new-mirror
4107 (yas--field-mirrors field))
4108 (yas--calculate-mirrors-in-fields snippet brand-new-mirror)
4109 (push (cons (match-beginning 0) real-match-end-0) yas--dollar-regions)))))
4111 (defun yas--simple-mirror-parse-create (snippet)
4112 "Parse the simple \"$n\" fields/mirrors/exitmarkers in SNIPPET."
4113 (while (re-search-forward yas--simple-mirror-regexp nil t)
4114 (let ((number (string-to-number (match-string-no-properties 1))))
4115 (cond ((zerop number)
4117 (setf (yas--snippet-exit snippet)
4118 (yas--make-exit (yas--make-marker (match-end 0))))
4120 (goto-char (match-beginning 0))
4121 (when yas-wrap-around-region
4122 (cond (yas-selected-text
4123 (insert yas-selected-text))
4124 ((and (eq yas-wrap-around-region 'cua)
4127 (insert (prog1 (get-register ?0)
4128 (set-register ?0 nil))))))
4129 (push (cons (point) (yas--exit-marker (yas--snippet-exit snippet)))
4130 yas--dollar-regions)))
4132 (let ((field (yas--snippet-find-field snippet number)))
4134 (let ((brand-new-mirror (yas--make-mirror
4135 (yas--make-marker (match-beginning 0))
4136 (yas--make-marker (match-beginning 0))
4138 (push brand-new-mirror
4139 (yas--field-mirrors field))
4140 (yas--calculate-mirrors-in-fields snippet brand-new-mirror))
4141 (push (yas--make-field number
4142 (yas--make-marker (match-beginning 0))
4143 (yas--make-marker (match-beginning 0))
4145 (yas--snippet-fields snippet))))
4146 (push (cons (match-beginning 0) (match-end 0))
4147 yas--dollar-regions))))))
4149 (defun yas--delete-regions (regions)
4150 "Sort disjuct REGIONS by start point, then delete from the back."
4151 (mapc #'(lambda (reg)
4152 (delete-region (car reg) (cdr reg)))
4155 (>= (car r1) (car r2))))))
4157 (defun yas--update-mirrors (snippet)
4158 "Updates all the mirrors of SNIPPET."
4160 (dolist (field-and-mirror (sort
4161 ;; make a list of ((F1 . M1) (F1 . M2) (F2 . M3) (F2 . M4) ...)
4162 ;; where F is the field that M is mirroring
4164 (mapcan #'(lambda (field)
4165 (mapcar #'(lambda (mirror)
4166 (cons field mirror))
4167 (yas--field-mirrors field)))
4168 (yas--snippet-fields snippet))
4169 ;; then sort this list so that entries with mirrors with parent
4170 ;; fields appear before. This was important for fixing #290, and
4171 ;; luckily also handles the case where a mirror in a field causes
4172 ;; another mirror to need reupdating
4174 #'(lambda (field-and-mirror1 field-and-mirror2)
4175 (yas--mirror-parent-field (cdr field-and-mirror1)))))
4176 (let* ((field (car field-and-mirror))
4177 (mirror (cdr field-and-mirror))
4178 (parent-field (yas--mirror-parent-field mirror)))
4179 ;; before updating a mirror with a parent-field, maybe advance
4183 (yas--advance-start-maybe mirror (yas--fom-start parent-field)))
4184 ;; update this mirror
4186 (yas--mirror-update-display mirror field)
4187 ;; `yas--place-overlays' is needed if the active field and
4188 ;; protected overlays have been changed because of insertions
4189 ;; in `yas--mirror-update-display'
4191 (when (eq field (yas--snippet-active-field snippet))
4192 (yas--place-overlays snippet field))))))
4194 (defun yas--mirror-update-display (mirror field)
4195 "Update MIRROR according to FIELD (and mirror transform)."
4197 (let* ((mirror-parent-field (yas--mirror-parent-field mirror))
4198 (reflection (and (not (and mirror-parent-field
4199 (yas--field-modified-p mirror-parent-field)))
4200 (or (yas--apply-transform mirror field 'empty-on-nil)
4201 (yas--field-text-for-display field)))))
4202 (when (and reflection
4203 (not (string= reflection (buffer-substring-no-properties (yas--mirror-start mirror)
4204 (yas--mirror-end mirror)))))
4205 (goto-char (yas--mirror-start mirror))
4206 (yas--inhibit-overlay-hooks
4207 (insert reflection))
4208 (if (> (yas--mirror-end mirror) (point))
4209 (delete-region (point) (yas--mirror-end mirror))
4210 (set-marker (yas--mirror-end mirror) (point))
4211 (yas--advance-start-maybe (yas--mirror-next mirror) (point))
4212 ;; super-special advance
4213 (yas--advance-end-of-parents-maybe mirror-parent-field (point))))))
4215 (defun yas--field-update-display (field snippet)
4216 "Much like `yas--mirror-update-display', but for fields."
4217 (when (yas--field-transform field)
4218 (let ((transformed (and (not (eq (yas--field-number field) 0))
4219 (yas--apply-transform field field)))
4221 (when (and transformed
4222 (not (string= transformed (buffer-substring-no-properties (yas--field-start field)
4223 (yas--field-end field)))))
4224 (setf (yas--field-modified-p field) t)
4225 (goto-char (yas--field-start field))
4226 (yas--inhibit-overlay-hooks
4227 (insert transformed)
4228 (if (> (yas--field-end field) (point))
4229 (delete-region (point) (yas--field-end field))
4230 (set-marker (yas--field-end field) (point))
4231 (yas--advance-start-maybe (yas--field-next field) (point)))
4235 ;;; Post-command hook:
4237 (defun yas--post-command-handler ()
4238 "Handles various yasnippet conditions after each command."
4239 (cond (yas--protection-violation
4240 (goto-char yas--protection-violation)
4241 (setq yas--protection-violation nil))
4242 ((eq 'undo this-command)
4244 ;; After undo revival the correct field is sometimes not
4245 ;; restored correctly, this condition handles that
4247 (let* ((snippet (car (yas--snippets-at-point)))
4248 (target-field (and snippet
4249 (find-if-not #'(lambda (field)
4250 (yas--field-probably-deleted-p snippet field))
4252 (cons (yas--snippet-active-field snippet)
4253 (yas--snippet-fields snippet)))))))
4255 (yas--move-to-field snippet target-field))))
4256 ((not (yas--undo-in-progress))
4257 ;; When not in an undo, check if we must commit the snippet
4258 ;; (user exited it).
4259 (yas--check-commit-snippet))))
4263 ;; The docstrings for some functions are generated dynamically
4264 ;; depending on the context.
4266 (put 'yas-expand 'function-documentation
4267 '(yas--expand-from-trigger-key-doc))
4268 (defun yas--expand-from-trigger-key-doc ()
4269 "A doc synthesizer for `yas--expand-from-trigger-key-doc'."
4270 (let ((fallback-description
4271 (cond ((eq yas-fallback-behavior 'call-other-command)
4272 (let* ((yas-minor-mode nil)
4273 (fallback (key-binding (read-kbd-macro (yas--trigger-key-for-fallback)))))
4275 (format " call command `%s'." (pp-to-string fallback)))
4277 ((eq yas-fallback-behavior 'return-nil)
4280 ", defer to `yas--fallback-behaviour' :-)"))))
4281 (concat "Expand a snippet before point. If no snippet
4282 expansion is possible,"
4283 fallback-description
4284 "\n\nOptional argument FIELD is for non-interactive use and is an
4285 object satisfying `yas--field-p' to restrict the expansion to.")))
4287 (put 'yas-expand-from-keymap 'function-documentation '(yas--expand-from-keymap-doc))
4288 (defun yas--expand-from-keymap-doc ()
4289 "A doc synthesizer for `yas--expand-from-keymap-doc'."
4290 (add-hook 'temp-buffer-show-hook 'yas--snippet-description-finish-runonce)
4291 (concat "Expand/run snippets from keymaps, possibly falling back to original binding.\n"
4292 (when (eq this-command 'describe-key)
4293 (let* ((vec (this-single-command-keys))
4294 (templates (mapcan #'(lambda (table)
4295 (yas--fetch table vec))
4296 (yas--get-snippet-tables)))
4297 (yas--direct-keymaps nil)
4298 (fallback (key-binding vec)))
4299 (concat "In this case, "
4301 (concat "these snippets are bound to this key:\n"
4302 (yas--template-pretty-list templates)
4303 "\n\nIf none of these expands, "))
4305 (format "fallback `%s' will be called." (pp-to-string fallback)))
4306 "no fallback keybinding is called."))))))
4308 (defun yas--template-pretty-list (templates)
4310 (yas-buffer-local-condition 'always))
4311 (dolist (plate templates)
4312 (setq acc (concat acc "\n*) "
4313 (propertize (concat "\\\\snippet `" (car plate) "'")
4314 'yasnippet (cdr plate)))))
4317 (define-button-type 'help-snippet-def
4318 :supertype 'help-xref
4319 'help-function (lambda (template) (yas--visit-snippet-file-1 template))
4320 'help-echo (purecopy "mouse-2, RET: find snippets's definition"))
4322 (defun yas--snippet-description-finish-runonce ()
4323 "Final adjustments for the help buffer when snippets are concerned."
4324 (yas--create-snippet-xrefs)
4325 (remove-hook 'temp-buffer-show-hook 'yas--snippet-description-finish-runonce))
4327 (defun yas--create-snippet-xrefs ()
4329 (goto-char (point-min))
4330 (while (search-forward-regexp "\\\\\\\\snippet[ \s\t]+`\\([^']+\\)'" nil t)
4331 (let ((template (get-text-property (match-beginning 1)
4334 (help-xref-button 1 'help-snippet-def template)
4335 (kill-region (match-end 1) (match-end 0))
4336 (kill-region (match-beginning 0) (match-beginning 1)))))))
4338 (defun yas--expand-uuid (mode-symbol uuid &optional start end expand-env)
4339 "Expand a snippet registered in MODE-SYMBOL's table with UUID.
4341 Remaining args as in `yas-expand-snippet'."
4342 (let* ((table (gethash mode-symbol yas--tables))
4343 (yas--current-template (and table
4344 (gethash uuid (yas--table-uuidhash table)))))
4345 (when yas--current-template
4346 (yas-expand-snippet (yas--template-content yas--current-template)))))
4350 (defvar yas-verbosity 4
4351 "Log level for `yas--message' 4 means trace most anything, 0 means nothing.")
4353 (defun yas--message (level message &rest args)
4354 "When LEVEL is above `yas-verbosity-level', log MESSAGE and ARGS."
4355 (when (> yas-verbosity level)
4356 (message (apply #'yas--format message args))))
4358 (defun yas--format (format-control &rest format-args)
4359 (apply #'format (concat "[yas] " format-control) format-args))
4366 ;; `locate-dominating-file'
4367 ;; `region-active-p'
4369 ;; added for compatibility in emacsen < 23
4370 (unless (>= emacs-major-version 23)
4371 (unless (fboundp 'region-active-p)
4372 (defun region-active-p () (and transient-mark-mode mark-active)))
4374 (unless (fboundp 'locate-dominating-file)
4375 (defvar locate-dominating-stop-dir-regexp
4376 "\\`\\(?:[\\/][\\/][^\\/]+[\\/]\\|/\\(?:net\\|afs\\|\\.\\.\\.\\)/\\)\\'"
4377 "Regexp of directory names which stop the search in `locate-dominating-file'.
4378 Any directory whose name matches this regexp will be treated like
4379 a kind of root directory by `locate-dominating-file' which will stop its search
4380 when it bumps into it.
4381 The default regexp prevents fruitless and time-consuming attempts to find
4382 special files in directories in which filenames are interpreted as hostnames,
4383 or mount points potentially requiring authentication as a different user.")
4385 (defun locate-dominating-file (file name)
4386 "Look up the directory hierarchy from FILE for a file named NAME.
4387 Stop at the first parent directory containing a file NAME,
4388 and return the directory. Return nil if not found."
4389 ;; We used to use the above locate-dominating-files code, but the
4390 ;; directory-files call is very costly, so we're much better off doing
4391 ;; multiple calls using the code in here.
4393 ;; Represent /home/luser/foo as ~/foo so that we don't try to look for
4394 ;; `name' in /home or in /.
4395 (setq file (abbreviate-file-name file))
4398 ;; `user' is not initialized outside the loop because
4399 ;; `file' may not exist, so we may have to walk up part of the
4400 ;; hierarchy before we find the "initial UUID".
4403 (while (not (or root
4405 ;; FIXME: Disabled this heuristic because it is sometimes
4407 ;; As a heuristic, we stop looking up the hierarchy of
4408 ;; directories as soon as we find a directory belonging
4409 ;; to another user. This should save us from looking in
4410 ;; things like /net and /afs. This assumes that all the
4411 ;; files inside a project belong to the same user.
4412 ;; (let ((prev-user user))
4413 ;; (setq user (nth 2 (file-attributes file)))
4414 ;; (and prev-user (not (equal user prev-user))))
4415 (string-match locate-dominating-stop-dir-regexp file)))
4416 (setq try (file-exists-p (expand-file-name name file)))
4417 (cond (try (setq root file))
4418 ((equal file (setq prev-file file
4419 file (file-name-directory
4420 (directory-file-name file))))
4424 ;; `c-neutralize-syntax-in-CPP` sometimes fires "End of Buffer" error
4425 ;; (when it execute forward-char) and interrupt the after change
4426 ;; hook. Thus prevent the insert-behind hook of yasnippet to be
4427 ;; invoked. Here's a way to reproduce it:
4429 ;; # open a *new* Emacs.
4430 ;; # load yasnippet.
4431 ;; # open a *new* .cpp file.
4432 ;; # input "inc" and press TAB to expand the snippet.
4433 ;; # select the `#include <...>` snippet.
4434 ;; # type inside `<>`
4436 (defadvice c-neutralize-syntax-in-CPP
4437 (around yas--mp/c-neutralize-syntax-in-CPP activate)
4438 "Adviced `c-neutralize-syntax-in-CPP' to properly
4439 handle the end-of-buffer error fired in it by calling
4440 `forward-char' at the end of buffer."
4443 (error (message (error-message-string err)))))
4445 ;; disable c-electric-* serial command in YAS fields
4446 (add-hook 'c-mode-common-hook
4448 (dolist (k '(":" ">" ";" "<" "{" "}"))
4449 (define-key (symbol-value (make-local-variable 'yas-keymap))
4450 k 'self-insert-command))))
4452 ;;; Backward compatibility to yasnippet <= 0.7
4453 (defvar yas--exported-syms '(;; `defcustom's
4456 yas-prompt-functions
4458 yas-also-auto-indent-first-line
4463 yas-skip-and-clear-key
4464 yas-triggers-in-field
4465 yas-fallback-behavior
4466 yas-choose-keys-first
4467 yas-choose-tables-first
4470 yas-wrap-around-region
4473 yas-expand-only-for-last-commands
4474 yas-field-highlight-face
4476 ;; these vars can be customized as well
4482 yas-after-exit-snippet-hook
4483 yas-before-expand-snippet-hook
4484 yas-buffer-local-condition
4486 ;; prompting functions
4491 yas-completing-prompt
4494 ;; interactive functions
4499 yas-direct-keymaps-reload
4503 yas-compile-directory
4506 yas-expand-from-trigger-key
4507 yas-expand-from-keymap
4509 yas-visit-snippet-file
4511 yas-load-snippet-buffer
4514 yas-next-field-or-maybe-expand
4519 yas-exit-all-snippets
4520 yas-skip-and-clear-or-delete-char
4522 ;; symbols that I "exported" for use
4523 ;; in snippets and hookage
4541 yas-default-from-field
4544 yas-define-condition-cache
4545 yas-hippie-try-expand
4548 ;; debug definitions
4549 ;; yas-debug-snippet-vars
4550 ;; yas-exterminate-package
4553 ;; testing definitions
4554 ;; yas-should-expand
4555 ;; yas-should-not-expand
4557 ;; yas-make-file-or-dirs
4559 ;; yas-saving-variables
4560 ;; yas-call-with-snippet-dirs
4561 ;; yas-with-snippet-dirs
4563 "Exported yasnippet symbols.
4565 i.e. ones that I will try to keep in future yasnippet versions
4566 and ones that other elisp libraries can more or less safely rely
4569 (defvar yas--dont-backport '(yas-active-keys)
4570 "Exported symbols that don't map back to \"yas/*\" variants.")
4572 (dolist (sym (set-difference yas--exported-syms yas--dont-backport))
4573 (let ((backported (intern (replace-regexp-in-string "^yas-" "yas/" (symbol-name sym)))))
4575 (make-obsolete-variable backported sym "yasnippet 0.8")
4576 (defvaralias backported sym))
4578 (make-obsolete backported sym "yasnippet 0.8")
4579 (defalias backported sym))))
4582 (provide 'yasnippet)
4584 ;;; yasnippet.el ends here