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 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", puting 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 (unless (fboundp 'cl-flet)
141 (defalias 'cl-flet 'flet)
142 (put 'cl-flet 'lisp-indent-function 1)
143 (put 'cl-flet 'edebug-form-spec '((&rest (defun*)) cl-declarations body))))
146 ;;; User customizable variables
148 (defgroup yasnippet nil
149 "Yet Another Snippet extension"
152 (defvar yas--load-file-name load-file-name
153 "Store the filename that yasnippet.el was originally loaded from.")
155 (defcustom yas-snippet-dirs (remove nil
156 (list "~/.emacs.d/snippets"
157 (when yas--load-file-name
158 (concat (file-name-directory yas--load-file-name) "snippets"))))
159 "Directory or list of snippet dirs for each major mode.
161 The directory where user-created snippets are to be stored. Can
162 also be a list of directories. In that case, when used for
163 bulk (re)loading of snippets (at startup or via
164 `yas-reload-all'), directories appearing earlier in the list
165 shadow other dir's snippets. Also, the first directory is taken
166 as the default for storing the user's new snippets."
167 :type '(choice (string :tag "Single directory (string)")
168 (repeat :args (string) :tag "List of directories (strings)"))
171 :set #'(lambda (symbol new)
172 (let ((old (and (boundp symbol)
173 (symbol-value symbol))))
174 (set-default symbol new)
175 (unless (or (not (fboundp 'yas-reload-all))
179 (defun yas-snippet-dirs ()
180 "Returns `yas-snippet-dirs' (which see) as a list."
181 (if (listp yas-snippet-dirs) yas-snippet-dirs (list yas-snippet-dirs)))
183 (defvaralias 'yas/root-directory 'yas-snippet-dirs)
185 (defcustom yas-prompt-functions '(yas-x-prompt
187 yas-completing-prompt
190 "Functions to prompt for keys, templates, etc interactively.
192 These functions are called with the following arguments:
194 - PROMPT: A string to prompt the user
196 - CHOICES: a list of strings or objects.
198 - optional DISPLAY-FN : A function that, when applied to each of
199 the objects in CHOICES will return a string.
201 The return value of any function you put here should be one of
202 the objects in CHOICES, properly formatted with DISPLAY-FN (if
205 - To signal that your particular style of prompting is
206 unavailable at the moment, you can also have the function return
209 - To signal that the user quit the prompting process, you can
212 (signal 'quit \"user quit!\")."
213 :type '(repeat function)
216 (defcustom yas-indent-line 'auto
217 "Controls indenting applied to a recent snippet expansion.
219 The following values are possible:
221 - `fixed' Indent the snippet to the current column;
223 - `auto' Indent each line of the snippet with `indent-according-to-mode'
225 Every other value means don't apply any snippet-side indendation
226 after expansion (the manual per-line \"$>\" indentation still
228 :type '(choice (const :tag "Nothing" nothing)
229 (const :tag "Fixed" fixed)
230 (const :tag "Auto" auto))
233 (defcustom yas-also-auto-indent-first-line nil
234 "Non-nil means also auto indent first line according to mode.
236 Naturally this is only valid when `yas-indent-line' is `auto'"
240 (defcustom yas-snippet-revival t
241 "Non-nil means re-activate snippet fields after undo/redo."
245 (defcustom yas-trigger-key "<tab>"
246 "The key bound to `yas-expand' when `yas-minor-mode' is active.
248 Value is a string that is converted to the internal Emacs key
249 representation using `read-kbd-macro'."
252 :set #'(lambda (symbol key)
253 (let ((old (and (boundp symbol)
254 (symbol-value symbol))))
255 (set-default symbol key)
256 ;; On very first loading of this defcustom,
257 ;; `yas-trigger-key' is *not* loaded.
258 (if (fboundp 'yas--trigger-key-reload)
259 (yas--trigger-key-reload old)))))
261 (defcustom yas-next-field-key '("TAB" "<tab>")
262 "The key to navigate to next field when a snippet is active.
264 Value is a string that is converted to the internal Emacs key
265 representation using `read-kbd-macro'.
267 Can also be a list of strings."
268 :type '(choice (string :tag "String")
269 (repeat :args (string) :tag "List of strings"))
271 :set #'(lambda (symbol val)
272 (set-default symbol val)
273 (if (fboundp 'yas--init-yas-in-snippet-keymap)
274 (yas--init-yas-in-snippet-keymap))))
277 (defcustom yas-prev-field-key '("<backtab>" "<S-tab>")
278 "The key to navigate to previous field when a snippet is active.
280 Value is a string that is converted to the internal Emacs key
281 representation using `read-kbd-macro'.
283 Can also be a list of strings."
284 :type '(choice (string :tag "String")
285 (repeat :args (string) :tag "List of strings"))
287 :set #'(lambda (symbol val)
288 (set-default symbol val)
289 (if (fboundp 'yas--init-yas-in-snippet-keymap)
290 (yas--init-yas-in-snippet-keymap))))
292 (defcustom yas-skip-and-clear-key '("C-d" "<delete>" "<deletechar>")
293 "The key to clear the currently active field.
295 Value is a string that is converted to the internal Emacs key
296 representation using `read-kbd-macro'.
298 Can also be a list of strings."
299 :type '(choice (string :tag "String")
300 (repeat :args (string) :tag "List of strings"))
302 :set #'(lambda (symbol val)
303 (set-default symbol val)
304 (if (fboundp 'yas--init-yas-in-snippet-keymap)
305 (yas--init-yas-in-snippet-keymap))))
307 (defcustom yas-triggers-in-field nil
308 "If non-nil, `yas-next-field-key' can trigger stacked expansions.
310 Otherwise, `yas-next-field-key' just tries to move on to the next
315 (defcustom yas-fallback-behavior 'call-other-command
316 "How to act when `yas-trigger-key' does *not* expand a snippet.
318 - `call-other-command' means try to temporarily disable YASnippet
319 and call the next command bound to `yas-trigger-key'.
321 - nil or the symbol `return-nil' mean do nothing. (and
322 `yas-expand' returns nil)
324 - A lisp form (apply COMMAND . ARGS) means interactively call
325 COMMAND, if ARGS is non-nil, call COMMAND non-interactively
326 with ARGS as arguments."
327 :type '(choice (const :tag "Call previous command" call-other-command)
328 (const :tag "Do nothing" return-nil))
331 (defcustom yas-choose-keys-first nil
332 "If non-nil, prompt for snippet key first, then for template.
334 Otherwise prompts for all possible snippet names.
336 This affects `yas-insert-snippet' and `yas-visit-snippet-file'."
340 (defcustom yas-choose-tables-first nil
341 "If non-nil, and multiple eligible snippet tables, prompts user for tables first.
343 Otherwise, user chooses between the merging together of all
346 This affects `yas-insert-snippet', `yas-visit-snippet-file'"
350 (defcustom yas-use-menu 'abbreviate
351 "Display a YASnippet menu in the menu bar.
353 When non-nil, submenus for each snippet table will be listed
354 under the menu \"Yasnippet\".
356 - If set to `abbreviate', only the current major-mode
357 menu and the modes set in `yas-extra-modes' are listed.
359 - If set to `full', every submenu is listed
361 - It set to nil, don't display a menu at all (this requires a
362 `yas-reload-all' call if the menu is already visible).
364 Any other non-nil value, every submenu is listed."
365 :type '(choice (const :tag "Full" full)
366 (const :tag "Abbreviate" abbreviate)
367 (const :tag "No menu" nil))
370 (defcustom yas-trigger-symbol (if (eq window-system 'mac)
371 (char-to-string ?\x21E5) ;; little ->| sign
373 "The text that will be used in menu to represent the trigger."
377 (defcustom yas-wrap-around-region nil
378 "If non-nil, snippet expansion wraps around selected region.
380 The wrapping occurs just before the snippet's exit marker. This
381 can be overriden on a per-snippet basis."
385 (defcustom yas-good-grace t
386 "If non-nil, don't raise errors in inline elisp evaluation.
388 An error string \"[yas] error\" is returned instead."
392 (defcustom yas-visit-from-menu nil
393 "If non-nil visit snippets's files from menu, instead of expanding them.
395 This cafn only work when snippets are loaded from files."
399 (defcustom yas-expand-only-for-last-commands nil
400 "List of `last-command' values to restrict tab-triggering to, or nil.
402 Leave this set at nil (the default) to be able to trigger an
403 expansion simply by placing the cursor after a valid tab trigger,
404 using whichever commands.
406 Optionallly, set this to something like '(self-insert-command) if
407 you to wish restrict expansion to only happen when the last
408 letter of the snippet tab trigger was typed immediately before
409 the trigger key itself."
410 :type '(repeat function)
413 ;; Only two faces, and one of them shouldn't even be used...
415 (defface yas-field-highlight-face
416 '((t (:inherit 'region)))
417 "The face used to highlight the currently active field of a snippet"
420 (defface yas--field-debug-face
422 "The face used for debugging some overlays normally hidden"
426 ;;; User can also customize the next defvars
428 (defun yas--define-some-keys (keys keymap definition)
429 "Bind KEYS to DEFINITION in KEYMAP, read with `read-kbd-macro'."
430 (let ((keys (or (and (listp keys) keys)
433 (define-key keymap (read-kbd-macro key) definition))))
435 (defun yas--init-yas-in-snippet-keymap ()
437 (let ((map (make-sparse-keymap)))
438 (mapc #'(lambda (binding)
439 (yas--define-some-keys (car binding) map (cdr binding)))
440 `((,yas-next-field-key . yas-next-field-or-maybe-expand)
441 (,yas-prev-field-key . yas-prev-field)
442 ("C-g" . yas-abort-snippet)
443 (,yas-skip-and-clear-key . yas-skip-and-clear-or-delete-char)))
446 (defvar yas-keymap (yas--init-yas-in-snippet-keymap)
447 "The keymap active while a snippet expansion is in progress.")
449 (defvar yas-key-syntaxes (list "w" "w_" "w_." "w_.()" "^ ")
450 "List of character syntaxes used to find a trigger key before point.
451 The list is tried in the order while scanning characters
452 backwards from point. For example, if the list is '(\"w\" \"w_\")
453 first look for trigger keys which are composed exclusively of
454 \"word\"-syntax characters, and then, if that fails, look for
455 keys which are either of \"word\" or \"symbol\"
456 syntax. Triggering after
460 will, according to the \"w\" element first try \"bar\". If that
461 isn't a trigger key, \"foo-bar\" is tried, respecting a second
464 (defvar yas-after-exit-snippet-hook
466 "Hooks to run after a snippet exited.
468 The hooks will be run in an environment where some variables bound to
471 `yas-snippet-beg' : The beginning of the region of the snippet.
473 `yas-snippet-end' : Similar to beg.
475 Attention: These hooks are not run when exiting nested/stackd snippet expansion!")
477 (defvar yas-before-expand-snippet-hook
479 "Hooks to run just before expanding a snippet.")
481 (defvar yas-buffer-local-condition
482 '(if (and (or (fourth (syntax-ppss))
483 (fifth (syntax-ppss)))
484 (eq (symbol-function this-command) 'yas-expand-from-trigger-key))
485 '(require-snippet-condition . force-in-comment)
487 "Snippet expanding condition.
489 This variable is a lisp form which is evaluated everytime a
490 snippet expansion is attemped:
492 * If it evaluates to nil, no snippets can be expanded.
494 * If it evaluates to the a cons (require-snippet-condition
497 * Snippets bearing no \"# condition:\" directive are not
500 * Snippets bearing conditions that evaluate to nil (or
501 produce an error) won't be onsidered.
503 * If the snippet has a condition that evaluates to non-nil
506 * If REQUIREMENT is t, the snippet is considered
508 * If REQUIREMENT is `eq' RESULT, the snippet is
511 * Otherwise, the snippet is not considered.
513 * If it evaluates to the symbol 'always, all snippets are
514 considered for expansion, regardless of any conditions.
516 * If it evaluates to t or some other non-nil value
518 * Snippet bearing no conditions, or conditions that
519 evaluate to non-nil, are considered for expansion.
521 * Otherwise, the snippet is not considered.
523 Here's an example preventing snippets from being expanded from
524 inside comments, in `python-mode' only, with the exception of
525 snippets returning the symbol 'force-in-comment in their
528 (add-hook 'python-mode-hook
530 (setq yas-buffer-local-condition
531 '(if (python-in-string/comment)
532 '(require-snippet-condition . force-in-comment)
535 The default value is similar, it filters out potential snippet
536 expansions inside comments and string literals, unless the
537 snippet itself contains a condition that returns the symbol
538 `force-in-comment'.")
541 ;;; Internal variables
543 (defvar yas--version "0.8.0 (beta)")
545 (defvar yas--menu-table (make-hash-table)
546 "A hash table of MAJOR-MODE symbols to menu keymaps.")
548 (defvar yas--known-modes
549 '(ruby-mode rst-mode markdown-mode)
550 "A list of mode which is well known but not part of emacs.")
552 (defvar yas--escaped-characters
553 '(?\\ ?` ?\" ?' ?$ ?} ?{ ?\( ?\))
554 "List of characters which *might* need to be escaped.")
556 (defconst yas--field-regexp
557 "${\\([0-9]+:\\)?\\([^}]*\\)}"
558 "A regexp to *almost* recognize a field.")
560 (defconst yas--multi-dollar-lisp-expression-regexp
561 "$+[ \t\n]*\\(([^)]*)\\)"
562 "A regexp to *almost* recognize a \"$(...)\" expression.")
564 (defconst yas--backquote-lisp-expression-regexp
566 "A regexp to recognize a \"`lisp-expression`\" expression." )
568 (defconst yas--transform-mirror-regexp
569 "${\\(?:\\([0-9]+\\):\\)?$\\([ \t\n]*([^}]*\\)"
570 "A regexp to *almost* recognize a mirror with a transform.")
572 (defconst yas--simple-mirror-regexp
574 "A regexp to recognize a simple mirror.")
576 (defvar yas--snippet-id-seed 0
577 "Contains the next id for a snippet.")
579 (defun yas--snippet-next-id ()
580 (let ((id yas--snippet-id-seed))
581 (incf yas--snippet-id-seed)
587 ;; XXX: `last-buffer-undo-list' is somehow needed in Carbon Emacs for MacOSX
588 (defvar last-buffer-undo-list nil)
590 (defvar yas--minor-mode-menu nil
591 "Holds the YASnippet menu")
593 (defun yas--init-minor-keymap ()
594 (let ((map (make-sparse-keymap)))
596 (easy-menu-define yas--minor-mode-menu
598 "Menu used when `yas-minor-mode' is active."
601 ["Expand trigger" yas-expand
602 :help "Possibly expand tab trigger before point"]
603 ["Insert at point..." yas-insert-snippet
604 :help "Prompt for an expandable snippet and expand it at point"]
605 ["New snippet..." yas-new-snippet
606 :help "Create a new snippet in an appropriate directory"]
607 ["Visit snippet file..." yas-visit-snippet-file
608 :help "Prompt for an expandable snippet and find its file"]
610 ("Snippet menu behaviour"
611 ["Visit snippets" (setq yas-visit-from-menu t)
612 :help "Visit snippets from the menu"
613 :active t :style radio :selected yas-visit-from-menu]
614 ["Expand snippets" (setq yas-visit-from-menu nil)
615 :help "Expand snippets from the menu"
616 :active t :style radio :selected (not yas-visit-from-menu)]
618 ["Show all known modes" (setq yas-use-menu 'full)
619 :help "Show one snippet submenu for each loaded table"
620 :active t :style radio :selected (eq yas-use-menu 'full)]
621 ["Abbreviate according to current mode" (setq yas-use-menu 'abbreviate)
622 :help "Show only snippet submenus for the current active modes"
623 :active t :style radio :selected (eq yas-use-menu 'abbreviate)])
625 ["Auto" (setq yas-indent-line 'auto)
626 :help "Indent each line of the snippet with `indent-according-to-mode'"
627 :active t :style radio :selected (eq yas-indent-line 'auto)]
628 ["Fixed" (setq yas-indent-line 'fixed)
629 :help "Indent the snippet to the current column"
630 :active t :style radio :selected (eq yas-indent-line 'fixed)]
631 ["None" (setq yas-indent-line 'none)
632 :help "Don't apply any particular snippet indentation after expansion"
633 :active t :style radio :selected (not (member yas-indent-line '(fixed auto)))]
635 ["Also auto indent first line" (setq yas-also-auto-indent-first-line
636 (not yas-also-auto-indent-first-line))
637 :help "When auto-indenting also, auto indent the first line menu"
638 :active (eq yas-indent-line 'auto)
639 :style toggle :selected yas-also-auto-indent-first-line]
642 ["System X-widget" (setq yas-prompt-functions
644 (remove 'yas-x-prompt
645 yas-prompt-functions)))
646 :help "Use your windowing system's (gtk, mac, windows, etc...) default menu"
647 :active t :style radio :selected (eq (car yas-prompt-functions)
649 ["Dropdown-list" (setq yas-prompt-functions
650 (cons 'yas-dropdown-prompt
651 (remove 'yas-dropdown-prompt
652 yas-prompt-functions)))
653 :help "Use a special dropdown list"
654 :active t :style radio :selected (eq (car yas-prompt-functions)
655 'yas-dropdown-prompt)]
656 ["Ido" (setq yas-prompt-functions
657 (cons 'yas-ido-prompt
658 (remove 'yas-ido-prompt
659 yas-prompt-functions)))
660 :help "Use an ido-style minibuffer prompt"
661 :active t :style radio :selected (eq (car yas-prompt-functions)
663 ["Completing read" (setq yas-prompt-functions
664 (cons 'yas-completing-prompt
665 (remove 'yas-completing-prompt
666 yas-prompt-functions)))
667 :help "Use a normal minibuffer prompt"
668 :active t :style radio :selected (eq (car yas-prompt-functions)
669 'yas-completing-prompt)]
672 ["Wrap region in exit marker"
673 (setq yas-wrap-around-region
674 (not yas-wrap-around-region))
675 :help "If non-nil automatically wrap the selected text in the $0 snippet exit"
676 :style toggle :selected yas-wrap-around-region]
677 ["Allow stacked expansions "
678 (setq yas-triggers-in-field
679 (not yas-triggers-in-field))
680 :help "If non-nil allow snippets to be triggered inside other snippet fields"
681 :style toggle :selected yas-triggers-in-field]
682 ["Revive snippets on undo "
683 (setq yas-snippet-revival
684 (not yas-snippet-revival))
685 :help "If non-nil allow snippets to become active again after undo"
686 :style toggle :selected yas-snippet-revival]
689 (not yas-good-grace))
690 :help "If non-nil don't raise errors in bad embedded eslip in snippets"
691 :style toggle :selected yas-good-grace]
694 ["Load snippets..." yas-load-directory
695 :help "Load snippets from a specific directory"]
696 ["Reload everything" yas-reload-all
697 :help "Cleanup stuff, reload snippets, rebuild menus"]
699 :help "Display some information about YASsnippet"])))
701 ;; Now for the stuff that has direct keybindings
703 (define-key map "\C-c&\C-s" 'yas-insert-snippet)
704 (define-key map "\C-c&\C-n" 'yas-new-snippet)
705 (define-key map "\C-c&\C-v" 'yas-visit-snippet-file)
708 (defvar yas-minor-mode-map (yas--init-minor-keymap)
709 "The keymap used when `yas-minor-mode' is active.")
711 (defun yas--trigger-key-reload (&optional unbind-key)
712 "Rebind `yas-expand' to the new value of `yas-trigger-key'.
714 With optional UNBIND-KEY, try to unbind that key from
715 `yas-minor-mode-map'."
716 (when (and unbind-key
718 (not (string= unbind-key "")))
719 (define-key yas-minor-mode-map (read-kbd-macro unbind-key) nil))
720 (when (and yas-trigger-key
721 (stringp yas-trigger-key)
722 (not (string= yas-trigger-key "")))
723 (define-key yas-minor-mode-map (read-kbd-macro yas-trigger-key) 'yas-expand)))
725 (defvar yas--tables (make-hash-table)
726 "A hash table of mode symbols to `yas--table' objects.")
728 (defvar yas--parents (make-hash-table)
729 "A hash table of mode symbols do lists of direct parent mode symbols.
731 This list is populated when reading the \".yas-parents\" files
732 found when traversing snippet directories with
733 `yas-load-directory'.
735 There might be additionalal parenting information stored in the
736 `derived-mode-parent' property of some mode symbols, but that is
739 (defvar yas--direct-keymaps (list)
740 "Keymap alist supporting direct snippet keybindings.
742 This variable is is placed in `emulation-mode-map-alists'.
744 Its elements looks like (TABLE-NAME . KEYMAP). They're
745 instantiated on `yas-reload-all' but KEYMAP is added to only when
746 loading snippets. `yas--direct-TABLE-NAME' is then a variable set
747 buffer-locally when entering `yas-minor-mode'. KEYMAP binds all
748 defined direct keybindings to the command
749 `yas-expand-from-keymap' which then which snippet to expand.")
751 (defun yas-direct-keymaps-reload ()
752 "Force reload the direct keybinding for active snippet tables."
754 (setq yas--direct-keymaps nil)
755 (maphash #'(lambda (name table)
756 (push (cons (intern (format "yas--direct-%s" name))
757 (yas--table-direct-keymap table))
758 yas--direct-keymaps))
761 (defun yas--modes-to-activate ()
762 "Compute list of mode symbols that are active for `yas-expand'
764 (let ((modes-to-activate (list major-mode))
766 (while (setq mode (get mode 'derived-mode-parent))
767 (push mode modes-to-activate))
768 (dolist (mode (yas-extra-modes))
769 (push mode modes-to-activate))
771 (append modes-to-activate
772 (mapcan #'(lambda (mode)
773 (yas--all-parents mode))
774 modes-to-activate)))))
776 (defvar yas-minor-mode-hook nil
777 "Hook run when yas-minor-mode is turned on")
780 (define-minor-mode yas-minor-mode
781 "Toggle YASnippet mode.
783 When YASnippet mode is enabled, the `yas-trigger-key' key expands
784 snippets of code depending on the major mode.
786 With no argument, this command toggles the mode.
787 positive prefix argument turns on the mode.
788 Negative prefix argument turns off the mode.
790 You can customize the key through `yas-trigger-key'.
793 \\{yas-minor-mode-map}"
795 ;; The indicator for the mode line.
798 (cond (yas-minor-mode
799 ;; Reload the trigger key
801 (yas--trigger-key-reload)
802 ;; Install the direct keymaps in `emulation-mode-map-alists'
803 ;; (we use `add-hook' even though it's not technically a hook,
804 ;; but it works). Then define variables named after modes to
805 ;; index `yas--direct-keymaps'.
807 ;; Also install the post-command-hook.
809 (add-hook 'emulation-mode-map-alists 'yas--direct-keymaps)
810 (add-hook 'post-command-hook 'yas--post-command-handler nil t)
811 ;; Set the `yas--direct-%s' vars for direct keymap expansion
813 (dolist (mode (yas--modes-to-activate))
814 (let ((name (intern (format "yas--direct-%s" mode))))
815 (set-default name nil)
816 (set (make-local-variable name) t)))
819 (yas--load-pending-jits))
821 ;; Uninstall the direct keymaps and the post-command hook
823 (remove-hook 'post-command-hook 'yas--post-command-handler t)
824 (remove-hook 'emulation-mode-map-alists 'yas--direct-keymaps))))
826 (defvar yas--dont-activate '(minibufferp)
827 "If non-nil don't let `yas-minor-mode-on' active yas for this buffer.
829 If a function, then its result is used.
831 If a list of functions, then all functions must return nil to
832 activate yas for this buffer.
834 `yas-minor-mode-on' is usually called by `yas-global-mode' so
835 this effectively lets you define exceptions to the \"global\"
836 behaviour. Can also be a function of zero arguments.")
837 (make-variable-buffer-local 'yas--dont-activate)
839 (defun yas-minor-mode-on ()
840 "Turn on YASnippet minor mode.
842 Do this unless `yas--dont-activate' is truish "
844 (unless (cond ((functionp yas--dont-activate)
845 (funcall yas--dont-activate))
846 ((consp yas--dont-activate)
847 (some #'funcall yas--dont-activate))
848 (yas--dont-activate))
849 ;; Load all snippets definitions unless we still don't have a
850 ;; root-directory or some snippets have already been loaded.
855 (define-globalized-minor-mode yas-global-mode yas-minor-mode yas-minor-mode-on
859 (defun yas--global-mode-reload-with-jit-maybe ()
860 (when yas-global-mode (yas-reload-all)))
862 (add-hook 'yas-global-mode-hook 'yas--global-mode-reload-with-jit-maybe)
864 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
867 (defvar yas--font-lock-keywords
868 (append '(("^#.*$" . font-lock-comment-face))
869 lisp-font-lock-keywords
870 lisp-font-lock-keywords-1
871 lisp-font-lock-keywords-2
873 (0 font-lock-keyword-face)
874 (1 font-lock-string-face t))
876 (0 font-lock-keyword-face)
877 (1 font-lock-warning-face t))
878 ("${" font-lock-keyword-face)
879 ("$[0-9]+?" font-lock-preprocessor-face)
880 ("\\(\\$(\\)" 1 font-lock-preprocessor-face)
882 (0 font-lock-keyword-face)))))
884 (defun yas--init-major-keymap ()
885 (let ((map (make-sparse-keymap)))
886 (easy-menu-define nil
888 "Menu used when snippet-mode is active."
890 (mapcar #'(lambda (ent)
892 (define-key map (third ent) (second ent)))
893 (vector (first ent) (second ent) t))
895 (list "Load this snippet" 'yas-load-snippet-buffer "\C-c\C-c")
896 (list "Try out this snippet" 'yas-tryout-snippet "\C-c\C-t")))))
899 (defvar snippet-mode-map
900 (yas--init-major-keymap)
901 "The keymap used when `snippet-mode' is active")
904 (define-derived-mode snippet-mode text-mode "Snippet"
905 "A mode for editing yasnippets"
906 (setq font-lock-defaults '(yas--font-lock-keywords))
907 (set (make-local-variable 'require-final-newline) nil)
908 (set (make-local-variable 'comment-start) "#")
909 (set (make-local-variable 'comment-start-skip) "#+[\t ]*"))
913 ;;; Internal structs for template management
915 (defstruct (yas--template (:constructor yas--make-blank-template))
916 "A template for a snippet."
926 group ;; as dictated by the #group: directive or .yas-make-groups
927 perm-group ;; as dictated by `yas-define-menu'
931 (defun yas--populate-template (template &rest args)
932 "Helper function to populate a template with properties"
936 (position (intern (substring (symbol-name (car args)) 1))
937 (mapcar #'car (get 'yas--template 'cl-struct-slots)))
939 (setq args (cddr args)))
942 (defstruct (yas--table (:constructor yas--make-snippet-table (name)))
943 "A table to store snippets for a particular mode.
945 Has the following fields:
949 A symbol name normally corresponding to a major mode, but can
950 also be a pseudo major-mode to be referenced in
951 `yas-extra-modes', for example.
955 A hash table (KEY . NAMEHASH), known as the \"keyhash\". KEY is
956 a string or a vector, where the former is the snippet's trigger
957 and the latter means it's a direct keybinding. NAMEHASH is yet
958 another hash of (NAME . TEMPLATE) where NAME is the snippet's
959 name and TEMPLATE is a `yas--template' object.
961 `yas--table-direct-keymap'
963 A keymap for the snippets in this table that have direct
964 keybindings. This is kept in sync with the keyhash, i.e., all
965 the elements of the keyhash that are vectors appear here as
966 bindings to `yas-expand-from-keymap'.
968 `yas--table-uuidhash'
970 A hash table mapping snippets uuid's to the same `yas--template'
971 objects. A snippet uuid defaults to the snippet's name.
974 (hash (make-hash-table :test 'equal))
975 (uuidhash (make-hash-table :test 'equal))
977 (direct-keymap (make-sparse-keymap)))
979 (defun yas--get-template-by-uuid (mode uuid)
980 "Find the snippet template in MODE by its UUID."
981 (let* ((table (gethash mode yas--tables mode)))
983 (gethash uuid (yas--table-uuidhash table)))))
985 ;; Apropos storing/updating in TABLE, this works in two steps:
987 ;; 1. `yas--remove-template-by-uuid' removes any
988 ;; keyhash-namehash-template mappings from TABLE, grabing the
989 ;; snippet by its uuid. Also removes mappings from TABLE's
990 ;; `yas--table-direct-keymap' (FIXME: and should probably take care
991 ;; of potentially stale menu bindings right?.)
993 ;; 2. `yas--add-template' adds this all over again.
995 ;; Create a new or add to an existing keyhash-namehash mapping.
997 ;; For reference on understanding this, consider three snippet
1000 ;; A: # name: The Foo
1002 ;; # binding: C-c M-l
1004 ;; B: # name: Mrs Foo
1007 ;; C: # name: The Bar
1008 ;; # binding: C-c M-l
1013 ;; keyhash namehashes(3) yas--template structs(4)
1014 ;; -----------------------------------------------------
1017 ;; "foo" ---> "The Foo" ---> [yas--template A] |
1018 ;; "Mrs Foo" ---> [yas--template B] |
1020 ;; [C-c M-l] ---> "The Foo" -------------------------/
1021 ;; "The Bar" ---> [yas--template C]
1023 ;; "baz" ---> "Baz" ---> [yas--template D]
1025 ;; Additionally, since uuid defaults to the name, we have a
1026 ;; `yas--table-uuidhash' for TABLE
1028 ;; uuidhash yas--template structs
1029 ;; -------------------------------
1030 ;; "The Foo" ---> [yas--template A]
1031 ;; "Mrs Foo" ---> [yas--template B]
1032 ;; "The Bar" ---> [yas--template C]
1033 ;; "Baz" ---> [yas--template D]
1035 ;; FIXME: the more I look at this data-structure the more I think I'm
1036 ;; stupid. There has to be an easier way (but beware lots of code
1037 ;; depends on this).
1039 (defun yas--remove-template-by-uuid (table uuid)
1040 "Remove from TABLE a template identified by UUID."
1041 (let ((template (gethash uuid (yas--table-uuidhash table))))
1043 (let* ((name (yas--template-name template))
1045 ;; Remove the name from each of the targeted namehashes
1047 (maphash #'(lambda (k v)
1048 (let ((template (gethash name v)))
1050 (eq uuid (yas--template-uuid template)))
1052 (when (zerop (hash-table-count v))
1053 (push k empty-keys)))))
1054 (yas--table-hash table))
1055 ;; Remove the namehash themselves if they've become empty
1057 (dolist (key empty-keys)
1059 (define-key (yas--table-direct-keymap table) key nil))
1060 (remhash key (yas--table-hash table)))
1062 ;; Finally, remove the uuid from the uuidhash
1064 (remhash uuid (yas--table-uuidhash table))))))
1066 (defun yas--add-template (table template)
1067 "Store in TABLE the snippet template TEMPLATE.
1069 KEY can be a string (trigger key) of a vector (direct
1071 (let ((name (yas--template-name template))
1072 (key (yas--template-key template))
1073 (keybinding (yas--template-keybinding template))
1074 (menu-binding-pair (yas--template-menu-binding-pair-get-create template)))
1075 (dolist (k (remove nil (list key keybinding)))
1079 (yas--table-hash table))
1081 (make-hash-table :test 'equal)
1082 (yas--table-hash table))))
1084 (define-key (yas--table-direct-keymap table) k 'yas-expand-from-keymap)))
1086 ;; Update TABLE's `yas--table-uuidhash'
1087 (puthash (yas--template-uuid template)
1089 (yas--table-uuidhash table))))
1091 (defun yas--update-template (table template)
1092 "Add or update TEMPLATE in TABLE.
1094 Also takes care of adding and updating to the associated menu."
1095 ;; Remove from table by uuid
1097 (yas--remove-template-by-uuid table (yas--template-uuid template))
1098 ;; Add to table again
1100 (yas--add-template table template)
1101 ;; Take care of the menu
1104 (yas--update-template-menu table template)))
1106 (defun yas--update-template-menu (table template)
1107 "Update every menu-related for TEMPLATE"
1108 (let ((menu-binding-pair (yas--template-menu-binding-pair-get-create template))
1109 (key (yas--template-key template))
1110 (keybinding (yas--template-keybinding template)))
1111 ;; The snippet might have changed name or keys, so update
1112 ;; user-visible strings
1114 (unless (eq (cdr menu-binding-pair) :none)
1115 ;; the menu item name
1117 (setf (cadar menu-binding-pair) (yas--template-name template))
1118 ;; the :keys information (also visible to the user)
1119 (setf (getf (cdr (car menu-binding-pair)) :keys)
1120 (or (and keybinding (key-description keybinding))
1121 (and key (concat key yas-trigger-symbol))))))
1122 (unless (yas--template-menu-managed-by-yas-define-menu template)
1124 (yas--menu-keymap-get-create (yas--table-mode table)
1125 (mapcar #'yas--table-mode
1126 (yas--table-parents table))))
1127 (group (yas--template-group template)))
1128 ;; Remove from menu keymap
1130 (assert menu-keymap)
1131 (yas--delete-from-keymap menu-keymap (yas--template-uuid template))
1133 ;; Add necessary subgroups as necessary.
1135 (dolist (subgroup group)
1136 (let ((subgroup-keymap (lookup-key menu-keymap (vector (make-symbol subgroup)))))
1137 (unless (and subgroup-keymap
1138 (keymapp subgroup-keymap))
1139 (setq subgroup-keymap (make-sparse-keymap))
1140 (define-key menu-keymap (vector (make-symbol subgroup))
1141 `(menu-item ,subgroup ,subgroup-keymap)))
1142 (setq menu-keymap subgroup-keymap)))
1144 ;; Add this entry to the keymap
1146 (define-key menu-keymap
1147 (vector (make-symbol (yas--template-uuid template)))
1148 (car (yas--template-menu-binding-pair template))))))
1150 (defun yas--namehash-templates-alist (namehash)
1152 (maphash #'(lambda (k v)
1153 (push (cons k v) alist))
1157 (defun yas--fetch (table key)
1158 "Fetch templates in TABLE by KEY.
1160 Return a list of cons (NAME . TEMPLATE) where NAME is a
1161 string and TEMPLATE is a `yas--template' structure."
1162 (let* ((keyhash (yas--table-hash table))
1163 (namehash (and keyhash (gethash key keyhash))))
1165 (yas--filter-templates-by-condition (yas--namehash-templates-alist namehash)))))
1168 ;;; Filtering/condition logic
1170 (defun yas--eval-condition (condition)
1177 (yas--message 1 "Error in condition evaluation: %s" (error-message-string err))
1181 (defun yas--filter-templates-by-condition (templates)
1182 "Filter the templates using the applicable condition.
1184 TEMPLATES is a list of cons (NAME . TEMPLATE) where NAME is a
1185 string and TEMPLATE is a `yas--template' structure.
1187 This function implements the rules described in
1188 `yas-buffer-local-condition'. See that variables documentation."
1189 (let ((requirement (yas--require-template-specific-condition-p)))
1190 (if (eq requirement 'always)
1192 (remove-if-not #'(lambda (pair)
1193 (yas--template-can-expand-p
1194 (yas--template-condition (cdr pair)) requirement))
1197 (defun yas--require-template-specific-condition-p ()
1198 "Decides if this buffer requests/requires snippet-specific
1199 conditions to filter out potential expansions."
1200 (if (eq 'always yas-buffer-local-condition)
1202 (let ((local-condition (or (and (consp yas-buffer-local-condition)
1203 (yas--eval-condition yas-buffer-local-condition))
1204 yas-buffer-local-condition)))
1205 (when local-condition
1206 (if (eq local-condition t)
1208 (and (consp local-condition)
1209 (eq 'require-snippet-condition (car local-condition))
1210 (symbolp (cdr local-condition))
1211 (cdr local-condition)))))))
1213 (defun yas--template-can-expand-p (condition requirement)
1214 "Evaluates CONDITION and REQUIREMENT and returns a boolean"
1215 (let* ((result (or (null condition)
1216 (yas--eval-condition condition))))
1217 (cond ((eq requirement t)
1220 (eq requirement result)))))
1222 (defun yas--all-parents (mode)
1223 "Returns a list of all parent modes of MODE"
1224 (let ((parents (gethash mode yas--parents)))
1226 (mapcan #'yas--all-parents parents))))
1228 (defun yas--table-templates (table)
1231 (maphash #'(lambda (key namehash)
1232 (maphash #'(lambda (name template)
1233 (push (cons name template) acc))
1235 (yas--table-hash table))
1236 (yas--filter-templates-by-condition acc))))
1238 (defun yas--current-key ()
1239 "Get the key under current position. A key is used to find
1240 the template of a snippet in the current snippet-table."
1241 (let ((start (point))
1243 (syntaxes yas-key-syntaxes)
1247 (while (and (not done) syntaxes)
1248 (setq syntax (car syntaxes))
1249 (setq syntaxes (cdr syntaxes))
1251 (skip-syntax-backward syntax)
1252 (setq start (point)))
1254 (mapcan #'(lambda (table)
1255 (yas--fetch table (buffer-substring-no-properties start end)))
1256 (yas--get-snippet-tables)))
1265 (defun yas--table-all-keys (table)
1266 "Get trigger keys of all active snippets in TABLE"
1268 (maphash #'(lambda (key namehash)
1269 (when (yas--filter-templates-by-condition (yas--namehash-templates-alist namehash))
1271 (yas--table-hash table))
1274 (defun yas--table-mode (table)
1275 (intern (yas--table-name table)))
1278 ;;; Internal functions:
1280 (defun yas--real-mode? (mode)
1281 "Try to find out if MODE is a real mode. The MODE bound to
1282 a function (like `c-mode') is considered real mode. Other well
1283 known mode like `ruby-mode' which is not part of Emacs might
1284 not bound to a function until it is loaded. So yasnippet keeps
1285 a list of modes like this to help the judgement."
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'."
1531 (sort templates #'(lambda (t1 t2)
1532 (< (length (yas--template-name t1))
1533 (length (yas--template-name t2))))))
1534 (if yas--x-pretty-prompt-templates
1535 (yas--x-pretty-prompt-templates "Choose a snippet" templates)
1536 (some #'(lambda (fn)
1537 (funcall fn (or prompt "Choose a snippet: ")
1539 #'yas--template-name))
1540 yas-prompt-functions))))
1542 (defun yas--prompt-for-keys (keys &optional prompt)
1543 "Interactively choose a template key from the list KEYS."
1545 (some #'(lambda (fn)
1546 (funcall fn (or prompt "Choose a snippet key: ") keys))
1547 yas-prompt-functions)))
1549 (defun yas--prompt-for-table (tables &optional prompt)
1551 (some #'(lambda (fn)
1552 (funcall fn (or prompt "Choose a snippet table: ")
1555 yas-prompt-functions)))
1557 (defun yas-x-prompt (prompt choices &optional display-fn)
1558 "Display choices in a x-window prompt."
1559 ;; FIXME: HACK: if we notice that one of the objects in choices is
1560 ;; actually a `yas--template', defer to `yas--x-prompt-pretty-templates'
1562 ;; This would be better implemented by passing CHOICES as a
1563 ;; strucutred tree rather than a list. Modifications would go as far
1564 ;; up as `yas--all-templates' I think.
1566 (when (and window-system choices)
1568 (let (menu d) ;; d for display
1570 (setq d (or (and display-fn (funcall display-fn c))
1573 (push (cons (concat " " d) c) menu))
1575 (push (car d) menu))))
1576 (setq menu (list prompt (push "title" menu)))
1577 (x-popup-menu (if (fboundp 'posn-at-point)
1578 (let ((x-y (posn-x-y (posn-at-point (point)))))
1579 (list (list (+ (car x-y) 10)
1587 (defun yas--x-pretty-prompt-templates (prompt templates)
1588 "Display TEMPLATES, grouping neatly by table name."
1589 (let ((organized (make-hash-table :test #'equal))
1593 (dolist (tl templates)
1594 (puthash (yas--template-table tl)
1596 (gethash (yas--template-table tl) organized))
1598 (setq more-than-one-table (> (hash-table-count organized) 1))
1599 (setq prefix (if more-than-one-table
1601 (if more-than-one-table
1602 (maphash #'(lambda (table templates)
1603 (push (yas--table-name table) menu)
1604 (dolist (tl templates)
1605 (push (cons (concat prefix (yas--template-name tl)) tl) menu))) organized)
1606 (setq menu (mapcar #'(lambda (tl) (cons (concat prefix (yas--template-name tl)) tl)) templates)))
1608 (setq menu (nreverse menu))
1609 (or (x-popup-menu (if (fboundp 'posn-at-point)
1610 (let ((x-y (posn-x-y (posn-at-point (point)))))
1611 (list (list (+ (car x-y) 10)
1615 (list prompt (push "title" menu)))
1618 (defun yas-ido-prompt (prompt choices &optional display-fn)
1619 (when (and (fboundp 'ido-completing-read)
1620 (or (>= emacs-major-version 24)
1622 (yas-completing-prompt prompt choices display-fn #'ido-completing-read)))
1624 (eval-when-compile (require 'dropdown-list nil t))
1625 (defun yas-dropdown-prompt (prompt choices &optional display-fn)
1626 (when (featurep 'dropdown-list)
1627 (let (formatted-choices
1631 (dolist (choice choices)
1632 (setq d (or (and display-fn (funcall display-fn choice))
1635 (push d formatted-choices)
1636 (push choice filtered-choices)))
1638 (setq n (and formatted-choices (dropdown-list formatted-choices)))
1640 (nth n filtered-choices)
1643 (defun yas-completing-prompt (prompt choices &optional display-fn completion-fn)
1644 (let (formatted-choices
1648 (completion-fn (or completion-fn
1649 #'completing-read)))
1650 (dolist (choice choices)
1651 (setq d (or (and display-fn (funcall display-fn choice))
1654 (push d formatted-choices)
1655 (push choice filtered-choices)))
1656 (setq chosen (and formatted-choices
1657 (funcall completion-fn prompt
1663 (let ((position (or (and chosen
1664 (position chosen formatted-choices :test #'string=))
1666 (nth position filtered-choices))))
1668 (defun yas-no-prompt (prompt choices &optional display-fn)
1671 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1672 ;; Loading snippets from files
1674 (defun yas--load-yas-setup-file (file)
1675 (load file 'noerror))
1677 (defun yas-load-directory (top-level-dir &optional use-jit)
1678 "Load snippets in directory hierarchy TOP-LEVEL-DIR.
1680 Below TOP-LEVEL-DIR each directory should be a mode name.
1682 Optional USE-JIT use jit-loading of snippets."
1683 (interactive "DSelect the root directory: ")
1684 (unless yas-snippet-dirs
1685 (setq yas-snippet-dirs top-level-dir))
1686 (dolist (dir (yas--subdirs top-level-dir))
1687 (let* ((major-mode-and-parents (yas--compute-major-mode-and-parents
1688 (concat dir "/dummy")))
1689 (mode-sym (car major-mode-and-parents))
1690 (parents (cdr major-mode-and-parents)))
1691 ;; Attention: The parents and the menus are already defined
1692 ;; here, even if the snippets are later jit-loaded.
1694 ;; * We need to know the parents at this point since entering a
1695 ;; given mode should jit load for its parents
1696 ;; immediately. This could be reviewed, the parents could be
1697 ;; discovered just-in-time-as well
1699 ;; * We need to create the menus here to support the `full'
1700 ;; option to `yas-use-menu' (all known snippet menus are shown to the user)
1702 (yas--define-parents mode-sym parents)
1703 (yas--menu-keymap-get-create mode-sym)
1704 (let ((form `(yas--load-directory-1 ,dir
1708 (yas--schedule-jit mode-sym form)
1710 (when (interactive-p)
1711 (yas--message 3 "Loaded snippets from %s." top-level-dir)))
1713 (defun yas--load-directory-1 (directory mode-sym parents &optional no-compiled-snippets)
1714 "Recursively load snippet templates from DIRECTORY."
1715 (unless (file-exists-p (concat directory "/" ".yas-skip"))
1716 (if (and (not no-compiled-snippets)
1717 (progn (yas--message 2 "Loading compiled snippets from %s" directory) t)
1718 (load (expand-file-name ".yas-compiled-snippets" directory) 'noerror (<= yas-verbosity 3)))
1719 (yas--message 2 "Loading snippet files from %s" directory)
1720 (yas--load-directory-2 directory mode-sym))))
1722 (defun yas--load-directory-2 (directory mode-sym)
1723 ;; Load .yas-setup.el files wherever we find them
1725 (yas--load-yas-setup-file (expand-file-name ".yas-setup" directory))
1726 (let* ((default-directory directory)
1728 ;; load the snippet files
1731 (dolist (file (yas--subdirs directory 'no-subdirs-just-files))
1732 (when (file-readable-p file)
1733 (insert-file-contents file nil nil nil t)
1734 (push (yas--parse-template file)
1737 (yas-define-snippets mode-sym
1739 ;; now recurse to a lower level
1741 (dolist (subdir (yas--subdirs directory))
1742 (yas--load-directory-2 subdir
1745 (defun yas--load-snippet-dirs (&optional nojit)
1746 "Reload the directories listed in `yas-snippet-dirs' or
1747 prompt the user to select one."
1749 (if yas-snippet-dirs
1750 (dolist (directory (reverse (yas-snippet-dirs)))
1751 (cond ((file-directory-p directory)
1752 (yas-load-directory directory (not nojit))
1754 (yas--message 3 "Loaded %s" directory)
1755 (yas--message 3 "Prepared just-in-time loading for %s" directory)))
1757 (push (yas--message 0 "Check your `yas-snippet-dirs': %s is not a directory" directory) errors))))
1758 (call-interactively 'yas-load-directory))
1761 (defun yas-reload-all (&optional interactive)
1762 "Reload all snippets and rebuild the YASnippet menu.
1764 When called interactively force immediate reload of all known
1765 snippets under `yas-snippet-dirs', otherwise use just-in-time
1770 (snippet-editing-buffers
1771 (remove-if-not #'(lambda (buffer)
1772 (with-current-buffer buffer yas--editing-template))
1774 ;; Warn if there are buffers visiting snippets, since reloading will break
1775 ;; any on-line editing of those buffers.
1777 (when snippet-editing-buffers
1779 (if (y-or-n-p "Some buffers editing live snippets, close them and proceed with reload?")
1780 (mapc #'kill-buffer snippet-editing-buffers)
1781 (yas--message 1 "Aborted reload...")
1783 ;; in a non-interactive use, at least set
1784 ;; `yas--editing-template' to nil, make it guess it next time around
1785 (mapc #'(lambda (buffer) (setq yas--editing-template nil)) (buffer-list))))
1787 ;; Empty all snippet tables, parenting info and all menu tables
1789 (setq yas--tables (make-hash-table))
1790 (setq yas--parents (make-hash-table))
1791 (setq yas--menu-table (make-hash-table))
1793 ;; Cancel all pending 'yas--scheduled-jit-loads'
1795 (setq yas--scheduled-jit-loads (make-hash-table))
1797 ;; Init the `yas-minor-mode-map', taking care not to break the
1800 (setcdr yas-minor-mode-map (cdr (yas--init-minor-keymap)))
1802 ;; Reload the directories listed in `yas-snippet-dirs' or prompt
1803 ;; the user to select one.
1805 (setq errors (yas--load-snippet-dirs interactive))
1806 ;; Reload the direct keybindings
1808 (yas-direct-keymaps-reload)
1809 ;; Reload the trigger-key (shoudn't be needed, but see issue #237)
1811 (yas--trigger-key-reload)
1813 (yas--message 3 "Reloaded everything%s...%s."
1814 (if interactive "" " (snippets will load just-in-time)")
1815 (if errors " (some errors, check *Messages*)" "")))))
1817 (defun yas--load-pending-jits ()
1818 (when yas-minor-mode
1819 (dolist (mode (yas--modes-to-activate))
1820 (let ((forms (reverse (gethash mode yas--scheduled-jit-loads))))
1821 ;; must reverse to maintain coherence with `yas-snippet-dirs'
1822 (dolist (form forms)
1823 (yas--message 3 "Loading for `%s', just-in-time: %s!" mode form)
1825 (remhash mode yas--scheduled-jit-loads)))))
1827 ;; (when (<= emacs-major-version 22)
1828 ;; (add-hook 'after-change-major-mode-hook 'yas--load-pending-jits))
1830 (defun yas--quote-string (string)
1831 "Escape and quote STRING.
1832 foo\"bar\\! -> \"foo\\\"bar\\\\!\""
1834 (replace-regexp-in-string "[\\\"]"
1839 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1840 ;;; Snippet compilation function
1842 (defun yas--initialize ()
1843 "For backward compatibility, enable `yas-minor-mode' globally"
1844 (yas-global-mode 1))
1846 (defun yas-compile-directory (top-level-dir)
1847 "Create .yas-compiled-snippets.el files under subdirs of TOP-LEVEL-DIR.
1849 This works by stubbing a few functions, then calling
1850 `yas-load-directory'."
1851 (interactive "DTop level snippet directory?")
1852 (cl-flet ((yas--load-yas-setup-file
1854 (let ((elfile (concat file ".el")))
1855 (when (file-exists-p elfile)
1856 (insert ";;; .yas-setup.el support file if any:\n;;;\n")
1857 (insert-file-contents elfile)
1860 (yas-define-snippets
1862 (insert ";;; Snippet definitions:\n;;;\n")
1863 (let ((literal-snippets (list))
1865 (dolist (snippet snippets)
1866 (let ((key (first snippet))
1867 (template-content (second snippet))
1868 (name (third snippet))
1869 (condition (fourth snippet))
1870 (group (fifth snippet))
1871 (expand-env (sixth snippet))
1872 (file nil) ;; (seventh snippet)) ;; omit on purpose
1873 (binding (eighth snippet))
1874 (uuid (ninth snippet)))
1885 (insert (pp-to-string `(yas-define-snippets ',mode ',literal-snippets)))
1887 (yas--load-directory-1
1888 (dir mode parents &rest ignore)
1889 (let ((output-file (concat (file-name-as-directory dir) ".yas-compiled-snippets.el")))
1890 (with-temp-file output-file
1891 (insert (format ";;; Compiled snippets and support files for `%s'\n" mode))
1892 (yas--load-directory-2 dir mode)
1893 (insert (format ";;; Do not edit! File generated at %s\n" (current-time-string)))))))
1894 (yas-load-directory top-level-dir nil)))
1896 (defun yas-recompile-all ()
1897 "Compile every dir in `yas-snippet-dirs'."
1899 (mapc #'yas-compile-directory (yas-snippet-dirs)))
1905 (defvar yas--scheduled-jit-loads (make-hash-table)
1906 "Alist of mode-symbols to forms to be evaled when `yas-minor-mode' kicks in.")
1908 (defun yas--schedule-jit (mode form)
1911 (gethash mode yas--scheduled-jit-loads))
1912 yas--scheduled-jit-loads))
1915 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1916 ;;; Some user level functions
1921 (message (concat "yasnippet (version "
1923 ") -- pluskid <pluskid@gmail.com>/joaotavora <joaotavora@gmail.com>")))
1925 (defun yas--define-parents (mode parents)
1926 "Add PARENTS to the list of MODE's parents"
1927 (puthash mode (remove-duplicates
1929 (gethash mode yas--parents)))
1932 (defun yas-define-snippets (mode snippets)
1933 "Define SNIPPETS for MODE.
1935 SNIPPETS is a list of snippet definitions, each taking the
1938 (KEY TEMPLATE NAME CONDITION GROUP EXPAND-ENV FILE KEYBINDING UUID)
1940 Within these, only KEY and TEMPLATE are actually mandatory.
1942 TEMPLATE might be a lisp form or a string, depending on whether
1943 this is a snippet or a snippet-command.
1945 CONDITION, EXPAND-ENV and KEYBINDING are lisp forms, they have
1946 been `yas--read-lisp'-ed and will eventually be
1947 `yas--eval-lisp'-ed.
1949 The remaining elements are strings.
1951 FILE is probably of very little use if you're programatically
1954 UUID is the snippets \"unique-id\". Loading a second snippet file
1955 with the same uuid replaced the previous snippet.
1957 You can use `yas--parse-template' to return such lists based on
1958 the current buffers contents."
1959 (let ((snippet-table (yas--table-get-create mode))
1961 (dolist (snippet snippets)
1962 (setq template (yas-define-snippets-1 snippet
1966 (defun yas-define-snippets-1 (snippet snippet-table)
1967 "Helper for `yas-define-snippets'."
1968 ;; X) Calculate some more defaults on the values returned by
1969 ;; `yas--parse-template'.
1971 (let* ((file (seventh snippet))
1973 (name (or (third snippet)
1975 (file-name-directory file))))
1976 (condition (fourth snippet))
1977 (group (fifth snippet))
1978 (keybinding (yas--read-keybinding (eighth snippet)))
1979 (uuid (or (ninth snippet)
1981 (template (or (gethash uuid (yas--table-uuidhash snippet-table))
1982 (yas--make-blank-template))))
1983 ;; X) populate the template object
1985 (yas--populate-template template
1986 :table snippet-table
1988 :content (second snippet)
1991 :condition condition
1992 :expand-env (sixth snippet)
1993 :file (seventh snippet)
1994 :keybinding keybinding
1996 ;; X) Update this template in the appropriate table. This step
1997 ;; also will take care of adding the key indicators in the
1998 ;; templates menu entry, if any
2000 (yas--update-template snippet-table template)
2001 ;; X) Return the template
2007 ;;; Apropos snippet menu:
2009 ;; The snippet menu keymaps are store by mode in hash table called
2010 ;; `yas--menu-table'. They are linked to the main menu in
2011 ;; `yas--menu-keymap-get-create' and are initially created empty,
2012 ;; reflecting the table hierarchy.
2014 ;; They can be populated in two mutually exclusive ways: (1) by
2015 ;; reading `yas--template-group', which in turn is populated by the "#
2016 ;; group:" directives of the snippets or the ".yas-make-groups" file
2017 ;; or (2) by using a separate `yas-define-menu' call, which declares a
2018 ;; menu structure based on snippets uuids.
2020 ;; Both situations are handled in `yas--update-template-menu', which
2021 ;; uses the predicate `yas--template-menu-managed-by-yas-define-menu'
2022 ;; that can tell between the two situations.
2026 ;; * if `yas-define-menu' is used it must run before
2027 ;; `yas-define-snippets' and the UUIDS must match, otherwise we get
2028 ;; duplicate entries. The `yas--template' objects are created in
2029 ;; `yas-define-menu', holding nothing but the menu entry,
2030 ;; represented by a pair of ((menu-item NAME :keys KEYS) TYPE) and
2031 ;; stored in `yas--template-menu-binding-pair'. The (menu-item ...)
2032 ;; part is then stored in the menu keymap itself which make the item
2033 ;; appear to the user. These limitations could probably be revised.
2035 ;; * The `yas--template-perm-group' slot is only used in
2036 ;; `yas-describe-tables'.
2038 (defun yas--template-menu-binding-pair-get-create (template &optional type)
2039 "Get TEMPLATE's menu binding or assign it a new one.
2041 TYPE may be `:stay', signalling this menu binding should be
2042 static in the menu."
2043 (or (yas--template-menu-binding-pair template)
2044 (let ((key (yas--template-key template))
2045 (keybinding (yas--template-keybinding template)))
2046 (setf (yas--template-menu-binding-pair template)
2047 (cons `(menu-item ,(or (yas--template-name template)
2048 (yas--template-uuid template))
2049 ,(yas--make-menu-binding template)
2052 (defun yas--template-menu-managed-by-yas-define-menu (template)
2053 "Non-nil if TEMPLATE's menu entry was included in a `yas-define-menu' call."
2054 (cdr (yas--template-menu-binding-pair template)))
2057 (defun yas--show-menu-p (mode)
2058 (cond ((eq yas-use-menu 'abbreviate)
2060 (mapcar #'(lambda (table)
2061 (yas--table-mode table))
2062 (yas--get-snippet-tables))))
2063 ((eq yas-use-menu 'full)
2065 ((eq yas-use-menu t)
2068 (defun yas--delete-from-keymap (keymap uuid)
2069 "Recursively delete items with UUID from KEYMAP and its submenus."
2071 ;; XXX: This used to skip any submenus named \"parent mode\"
2073 ;; First of all, recursively enter submenus, i.e. the tree is
2074 ;; searched depth first so that stale submenus can be found in the
2077 (mapc #'(lambda (item)
2078 (when (and (listp (cdr item))
2079 (keymapp (third (cdr item))))
2080 (yas--delete-from-keymap (third (cdr item)) uuid)))
2082 ;; Set the uuid entry to nil
2084 (define-key keymap (vector (make-symbol uuid)) nil)
2085 ;; Destructively modify keymap
2087 (setcdr keymap (delete-if #'(lambda (item)
2088 (or (null (cdr item))
2089 (and (keymapp (third (cdr item)))
2090 (null (cdr (third (cdr item)))))))
2093 (defun yas-define-menu (mode menu &optional omit-items)
2094 "Define a snippet menu for MODE according to MENU, ommitting OMIT-ITEMS.
2096 MENU is a list, its elements can be:
2098 - (yas-item UUID) : Creates an entry the snippet identified with
2099 UUID. The menu entry for a snippet thus identified is
2100 permanent, i.e. it will never move (be reordered) in the menu.
2102 - (yas-separator) : Creates a separator
2104 - (yas-submenu NAME SUBMENU) : Creates a submenu with NAME,
2105 SUBMENU has the same form as MENU. NAME is also added to the
2106 list of groups of the snippets defined thereafter.
2108 OMIT-ITEMS is a list of snippet uuid's that will always be
2109 ommited from MODE's menu, even if they're manually loaded.
2111 This function does nothing if `yas-use-menu' is nil.
2114 (let* ((table (yas--table-get-create mode))
2115 (hash (yas--table-uuidhash table)))
2116 (yas--define-menu-1 table
2117 (yas--menu-keymap-get-create mode)
2120 (dolist (uuid omit-items)
2121 (let ((template (or (gethash uuid hash)
2122 (yas--populate-template (puthash uuid
2123 (yas--make-blank-template)
2127 (setf (yas--template-menu-binding-pair template) (cons nil :none)))))))
2129 (defun yas--define-menu-1 (table menu-keymap menu uuidhash &optional group-list)
2130 (dolist (e (reverse menu))
2131 (cond ((eq (first e) 'yas-item)
2132 (let ((template (or (gethash (second e) uuidhash)
2133 (yas--populate-template (puthash (second e)
2134 (yas--make-blank-template)
2137 :perm-group group-list
2138 :uuid (second e)))))
2139 (define-key menu-keymap (vector (gensym))
2140 (car (yas--template-menu-binding-pair-get-create template :stay)))))
2141 ((eq (first e) 'yas-submenu)
2142 (let ((subkeymap (make-sparse-keymap)))
2143 (define-key menu-keymap (vector (gensym))
2144 `(menu-item ,(second e) ,subkeymap))
2145 (yas--define-menu-1 table
2149 (append group-list (list (second e))))))
2150 ((eq (first e) 'yas-separator)
2151 (define-key menu-keymap (vector (gensym))
2152 '(menu-item "----")))
2154 (yas--message 3 "Don't know anything about menu entry %s" (first e))))))
2156 (defun yas--define (mode key template &optional name condition group)
2157 "Define a snippet. Expanding KEY into TEMPLATE.
2159 NAME is a description to this template. Also update the menu if
2160 `yas-use-menu' is t. CONDITION is the condition attached to
2161 this snippet. If you attach a condition to a snippet, then it
2162 will only be expanded when the condition evaluated to non-nil."
2163 (yas-define-snippets mode
2164 (list (list key template name condition group))))
2166 (defun yas-hippie-try-expand (first-time?)
2167 "Integrate with hippie expand. Just put this function in
2168 `hippie-expand-try-functions-list'."
2169 (when yas-minor-mode
2170 (if (not first-time?)
2171 (let ((yas-fallback-behavior 'return-nil))
2177 ;;; Apropos condition-cache:
2182 (defvar yas--condition-cache-timestamp nil)
2183 (defmacro yas-define-condition-cache (func doc &rest body)
2184 "Define a function FUNC with doc DOC and body BODY, BODY is
2185 executed at most once every snippet expansion attempt, to check
2186 expansion conditions.
2188 It doesn't make any sense to call FUNC programatically."
2189 `(defun ,func () ,(if (and doc
2192 "\n\nFor use in snippets' conditions. Within each
2193 snippet-expansion routine like `yas-expand', computes actual
2194 value for the first time then always returns a cached value.")
2195 (setq body (cons doc body))
2197 (let ((timestamp-and-value (get ',func 'yas--condition-cache)))
2198 (if (equal (car timestamp-and-value) yas--condition-cache-timestamp)
2199 (cdr timestamp-and-value)
2200 (let ((new-value (progn
2203 (put ',func 'yas--condition-cache (cons yas--condition-cache-timestamp new-value))
2206 (defalias 'yas-expand 'yas-expand-from-trigger-key)
2207 (defun yas-expand-from-trigger-key (&optional field)
2208 "Expand a snippet before point.
2210 If no snippet expansion is possible, fall back to the behaviour
2211 defined in `yas-fallback-behavior'.
2213 Optional argument FIELD is for non-interactive use and is an
2214 object satisfying `yas--field-p' to restrict the expansion to."
2216 (setq yas--condition-cache-timestamp (current-time))
2217 (let (templates-and-pos)
2218 (unless (and yas-expand-only-for-last-commands
2219 (not (member last-command yas-expand-only-for-last-commands)))
2220 (setq templates-and-pos (if field
2222 (narrow-to-region (yas--field-start field)
2223 (yas--field-end field))
2225 (yas--current-key))))
2226 (if (and templates-and-pos
2227 (first templates-and-pos))
2228 (yas--expand-or-prompt-for-template (first templates-and-pos)
2229 (second templates-and-pos)
2230 (third templates-and-pos))
2231 (yas--fallback 'trigger-key))))
2233 (defun yas-expand-from-keymap ()
2234 "Directly expand some snippets, searching `yas--direct-keymaps'.
2236 If expansion fails, execute the previous binding for this key"
2238 (setq yas--condition-cache-timestamp (current-time))
2239 (let* ((yas--prefix current-prefix-arg)
2240 (vec (subseq (this-command-keys-vector) (if current-prefix-arg
2241 universal-argument-num-events
2243 (templates (mapcan #'(lambda (table)
2244 (yas--fetch table vec))
2245 (yas--get-snippet-tables))))
2247 (yas--expand-or-prompt-for-template templates)
2248 (let ((yas-fallback-behavior 'call-other-command))
2251 (defun yas--expand-or-prompt-for-template (templates &optional start end)
2252 "Expand one of TEMPLATES from START to END.
2254 Prompt the user if TEMPLATES has more than one element, else
2255 expand immediately. Common gateway for
2256 `yas-expand-from-trigger-key' and `yas-expand-from-keymap'."
2257 (let ((yas--current-template (or (and (rest templates) ;; more than one
2258 (yas--prompt-for-template (mapcar #'cdr templates)))
2260 (when yas--current-template
2261 (yas-expand-snippet (yas--template-content yas--current-template)
2264 (yas--template-expand-env yas--current-template)))))
2266 (defun yas--trigger-key-for-fallback ()
2267 ;; When `yas-trigger-key' is <tab> it correctly overrides
2268 ;; org-mode's <tab>, for example and searching for fallbacks
2269 ;; correctly returns `org-cycle'. However, most other modes bind
2270 ;; "TAB" (which is translated from <tab>), and calling
2271 ;; (key-binding "TAB") does not place return that command into
2272 ;; our command-2 local. So we cheat.
2274 (if (string= yas-trigger-key "<tab>")
2278 (defun yas--fallback (&optional from-trigger-key-p)
2279 "Fallback after expansion has failed.
2281 Common gateway for `yas-expand-from-trigger-key' and
2282 `yas-expand-from-keymap'."
2283 (cond ((eq yas-fallback-behavior 'return-nil)
2286 ((eq yas-fallback-behavior 'call-other-command)
2287 (let* ((yas-minor-mode nil)
2288 (yas--direct-keymaps nil)
2289 (yas-trigger-key (yas--trigger-key-for-fallback))
2290 (keys-1 (this-command-keys-vector))
2291 (keys-2 (and yas-trigger-key
2293 (stringp yas-trigger-key)
2294 (read-kbd-macro yas-trigger-key)))
2295 (command-1 (and keys-1 (key-binding keys-1)))
2296 (command-2 (and keys-2 (key-binding keys-2)))
2297 ;; An (ugly) safety: prevents infinite recursion of
2298 ;; yas-expand* calls.
2299 (command (or (and (symbolp command-1)
2300 (not (string-match "yas-expand" (symbol-name command-1)))
2302 (and (symbolp command-2)
2304 (when (and (commandp command)
2305 (not (string-match "yas-expand" (symbol-name command))))
2306 (setq this-command command)
2307 (call-interactively command))))
2308 ((and (listp yas-fallback-behavior)
2309 (cdr yas-fallback-behavior)
2310 (eq 'apply (car yas-fallback-behavior)))
2311 (if (cddr yas-fallback-behavior)
2312 (apply (cadr yas-fallback-behavior)
2313 (cddr yas-fallback-behavior))
2314 (when (commandp (cadr yas-fallback-behavior))
2315 (setq this-command (cadr yas-fallback-behavior))
2316 (call-interactively (cadr yas-fallback-behavior)))))
2318 ;; also return nil if all the other fallbacks have failed
2323 ;;; Utils for snippet development:
2325 (defun yas--all-templates (tables)
2326 "Get `yas--template' objects in TABLES, applicable for buffer and point.
2328 Honours `yas-choose-tables-first', `yas-choose-keys-first' and
2329 `yas-buffer-local-condition'"
2330 (when yas-choose-tables-first
2331 (setq tables (list (yas--prompt-for-table tables))))
2333 (if yas-choose-keys-first
2334 (let ((key (yas--prompt-for-keys
2335 (mapcan #'yas--table-all-keys tables))))
2337 (mapcan #'(lambda (table)
2338 (yas--fetch table key))
2340 (remove-duplicates (mapcan #'yas--table-templates tables)
2343 (defun yas-insert-snippet (&optional no-condition)
2344 "Choose a snippet to expand, pop-up a list of choices according
2345 to `yas--prompt-function'.
2347 With prefix argument NO-CONDITION, bypass filtering of snippets
2350 (setq yas--condition-cache-timestamp (current-time))
2351 (let* ((yas-buffer-local-condition (or (and no-condition
2353 yas-buffer-local-condition))
2354 (templates (yas--all-templates (yas--get-snippet-tables)))
2355 (yas--current-template (and templates
2356 (or (and (rest templates) ;; more than one template for same key
2357 (yas--prompt-for-template templates))
2359 (where (if (region-active-p)
2360 (cons (region-beginning) (region-end))
2361 (cons (point) (point)))))
2362 (if yas--current-template
2363 (yas-expand-snippet (yas--template-content yas--current-template)
2366 (yas--template-expand-env yas--current-template))
2367 (yas--message 3 "No snippets can be inserted here!"))))
2369 (defun yas-visit-snippet-file ()
2370 "Choose a snippet to edit, selection like `yas-insert-snippet'.
2372 Only success if selected snippet was loaded from a file. Put the
2373 visited file in `snippet-mode'."
2375 (let* ((yas-buffer-local-condition 'always)
2376 (templates (yas--all-templates (yas--get-snippet-tables)))
2377 (yas-prompt-functions '(yas-ido-prompt yas-completing-prompt))
2378 (template (and templates
2379 (or (yas--prompt-for-template templates
2380 "Choose a snippet template to edit: ")
2384 (yas--visit-snippet-file-1 template)
2385 (message "No snippets tables active!"))))
2387 (defun yas--visit-snippet-file-1 (template)
2388 (let ((file (yas--template-file template)))
2389 (cond ((and file (file-readable-p file))
2390 (find-file-other-window file)
2392 (set (make-local-variable 'yas--editing-template) template))
2394 (message "Original file %s no longer exists!" file))
2396 (switch-to-buffer (format "*%s*"(yas--template-name template)))
2397 (let ((type 'snippet))
2398 (when (listp (yas--template-content template))
2399 (insert (format "# type: command\n"))
2400 (setq type 'command))
2401 (insert (format "# key: %s\n" (yas--template-key template)))
2402 (insert (format "# name: %s\n" (yas--template-name template)))
2403 (when (yas--template-keybinding template)
2404 (insert (format "# binding: %s\n" (yas--template-keybinding template))))
2405 (when (yas--template-expand-env template)
2406 (insert (format "# expand-env: %s\n" (yas--template-expand-env template))))
2407 (when (yas--template-condition template)
2408 (insert (format "# condition: %s\n" (yas--template-condition template))))
2410 (insert (if (eq type 'command)
2411 (pp-to-string (yas--template-content template))
2412 (yas--template-content template))))
2414 (set (make-local-variable 'yas--editing-template) template)))))
2416 (defun yas--guess-snippet-directories-1 (table)
2417 "Guesses possible snippet subdirectories for TABLE."
2418 (cons (yas--table-name table)
2419 (mapcan #'(lambda (parent)
2420 (yas--guess-snippet-directories-1
2422 (yas--table-parents table))))
2424 (defun yas--guess-snippet-directories (&optional table)
2425 "Try to guess suitable directories based on the current active
2426 tables (or optional TABLE).
2428 Returns a list of elemts (TABLE . DIRS) where TABLE is a
2429 `yas--table' object and DIRS is a list of all possible directories
2430 where snippets of table might exist."
2431 (let ((main-dir (replace-regexp-in-string
2433 (or (first (or (yas-snippet-dirs)
2434 (setq yas-snippet-dirs '("~/.emacs.d/snippets")))))))
2435 (tables (or (and table
2437 (yas--get-snippet-tables))))
2438 ;; HACK! the snippet table created here is actually registered!
2440 (unless (or table (gethash major-mode yas--tables))
2441 (push (yas--table-get-create major-mode)
2444 (mapcar #'(lambda (table)
2446 (mapcar #'(lambda (subdir)
2447 (concat main-dir "/" subdir))
2448 (yas--guess-snippet-directories-1 table))))
2451 (defun yas--make-directory-maybe (table-and-dirs &optional main-table-string)
2452 "Returns a dir inside TABLE-AND-DIRS, prompts for creation if none exists."
2453 (or (some #'(lambda (dir) (when (file-directory-p dir) dir)) (cdr table-and-dirs))
2454 (let ((candidate (first (cdr table-and-dirs))))
2455 (unless (file-writable-p (file-name-directory candidate))
2456 (error (yas--format "%s is not writable." candidate)))
2457 (if (y-or-n-p (format "Guessed directory (%s) for%s%s table \"%s\" does not exist! Create? "
2459 (if (gethash (yas--table-mode (car table-and-dirs))
2463 (or main-table-string
2465 (yas--table-name (car table-and-dirs))))
2467 (make-directory candidate 'also-make-parents)
2468 ;; create the .yas-parents file here...
2471 (defun yas-new-snippet (&optional no-template)
2472 "Pops a new buffer for writing a snippet.
2474 Expands a snippet-writing snippet, unless the optional prefix arg
2475 NO-TEMPLATE is non-nil."
2477 (let ((guessed-directories (yas--guess-snippet-directories)))
2479 (switch-to-buffer "*new snippet*")
2481 (kill-all-local-variables)
2484 (set (make-local-variable 'yas--guessed-modes) (mapcar #'(lambda (d)
2485 (yas--table-mode (car d)))
2486 guessed-directories))
2487 (unless no-template (yas-expand-snippet "\
2488 # -*- mode: snippet -*-
2490 # key: ${2:${1:$(replace-regexp-in-string \"\\\\\\\\(\\\\\\\\w+\\\\\\\\).*\" \"\\\\\\\\1\" yas-text)}}${3:
2491 # binding: ${4:direct-keybinding}}${5:
2492 # expand-env: ((${6:some-var} ${7:some-value}))}${8:
2497 (defun yas--compute-major-mode-and-parents (file)
2498 "Given FILE, find the nearest snippet directory for a given
2499 mode, then return a list (MODE-SYM PARENTS), the mode's symbol and a list
2500 representing one or more of the mode's parents.
2502 Note that MODE-SYM need not be the symbol of a real major mode,
2503 neither do the elements of PARENTS."
2504 (let* ((file-dir (and file
2505 (directory-file-name (or (some #'(lambda (special)
2506 (locate-dominating-file file special))
2510 (directory-file-name (file-name-directory file))))))
2511 (parents-file-name (concat file-dir "/.yas-parents"))
2512 (major-mode-name (and file-dir
2513 (file-name-nondirectory file-dir)))
2514 (major-mode-sym (or (and major-mode-name
2515 (intern major-mode-name))))
2516 (parents (when (file-readable-p parents-file-name)
2520 (insert-file-contents parents-file-name)
2521 (buffer-substring-no-properties (point-min)
2523 (when major-mode-sym
2524 (cons major-mode-sym parents))))
2526 (defvar yas--editing-template nil
2527 "Supporting variable for `yas-load-snippet-buffer' and `yas--visit-snippet'")
2529 (defvar yas--current-template nil
2530 "Holds the current template being expanded into a snippet.")
2532 (defvar yas--guessed-modes nil
2533 "List of guessed modes supporting `yas-load-snippet-buffer'.")
2535 (defun yas--read-table ()
2536 "Ask user for a snippet table, help with some guessing."
2537 (let ((prompt (if (and (featurep 'ido)
2539 'ido-completing-read 'completing-read)))
2540 (unless yas--guessed-modes
2541 (set (make-local-variable 'yas--guessed-modes)
2542 (or (yas--compute-major-mode-and-parents buffer-file-name))))
2544 (funcall prompt (format "Choose or enter a table (yas guesses %s): "
2545 (if yas--guessed-modes
2546 (first yas--guessed-modes)
2548 (mapcar #'symbol-name yas--guessed-modes)
2553 (if (first yas--guessed-modes)
2554 (symbol-name (first yas--guessed-modes)))))))
2556 (defun yas-load-snippet-buffer (table &optional interactive)
2557 "Parse and load current buffer's snippet definition into TABLE.
2559 TABLE is a symbol naming a passed to `yas--table-get-create'.
2561 When called interactively, prompt for the table name and
2562 whether (and where) to save the snippet, then quit the window."
2563 (interactive (list (yas--read-table) t))
2565 ;; We have `yas--editing-template', this buffer's content comes from a
2566 ;; template which is already loaded and neatly positioned,...
2568 (yas--editing-template
2569 (yas-define-snippets-1 (yas--parse-template (yas--template-file yas--editing-template))
2570 (yas--template-table yas--editing-template)))
2571 ;; Try to use `yas--guessed-modes'. If we don't have that use the
2572 ;; value from `yas--compute-major-mode-and-parents'
2575 (unless yas--guessed-modes
2576 (set (make-local-variable 'yas--guessed-modes) (or (yas--compute-major-mode-and-parents buffer-file-name))))
2577 (let* ((table (yas--table-get-create table)))
2578 (set (make-local-variable 'yas--editing-template)
2579 (yas-define-snippets-1 (yas--parse-template buffer-file-name)
2582 (when (and interactive
2584 ;; Only offer to save this if it looks like a library or new
2585 ;; snippet (loaded from elisp, from a dir in `yas-snippet-dirs'
2586 ;; which is not the first, or from an unwritable file)
2588 (not (yas--template-file yas--editing-template))
2589 (not (file-writable-p (yas--template-file yas--editing-template)))
2590 (and (listp yas-snippet-dirs)
2591 (second yas-snippet-dirs)
2592 (not (string-match (expand-file-name (first yas-snippet-dirs))
2593 (yas--template-file yas--editing-template)))))
2594 (y-or-n-p (yas--format "Looks like a library or new snippet. Save to new file? ")))
2595 (let* ((option (first (yas--guess-snippet-directories (yas--template-table yas--editing-template))))
2597 (yas--make-directory-maybe option))))
2599 (let ((default-file-name (or (and (yas--template-file yas--editing-template)
2600 (file-name-nondirectory (yas--template-file yas--editing-template)))
2601 (yas--template-name yas--editing-template))))
2602 (write-file (concat chosen "/"
2603 (read-from-minibuffer (format "File name to create in %s? " chosen)
2604 default-file-name)))
2605 (setf (yas--template-file yas--editing-template) buffer-file-name)))))
2607 (yas--message 3 "Snippet \"%s\" loaded for %s."
2608 (yas--template-name yas--editing-template)
2609 (yas--table-name (yas--template-table yas--editing-template)))
2610 (quit-window interactive)))
2612 (defun yas-tryout-snippet (&optional debug)
2613 "Test current buffers's snippet template in other buffer."
2615 (let* ((major-mode-and-parent (yas--compute-major-mode-and-parents buffer-file-name))
2616 (parsed (yas--parse-template))
2617 (test-mode (or (and (car major-mode-and-parent)
2618 (fboundp (car major-mode-and-parent))
2619 (car major-mode-and-parent))
2620 (first yas--guessed-modes)
2621 (intern (read-from-minibuffer (yas--format "Please input a mode: ")))))
2622 (yas--current-template
2625 (yas--populate-template (yas--make-blank-template)
2626 :table nil ;; no tables for ephemeral snippets
2628 :content (second parsed)
2629 :name (third parsed)
2630 :expand-env (sixth parsed)))))
2631 (cond (yas--current-template
2632 (let ((buffer-name (format "*testing snippet: %s*" (yas--template-name yas--current-template))))
2633 (kill-buffer (get-buffer-create buffer-name))
2634 (switch-to-buffer (get-buffer-create buffer-name))
2635 (setq buffer-undo-list nil)
2636 (condition-case nil (funcall test-mode) (error nil))
2638 (setq buffer-read-only nil)
2639 (yas-expand-snippet (yas--template-content yas--current-template)
2642 (yas--template-expand-env yas--current-template))
2644 (require 'yasnippet-debug nil t))
2645 (add-hook 'post-command-hook 'yas-debug-snippet-vars nil t))))
2647 (yas--message 3 "Cannot test snippet for unknown major mode")))))
2649 (defun yas-active-keys ()
2650 "Return all active trigger keys for current buffer and point"
2651 (remove-duplicates (mapcan #'yas--table-all-keys (yas--get-snippet-tables))
2654 (defun yas--template-fine-group (template)
2655 (car (last (or (yas--template-group template)
2656 (yas--template-perm-group template)))))
2658 (defun yas-describe-tables (&optional choose)
2659 "Display snippets for each table."
2661 (let* ((by-name-hash (and choose
2662 (y-or-n-p "Show by namehash? ")))
2663 (buffer (get-buffer-create "*YASnippet tables*"))
2664 (active-tables (yas--get-snippet-tables))
2665 (remain-tables (let ((all))
2666 (maphash #'(lambda (k v)
2667 (unless (find v active-tables)
2671 (table-lists (list active-tables remain-tables))
2672 (original-buffer (current-buffer))
2674 (yas--condition-cache-timestamp (current-time)))
2675 (with-current-buffer buffer
2676 (setq buffer-read-only nil)
2678 (cond ((not by-name-hash)
2679 (insert "YASnippet tables: \n")
2680 (while (and table-lists
2682 (dolist (table (car table-lists))
2683 (yas--describe-pretty-table table original-buffer))
2684 (setq table-lists (cdr table-lists))
2686 (yas--create-snippet-xrefs)
2687 (display-buffer buffer)
2688 (setq continue (and choose (y-or-n-p "Show also non-active tables? ")))))
2689 (yas--create-snippet-xrefs)
2693 (insert "\n\nYASnippet tables by NAMEHASH: \n")
2694 (dolist (table (append active-tables remain-tables))
2695 (insert (format "\nSnippet table `%s':\n\n" (yas--table-name table)))
2697 (maphash #'(lambda (k v)
2699 (yas--table-hash table))
2701 (insert (format " key %s maps snippets: %s\n" key
2703 (maphash #'(lambda (k v)
2705 (gethash key (yas--table-hash table)))
2708 (setq buffer-read-only t))
2709 (display-buffer buffer)))
2711 (defun yas--describe-pretty-table (table &optional original-buffer)
2712 (insert (format "\nSnippet table `%s'"
2713 (yas--table-name table)))
2714 (if (yas--table-parents table)
2715 (insert (format " parents: %s\n"
2716 (mapcar #'yas--table-name
2717 (yas--table-parents table))))
2719 (insert (make-string 100 ?-) "\n")
2720 (insert "group state name key binding\n")
2721 (let ((groups-hash (make-hash-table :test #'equal)))
2722 (maphash #'(lambda (k v)
2723 (let ((group (or (yas--template-fine-group v)
2725 (when (yas--template-name v)
2727 (cons v (gethash group groups-hash))
2729 (yas--table-uuidhash table))
2731 #'(lambda (group templates)
2732 (setq group (truncate-string-to-width group 25 0 ? "..."))
2733 (insert (make-string 100 ?-) "\n")
2734 (dolist (p templates)
2735 (let ((name (truncate-string-to-width (propertize (format "\\\\snippet `%s'" (yas--template-name p))
2739 (setq group (make-string (length group) ? ))))
2740 (condition-string (let ((condition (yas--template-condition p)))
2743 (with-current-buffer original-buffer
2744 (if (yas--eval-condition condition)
2749 (insert condition-string " ")
2751 (if (string-match "\\.\\.\\.$" name)
2755 (insert (truncate-string-to-width (or (yas--template-key p) "")
2757 (insert (truncate-string-to-width (key-description (yas--template-keybinding p))
2764 ;;; User convenience functions, for using in snippet definitions
2766 (defvar yas-modified-p nil
2767 "Non-nil if field has been modified by user or transformation.")
2769 (defvar yas-moving-away-p nil
2770 "Non-nil if user is about to exit field.")
2772 (defvar yas-text nil
2773 "Contains current field text.")
2775 (defun yas-substr (str pattern &optional subexp)
2776 "Search PATTERN in STR and return SUBEXPth match.
2778 If found, the content of subexp group SUBEXP (default 0) is
2779 returned, or else the original STR will be returned."
2780 (let ((grp (or subexp 0)))
2782 (if (string-match pattern str)
2783 (match-string-no-properties grp str)
2786 (defun yas-choose-value (&rest possibilities)
2787 "Prompt for a string in POSSIBILITIES and return it.
2789 The last element of POSSIBILITIES may be a list of strings."
2790 (unless (or yas-moving-away-p
2792 (setq possibilities (nreverse possibilities))
2793 (setq possibilities (if (listp (car possibilities))
2794 (append (reverse (car possibilities)) (rest possibilities))
2796 (some #'(lambda (fn)
2797 (funcall fn "Choose: " possibilities))
2798 yas-prompt-functions)))
2800 (defun yas-key-to-value (alist)
2801 "Prompt for a string in the list POSSIBILITIES and return it."
2802 (unless (or yas-moving-away-p
2804 (let ((key (read-key-sequence "")))
2806 (or (cdr (find key alist :key #'car :test #'string=))
2809 (defun yas-throw (text)
2810 "Throw a yas--exception with TEXT as the reason."
2811 (throw 'yas--exception (cons 'yas--exception text)))
2813 (defun yas-verify-value (possibilities)
2814 "Verify that the current field value is in POSSIBILITIES
2816 Otherwise throw exception."
2817 (when (and yas-moving-away-p (notany #'(lambda (pos) (string= pos yas-text)) possibilities))
2818 (yas-throw (yas--format "Field only allows %s" possibilities))))
2820 (defun yas-field-value (number)
2821 "Get the string for field with NUMBER.
2823 Use this in primary and mirror transformations to tget."
2824 (let* ((snippet (car (yas--snippets-at-point)))
2826 (yas--snippet-find-field snippet number))))
2828 (yas--field-text-for-display field))))
2831 "Return `yas-text' if that exists and is non-empty, else nil."
2833 (not (string= "" yas-text)))
2836 (defun yas-selected-text ()
2837 "Return `yas-selected-text' if that exists and is non-empty, else nil."
2838 (if (and yas-selected-text
2839 (not (string= "" yas-selected-text)))
2842 (defun yas--get-field-once (number &optional transform-fn)
2843 (unless yas-modified-p
2845 (funcall transform-fn (yas-field-value number))
2846 (yas-field-value number))))
2848 (defun yas-default-from-field (number)
2849 (unless yas-modified-p
2850 (yas-field-value number)))
2852 (defun yas-inside-string ()
2853 (equal 'font-lock-string-face (get-char-property (1- (point)) 'face)))
2855 (defun yas-unimplemented (&optional missing-feature)
2856 (if yas--current-template
2857 (if (y-or-n-p (format "This snippet is unimplemented (missing %s) Visit the snippet definition? "
2860 (yas--visit-snippet-file-1 yas--current-template))
2861 (message "No implementation. Missing %s" (or missing-feature "something"))))
2864 ;;; Snippet expansion and field management
2866 (defvar yas--active-field-overlay nil
2867 "Overlays the currently active field.")
2869 (defvar yas--field-protection-overlays nil
2870 "Two overlays protect the current active field ")
2872 (defconst yas--prefix nil
2873 "A prefix argument for expansion direct from keybindings")
2875 (defvar yas-selected-text nil
2876 "The selected region deleted on the last snippet expansion.")
2878 (defvar yas--start-column nil
2879 "The column where the snippet expansion started.")
2881 (make-variable-buffer-local 'yas--active-field-overlay)
2882 (make-variable-buffer-local 'yas--field-protection-overlays)
2883 (put 'yas--active-field-overlay 'permanent-local t)
2884 (put 'yas--field-protection-overlays 'permanent-local t)
2886 (defstruct (yas--snippet (:constructor yas--make-snippet ()))
2892 (id (yas--snippet-next-id) :read-only t)
2893 (control-overlay nil)
2895 ;; stacked expansion: the `previous-active-field' slot saves the
2896 ;; active field where the child expansion took place
2897 previous-active-field
2900 (defstruct (yas--field (:constructor yas--make-field (number start end parent-field)))
2910 (defstruct (yas--mirror (:constructor yas--make-mirror (start end transform)))
2917 (defstruct (yas--exit (:constructor yas--make-exit (marker)))
2921 (defun yas--apply-transform (field-or-mirror field &optional empty-on-nil-p)
2922 "Calculate transformed string for FIELD-OR-MIRROR from FIELD.
2924 If there is no transform for ht field, return nil.
2926 If there is a transform but it returns nil, return the empty
2927 string iff EMPTY-ON-NIL-P is true."
2928 (let* ((yas-text (yas--field-text-for-display field))
2930 (yas-modified-p (yas--field-modified-p field))
2931 (yas-moving-away-p nil)
2932 (transform (if (yas--mirror-p field-or-mirror)
2933 (yas--mirror-transform field-or-mirror)
2934 (yas--field-transform field-or-mirror)))
2935 (start-point (if (yas--mirror-p field-or-mirror)
2936 (yas--mirror-start field-or-mirror)
2937 (yas--field-start field-or-mirror)))
2938 (transformed (and transform
2940 (goto-char start-point)
2941 (let ((ret (yas--eval-lisp transform)))
2942 (or ret (and empty-on-nil-p "")))))))
2945 (defsubst yas--replace-all (from to &optional text)
2946 "Replace all occurance from FROM to TO.
2948 With optional string TEXT do it in that string."
2950 (replace-regexp-in-string (regexp-quote from) to text t t)
2951 (goto-char (point-min))
2952 (while (search-forward from nil t)
2953 (replace-match to t t text))))
2955 (defun yas--snippet-find-field (snippet number)
2956 (find-if #'(lambda (field)
2957 (eq number (yas--field-number field)))
2958 (yas--snippet-fields snippet)))
2960 (defun yas--snippet-sort-fields (snippet)
2961 "Sort the fields of SNIPPET in navigation order."
2962 (setf (yas--snippet-fields snippet)
2963 (sort (yas--snippet-fields snippet)
2964 #'yas--snippet-field-compare)))
2966 (defun yas--snippet-field-compare (field1 field2)
2967 "Compare two fields. The field with a number is sorted first.
2968 If they both have a number, compare through the number. If neither
2969 have, compare through the field's start point"
2970 (let ((n1 (yas--field-number field1))
2971 (n2 (yas--field-number field2)))
2974 (or (zerop n2) (and (not (zerop n1))
2979 (< (yas--field-start field1)
2980 (yas--field-start field2))))))
2982 (defun yas--field-probably-deleted-p (snippet field)
2983 "Guess if SNIPPET's FIELD should be skipped."
2985 ;; field must be zero lentgh
2987 (zerop (- (yas--field-start field) (yas--field-end field)))
2990 ;; 1) is a nested field and it's been modified
2992 (and (yas--field-parent-field field)
2993 (yas--field-modified-p field))
2994 ;; 2) ends just before the snippet end
2996 (and (eq field (car (last (yas--snippet-fields snippet))))
2997 (= (yas--field-start field) (overlay-end (yas--snippet-control-overlay snippet)))))
2998 ;; the field numbered 0, just before the exit marker, should
3001 (not (zerop (yas--field-number field)))))
3003 (defun yas--snippets-at-point (&optional all-snippets)
3004 "Return a sorted list of snippets at point, most recently
3007 (remove nil (remove-duplicates (mapcar #'(lambda (ov)
3008 (overlay-get ov 'yas--snippet))
3010 (overlays-in (point-min) (point-max))
3011 (nconc (overlays-at (point)) (overlays-at (1- (point))))))))
3013 (<= (yas--snippet-id s2) (yas--snippet-id s1)))))
3015 (defun yas-next-field-or-maybe-expand ()
3016 "Try to expand a snippet at a key before point, otherwise
3017 delegate to `yas-next-field'."
3019 (if yas-triggers-in-field
3020 (let ((yas-fallback-behavior 'return-nil)
3021 (active-field (overlay-get yas--active-field-overlay 'yas--field)))
3023 (unless (yas-expand-from-trigger-key active-field)
3027 (defun yas-next-field (&optional arg)
3028 "Navigate to next field. If there's none, exit the snippet."
3032 (snippet (first (yas--snippets-at-point)))
3033 (active-field (overlay-get yas--active-field-overlay 'yas--field))
3034 (live-fields (remove-if #'(lambda (field)
3035 (and (not (eq field active-field))
3036 (yas--field-probably-deleted-p snippet field)))
3037 (yas--snippet-fields snippet)))
3038 (active-field-pos (position active-field live-fields))
3039 (target-pos (and active-field-pos (+ arg active-field-pos)))
3040 (target-field (and target-pos (nth target-pos live-fields))))
3041 ;; First check if we're moving out of a field with a transform
3043 (when (and active-field
3044 (yas--field-transform active-field))
3045 (let* ((yas-moving-away-p t)
3046 (yas-text (yas--field-text-for-display active-field))
3048 (yas-modified-p (yas--field-modified-p active-field)))
3049 ;; primary field transform: exit call to field-transform
3050 (yas--eval-lisp (yas--field-transform active-field))))
3051 ;; Now actually move...
3052 (cond ((and target-pos (>= target-pos (length live-fields)))
3053 (yas-exit-snippet snippet))
3055 (yas--move-to-field snippet target-field))
3059 (defun yas--place-overlays (snippet field)
3060 "Correctly place overlays for SNIPPET's FIELD"
3061 (yas--make-move-field-protection-overlays snippet field)
3062 (yas--make-move-active-field-overlay snippet field))
3064 (defun yas--move-to-field (snippet field)
3065 "Update SNIPPET to move to field FIELD.
3067 Also create some protection overlays"
3068 (goto-char (yas--field-start field))
3069 (yas--place-overlays snippet field)
3070 (overlay-put yas--active-field-overlay 'yas--field field)
3071 (let ((number (yas--field-number field)))
3072 ;; check for the special ${0: ...} field
3073 (if (and number (zerop number))
3075 (set-mark (yas--field-end field))
3076 (setf (yas--snippet-force-exit snippet)
3077 (or (yas--field-transform field)
3079 ;; make this field active
3080 (setf (yas--snippet-active-field snippet) field)
3081 ;; primary field transform: first call to snippet transform
3082 (unless (yas--field-modified-p field)
3083 (if (yas--field-update-display field snippet)
3084 (yas--update-mirrors snippet)
3085 (setf (yas--field-modified-p field) nil))))))
3087 (defun yas-prev-field ()
3088 "Navigate to prev field. If there's none, exit the snippet."
3090 (yas-next-field -1))
3092 (defun yas-abort-snippet (&optional snippet)
3094 (let ((snippet (or snippet
3095 (car (yas--snippets-at-point)))))
3097 (setf (yas--snippet-force-exit snippet) t))))
3099 (defun yas-exit-snippet (snippet)
3100 "Goto exit-marker of SNIPPET."
3101 (interactive (list (first (yas--snippets-at-point))))
3103 (setf (yas--snippet-force-exit snippet) t)
3104 (goto-char (if (yas--snippet-exit snippet)
3105 (yas--exit-marker (yas--snippet-exit snippet))
3106 (overlay-end (yas--snippet-control-overlay snippet))))))
3108 (defun yas-exit-all-snippets ()
3109 "Exit all snippets."
3111 (mapc #'(lambda (snippet)
3112 (yas-exit-snippet snippet)
3113 (yas--check-commit-snippet))
3114 (yas--snippets-at-point 'all-snippets)))
3117 ;;; Some low level snippet-routines:
3119 (defmacro yas--inhibit-overlay-hooks (&rest body)
3120 "Run BODY with `yas--inhibit-overlay-hooks' set to t."
3121 (declare (indent 0))
3122 `(let ((yas--inhibit-overlay-hooks t))
3125 (defvar yas-snippet-beg nil "Beginning position of the last snippet commited.")
3126 (defvar yas-snippet-end nil "End position of the last snippet commited.")
3128 (defun yas--commit-snippet (snippet)
3129 "Commit SNIPPET, but leave point as it is. This renders the
3130 snippet as ordinary text."
3132 (let ((control-overlay (yas--snippet-control-overlay snippet)))
3134 ;; Save the end of the moribund snippet in case we need to revive it
3135 ;; its original expansion.
3137 (when (and control-overlay
3138 (overlay-buffer control-overlay))
3139 (setq yas-snippet-beg (overlay-start control-overlay))
3140 (setq yas-snippet-end (overlay-end control-overlay))
3141 (delete-overlay control-overlay))
3143 (yas--inhibit-overlay-hooks
3144 (when yas--active-field-overlay
3145 (delete-overlay yas--active-field-overlay))
3146 (when yas--field-protection-overlays
3147 (mapc #'delete-overlay yas--field-protection-overlays)))
3149 ;; stacked expansion: if the original expansion took place from a
3150 ;; field, make sure we advance it here at least to
3151 ;; `yas-snippet-end'...
3153 (let ((previous-field (yas--snippet-previous-active-field snippet)))
3154 (when (and yas-snippet-end previous-field)
3155 (yas--advance-end-maybe previous-field yas-snippet-end)))
3157 ;; Convert all markers to points,
3159 (yas--markers-to-points snippet)
3161 ;; Take care of snippet revival
3163 (if yas-snippet-revival
3164 (push `(apply yas--snippet-revive ,yas-snippet-beg ,yas-snippet-end ,snippet)
3166 ;; Dismember the snippet... this is useful if we get called
3167 ;; again from `yas--take-care-of-redo'....
3168 (setf (yas--snippet-fields snippet) nil)))
3170 (yas--message 3 "Snippet %s exited." (yas--snippet-id snippet)))
3172 (defun yas--safely-run-hooks (hook-var)
3173 (condition-case error
3174 (run-hooks hook-var)
3176 (yas--message 3 "%s error: %s" hook-var (error-message-string error)))))
3179 (defun yas--check-commit-snippet ()
3180 "Checks if point exited the currently active field of the
3181 snippet, if so cleans up the whole snippet up."
3182 (let* ((snippets (yas--snippets-at-point 'all-snippets))
3183 (snippets-left snippets)
3184 (snippet-exit-transform))
3185 (dolist (snippet snippets)
3186 (let ((active-field (yas--snippet-active-field snippet)))
3187 (setq snippet-exit-transform (yas--snippet-force-exit snippet))
3188 (cond ((or snippet-exit-transform
3189 (not (and active-field (yas--field-contains-point-p active-field))))
3190 (setq snippets-left (delete snippet snippets-left))
3191 (setf (yas--snippet-force-exit snippet) nil)
3192 (yas--commit-snippet snippet))
3194 (or (not yas--active-field-overlay)
3195 (not (overlay-buffer yas--active-field-overlay))))
3197 ;; stacked expansion: this case is mainly for recent
3198 ;; snippet exits that place us back int the field of
3202 (yas--move-to-field snippet active-field)
3203 (yas--update-mirrors snippet)))
3206 (unless (or (null snippets) snippets-left)
3207 (if snippet-exit-transform
3208 (yas--eval-lisp-no-saves snippet-exit-transform))
3209 (yas--safely-run-hooks 'yas-after-exit-snippet-hook))))
3211 ;; Apropos markers-to-points:
3213 ;; This was found useful for performance reasons, so that an
3214 ;; excessive number of live markers aren't kept around in the
3215 ;; `buffer-undo-list'. However, in `markers-to-points', the
3216 ;; set-to-nil markers can't simply be discarded and replaced with
3217 ;; fresh ones in `points-to-markers'. The original marker that was
3218 ;; just set to nil has to be reused.
3220 ;; This shouldn't bring horrible problems with undo/redo, but it
3223 (defun yas--markers-to-points (snippet)
3224 "Convert all markers in SNIPPET to a cons (POINT . MARKER)
3225 where POINT is the original position of the marker and MARKER is
3226 the original marker object with the position set to nil."
3227 (dolist (field (yas--snippet-fields snippet))
3228 (let ((start (marker-position (yas--field-start field)))
3229 (end (marker-position (yas--field-end field))))
3230 (set-marker (yas--field-start field) nil)
3231 (set-marker (yas--field-end field) nil)
3232 (setf (yas--field-start field) (cons start (yas--field-start field)))
3233 (setf (yas--field-end field) (cons end (yas--field-end field))))
3234 (dolist (mirror (yas--field-mirrors field))
3235 (let ((start (marker-position (yas--mirror-start mirror)))
3236 (end (marker-position (yas--mirror-end mirror))))
3237 (set-marker (yas--mirror-start mirror) nil)
3238 (set-marker (yas--mirror-end mirror) nil)
3239 (setf (yas--mirror-start mirror) (cons start (yas--mirror-start mirror)))
3240 (setf (yas--mirror-end mirror) (cons end (yas--mirror-end mirror))))))
3241 (let ((snippet-exit (yas--snippet-exit snippet)))
3243 (let ((exit (marker-position (yas--exit-marker snippet-exit))))
3244 (set-marker (yas--exit-marker snippet-exit) nil)
3245 (setf (yas--exit-marker snippet-exit) (cons exit (yas--exit-marker snippet-exit)))))))
3247 (defun yas--points-to-markers (snippet)
3248 "Convert all cons (POINT . MARKER) in SNIPPET to markers. This
3249 is done by setting MARKER to POINT with `set-marker'."
3250 (dolist (field (yas--snippet-fields snippet))
3251 (setf (yas--field-start field) (set-marker (cdr (yas--field-start field))
3252 (car (yas--field-start field))))
3253 (setf (yas--field-end field) (set-marker (cdr (yas--field-end field))
3254 (car (yas--field-end field))))
3255 (dolist (mirror (yas--field-mirrors field))
3256 (setf (yas--mirror-start mirror) (set-marker (cdr (yas--mirror-start mirror))
3257 (car (yas--mirror-start mirror))))
3258 (setf (yas--mirror-end mirror) (set-marker (cdr (yas--mirror-end mirror))
3259 (car (yas--mirror-end mirror))))))
3260 (let ((snippet-exit (yas--snippet-exit snippet)))
3262 (setf (yas--exit-marker snippet-exit) (set-marker (cdr (yas--exit-marker snippet-exit))
3263 (car (yas--exit-marker snippet-exit)))))))
3265 (defun yas--field-contains-point-p (field &optional point)
3266 (let ((point (or point
3268 (and (>= point (yas--field-start field))
3269 (<= point (yas--field-end field)))))
3271 (defun yas--field-text-for-display (field)
3272 "Return the propertized display text for field FIELD. "
3273 (buffer-substring (yas--field-start field) (yas--field-end field)))
3275 (defun yas--undo-in-progress ()
3276 "True if some kind of undo is in progress"
3277 (or undo-in-progress
3278 (eq this-command 'undo)
3279 (eq this-command 'redo)))
3281 (defun yas--make-control-overlay (snippet start end)
3282 "Creates the control overlay that surrounds the snippet and
3284 (let ((overlay (make-overlay start
3289 (overlay-put overlay 'keymap yas-keymap)
3290 (overlay-put overlay 'priority 100)
3291 (overlay-put overlay 'yas--snippet snippet)
3294 (defun yas-skip-and-clear-or-delete-char (&optional field)
3295 "Clears unmodified field if at field start, skips to next tab.
3297 Otherwise deletes a character normally by calling `delete-char'."
3299 (let ((field (or field
3300 (and yas--active-field-overlay
3301 (overlay-buffer yas--active-field-overlay)
3302 (overlay-get yas--active-field-overlay 'yas--field)))))
3304 (not (yas--field-modified-p field))
3305 (eq (point) (marker-position (yas--field-start field))))
3306 (yas--skip-and-clear field)
3309 (call-interactively 'delete-char)))))
3311 (defun yas--skip-and-clear (field)
3312 "Deletes the region of FIELD and sets it modified state to t"
3313 ;; Just before skipping-and-clearing the field, mark its children
3314 ;; fields as modified, too. If the childen have mirrors-in-fields
3315 ;; this prevents them from updating erroneously (we're skipping and
3318 (yas--mark-this-and-children-modified field)
3319 (delete-region (yas--field-start field) (yas--field-end field)))
3321 (defun yas--mark-this-and-children-modified (field)
3322 (setf (yas--field-modified-p field) t)
3323 (let ((fom (yas--field-next field)))
3325 (yas--fom-parent-field fom))
3326 (when (and (eq (yas--fom-parent-field fom) field)
3328 (yas--mark-this-and-children-modified fom))
3329 (setq fom (yas--fom-next fom)))))
3331 (defun yas--make-move-active-field-overlay (snippet field)
3332 "Place the active field overlay in SNIPPET's FIELD.
3334 Move the overlay, or create it if it does not exit."
3335 (if (and yas--active-field-overlay
3336 (overlay-buffer yas--active-field-overlay))
3337 (move-overlay yas--active-field-overlay
3338 (yas--field-start field)
3339 (yas--field-end field))
3340 (setq yas--active-field-overlay
3341 (make-overlay (yas--field-start field)
3342 (yas--field-end field)
3344 (overlay-put yas--active-field-overlay 'priority 100)
3345 (overlay-put yas--active-field-overlay 'face 'yas-field-highlight-face)
3346 (overlay-put yas--active-field-overlay 'yas--snippet snippet)
3347 (overlay-put yas--active-field-overlay 'modification-hooks '(yas--on-field-overlay-modification))
3348 (overlay-put yas--active-field-overlay 'insert-in-front-hooks
3349 '(yas--on-field-overlay-modification))
3350 (overlay-put yas--active-field-overlay 'insert-behind-hooks
3351 '(yas--on-field-overlay-modification))))
3353 (defvar yas--inhibit-overlay-hooks nil
3354 "Bind this temporarity to non-nil to prevent running `yas--on-*-modification'.")
3356 (defun yas--on-field-overlay-modification (overlay after? beg end &optional length)
3357 "Clears the field and updates mirrors, conditionally.
3359 Only clears the field if it hasn't been modified and it point it
3360 at field start. This hook doesn't do anything if an undo is in
3362 (unless (or yas--inhibit-overlay-hooks
3363 (yas--undo-in-progress))
3364 (let* ((field (overlay-get overlay 'yas--field))
3365 (number (and field (yas--field-number field)))
3366 (snippet (overlay-get yas--active-field-overlay 'yas--snippet)))
3368 (yas--advance-end-maybe field (overlay-end overlay))
3370 (yas--field-update-display field snippet))
3371 (yas--update-mirrors snippet))
3373 (when (and (not after?)
3374 (not (yas--field-modified-p field))
3375 (eq (point) (if (markerp (yas--field-start field))
3376 (marker-position (yas--field-start field))
3377 (yas--field-start field))))
3378 (yas--skip-and-clear field))
3379 (setf (yas--field-modified-p field) t))))))
3381 ;;; Apropos protection overlays:
3383 ;; These exist for nasty users who will try to delete parts of the
3384 ;; snippet outside the active field. Actual protection happens in
3385 ;; `yas--on-protection-overlay-modification'.
3387 ;; Currently this signals an error which inhibits the command. For
3388 ;; commands that move point (like `kill-line'), point is restored in
3389 ;; the `yas--post-command-handler' using a global
3390 ;; `yas--protection-violation' variable.
3392 ;; Alternatively, I've experimented with an implementation that
3393 ;; commits the snippet before actually calling `this-command'
3394 ;; interactively, and then signals an eror, which is ignored. but
3395 ;; blocks all other million modification hooks. This presented some
3396 ;; problems with stacked expansion.
3398 (defun yas--make-move-field-protection-overlays (snippet field)
3399 "Place protection overlays surrounding SNIPPET's FIELD.
3401 Move the overlays, or create them if they do not exit."
3402 (let ((start (yas--field-start field))
3403 (end (yas--field-end field)))
3404 ;; First check if the (1+ end) is contained in the buffer,
3405 ;; otherwise we'll have to do a bit of cheating and silently
3406 ;; insert a newline. the `(1+ (buffer-size))' should prevent this
3407 ;; when using stacked expansion
3409 (when (< (buffer-size) end)
3411 (yas--inhibit-overlay-hooks
3412 (goto-char (point-max))
3414 ;; go on to normal overlay creation/moving
3416 (cond ((and yas--field-protection-overlays
3417 (every #'overlay-buffer yas--field-protection-overlays))
3418 (move-overlay (first yas--field-protection-overlays) (1- start) start)
3419 (move-overlay (second yas--field-protection-overlays) end (1+ end)))
3421 (setq yas--field-protection-overlays
3422 (list (make-overlay (1- start) start nil t nil)
3423 (make-overlay end (1+ end) nil t nil)))
3424 (dolist (ov yas--field-protection-overlays)
3425 (overlay-put ov 'face 'yas--field-debug-face)
3426 (overlay-put ov 'yas--snippet snippet)
3427 ;; (overlay-put ov 'evaporate t)
3428 (overlay-put ov 'modification-hooks '(yas--on-protection-overlay-modification)))))))
3430 (defvar yas--protection-violation nil
3431 "When non-nil, signals attempts to erronesly exit or modify the snippet.
3433 Functions in the `post-command-hook', for example
3434 `yas--post-command-handler' can check it and reset its value to
3435 nil. The variables value is the point where the violation
3438 (defun yas--on-protection-overlay-modification (overlay after? beg end &optional length)
3439 "Signals a snippet violation, then issues error.
3441 The error should be ignored in `debug-ignored-errors'"
3442 (unless yas--inhibit-overlay-hooks
3443 (cond ((not (or after?
3444 (yas--undo-in-progress)))
3445 (setq yas--protection-violation (point))
3446 (error "Exit the snippet first!")))))
3448 (add-to-list 'debug-ignored-errors "^Exit the snippet first!$")
3451 ;; Snippet expansion and "stacked" expansion:
3453 ;; Stacked expansion is when you try to expand a snippet when already
3454 ;; inside a snippet expansion.
3456 ;; The parent snippet does not run its fields modification hooks
3457 ;; (`yas--on-field-overlay-modification' and
3458 ;; `yas--on-protection-overlay-modification') while the child snippet
3459 ;; is active. This means, among other things, that the mirrors of the
3460 ;; parent snippet are not updated, this only happening when one exits
3461 ;; the child snippet.
3463 ;; Unfortunately, this also puts some ugly (and not fully-tested)
3464 ;; bits of code in `yas-expand-snippet' and
3465 ;; `yas--commit-snippet'. I've tried to mark them with "stacked
3468 ;; This was thought to be safer in in an undo/redo perpective, but
3469 ;; maybe the correct implementation is to make the globals
3470 ;; `yas--active-field-overlay' and `yas--field-protection-overlays' be
3471 ;; snippet-local and be active even while the child snippet is
3472 ;; running. This would mean a lot of overlay modification hooks
3473 ;; running, but if managed correctly (including overlay priorities)
3474 ;; they should account for all situations...
3476 (defun yas-expand-snippet (content &optional start end expand-env)
3477 "Expand snippet CONTENT at current point.
3479 Text between START and END will be deleted before inserting
3480 template. EXPAND-ENV is are let-style variable to value bindings
3481 considered when expanding the snippet."
3482 (run-hooks 'yas-before-expand-snippet-hook)
3485 (let* ((yas-selected-text (or yas-selected-text
3486 (and (region-active-p)
3487 (buffer-substring-no-properties (region-beginning)
3490 (and (region-active-p)
3494 (and (region-active-p)
3497 (to-delete (and start
3499 (buffer-substring-no-properties start end)))
3502 (setq yas--indent-original-column (current-column))
3503 ;; Delete the region to delete, this *does* get undo-recorded.
3505 (when (and to-delete
3507 (delete-region start end))
3509 (cond ((listp content)
3510 ;; x) This is a snippet-command
3512 (yas--eval-lisp-no-saves content))
3514 ;; x) This is a snippet-snippet :-)
3516 ;; Narrow the region down to the content, shoosh the
3517 ;; `buffer-undo-list', and create the snippet, the new
3518 ;; snippet updates its mirrors once, so we are left with
3519 ;; some plain text. The undo action for deleting this
3520 ;; plain text will get recorded at the end.
3522 ;; stacked expansion: also shoosh the overlay modification hooks
3524 (narrow-to-region start start)
3525 (let ((buffer-undo-list t))
3526 ;; snippet creation might evaluate users elisp, which
3527 ;; might generate errors, so we have to be ready to catch
3528 ;; them mostly to make the undo information
3530 (setq yas--start-column (save-restriction (widen) (current-column)))
3531 (yas--inhibit-overlay-hooks
3534 (eval `(let* ,expand-env
3536 (yas--snippet-create (point-min) (point-max))))
3538 (yas--snippet-create (point-min) (point-max)))))))
3540 ;; stacked-expansion: This checks for stacked expansion, save the
3541 ;; `yas--previous-active-field' and advance its boudary.
3543 (let ((existing-field (and yas--active-field-overlay
3544 (overlay-buffer yas--active-field-overlay)
3545 (overlay-get yas--active-field-overlay 'yas--field))))
3546 (when existing-field
3547 (setf (yas--snippet-previous-active-field snippet) existing-field)
3548 (yas--advance-end-maybe existing-field (overlay-end yas--active-field-overlay))))
3550 ;; Exit the snippet immediately if no fields
3552 (unless (yas--snippet-fields snippet)
3553 (yas-exit-snippet snippet))
3555 ;; Push two undo actions: the deletion of the inserted contents of
3556 ;; the new snippet (without the "key") followed by an apply of
3557 ;; `yas--take-care-of-redo' on the newly inserted snippet boundaries
3559 ;; A small exception, if `yas-also-auto-indent-first-line'
3560 ;; is t and `yas--indent' decides to indent the line to a
3561 ;; point before the actual expansion point, undo would be
3562 ;; messed up. We call the early point "newstart"". case,
3563 ;; and attempt to fix undo.
3565 (let ((newstart (overlay-start (yas--snippet-control-overlay snippet)))
3566 (end (overlay-end (yas--snippet-control-overlay snippet))))
3567 (when (< newstart start)
3568 (push (cons (make-string (- start newstart) ? ) newstart) buffer-undo-list))
3569 (push (cons newstart end) buffer-undo-list)
3570 (push `(apply yas--take-care-of-redo ,start ,end ,snippet)
3572 ;; Now, schedule a move to the first field
3574 (let ((first-field (car (yas--snippet-fields snippet))))
3576 (sit-for 0) ;; fix issue 125
3577 (yas--move-to-field snippet first-field)))
3578 (yas--message 3 "snippet expanded.")
3581 (defun yas--take-care-of-redo (beg end snippet)
3582 "Commits SNIPPET, which in turn pushes an undo action for
3585 Meant to exit in the `buffer-undo-list'."
3586 ;; slightly optimize: this action is only needed for snippets with
3587 ;; at least one field
3588 (when (yas--snippet-fields snippet)
3589 (yas--commit-snippet snippet)))
3591 (defun yas--snippet-revive (beg end snippet)
3592 "Revives the SNIPPET and creates a control overlay from BEG to
3595 BEG and END are, we hope, the original snippets boudaries. All
3596 the markers/points exiting existing inside SNIPPET should point
3597 to their correct locations *at the time the snippet is revived*.
3599 After revival, push the `yas--take-care-of-redo' in the
3601 ;; Reconvert all the points to markers
3603 (yas--points-to-markers snippet)
3604 ;; When at least one editable field existed in the zombie snippet,
3605 ;; try to revive the whole thing...
3607 (let ((target-field (or (yas--snippet-active-field snippet)
3608 (car (yas--snippet-fields snippet)))))
3610 (setf (yas--snippet-control-overlay snippet) (yas--make-control-overlay snippet beg end))
3611 (overlay-put (yas--snippet-control-overlay snippet) 'yas--snippet snippet)
3613 (yas--move-to-field snippet target-field)
3615 (push `(apply yas--take-care-of-redo ,beg ,end ,snippet)
3616 buffer-undo-list))))
3618 (defun yas--snippet-create (begin end)
3619 "Creates a snippet from an template inserted between BEGIN and END.
3621 Returns the newly created snippet."
3622 (let ((snippet (yas--make-snippet)))
3624 (yas--snippet-parse-create snippet)
3626 ;; Sort and link each field
3627 (yas--snippet-sort-fields snippet)
3629 ;; Create keymap overlay for snippet
3630 (setf (yas--snippet-control-overlay snippet)
3631 (yas--make-control-overlay snippet (point-min) (point-max)))
3634 (goto-char (point-max))
3639 ;;; Apropos adjacencies and "fom's":
3641 ;; Once the $-constructs bits like "$n" and "${:n" are deleted in the
3642 ;; recently expanded snippet, we might actually have many fields,
3643 ;; mirrors (and the snippet exit) in the very same position in the
3644 ;; buffer. Therefore we need to single-link the
3645 ;; fields-or-mirrors-or-exit (which I have abbreviated to "fom")
3646 ;; according to their original positions in the buffer.
3648 ;; Then we have operation `yas--advance-end-maybe' and
3649 ;; `yas--advance-start-maybe', which conditionally push the starts and
3650 ;; ends of these foms down the chain.
3652 ;; This allows for like the printf with the magic ",":
3654 ;; printf ("${1:%s}\\n"${1:$(if (string-match "%" text) "," "\);")} \
3655 ;; $2${1:$(if (string-match "%" text) "\);" "")}$0
3657 (defun yas--fom-start (fom)
3658 (cond ((yas--field-p fom)
3659 (yas--field-start fom))
3660 ((yas--mirror-p fom)
3661 (yas--mirror-start fom))
3663 (yas--exit-marker fom))))
3665 (defun yas--fom-end (fom)
3666 (cond ((yas--field-p fom)
3667 (yas--field-end fom))
3668 ((yas--mirror-p fom)
3669 (yas--mirror-end fom))
3671 (yas--exit-marker fom))))
3673 (defun yas--fom-next (fom)
3674 (cond ((yas--field-p fom)
3675 (yas--field-next fom))
3676 ((yas--mirror-p fom)
3677 (yas--mirror-next fom))
3679 (yas--exit-next fom))))
3681 (defun yas--fom-parent-field (fom)
3682 (cond ((yas--field-p fom)
3683 (yas--field-parent-field fom))
3684 ((yas--mirror-p fom)
3685 (yas--mirror-parent-field fom))
3689 (defun yas--calculate-adjacencies (snippet)
3690 "Calculate adjacencies for fields or mirrors of SNIPPET.
3692 This is according to their relative positions in the buffer, and
3693 has to be called before the $-constructs are deleted."
3694 (cl-flet ((yas--fom-set-next-fom (fom nextfom)
3695 (cond ((yas--field-p fom)
3696 (setf (yas--field-next fom) nextfom))
3697 ((yas--mirror-p fom)
3698 (setf (yas--mirror-next fom) nextfom))
3700 (setf (yas--exit-next fom) nextfom))))
3701 (yas--compare-fom-begs (fom1 fom2)
3702 (if (= (yas--fom-start fom2) (yas--fom-start fom1))
3703 (yas--mirror-p fom2)
3704 (>= (yas--fom-start fom2) (yas--fom-start fom1))))
3705 (yas--link-foms (fom1 fom2)
3706 (yas--fom-set-next-fom fom1 fom2)))
3707 ;; make some yas--field, yas--mirror and yas--exit soup
3709 (when (yas--snippet-exit snippet)
3710 (push (yas--snippet-exit snippet) soup))
3711 (dolist (field (yas--snippet-fields snippet))
3713 (dolist (mirror (yas--field-mirrors field))
3714 (push mirror soup)))
3717 #'yas--compare-fom-begs))
3719 (reduce #'yas--link-foms soup)))))
3721 (defun yas--calculate-mirrors-in-fields (snippet mirror)
3722 "Attempt to assign a parent field of SNIPPET to the mirror MIRROR.
3724 Use the tighest containing field if more than one field contains
3725 the mirror. Intended to be called *before* the dollar-regions are
3727 (let ((min (point-min))
3729 (dolist (field (yas--snippet-fields snippet))
3730 (when (and (<= (yas--field-start field) (yas--mirror-start mirror))
3731 (<= (yas--mirror-end mirror) (yas--field-end field))
3732 (< min (yas--field-start field))
3733 (< (yas--field-end field) max))
3734 (setq min (yas--field-start field)
3735 max (yas--field-end field))
3736 (setf (yas--mirror-parent-field mirror) field)))))
3738 (defun yas--advance-end-maybe (fom newend)
3739 "Maybe advance FOM's end to NEWEND if it needs it.
3743 * call `yas--advance-start-maybe' on FOM's next fom.
3745 * in case FOM is field call `yas--advance-end-maybe' on its parent
3748 Also, if FOM is an exit-marker, always call
3749 `yas--advance-start-maybe' on its next fom. This is beacuse
3750 exit-marker have identical start and end markers.
3753 (cond ((and fom (< (yas--fom-end fom) newend))
3754 (set-marker (yas--fom-end fom) newend)
3755 (yas--advance-start-maybe (yas--fom-next fom) newend)
3756 (yas--advance-end-of-parents-maybe (yas--fom-parent-field fom) newend))
3758 (yas--advance-start-maybe (yas--fom-next fom) newend))))
3760 (defun yas--advance-start-maybe (fom newstart)
3761 "Maybe advance FOM's start to NEWSTART if it needs it.
3763 If it does, also call `yas--advance-end-maybe' on FOM."
3764 (when (and fom (< (yas--fom-start fom) newstart))
3765 (set-marker (yas--fom-start fom) newstart)
3766 (yas--advance-end-maybe fom newstart)))
3768 (defun yas--advance-end-of-parents-maybe (field newend)
3769 "Like `yas--advance-end-maybe' but for parent fields.
3771 Only works for fields and doesn't care about the start of the
3772 next FOM. Works its way up recursively for parents of parents."
3774 (< (yas--field-end field) newend))
3775 (set-marker (yas--field-end field) newend)
3776 (yas--advance-end-of-parents-maybe (yas--field-parent-field field) newend)))
3778 (defvar yas--dollar-regions nil
3779 "When expanding the snippet the \"parse-create\" functions add
3780 cons cells to this var")
3782 (defvar yas--backquote-markers-and-strings nil
3783 "List of (MARKER . STRING) marking where the the values
3784 from backquoted lisp expressions should be inserted at the end of
3787 (defun yas--snippet-parse-create (snippet)
3788 "Parse a recently inserted snippet template, creating all
3789 necessary fields, mirrors and exit points.
3791 Meant to be called in a narrowed buffer, does various passes"
3792 (let ((parse-start (point)))
3793 ;; Reset the yas--dollar-regions
3795 (setq yas--dollar-regions nil)
3796 ;; protect just the backquotes
3798 (yas--protect-escapes nil '(?`))
3799 ;; replace all backquoted expressions
3801 (goto-char parse-start)
3802 (yas--save-backquotes)
3803 ;; protect escaped characters
3805 (yas--protect-escapes)
3806 ;; parse fields with {}
3808 (goto-char parse-start)
3809 (yas--field-parse-create snippet)
3810 ;; parse simple mirrors and fields
3812 (goto-char parse-start)
3813 (yas--simple-mirror-parse-create snippet)
3814 ;; parse mirror transforms
3816 (goto-char parse-start)
3817 (yas--transform-mirror-parse-create snippet)
3818 ;; calculate adjacencies of fields and mirrors
3820 (yas--calculate-adjacencies snippet)
3821 ;; Delete $-constructs
3823 (yas--delete-regions yas--dollar-regions)
3824 ;; restore backquoted expression values
3826 (yas--restore-backquotes)
3829 (goto-char parse-start)
3830 (yas--restore-escapes)
3831 ;; update mirrors for the first time
3833 (yas--update-mirrors snippet)
3834 ;; indent the best we can
3836 (goto-char parse-start)
3837 (yas--indent snippet)))
3839 (defun yas--indent-according-to-mode (snippet-markers)
3840 "Indent current line according to mode, preserving
3842 ;;; Apropos indenting problems....
3844 ;; `indent-according-to-mode' uses whatever `indent-line-function'
3845 ;; is available. Some implementations of these functions delete text
3846 ;; before they insert. If there happens to be a marker just after
3847 ;; the text being deleted, the insertion actually happens after the
3848 ;; marker, which misplaces it.
3850 ;; This would also happen if we had used overlays with the
3851 ;; `front-advance' property set to nil.
3853 ;; This is why I have these `trouble-markers', they are the ones at
3854 ;; they are the ones at the first non-whitespace char at the line
3855 ;; (i.e. at `yas--real-line-beginning'. After indentation takes place
3856 ;; we should be at the correct to restore them to. All other
3857 ;; non-trouble-markers have been *pushed* and don't need special
3860 (goto-char (yas--real-line-beginning))
3861 (let ((trouble-markers (remove-if-not #'(lambda (marker)
3867 (indent-according-to-mode)
3868 (error (yas--message 3 "Warning: `yas--indent-according-to-mode' having problems running %s" indent-line-function)
3870 (mapc #'(lambda (marker)
3871 (set-marker marker (point)))
3874 (defvar yas--indent-original-column nil)
3875 (defun yas--indent (snippet)
3876 (let ((snippet-markers (yas--collect-snippet-markers snippet)))
3877 ;; Look for those $>
3879 (while (re-search-forward "$>" nil t)
3880 (delete-region (match-beginning 0) (match-end 0))
3881 (when (not (eq yas-indent-line 'auto))
3882 (yas--indent-according-to-mode snippet-markers))))
3883 ;; Now do stuff for 'fixed and 'auto
3885 (cond ((eq yas-indent-line 'fixed)
3886 (while (and (zerop (forward-line))
3887 (zerop (current-column)))
3888 (indent-to-column yas--indent-original-column)))
3889 ((eq yas-indent-line 'auto)
3890 (let ((end (set-marker (make-marker) (point-max)))
3891 (indent-first-line-p yas-also-auto-indent-first-line))
3892 (while (and (zerop (if indent-first-line-p
3895 (setq indent-first-line-p nil))
3899 (yas--indent-according-to-mode snippet-markers))))
3903 (defun yas--collect-snippet-markers (snippet)
3904 "Make a list of all the markers used by SNIPPET."
3906 (dolist (field (yas--snippet-fields snippet))
3907 (push (yas--field-start field) markers)
3908 (push (yas--field-end field) markers)
3909 (dolist (mirror (yas--field-mirrors field))
3910 (push (yas--mirror-start mirror) markers)
3911 (push (yas--mirror-end mirror) markers)))
3912 (let ((snippet-exit (yas--snippet-exit snippet)))
3913 (when (and snippet-exit
3914 (marker-buffer (yas--exit-marker snippet-exit)))
3915 (push (yas--exit-marker snippet-exit) markers)))
3918 (defun yas--real-line-beginning ()
3919 (let ((c (char-after (line-beginning-position)))
3920 (n (line-beginning-position)))
3921 (while (or (eql c ?\ )
3924 (setq c (char-after n)))
3927 (defun yas--escape-string (escaped)
3928 (concat "YASESCAPE" (format "%d" escaped) "PROTECTGUARD"))
3930 (defun yas--protect-escapes (&optional text escaped)
3931 "Protect all escaped characters with their numeric ASCII value.
3933 With optional string TEXT do it in string instead of buffer."
3934 (let ((changed-text text)
3935 (text-provided-p text))
3936 (mapc #'(lambda (escaped)
3938 (yas--replace-all (concat "\\" (char-to-string escaped))
3939 (yas--escape-string escaped)
3940 (when text-provided-p changed-text))))
3941 (or escaped yas--escaped-characters))
3944 (defun yas--restore-escapes (&optional text escaped)
3945 "Restore all escaped characters from their numeric ASCII value.
3947 With optional string TEXT do it in string instead of the buffer."
3948 (let ((changed-text text)
3949 (text-provided-p text))
3950 (mapc #'(lambda (escaped)
3952 (yas--replace-all (yas--escape-string escaped)
3953 (char-to-string escaped)
3954 (when text-provided-p changed-text))))
3955 (or escaped yas--escaped-characters))
3958 (defun yas--save-backquotes ()
3959 "Save all the \"`(lisp-expression)`\"-style expression
3960 with their evaluated value into `yas--backquote-markers-and-strings'"
3961 (while (re-search-forward yas--backquote-lisp-expression-regexp nil t)
3962 (let ((current-string (match-string-no-properties 1)) transformed)
3963 (delete-region (match-beginning 0) (match-end 0))
3964 (setq transformed (yas--eval-lisp (yas--read-lisp (yas--restore-escapes current-string '(?`)))))
3965 (goto-char (match-beginning 0))
3967 (let ((marker (make-marker)))
3968 (insert "Y") ;; quite horrendous, I love it :)
3969 (set-marker marker (point))
3971 (push (cons marker transformed) yas--backquote-markers-and-strings))))))
3973 (defun yas--restore-backquotes ()
3974 "Replace all the markers in
3975 `yas--backquote-markers-and-strings' with their values"
3976 (while yas--backquote-markers-and-strings
3977 (let* ((marker-and-string (pop yas--backquote-markers-and-strings))
3978 (marker (car marker-and-string))
3979 (string (cdr marker-and-string)))
3985 (set-marker marker nil)))))
3987 (defun yas--scan-sexps (from count)
3989 (with-syntax-table (standard-syntax-table)
3990 (scan-sexps from count))
3994 (defun yas--make-marker (pos)
3995 "Create a marker at POS with `nil' `marker-insertion-type'"
3996 (let ((marker (set-marker (make-marker) pos)))
3997 (set-marker-insertion-type marker nil)
4000 (defun yas--field-parse-create (snippet &optional parent-field)
4001 "Parse most field expressions, except for the simple one \"$n\".
4003 The following count as a field:
4005 * \"${n: text}\", for a numbered field with default text, as long as N is not 0;
4007 * \"${n: text$(expression)}, the same with a lisp expression;
4008 this is caught with the curiously named `yas--multi-dollar-lisp-expression-regexp'
4010 * the same as above but unnumbered, (no N:) and number is calculated automatically.
4012 When multiple expressions are found, only the last one counts."
4015 (while (re-search-forward yas--field-regexp nil t)
4016 (let* ((real-match-end-0 (yas--scan-sexps (1+ (match-beginning 0)) 1))
4017 (number (and (match-string-no-properties 1)
4018 (string-to-number (match-string-no-properties 1))))
4019 (brand-new-field (and real-match-end-0
4020 ;; break if on "$(" immediately
4021 ;; after the ":", this will be
4022 ;; caught as a mirror with
4024 (not (save-match-data
4025 (eq (string-match "$[ \t\n]*("
4026 (match-string-no-properties 2)) 0)))
4027 ;; allow ${0: some exit text}
4028 ;; (not (and number (zerop number)))
4029 (yas--make-field number
4030 (yas--make-marker (match-beginning 2))
4031 (yas--make-marker (1- real-match-end-0))
4033 (when brand-new-field
4034 (goto-char real-match-end-0)
4035 (push (cons (1- real-match-end-0) real-match-end-0)
4036 yas--dollar-regions)
4037 (push (cons (match-beginning 0) (match-beginning 2))
4038 yas--dollar-regions)
4039 (push brand-new-field (yas--snippet-fields snippet))
4042 (narrow-to-region (yas--field-start brand-new-field) (yas--field-end brand-new-field))
4043 (goto-char (point-min))
4044 (yas--field-parse-create snippet brand-new-field)))))))
4045 ;; if we entered from a parent field, now search for the
4046 ;; `yas--multi-dollar-lisp-expression-regexp'. THis is used for
4047 ;; primary field transformations
4051 (while (re-search-forward yas--multi-dollar-lisp-expression-regexp nil t)
4052 (let* ((real-match-end-1 (yas--scan-sexps (match-beginning 1) 1)))
4053 ;; commit the primary field transformation if:
4055 ;; 1. we don't find it in yas--dollar-regions (a subnested
4056 ;; field) might have already caught it.
4058 ;; 2. we really make sure we have either two '$' or some
4059 ;; text and a '$' after the colon ':'. This is a FIXME: work
4060 ;; my regular expressions and end these ugly hacks.
4062 (when (and real-match-end-1
4063 (not (member (cons (match-beginning 0)
4065 yas--dollar-regions))
4067 (char-before (1- (match-beginning 1))))))
4068 (let ((lisp-expression-string (buffer-substring-no-properties (match-beginning 1)
4070 (setf (yas--field-transform parent-field)
4071 (yas--read-lisp (yas--restore-escapes lisp-expression-string))))
4072 (push (cons (match-beginning 0) real-match-end-1)
4073 yas--dollar-regions)))))))
4075 (defun yas--transform-mirror-parse-create (snippet)
4076 "Parse the \"${n:$(lisp-expression)}\" mirror transformations."
4077 (while (re-search-forward yas--transform-mirror-regexp nil t)
4078 (let* ((real-match-end-0 (yas--scan-sexps (1+ (match-beginning 0)) 1))
4079 (number (string-to-number (match-string-no-properties 1)))
4081 (not (zerop number))
4082 (yas--snippet-find-field snippet number)))
4084 (and real-match-end-0
4086 (yas--make-mirror (yas--make-marker (match-beginning 0))
4087 (yas--make-marker (match-beginning 0))
4089 (yas--restore-escapes
4090 (buffer-substring-no-properties (match-beginning 2)
4091 (1- real-match-end-0))))))))
4092 (when brand-new-mirror
4093 (push brand-new-mirror
4094 (yas--field-mirrors field))
4095 (yas--calculate-mirrors-in-fields snippet brand-new-mirror)
4096 (push (cons (match-beginning 0) real-match-end-0) yas--dollar-regions)))))
4098 (defun yas--simple-mirror-parse-create (snippet)
4099 "Parse the simple \"$n\" fields/mirrors/exitmarkers."
4100 (while (re-search-forward yas--simple-mirror-regexp nil t)
4101 (let ((number (string-to-number (match-string-no-properties 1))))
4102 (cond ((zerop number)
4104 (setf (yas--snippet-exit snippet)
4105 (yas--make-exit (yas--make-marker (match-end 0))))
4107 (goto-char (match-beginning 0))
4108 (when yas-wrap-around-region
4109 (cond (yas-selected-text
4110 (insert yas-selected-text))
4111 ((and (eq yas-wrap-around-region 'cua)
4114 (insert (prog1 (get-register ?0)
4115 (set-register ?0 nil))))))
4116 (push (cons (point) (yas--exit-marker (yas--snippet-exit snippet)))
4117 yas--dollar-regions)))
4119 (let ((field (yas--snippet-find-field snippet number)))
4121 (let ((brand-new-mirror (yas--make-mirror
4122 (yas--make-marker (match-beginning 0))
4123 (yas--make-marker (match-beginning 0))
4125 (push brand-new-mirror
4126 (yas--field-mirrors field))
4127 (yas--calculate-mirrors-in-fields snippet brand-new-mirror))
4128 (push (yas--make-field number
4129 (yas--make-marker (match-beginning 0))
4130 (yas--make-marker (match-beginning 0))
4132 (yas--snippet-fields snippet))))
4133 (push (cons (match-beginning 0) (match-end 0))
4134 yas--dollar-regions))))))
4136 (defun yas--delete-regions (regions)
4137 "Sort disjuct REGIONS by start point, then delete from the back."
4138 (mapc #'(lambda (reg)
4139 (delete-region (car reg) (cdr reg)))
4142 (>= (car r1) (car r2))))))
4144 (defun yas--update-mirrors (snippet)
4145 "Updates all the mirrors of SNIPPET."
4147 (dolist (field-and-mirror (sort
4148 ;; make a list of ((F1 . M1) (F1 . M2) (F2 . M3) (F2 . M4) ...)
4149 ;; where F is the field that M is mirroring
4151 (mapcan #'(lambda (field)
4152 (mapcar #'(lambda (mirror)
4153 (cons field mirror))
4154 (yas--field-mirrors field)))
4155 (yas--snippet-fields snippet))
4156 ;; then sort this list so that entries with mirrors with parent
4157 ;; fields appear before. This was important for fixing #290, and
4158 ;; luckily also handles the case where a mirror in a field causes
4159 ;; another mirror to need reupdating
4161 #'(lambda (field-and-mirror1 field-and-mirror2)
4162 (yas--mirror-parent-field (cdr field-and-mirror1)))))
4163 (let* ((field (car field-and-mirror))
4164 (mirror (cdr field-and-mirror))
4165 (parent-field (yas--mirror-parent-field mirror)))
4166 ;; before updating a mirror with a parent-field, maybe advance
4170 (yas--advance-start-maybe mirror (yas--fom-start parent-field)))
4171 ;; update this mirror
4173 (yas--mirror-update-display mirror field)
4174 ;; `yas--place-overlays' is needed if the active field and
4175 ;; protected overlays have been changed because of insertions
4176 ;; in `yas--mirror-update-display'
4178 (when (eq field (yas--snippet-active-field snippet))
4179 (yas--place-overlays snippet field))))))
4181 (defun yas--mirror-update-display (mirror field)
4182 "Update MIRROR according to FIELD (and mirror transform)."
4184 (let* ((mirror-parent-field (yas--mirror-parent-field mirror))
4185 (reflection (and (not (and mirror-parent-field
4186 (yas--field-modified-p mirror-parent-field)))
4187 (or (yas--apply-transform mirror field 'empty-on-nil)
4188 (yas--field-text-for-display field)))))
4189 (when (and reflection
4190 (not (string= reflection (buffer-substring-no-properties (yas--mirror-start mirror)
4191 (yas--mirror-end mirror)))))
4192 (goto-char (yas--mirror-start mirror))
4193 (yas--inhibit-overlay-hooks
4194 (insert reflection))
4195 (if (> (yas--mirror-end mirror) (point))
4196 (delete-region (point) (yas--mirror-end mirror))
4197 (set-marker (yas--mirror-end mirror) (point))
4198 (yas--advance-start-maybe (yas--mirror-next mirror) (point))
4199 ;; super-special advance
4200 (yas--advance-end-of-parents-maybe mirror-parent-field (point))))))
4202 (defun yas--field-update-display (field snippet)
4203 "Much like `yas--mirror-update-display', but for fields"
4204 (when (yas--field-transform field)
4205 (let ((transformed (and (not (eq (yas--field-number field) 0))
4206 (yas--apply-transform field field)))
4208 (when (and transformed
4209 (not (string= transformed (buffer-substring-no-properties (yas--field-start field)
4210 (yas--field-end field)))))
4211 (setf (yas--field-modified-p field) t)
4212 (goto-char (yas--field-start field))
4213 (yas--inhibit-overlay-hooks
4214 (insert transformed)
4215 (if (> (yas--field-end field) (point))
4216 (delete-region (point) (yas--field-end field))
4217 (set-marker (yas--field-end field) (point))
4218 (yas--advance-start-maybe (yas--field-next field) (point)))
4222 ;;; Post-command hook:
4224 (defun yas--post-command-handler ()
4225 "Handles various yasnippet conditions after each command."
4226 (cond (yas--protection-violation
4227 (goto-char yas--protection-violation)
4228 (setq yas--protection-violation nil))
4229 ((eq 'undo this-command)
4231 ;; After undo revival the correct field is sometimes not
4232 ;; restored correctly, this condition handles that
4234 (let* ((snippet (car (yas--snippets-at-point)))
4235 (target-field (and snippet
4236 (find-if-not #'(lambda (field)
4237 (yas--field-probably-deleted-p snippet field))
4239 (cons (yas--snippet-active-field snippet)
4240 (yas--snippet-fields snippet)))))))
4242 (yas--move-to-field snippet target-field))))
4243 ((not (yas--undo-in-progress))
4244 ;; When not in an undo, check if we must commit the snippet
4245 ;; (user exited it).
4246 (yas--check-commit-snippet))))
4250 ;; The docstrings for some functions are generated dynamically
4251 ;; depending on the context.
4253 (put 'yas-expand 'function-documentation
4254 '(yas--expand-from-trigger-key-doc))
4255 (defun yas--expand-from-trigger-key-doc ()
4256 "A doc synthethizer for `yas--expand-from-trigger-key-doc'."
4257 (let ((fallback-description
4258 (cond ((eq yas-fallback-behavior 'call-other-command)
4259 (let* ((yas-minor-mode nil)
4260 (fallback (key-binding (read-kbd-macro (yas--trigger-key-for-fallback)))))
4262 (format " call command `%s'." (pp-to-string fallback)))
4264 ((eq yas-fallback-behavior 'return-nil)
4267 ", defer to `yas--fallback-behaviour' :-)"))))
4268 (concat "Expand a snippet before point. If no snippet
4269 expansion is possible,"
4270 fallback-description
4271 "\n\nOptional argument FIELD is for non-interactive use and is an
4272 object satisfying `yas--field-p' to restrict the expansion to.")))
4274 (put 'yas-expand-from-keymap 'function-documentation '(yas--expand-from-keymap-doc))
4275 (defun yas--expand-from-keymap-doc ()
4276 "A doc synthethizer for `yas--expand-from-keymap-doc'."
4277 (add-hook 'temp-buffer-show-hook 'yas--snippet-description-finish-runonce)
4278 (concat "Expand/run snippets from keymaps, possibly falling back to original binding.\n"
4279 (when (eq this-command 'describe-key)
4280 (let* ((vec (this-single-command-keys))
4281 (templates (mapcan #'(lambda (table)
4282 (yas--fetch table vec))
4283 (yas--get-snippet-tables)))
4284 (yas--direct-keymaps nil)
4285 (fallback (key-binding vec)))
4286 (concat "In this case, "
4288 (concat "these snippets are bound to this key:\n"
4289 (yas--template-pretty-list templates)
4290 "\n\nIf none of these expands, "))
4292 (format "fallback `%s' will be called." (pp-to-string fallback)))
4293 "no fallback keybinding is called."))))))
4295 (defun yas--template-pretty-list (templates)
4297 (yas-buffer-local-condition 'always))
4298 (dolist (plate templates)
4299 (setq acc (concat acc "\n*) "
4300 (propertize (concat "\\\\snippet `" (car plate) "'")
4301 'yasnippet (cdr plate)))))
4304 (define-button-type 'help-snippet-def
4305 :supertype 'help-xref
4306 'help-function (lambda (template) (yas--visit-snippet-file-1 template))
4307 'help-echo (purecopy "mouse-2, RET: find snippets's definition"))
4309 (defun yas--snippet-description-finish-runonce ()
4310 "Final adjustments for the help buffer when snippets are concerned."
4311 (yas--create-snippet-xrefs)
4312 (remove-hook 'temp-buffer-show-hook 'yas--snippet-description-finish-runonce))
4314 (defun yas--create-snippet-xrefs ()
4316 (goto-char (point-min))
4317 (while (search-forward-regexp "\\\\\\\\snippet[ \s\t]+`\\([^']+\\)'" nil t)
4318 (let ((template (get-text-property (match-beginning 1)
4321 (help-xref-button 1 'help-snippet-def template)
4322 (kill-region (match-end 1) (match-end 0))
4323 (kill-region (match-beginning 0) (match-beginning 1)))))))
4325 (defun yas--expand-uuid (mode-symbol uuid &optional start end expand-env)
4326 "Expand a snippet registered in MODE-SYMBOL's table with UUID.
4328 Remaining args as in `yas-expand-snippet'."
4329 (let* ((table (gethash mode-symbol yas--tables))
4330 (yas--current-template (and table
4331 (gethash uuid (yas--table-uuidhash table)))))
4332 (when yas--current-template
4333 (yas-expand-snippet (yas--template-content yas--current-template)))))
4337 (defvar yas-verbosity 4
4338 "Log level for `yas--message' 4 means trace most anything, 0 means nothing.")
4340 (defun yas--message (level message &rest args)
4341 (when (> yas-verbosity level)
4342 (message (apply #'yas--format message args))))
4344 (defun yas--format (format-control &rest format-args)
4345 (apply #'format (concat "[yas] " format-control) format-args))
4352 ;; `locate-dominating-file'
4353 ;; `region-active-p'
4355 ;; added for compatibility in emacsen < 23
4356 (unless (>= emacs-major-version 23)
4357 (unless (fboundp 'region-active-p)
4358 (defun region-active-p () (and transient-mark-mode mark-active)))
4360 (unless (fboundp 'locate-dominating-file)
4361 (defvar locate-dominating-stop-dir-regexp
4362 "\\`\\(?:[\\/][\\/][^\\/]+[\\/]\\|/\\(?:net\\|afs\\|\\.\\.\\.\\)/\\)\\'"
4363 "Regexp of directory names which stop the search in `locate-dominating-file'.
4364 Any directory whose name matches this regexp will be treated like
4365 a kind of root directory by `locate-dominating-file' which will stop its search
4366 when it bumps into it.
4367 The default regexp prevents fruitless and time-consuming attempts to find
4368 special files in directories in which filenames are interpreted as hostnames,
4369 or mount points potentially requiring authentication as a different user.")
4371 (defun locate-dominating-file (file name)
4372 "Look up the directory hierarchy from FILE for a file named NAME.
4373 Stop at the first parent directory containing a file NAME,
4374 and return the directory. Return nil if not found."
4375 ;; We used to use the above locate-dominating-files code, but the
4376 ;; directory-files call is very costly, so we're much better off doing
4377 ;; multiple calls using the code in here.
4379 ;; Represent /home/luser/foo as ~/foo so that we don't try to look for
4380 ;; `name' in /home or in /.
4381 (setq file (abbreviate-file-name file))
4384 ;; `user' is not initialized outside the loop because
4385 ;; `file' may not exist, so we may have to walk up part of the
4386 ;; hierarchy before we find the "initial UUID".
4389 (while (not (or root
4391 ;; FIXME: Disabled this heuristic because it is sometimes
4393 ;; As a heuristic, we stop looking up the hierarchy of
4394 ;; directories as soon as we find a directory belonging
4395 ;; to another user. This should save us from looking in
4396 ;; things like /net and /afs. This assumes that all the
4397 ;; files inside a project belong to the same user.
4398 ;; (let ((prev-user user))
4399 ;; (setq user (nth 2 (file-attributes file)))
4400 ;; (and prev-user (not (equal user prev-user))))
4401 (string-match locate-dominating-stop-dir-regexp file)))
4402 (setq try (file-exists-p (expand-file-name name file)))
4403 (cond (try (setq root file))
4404 ((equal file (setq prev-file file
4405 file (file-name-directory
4406 (directory-file-name file))))
4410 ;; `c-neutralize-syntax-in-CPP` sometimes fires "End of Buffer" error
4411 ;; (when it execute forward-char) and interrupt the after change
4412 ;; hook. Thus prevent the insert-behind hook of yasnippet to be
4413 ;; invoked. Here's a way to reproduce it:
4415 ;; # open a *new* Emacs.
4416 ;; # load yasnippet.
4417 ;; # open a *new* .cpp file.
4418 ;; # input "inc" and press TAB to expand the snippet.
4419 ;; # select the `#include <...>` snippet.
4420 ;; # type inside `<>`
4422 (defadvice c-neutralize-syntax-in-CPP
4423 (around yas--mp/c-neutralize-syntax-in-CPP activate)
4424 "Adviced `c-neutralize-syntax-in-CPP' to properly
4425 handle the end-of-buffer error fired in it by calling
4426 `forward-char' at the end of buffer."
4429 (error (message (error-message-string err)))))
4431 ;; disable c-electric-* serial command in YAS fields
4432 (add-hook 'c-mode-common-hook
4434 (dolist (k '(":" ">" ";" "<" "{" "}"))
4435 (define-key (symbol-value (make-local-variable 'yas-keymap))
4436 k 'self-insert-command))))
4438 ;;; Backward compatibility to to yasnippet <= 0.7
4439 (defvar yas--exported-syms '(;; `defcustom's
4442 yas-prompt-functions
4444 yas-also-auto-indent-first-line
4449 yas-skip-and-clear-key
4450 yas-triggers-in-field
4451 yas-fallback-behavior
4452 yas-choose-keys-first
4453 yas-choose-tables-first
4456 yas-wrap-around-region
4459 yas-expand-only-for-last-commands
4460 yas-field-highlight-face
4462 ;; these vars can be customized as well
4468 yas-after-exit-snippet-hook
4469 yas-before-expand-snippet-hook
4470 yas-buffer-local-condition
4472 ;; prompting functions
4477 yas-completing-prompt
4480 ;; interactive functions
4485 yas-direct-keymaps-reload
4489 yas-compile-directory
4492 yas-expand-from-trigger-key
4493 yas-expand-from-keymap
4495 yas-visit-snippet-file
4497 yas-load-snippet-buffer
4500 yas-next-field-or-maybe-expand
4505 yas-exit-all-snippets
4506 yas-skip-and-clear-or-delete-char
4508 ;; symbols that I "exported" for use
4509 ;; in snippets and hookage
4527 yas-default-from-field
4530 yas-define-condition-cache
4531 yas-hippie-try-expand
4534 ;; debug definitions
4535 ;; yas-debug-snippet-vars
4536 ;; yas-exterminate-package
4539 ;; testing definitions
4540 ;; yas-should-expand
4541 ;; yas-should-not-expand
4543 ;; yas-make-file-or-dirs
4545 ;; yas-saving-variables
4546 ;; yas-call-with-snippet-dirs
4547 ;; yas-with-snippet-dirs
4549 "Exported yassnippet symbols.
4551 i.e. ones that I will try to keep in future yasnippet versions
4552 and ones that other elisp libraries can more or less safely rely
4555 (defvar yas--dont-backport '(yas-active-keys)
4556 "Exported symbols that don't map back to \"yas/*\" variants")
4558 (dolist (sym (set-difference yas--exported-syms yas--dont-backport))
4559 (let ((backported (intern (replace-regexp-in-string "^yas-" "yas/" (symbol-name sym)))))
4561 (make-obsolete-variable backported sym "yasnippet 0.8")
4562 (defvaralias backported sym))
4564 (make-obsolete backported sym "yasnippet 0.8")
4565 (defalias backported sym))))
4568 (provide 'yasnippet)
4570 ;;; yasnippet.el ends here