1 ;;; yasnippet.el --- Yet another snippet extension for Emacs.
3 ;; Copyright (C) 2008-2012 Free Software Foundation, Inc.
4 ;; Authors: pluskid <pluskid@gmail.com>, João Távora <joaotavora@gmail.com>
6 ;; Package-version: 0.8.0
7 ;; X-URL: http://github.com/capitaomorte/yasnippet
8 ;; Keywords: convenience, emulation
9 ;; URL: http://github.com/capitaomorte/yasnippet
10 ;; EmacsWiki: YaSnippetMode
12 ;; This program is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; This program is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
27 ;; Basic steps to setup:
29 ;; (add-to-list 'load-path
30 ;; "~/path-to-yasnippet")
31 ;; (require 'yasnippet)
32 ;; (yas-global-mode 1)
35 ;; Interesting variables are:
39 ;; The directory where user-created snippets are to be
40 ;; stored. Can also be a list of directories. In that case,
41 ;; when used for bulk (re)loading of snippets (at startup or
42 ;; via `yas-reload-all'), directories appearing earlier in
43 ;; the list shadow other dir's snippets. Also, the first
44 ;; directory is taken as the default for storing the user's
47 ;; The deprecated `yas/root-directory' aliases this variable
48 ;; for backward-compatibility.
52 ;; A local variable that you can set in a hook to override
53 ;; snippet-lookup based on major mode. It is a symbol (or
54 ;; list of symbols) that correspond to subdirectories of
55 ;; `yas-snippet-dirs' and is used for deciding which
56 ;; snippets to consider for the active buffer.
58 ;; Deprecated `yas/mode-symbol' aliases this variable for
59 ;; backward-compatibility.
61 ;; Major commands are:
65 ;; Try to expand snippets before point. In `yas-minor-mode',
66 ;; this is normally bound to TAB, but you can customize it in
67 ;; `yas-minor-mode-map'.
69 ;; M-x yas-load-directory
71 ;; Prompts you for a directory hierarchy of snippets to load.
73 ;; M-x yas-insert-snippet
75 ;; Prompts you for possible snippet expansion if that is
76 ;; possible according to buffer-local and snippet-local
77 ;; expansion conditions. With prefix argument, ignore these
80 ;; M-x yas-visit-snippet-file
82 ;; Prompts you for possible snippet expansions like
83 ;; `yas-insert-snippet', but instead of expanding it, takes
84 ;; you directly to the snippet definition's file, if it
87 ;; M-x yas-new-snippet
89 ;; Lets you create a new snippet file in the correct
90 ;; subdirectory of `yas-snippet-dirs', according to the
93 ;; M-x yas-load-snippet-buffer
95 ;; When editing a snippet, this loads the snippet. This is
96 ;; bound to "C-c C-c" while in the `snippet-mode' editing
99 ;; M-x yas-tryout-snippet
101 ;; When editing a snippet, this opens a new empty buffer,
102 ;; sets it to the appropriate major mode and inserts the
103 ;; snippet there, so you can see what it looks like. This is
104 ;; bound to "C-c C-t" while in `snippet-mode'.
106 ;; M-x yas-describe-tables
108 ;; Lists known snippets in a separate buffer. User is
109 ;; prompted as to whether only the currently active tables
110 ;; are to be displayed, or all the tables for all major
113 ;; The `dropdown-list.el' extension is bundled with YASnippet, you
114 ;; can optionally use it the preferred "prompting method", putting in
115 ;; your .emacs file, for example:
117 ;; (require 'dropdown-list)
118 ;; (setq yas-prompt-functions '(yas-dropdown-prompt
120 ;; yas-completing-prompt))
122 ;; Also check out the customization group
124 ;; M-x customize-group RET yasnippet RET
126 ;; If you use the customization group to set variables
127 ;; `yas-snippet-dirs' or `yas-global-mode', make sure the path to
128 ;; "yasnippet.el" is present in the `load-path' *before* the
129 ;; `custom-set-variables' is executed in your .emacs file.
131 ;; For more information and detailed usage, refer to the project page:
132 ;; http://github.com/capitaomorte/yasnippet
142 (defvar yas--editing-template)
143 (defvar yas--guessed-modes)
144 (defvar yas--indent-original-column)
145 (defvar yas--scheduled-jit-loads)
147 (defvar yas-selected-text)
148 (defvar yas-verbosity))
150 ;; Future-proof against obsoleting flet, see github #324
153 (unless (fboundp 'cl-flet)
154 (defalias 'cl-flet 'flet)
155 (put 'cl-flet 'lisp-indent-function 1)
156 (put 'cl-flet 'edebug-form-spec '((&rest (defun*)) cl-declarations body))))
159 ;;; User customizable variables
161 (defgroup yasnippet nil
162 "Yet Another Snippet extension"
165 (defvar yas--load-file-name load-file-name
166 "Store the filename that yasnippet.el was originally loaded from.")
168 (defcustom yas-snippet-dirs (remove nil
169 (list "~/.emacs.d/snippets"
170 (when yas--load-file-name
171 (concat (file-name-directory yas--load-file-name) "snippets"))))
172 "Directory or list of snippet dirs for each major mode.
174 The directory where user-created snippets are to be stored. Can
175 also be a list of directories. In that case, when used for
176 bulk (re)loading of snippets (at startup or via
177 `yas-reload-all'), directories appearing earlier in the list
178 shadow other dir's snippets. Also, the first directory is taken
179 as the default for storing the user's new snippets."
180 :type '(choice (string :tag "Single directory (string)")
181 (repeat :args (string) :tag "List of directories (strings)"))
184 :set #'(lambda (symbol new)
185 (let ((old (and (boundp symbol)
186 (symbol-value symbol))))
187 (set-default symbol new)
188 (unless (or (not (fboundp 'yas-reload-all))
192 (defun yas-snippet-dirs ()
193 "Returns `yas-snippet-dirs' (which see) as a list."
194 (if (listp yas-snippet-dirs) yas-snippet-dirs (list yas-snippet-dirs)))
196 (defvaralias 'yas/root-directory 'yas-snippet-dirs)
198 (defcustom yas-prompt-functions '(yas-x-prompt
200 yas-completing-prompt
203 "Functions to prompt for keys, templates, etc interactively.
205 These functions are called with the following arguments:
207 - PROMPT: A string to prompt the user
209 - CHOICES: a list of strings or objects.
211 - optional DISPLAY-FN : A function that, when applied to each of
212 the objects in CHOICES will return a string.
214 The return value of any function you put here should be one of
215 the objects in CHOICES, properly formatted with DISPLAY-FN (if
218 - To signal that your particular style of prompting is
219 unavailable at the moment, you can also have the function return
222 - To signal that the user quit the prompting process, you can
225 (signal 'quit \"user quit!\")."
226 :type '(repeat function)
229 (defcustom yas-indent-line 'auto
230 "Controls indenting applied to a recent snippet expansion.
232 The following values are possible:
234 - `fixed' Indent the snippet to the current column;
236 - `auto' Indent each line of the snippet with `indent-according-to-mode'
238 Every other value means don't apply any snippet-side indentation
239 after expansion (the manual per-line \"$>\" indentation still
241 :type '(choice (const :tag "Nothing" nothing)
242 (const :tag "Fixed" fixed)
243 (const :tag "Auto" auto))
246 (defcustom yas-also-auto-indent-first-line nil
247 "Non-nil means also auto indent first line according to mode.
249 Naturally this is only valid when `yas-indent-line' is `auto'"
253 (defcustom yas-snippet-revival t
254 "Non-nil means re-activate snippet fields after undo/redo."
258 (defcustom yas-triggers-in-field nil
259 "If non-nil, allow stacked expansions (snippets inside snippets).
261 Otherwise `yas-next-field-or-maybe-expand' just moves on to the
266 (defcustom yas-fallback-behavior 'call-other-command
267 "How to act when `yas-expand' does *not* expand a snippet.
269 - `call-other-command' means try to temporarily disable YASnippet
270 and call the next command bound to whatever key was used to
273 - nil or the symbol `return-nil' mean do nothing. (and
274 `yas-expand' returns nil)
276 - A Lisp form (apply COMMAND . ARGS) means interactively call
277 COMMAND, if ARGS is non-nil, call COMMAND non-interactively
278 with ARGS as arguments."
279 :type '(choice (const :tag "Call previous command" call-other-command)
280 (const :tag "Do nothing" return-nil))
283 (defcustom yas-choose-keys-first nil
284 "If non-nil, prompt for snippet key first, then for template.
286 Otherwise prompts for all possible snippet names.
288 This affects `yas-insert-snippet' and `yas-visit-snippet-file'."
292 (defcustom yas-choose-tables-first nil
293 "If non-nil, and multiple eligible snippet tables, prompts user for tables first.
295 Otherwise, user chooses between the merging together of all
298 This affects `yas-insert-snippet', `yas-visit-snippet-file'"
302 (defcustom yas-use-menu 'abbreviate
303 "Display a YASnippet menu in the menu bar.
305 When non-nil, submenus for each snippet table will be listed
306 under the menu \"Yasnippet\".
308 - If set to `abbreviate', only the current major-mode
309 menu and the modes set in `yas-extra-modes' are listed.
311 - If set to `full', every submenu is listed
313 - It set to nil, don't display a menu at all (this requires a
314 `yas-reload-all' call if the menu is already visible).
316 Any other non-nil value, every submenu is listed."
317 :type '(choice (const :tag "Full" full)
318 (const :tag "Abbreviate" abbreviate)
319 (const :tag "No menu" nil))
322 (defcustom yas-trigger-symbol (if (eq window-system 'mac)
323 (char-to-string ?\x21E5) ;; little ->| sign
325 "The text that will be used in menu to represent the trigger."
329 (defcustom yas-wrap-around-region nil
330 "If non-nil, snippet expansion wraps around selected region.
332 The wrapping occurs just before the snippet's exit marker. This
333 can be overridden on a per-snippet basis."
337 (defcustom yas-good-grace t
338 "If non-nil, don't raise errors in inline elisp evaluation.
340 An error string \"[yas] error\" is returned instead."
344 (defcustom yas-visit-from-menu nil
345 "If non-nil visit snippets's files from menu, instead of expanding them.
347 This can only work when snippets are loaded from files."
351 (defcustom yas-expand-only-for-last-commands nil
352 "List of `last-command' values to restrict tab-triggering to, or nil.
354 Leave this set at nil (the default) to be able to trigger an
355 expansion simply by placing the cursor after a valid tab trigger,
356 using whichever commands.
358 Optionally, set this to something like '(self-insert-command) if
359 you to wish restrict expansion to only happen when the last
360 letter of the snippet tab trigger was typed immediately before
361 the trigger key itself."
362 :type '(repeat function)
365 ;; Only two faces, and one of them shouldn't even be used...
367 (defface yas-field-highlight-face
368 '((t (:inherit 'region)))
369 "The face used to highlight the currently active field of a snippet"
372 (defface yas--field-debug-face
374 "The face used for debugging some overlays normally hidden"
378 (defvar yas-keymap (let ((map (make-sparse-keymap)))
379 (define-key map [(tab)] 'yas-next-field-or-maybe-expand)
380 (define-key map (kbd "TAB") 'yas-next-field-or-maybe-expand)
381 (define-key map [(shift tab)] 'yas-prev-field)
382 (define-key map [backtab] 'yas-prev-field)
383 (define-key map (kbd "C-g") 'yas-abort-snippet)
384 (define-key map (kbd "C-d") 'yas-skip-and-clear-or-delete-char)
386 "The active keymap while a snippet expansion is in progress.")
388 (defvar yas-key-syntaxes (list "w" "w_" "w_." "w_.()" "^ ")
389 "List of character syntaxes used to find a trigger key before point.
390 The list is tried in the order while scanning characters
391 backwards from point. For example, if the list is '(\"w\" \"w_\")
392 first look for trigger keys which are composed exclusively of
393 \"word\"-syntax characters, and then, if that fails, look for
394 keys which are either of \"word\" or \"symbol\"
395 syntax. Triggering after
399 will, according to the \"w\" element first try \"bar\". If that
400 isn't a trigger key, \"foo-bar\" is tried, respecting a second
403 (defvar yas-after-exit-snippet-hook
405 "Hooks to run after a snippet exited.
407 The hooks will be run in an environment where some variables bound to
410 `yas-snippet-beg' : The beginning of the region of the snippet.
412 `yas-snippet-end' : Similar to beg.
414 Attention: These hooks are not run when exiting nested/stacked snippet expansion!")
416 (defvar yas-before-expand-snippet-hook
418 "Hooks to run just before expanding a snippet.")
420 (defvar yas-buffer-local-condition
421 '(if (and (or (fourth (syntax-ppss))
422 (fifth (syntax-ppss)))
423 (eq (symbol-function this-command) 'yas-expand-from-trigger-key))
424 '(require-snippet-condition . force-in-comment)
426 "Snippet expanding condition.
428 This variable is a Lisp form which is evaluated every time a
429 snippet expansion is attempted:
431 * If it evaluates to nil, no snippets can be expanded.
433 * If it evaluates to the a cons (require-snippet-condition
436 * Snippets bearing no \"# condition:\" directive are not
439 * Snippets bearing conditions that evaluate to nil (or
440 produce an error) won't be considered.
442 * If the snippet has a condition that evaluates to non-nil
445 * If REQUIREMENT is t, the snippet is considered
447 * If REQUIREMENT is `eq' RESULT, the snippet is
450 * Otherwise, the snippet is not considered.
452 * If it evaluates to the symbol 'always, all snippets are
453 considered for expansion, regardless of any conditions.
455 * If it evaluates to t or some other non-nil value
457 * Snippet bearing no conditions, or conditions that
458 evaluate to non-nil, are considered for expansion.
460 * Otherwise, the snippet is not considered.
462 Here's an example preventing snippets from being expanded from
463 inside comments, in `python-mode' only, with the exception of
464 snippets returning the symbol 'force-in-comment in their
467 (add-hook 'python-mode-hook
469 (setq yas-buffer-local-condition
470 '(if (python-in-string/comment)
471 '(require-snippet-condition . force-in-comment)
474 The default value is similar, it filters out potential snippet
475 expansions inside comments and string literals, unless the
476 snippet itself contains a condition that returns the symbol
477 `force-in-comment'.")
480 ;;; Internal variables
482 (defvar yas--version "0.8.0 (beta)")
484 (defvar yas--menu-table (make-hash-table)
485 "A hash table of MAJOR-MODE symbols to menu keymaps.")
487 (defvar yas--known-modes
488 '(ruby-mode rst-mode markdown-mode)
489 "A list of mode which is well known but not part of Emacs.")
491 (defvar yas--escaped-characters
492 '(?\\ ?` ?\" ?' ?$ ?} ?{ ?\( ?\))
493 "List of characters which *might* need to be escaped.")
495 (defconst yas--field-regexp
496 "${\\([0-9]+:\\)?\\([^}]*\\)}"
497 "A regexp to *almost* recognize a field.")
499 (defconst yas--multi-dollar-lisp-expression-regexp
500 "$+[ \t\n]*\\(([^)]*)\\)"
501 "A regexp to *almost* recognize a \"$(...)\" expression.")
503 (defconst yas--backquote-lisp-expression-regexp
505 "A regexp to recognize a \"`lisp-expression`\" expression." )
507 (defconst yas--transform-mirror-regexp
508 "${\\(?:\\([0-9]+\\):\\)?$\\([ \t\n]*([^}]*\\)"
509 "A regexp to *almost* recognize a mirror with a transform.")
511 (defconst yas--simple-mirror-regexp
513 "A regexp to recognize a simple mirror.")
515 (defvar yas--snippet-id-seed 0
516 "Contains the next id for a snippet.")
518 (defun yas--snippet-next-id ()
519 (let ((id yas--snippet-id-seed))
520 (incf yas--snippet-id-seed)
526 ;; XXX: `last-buffer-undo-list' is somehow needed in Carbon Emacs for MacOSX
527 (defvar last-buffer-undo-list nil)
529 (defvar yas--minor-mode-menu nil
530 "Holds the YASnippet menu.")
532 (defun yas--init-minor-keymap ()
533 "Set up the `yas-minor-mode' keymap."
534 (let ((map (make-sparse-keymap)))
536 (easy-menu-define yas--minor-mode-menu
538 "Menu used when `yas-minor-mode' is active."
541 ["Expand trigger" yas-expand
542 :help "Possibly expand tab trigger before point"]
543 ["Insert at point..." yas-insert-snippet
544 :help "Prompt for an expandable snippet and expand it at point"]
545 ["New snippet..." yas-new-snippet
546 :help "Create a new snippet in an appropriate directory"]
547 ["Visit snippet file..." yas-visit-snippet-file
548 :help "Prompt for an expandable snippet and find its file"]
550 ("Snippet menu behaviour"
551 ["Visit snippets" (setq yas-visit-from-menu t)
552 :help "Visit snippets from the menu"
553 :active t :style radio :selected yas-visit-from-menu]
554 ["Expand snippets" (setq yas-visit-from-menu nil)
555 :help "Expand snippets from the menu"
556 :active t :style radio :selected (not yas-visit-from-menu)]
558 ["Show all known modes" (setq yas-use-menu 'full)
559 :help "Show one snippet submenu for each loaded table"
560 :active t :style radio :selected (eq yas-use-menu 'full)]
561 ["Abbreviate according to current mode" (setq yas-use-menu 'abbreviate)
562 :help "Show only snippet submenus for the current active modes"
563 :active t :style radio :selected (eq yas-use-menu 'abbreviate)])
565 ["Auto" (setq yas-indent-line 'auto)
566 :help "Indent each line of the snippet with `indent-according-to-mode'"
567 :active t :style radio :selected (eq yas-indent-line 'auto)]
568 ["Fixed" (setq yas-indent-line 'fixed)
569 :help "Indent the snippet to the current column"
570 :active t :style radio :selected (eq yas-indent-line 'fixed)]
571 ["None" (setq yas-indent-line 'none)
572 :help "Don't apply any particular snippet indentation after expansion"
573 :active t :style radio :selected (not (member yas-indent-line '(fixed auto)))]
575 ["Also auto indent first line" (setq yas-also-auto-indent-first-line
576 (not yas-also-auto-indent-first-line))
577 :help "When auto-indenting also, auto indent the first line menu"
578 :active (eq yas-indent-line 'auto)
579 :style toggle :selected yas-also-auto-indent-first-line]
582 ["System X-widget" (setq yas-prompt-functions
584 (remove 'yas-x-prompt
585 yas-prompt-functions)))
586 :help "Use your windowing system's (gtk, mac, windows, etc...) default menu"
587 :active t :style radio :selected (eq (car yas-prompt-functions)
589 ["Dropdown-list" (setq yas-prompt-functions
590 (cons 'yas-dropdown-prompt
591 (remove 'yas-dropdown-prompt
592 yas-prompt-functions)))
593 :help "Use a special dropdown list"
594 :active t :style radio :selected (eq (car yas-prompt-functions)
595 'yas-dropdown-prompt)]
596 ["Ido" (setq yas-prompt-functions
597 (cons 'yas-ido-prompt
598 (remove 'yas-ido-prompt
599 yas-prompt-functions)))
600 :help "Use an ido-style minibuffer prompt"
601 :active t :style radio :selected (eq (car yas-prompt-functions)
603 ["Completing read" (setq yas-prompt-functions
604 (cons 'yas-completing-prompt
605 (remove 'yas-completing-prompt
606 yas-prompt-functions)))
607 :help "Use a normal minibuffer prompt"
608 :active t :style radio :selected (eq (car yas-prompt-functions)
609 'yas-completing-prompt)]
612 ["Wrap region in exit marker"
613 (setq yas-wrap-around-region
614 (not yas-wrap-around-region))
615 :help "If non-nil automatically wrap the selected text in the $0 snippet exit"
616 :style toggle :selected yas-wrap-around-region]
617 ["Allow stacked expansions "
618 (setq yas-triggers-in-field
619 (not yas-triggers-in-field))
620 :help "If non-nil allow snippets to be triggered inside other snippet fields"
621 :style toggle :selected yas-triggers-in-field]
622 ["Revive snippets on undo "
623 (setq yas-snippet-revival
624 (not yas-snippet-revival))
625 :help "If non-nil allow snippets to become active again after undo"
626 :style toggle :selected yas-snippet-revival]
629 (not yas-good-grace))
630 :help "If non-nil don't raise errors in bad embedded elisp in snippets"
631 :style toggle :selected yas-good-grace]
634 ["Load snippets..." yas-load-directory
635 :help "Load snippets from a specific directory"]
636 ["Reload everything" yas-reload-all
637 :help "Cleanup stuff, reload snippets, rebuild menus"]
639 :help "Display some information about YASnippet"])))
641 ;; Now for the stuff that has direct keybindings
643 (define-key map [(tab)] 'yas-expand)
644 (define-key map (kbd "TAB") 'yas-expand)
645 (define-key map "\C-c&\C-s" 'yas-insert-snippet)
646 (define-key map "\C-c&\C-n" 'yas-new-snippet)
647 (define-key map "\C-c&\C-v" 'yas-visit-snippet-file)
650 (defvar yas-minor-mode-map (yas--init-minor-keymap)
651 "The keymap used when `yas-minor-mode' is active.")
653 (defvar yas--tables (make-hash-table)
654 "A hash table of mode symbols to `yas--table' objects.")
656 (defvar yas--parents (make-hash-table)
657 "A hash table of mode symbols do lists of direct parent mode symbols.
659 This list is populated when reading the \".yas-parents\" files
660 found when traversing snippet directories with
661 `yas-load-directory'.
663 There might be additional parenting information stored in the
664 `derived-mode-parent' property of some mode symbols, but that is
667 (defvar yas--direct-keymaps (list)
668 "Keymap alist supporting direct snippet keybindings.
670 This variable is placed in `emulation-mode-map-alists'.
672 Its elements looks like (TABLE-NAME . KEYMAP). They're
673 instantiated on `yas-reload-all' but KEYMAP is added to only when
674 loading snippets. `yas--direct-TABLE-NAME' is then a variable set
675 buffer-locally when entering `yas-minor-mode'. KEYMAP binds all
676 defined direct keybindings to the command
677 `yas-expand-from-keymap' which then which snippet to expand.")
679 (defun yas-direct-keymaps-reload ()
680 "Force reload the direct keybinding for active snippet tables."
682 (setq yas--direct-keymaps nil)
683 (maphash #'(lambda (name table)
684 (push (cons (intern (format "yas--direct-%s" name))
685 (yas--table-direct-keymap table))
686 yas--direct-keymaps))
689 (defun yas--modes-to-activate ()
690 "Compute list of mode symbols that are active for `yas-expand'
692 (let ((modes-to-activate (list major-mode))
694 (while (setq mode (get mode 'derived-mode-parent))
695 (push mode modes-to-activate))
696 (dolist (mode (yas-extra-modes))
697 (push mode modes-to-activate))
699 (append modes-to-activate
700 (mapcan #'(lambda (mode)
701 (yas--all-parents mode))
702 modes-to-activate)))))
704 (defvar yas-minor-mode-hook nil
705 "Hook run when `yas-minor-mode' is turned on.")
708 (define-minor-mode yas-minor-mode
709 "Toggle YASnippet mode.
711 When YASnippet mode is enabled, `yas-expand', normally bound to
712 the TAB key, expands snippets of code depending on the major
715 With no argument, this command toggles the mode.
716 positive prefix argument turns on the mode.
717 Negative prefix argument turns off the mode.
720 \\{yas-minor-mode-map}"
722 ;; The indicator for the mode line.
725 (cond (yas-minor-mode
726 ;; Install the direct keymaps in `emulation-mode-map-alists'
727 ;; (we use `add-hook' even though it's not technically a hook,
728 ;; but it works). Then define variables named after modes to
729 ;; index `yas--direct-keymaps'.
731 ;; Also install the post-command-hook.
733 (add-hook 'emulation-mode-map-alists 'yas--direct-keymaps)
734 (add-hook 'post-command-hook 'yas--post-command-handler nil t)
735 ;; Set the `yas--direct-%s' vars for direct keymap expansion
737 (dolist (mode (yas--modes-to-activate))
738 (let ((name (intern (format "yas--direct-%s" mode))))
739 (set-default name nil)
740 (set (make-local-variable name) t)))
743 (yas--load-pending-jits))
745 ;; Uninstall the direct keymaps and the post-command hook
747 (remove-hook 'post-command-hook 'yas--post-command-handler t)
748 (remove-hook 'emulation-mode-map-alists 'yas--direct-keymaps))))
750 (defvar yas-dont-activate '(minibufferp)
751 "If non-nil don't let `yas-minor-mode-on' activate for this buffer.
753 If a function, then its result is used.
755 If a list of functions, then all functions must return nil to
756 activate yas for this buffer.
758 `yas-minor-mode-on' is usually called by `yas-global-mode' so
759 this effectively lets you define exceptions to the \"global\"
760 behaviour. Can also be a function of zero arguments.")
761 (make-variable-buffer-local 'yas-dont-activate)
763 (defun yas-minor-mode-on ()
764 "Turn on YASnippet minor mode.
766 Honour `yas-dont-activate', which see."
768 ;; Check `yas-dont-activate'
769 (unless (cond ((functionp yas-dont-activate)
770 (funcall yas-dont-activate))
771 ((consp yas-dont-activate)
772 (some #'funcall yas-dont-activate))
777 (define-globalized-minor-mode yas-global-mode yas-minor-mode yas-minor-mode-on
781 (defun yas--global-mode-reload-with-jit-maybe ()
782 "Run `yas-reload-all' when `yas-global-mode' is on."
783 (when yas-global-mode (yas-reload-all)))
785 (add-hook 'yas-global-mode-hook 'yas--global-mode-reload-with-jit-maybe)
787 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
790 (defvar yas--font-lock-keywords
791 (append '(("^#.*$" . font-lock-comment-face))
792 lisp-font-lock-keywords
793 lisp-font-lock-keywords-1
794 lisp-font-lock-keywords-2
796 (0 font-lock-keyword-face)
797 (1 font-lock-string-face t))
799 (0 font-lock-keyword-face)
800 (1 font-lock-warning-face t))
801 ("${" font-lock-keyword-face)
802 ("$[0-9]+?" font-lock-preprocessor-face)
803 ("\\(\\$(\\)" 1 font-lock-preprocessor-face)
805 (0 font-lock-keyword-face)))))
807 (defun yas--init-major-keymap ()
808 "Setup YASnippet major-mode keymap."
809 (let ((map (make-sparse-keymap)))
810 (easy-menu-define nil
812 "Menu used when snippet-mode is active."
814 (mapcar #'(lambda (ent)
816 (define-key map (third ent) (second ent)))
817 (vector (first ent) (second ent) t))
819 (list "Load this snippet" 'yas-load-snippet-buffer "\C-c\C-c")
820 (list "Try out this snippet" 'yas-tryout-snippet "\C-c\C-t")))))
823 (defvar snippet-mode-map
824 (yas--init-major-keymap)
825 "The keymap used when `snippet-mode' is active.")
828 (define-derived-mode snippet-mode text-mode "Snippet"
829 "A mode for editing yasnippets"
830 (setq font-lock-defaults '(yas--font-lock-keywords))
831 (set (make-local-variable 'require-final-newline) nil)
832 (set (make-local-variable 'comment-start) "#")
833 (set (make-local-variable 'comment-start-skip) "#+[\t ]*"))
837 ;;; Internal structs for template management
839 (defstruct (yas--template (:constructor yas--make-blank-template))
840 "A template for a snippet."
850 group ;; as dictated by the #group: directive or .yas-make-groups
851 perm-group ;; as dictated by `yas-define-menu'
855 (defun yas--populate-template (template &rest args)
856 "Helper function to populate TEMPLATE with properties."
860 (position (intern (substring (symbol-name (car args)) 1))
861 (mapcar #'car (get 'yas--template 'cl-struct-slots)))
863 (setq args (cddr args)))
866 (defstruct (yas--table (:constructor yas--make-snippet-table (name)))
867 "A table to store snippets for a particular mode.
869 Has the following fields:
873 A symbol name normally corresponding to a major mode, but can
874 also be a pseudo major-mode to be referenced in
875 `yas-extra-modes', for example.
879 A hash table (KEY . NAMEHASH), known as the \"keyhash\". KEY is
880 a string or a vector, where the former is the snippet's trigger
881 and the latter means it's a direct keybinding. NAMEHASH is yet
882 another hash of (NAME . TEMPLATE) where NAME is the snippet's
883 name and TEMPLATE is a `yas--template' object.
885 `yas--table-direct-keymap'
887 A keymap for the snippets in this table that have direct
888 keybindings. This is kept in sync with the keyhash, i.e., all
889 the elements of the keyhash that are vectors appear here as
890 bindings to `yas-expand-from-keymap'.
892 `yas--table-uuidhash'
894 A hash table mapping snippets uuid's to the same `yas--template'
895 objects. A snippet uuid defaults to the snippet's name.
898 (hash (make-hash-table :test 'equal))
899 (uuidhash (make-hash-table :test 'equal))
901 (direct-keymap (make-sparse-keymap)))
903 (defun yas--get-template-by-uuid (mode uuid)
904 "Find the snippet template in MODE by its UUID."
905 (let* ((table (gethash mode yas--tables mode)))
907 (gethash uuid (yas--table-uuidhash table)))))
909 ;; Apropos storing/updating in TABLE, this works in two steps:
911 ;; 1. `yas--remove-template-by-uuid' removes any
912 ;; keyhash-namehash-template mappings from TABLE, grabbing the
913 ;; snippet by its uuid. Also removes mappings from TABLE's
914 ;; `yas--table-direct-keymap' (FIXME: and should probably take care
915 ;; of potentially stale menu bindings right?.)
917 ;; 2. `yas--add-template' adds this all over again.
919 ;; Create a new or add to an existing keyhash-namehash mapping.
921 ;; For reference on understanding this, consider three snippet
924 ;; A: # name: The Foo
926 ;; # binding: C-c M-l
928 ;; B: # name: Mrs Foo
931 ;; C: # name: The Bar
932 ;; # binding: C-c M-l
937 ;; keyhash namehashes(3) yas--template structs(4)
938 ;; -----------------------------------------------------
941 ;; "foo" ---> "The Foo" ---> [yas--template A] |
942 ;; "Mrs Foo" ---> [yas--template B] |
944 ;; [C-c M-l] ---> "The Foo" -------------------------/
945 ;; "The Bar" ---> [yas--template C]
947 ;; "baz" ---> "Baz" ---> [yas--template D]
949 ;; Additionally, since uuid defaults to the name, we have a
950 ;; `yas--table-uuidhash' for TABLE
952 ;; uuidhash yas--template structs
953 ;; -------------------------------
954 ;; "The Foo" ---> [yas--template A]
955 ;; "Mrs Foo" ---> [yas--template B]
956 ;; "The Bar" ---> [yas--template C]
957 ;; "Baz" ---> [yas--template D]
959 ;; FIXME: the more I look at this data-structure the more I think I'm
960 ;; stupid. There has to be an easier way (but beware lots of code
963 (defun yas--remove-template-by-uuid (table uuid)
964 "Remove from TABLE a template identified by UUID."
965 (let ((template (gethash uuid (yas--table-uuidhash table))))
967 (let* ((name (yas--template-name template))
969 ;; Remove the name from each of the targeted namehashes
971 (maphash #'(lambda (k v)
972 (let ((template (gethash name v)))
974 (eq uuid (yas--template-uuid template)))
976 (when (zerop (hash-table-count v))
977 (push k empty-keys)))))
978 (yas--table-hash table))
979 ;; Remove the namehash themselves if they've become empty
981 (dolist (key empty-keys)
983 (define-key (yas--table-direct-keymap table) key nil))
984 (remhash key (yas--table-hash table)))
986 ;; Finally, remove the uuid from the uuidhash
988 (remhash uuid (yas--table-uuidhash table))))))
990 (defun yas--add-template (table template)
991 "Store in TABLE the snippet template TEMPLATE.
993 KEY can be a string (trigger key) of a vector (direct
995 (let ((name (yas--template-name template))
996 (key (yas--template-key template))
997 (keybinding (yas--template-keybinding template))
998 (menu-binding-pair (yas--template-menu-binding-pair-get-create template)))
999 (dolist (k (remove nil (list key keybinding)))
1003 (yas--table-hash table))
1005 (make-hash-table :test 'equal)
1006 (yas--table-hash table))))
1008 (define-key (yas--table-direct-keymap table) k 'yas-expand-from-keymap)))
1010 ;; Update TABLE's `yas--table-uuidhash'
1011 (puthash (yas--template-uuid template)
1013 (yas--table-uuidhash table))))
1015 (defun yas--update-template (table template)
1016 "Add or update TEMPLATE in TABLE.
1018 Also takes care of adding and updating to the associated menu."
1019 ;; Remove from table by uuid
1021 (yas--remove-template-by-uuid table (yas--template-uuid template))
1022 ;; Add to table again
1024 (yas--add-template table template)
1025 ;; Take care of the menu
1028 (yas--update-template-menu table template)))
1030 (defun yas--update-template-menu (table template)
1031 "Update every menu-related for TEMPLATE."
1032 (let ((menu-binding-pair (yas--template-menu-binding-pair-get-create template))
1033 (key (yas--template-key template))
1034 (keybinding (yas--template-keybinding template)))
1035 ;; The snippet might have changed name or keys, so update
1036 ;; user-visible strings
1038 (unless (eq (cdr menu-binding-pair) :none)
1039 ;; the menu item name
1041 (setf (cadar menu-binding-pair) (yas--template-name template))
1042 ;; the :keys information (also visible to the user)
1043 (setf (getf (cdr (car menu-binding-pair)) :keys)
1044 (or (and keybinding (key-description keybinding))
1045 (and key (concat key yas-trigger-symbol))))))
1046 (unless (yas--template-menu-managed-by-yas-define-menu template)
1048 (yas--menu-keymap-get-create (yas--table-mode table)
1049 (mapcar #'yas--table-mode
1050 (yas--table-parents table))))
1051 (group (yas--template-group template)))
1052 ;; Remove from menu keymap
1054 (assert menu-keymap)
1055 (yas--delete-from-keymap menu-keymap (yas--template-uuid template))
1057 ;; Add necessary subgroups as necessary.
1059 (dolist (subgroup group)
1060 (let ((subgroup-keymap (lookup-key menu-keymap (vector (make-symbol subgroup)))))
1061 (unless (and subgroup-keymap
1062 (keymapp subgroup-keymap))
1063 (setq subgroup-keymap (make-sparse-keymap))
1064 (define-key menu-keymap (vector (make-symbol subgroup))
1065 `(menu-item ,subgroup ,subgroup-keymap)))
1066 (setq menu-keymap subgroup-keymap)))
1068 ;; Add this entry to the keymap
1070 (define-key menu-keymap
1071 (vector (make-symbol (yas--template-uuid template)))
1072 (car (yas--template-menu-binding-pair template))))))
1074 (defun yas--namehash-templates-alist (namehash)
1075 "Return NAMEHASH as an alist."
1077 (maphash #'(lambda (k v)
1078 (push (cons k v) alist))
1082 (defun yas--fetch (table key)
1083 "Fetch templates in TABLE by KEY.
1085 Return a list of cons (NAME . TEMPLATE) where NAME is a
1086 string and TEMPLATE is a `yas--template' structure."
1087 (let* ((keyhash (yas--table-hash table))
1088 (namehash (and keyhash (gethash key keyhash))))
1090 (yas--filter-templates-by-condition (yas--namehash-templates-alist namehash)))))
1093 ;;; Filtering/condition logic
1095 (defun yas--eval-condition (condition)
1102 (yas--message 1 "Error in condition evaluation: %s" (error-message-string err))
1106 (defun yas--filter-templates-by-condition (templates)
1107 "Filter the templates using the applicable condition.
1109 TEMPLATES is a list of cons (NAME . TEMPLATE) where NAME is a
1110 string and TEMPLATE is a `yas--template' structure.
1112 This function implements the rules described in
1113 `yas-buffer-local-condition'. See that variables documentation."
1114 (let ((requirement (yas--require-template-specific-condition-p)))
1115 (if (eq requirement 'always)
1117 (remove-if-not #'(lambda (pair)
1118 (yas--template-can-expand-p
1119 (yas--template-condition (cdr pair)) requirement))
1122 (defun yas--require-template-specific-condition-p ()
1123 "Decides if this buffer requests/requires snippet-specific
1124 conditions to filter out potential expansions."
1125 (if (eq 'always yas-buffer-local-condition)
1127 (let ((local-condition (or (and (consp yas-buffer-local-condition)
1128 (yas--eval-condition yas-buffer-local-condition))
1129 yas-buffer-local-condition)))
1130 (when local-condition
1131 (if (eq local-condition t)
1133 (and (consp local-condition)
1134 (eq 'require-snippet-condition (car local-condition))
1135 (symbolp (cdr local-condition))
1136 (cdr local-condition)))))))
1138 (defun yas--template-can-expand-p (condition requirement)
1139 "Evaluates CONDITION and REQUIREMENT and returns a boolean."
1140 (let* ((result (or (null condition)
1141 (yas--eval-condition condition))))
1142 (cond ((eq requirement t)
1145 (eq requirement result)))))
1147 (defun yas--all-parents (mode)
1148 "Returns a list of all parent modes of MODE."
1149 (let ((parents (gethash mode yas--parents)))
1151 (mapcan #'yas--all-parents parents))))
1153 (defun yas--table-templates (table)
1156 (maphash #'(lambda (key namehash)
1157 (maphash #'(lambda (name template)
1158 (push (cons name template) acc))
1160 (yas--table-hash table))
1161 (yas--filter-templates-by-condition acc))))
1163 (defun yas--current-key ()
1164 "Get the key under current position. A key is used to find
1165 the template of a snippet in the current snippet-table."
1166 (let ((start (point))
1168 (syntaxes yas-key-syntaxes)
1172 (while (and (not done) syntaxes)
1173 (setq syntax (car syntaxes))
1174 (setq syntaxes (cdr syntaxes))
1176 (skip-syntax-backward syntax)
1177 (setq start (point)))
1179 (mapcan #'(lambda (table)
1180 (yas--fetch table (buffer-substring-no-properties start end)))
1181 (yas--get-snippet-tables)))
1190 (defun yas--table-all-keys (table)
1191 "Get trigger keys of all active snippets in TABLE."
1193 (maphash #'(lambda (key namehash)
1194 (when (yas--filter-templates-by-condition (yas--namehash-templates-alist namehash))
1196 (yas--table-hash table))
1199 (defun yas--table-mode (table)
1200 (intern (yas--table-name table)))
1203 ;;; Internal functions and macros:
1205 (defun yas--real-mode? (mode)
1206 "Try to find out if MODE is a real mode.
1208 The MODE bound to a function (like `c-mode') is considered real
1209 mode. Other well known mode like `ruby-mode' which is not part of
1210 Emacs might not bound to a function until it is loaded. So
1211 yasnippet keeps a list of modes like this to help the judgment."
1213 (find mode yas--known-modes)))
1215 (defun yas--eval-lisp (form)
1216 "Evaluate FORM and convert the result to string."
1217 (let ((retval (catch 'yas--exception
1223 (let ((result (eval form)))
1225 (format "%s" result))))))
1226 (error (if yas-good-grace
1227 (yas--format "elisp error! %s" (error-message-string err))
1228 (error (yas--format "elisp error: %s"
1229 (error-message-string err)))))))))
1230 (when (and (consp retval)
1231 (eq 'yas--exception (car retval)))
1232 (error (cdr retval)))
1235 (defun yas--eval-lisp-no-saves (form)
1238 (error (if yas-good-grace
1239 (yas--format "elisp error! %s" (error-message-string err))
1240 (error (yas--format "elisp error: %s"
1241 (error-message-string err)))))))
1243 (defun yas--read-lisp (string &optional nil-on-error)
1244 "Read STRING as a elisp expression and return it.
1246 In case STRING in an invalid expression and NIL-ON-ERROR is nil,
1247 return an expression that when evaluated will issue an error."
1250 (error (and (not nil-on-error)
1251 `(error (error-message-string ,err))))))
1253 (defun yas--read-keybinding (keybinding)
1254 "Read KEYBINDING as a snippet keybinding, return a vector."
1255 (when (and keybinding
1256 (not (string-match "keybinding" keybinding)))
1258 (let ((res (or (and (string-match "^\\[.*\\]$" keybinding)
1260 (read-kbd-macro keybinding 'need-vector))))
1263 (yas--message 3 "warning: keybinding \"%s\" invalid since %s."
1264 keybinding (error-message-string err))
1267 (defvar yas-extra-modes nil
1268 "If non-nil, also lookup snippets for this/these modes.
1270 Can be a symbol or a list of symbols.
1272 This variable probably makes more sense as buffer-local, so
1273 ensure your use `make-local-variable' when you set it.")
1274 (defun yas-extra-modes ()
1275 (if (listp yas-extra-modes) yas-extra-modes (list yas-extra-modes)))
1276 (defvaralias 'yas/mode-symbol 'yas-extra-modes)
1278 (defun yas--table-get-create (mode)
1279 "Get or create the snippet table corresponding to MODE."
1280 (let ((table (gethash mode
1283 (setq table (yas--make-snippet-table (symbol-name mode)))
1284 (puthash mode table yas--tables)
1285 (push (cons (intern (format "yas--direct-%s" mode))
1286 (yas--table-direct-keymap table))
1287 yas--direct-keymaps))
1290 (defun yas--get-snippet-tables ()
1291 "Get snippet tables for current buffer.
1293 Return a list of `yas--table' objects. The list of modes to
1294 consider is returned by `yas--modes-to-activate'"
1296 (mapcar #'(lambda (mode-name)
1297 (gethash mode-name yas--tables))
1298 (yas--modes-to-activate))))
1300 (defun yas--menu-keymap-get-create (mode &optional parents)
1301 "Get or create the menu keymap for MODE and its PARENTS.
1303 This may very well create a plethora of menu keymaps and arrange
1304 them all in `yas--menu-table'"
1305 (let* ((menu-keymap (or (gethash mode yas--menu-table)
1306 (puthash mode (make-sparse-keymap) yas--menu-table))))
1307 (mapc #'yas--menu-keymap-get-create parents)
1308 (define-key yas--minor-mode-menu (vector mode)
1309 `(menu-item ,(symbol-name mode) ,menu-keymap
1310 :visible (yas--show-menu-p ',mode)))
1313 (defmacro yas--called-interactively-p (&optional kind)
1314 "A backward-compatible version of `called-interactively-p'.
1316 Optional KIND is as documented at `called-interactively-p'
1317 in GNU Emacs 24.1 or higher."
1318 (if (eq 0 (cdr (subr-arity (symbol-function 'called-interactively-p))))
1319 '(called-interactively-p)
1320 `(called-interactively-p ,kind)))
1322 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1323 ;;; Template-related and snippet loading functions
1325 (defun yas--parse-template (&optional file)
1326 "Parse the template in the current buffer.
1328 Optional FILE is the absolute file name of the file being
1331 Optional GROUP is the group where the template is to go,
1332 otherwise we attempt to calculate it from FILE.
1334 Return a snippet-definition, i.e. a list
1336 (KEY TEMPLATE NAME CONDITION GROUP VARS FILE KEYBINDING UUID)
1338 If the buffer contains a line of \"# --\" then the contents above
1339 this line are ignored. Directives can set most of these with the syntax:
1341 # directive-name : directive-value
1343 Here's a list of currently recognized directives:
1354 (goto-char (point-min))
1355 (let* ((type 'snippet)
1357 (file-name-nondirectory file)))
1363 (yas--calculate-group file)))
1367 (if (re-search-forward "^# --\n" nil t)
1368 (progn (setq template
1369 (buffer-substring-no-properties (point)
1371 (setq bound (point))
1372 (goto-char (point-min))
1373 (while (re-search-forward "^# *\\([^ ]+?\\) *: *\\(.*\\)$" bound t)
1374 (when (string= "uuid" (match-string-no-properties 1))
1375 (setq uuid (match-string-no-properties 2)))
1376 (when (string= "type" (match-string-no-properties 1))
1377 (setq type (if (string= "command" (match-string-no-properties 2))
1380 (when (string= "key" (match-string-no-properties 1))
1381 (setq key (match-string-no-properties 2)))
1382 (when (string= "name" (match-string-no-properties 1))
1383 (setq name (match-string-no-properties 2)))
1384 (when (string= "condition" (match-string-no-properties 1))
1385 (setq condition (yas--read-lisp (match-string-no-properties 2))))
1386 (when (string= "group" (match-string-no-properties 1))
1387 (setq group (match-string-no-properties 2)))
1388 (when (string= "expand-env" (match-string-no-properties 1))
1389 (setq expand-env (yas--read-lisp (match-string-no-properties 2)
1391 (when (string= "binding" (match-string-no-properties 1))
1392 (setq binding (match-string-no-properties 2)))))
1394 (buffer-substring-no-properties (point-min) (point-max))))
1395 (unless (or key binding)
1396 (setq key (and file (file-name-nondirectory file))))
1397 (when (eq type 'command)
1398 (setq template (yas--read-lisp (concat "(progn" template ")"))))
1400 (setq group (split-string group "\\.")))
1401 (list key template name condition group expand-env file binding uuid)))
1403 (defun yas--calculate-group (file)
1404 "Calculate the group for snippet file path FILE."
1405 (let* ((dominating-dir (locate-dominating-file file
1406 ".yas-make-groups"))
1407 (extra-path (and dominating-dir
1408 (replace-regexp-in-string (concat "^"
1409 (expand-file-name dominating-dir))
1411 (expand-file-name file))))
1412 (extra-dir (and extra-path
1413 (file-name-directory extra-path)))
1414 (group (and extra-dir
1415 (replace-regexp-in-string "/"
1417 (directory-file-name extra-dir)))))
1420 (defun yas--subdirs (directory &optional filep)
1421 "Return subdirs or files of DIRECTORY according to FILEP."
1422 (remove-if (lambda (file)
1423 (or (string-match "^\\."
1424 (file-name-nondirectory file))
1425 (string-match "^#.*#$"
1426 (file-name-nondirectory file))
1428 (file-name-nondirectory file))
1430 (file-directory-p file)
1431 (not (file-directory-p file)))))
1432 (directory-files directory t)))
1434 (defun yas--make-menu-binding (template)
1435 (let ((mode (yas--table-mode (yas--template-table template))))
1436 `(lambda () (interactive) (yas--expand-or-visit-from-menu ',mode ,(yas--template-uuid template)))))
1438 (defun yas--expand-or-visit-from-menu (mode uuid)
1439 (let* ((table (yas--table-get-create mode))
1440 (yas--current-template (and table
1441 (gethash uuid (yas--table-uuidhash table)))))
1442 (when yas--current-template
1443 (if yas-visit-from-menu
1444 (yas--visit-snippet-file-1 yas--current-template)
1445 (let ((where (if (region-active-p)
1446 (cons (region-beginning) (region-end))
1447 (cons (point) (point)))))
1448 (yas-expand-snippet (yas--template-content yas--current-template)
1451 (yas--template-expand-env yas--current-template)))))))
1453 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1454 ;; Popping up for keys and templates
1456 (defvar yas--x-pretty-prompt-templates nil
1457 "If non-nil, attempt to prompt for templates like TextMate.")
1460 (defun yas--prompt-for-template (templates &optional prompt)
1461 "Interactively choose a template from the list TEMPLATES.
1463 TEMPLATES is a list of `yas--template'.
1465 Optional PROMPT sets the prompt to use."
1468 (sort templates #'(lambda (t1 t2)
1469 (< (length (yas--template-name t1))
1470 (length (yas--template-name t2))))))
1471 (if yas--x-pretty-prompt-templates
1472 (yas--x-pretty-prompt-templates "Choose a snippet" templates)
1473 (some #'(lambda (fn)
1474 (funcall fn (or prompt "Choose a snippet: ")
1476 #'yas--template-name))
1477 yas-prompt-functions))))
1479 (defun yas--prompt-for-keys (keys &optional prompt)
1480 "Interactively choose a template key from the list KEYS.
1482 Optional PROMPT sets the prompt to use."
1484 (some #'(lambda (fn)
1485 (funcall fn (or prompt "Choose a snippet key: ") keys))
1486 yas-prompt-functions)))
1488 (defun yas--prompt-for-table (tables &optional prompt)
1489 "Interactively choose a table from the list TABLES.
1491 Optional PROMPT sets the prompt to use."
1493 (some #'(lambda (fn)
1494 (funcall fn (or prompt "Choose a snippet table: ")
1497 yas-prompt-functions)))
1499 (defun yas-x-prompt (prompt choices &optional display-fn)
1500 "Display choices in a x-window prompt."
1501 ;; FIXME: HACK: if we notice that one of the objects in choices is
1502 ;; actually a `yas--template', defer to `yas--x-prompt-pretty-templates'
1504 ;; This would be better implemented by passing CHOICES as a
1505 ;; structured tree rather than a list. Modifications would go as far
1506 ;; up as `yas--all-templates' I think.
1508 (when (and window-system choices)
1510 (let (menu d) ;; d for display
1512 (setq d (or (and display-fn (funcall display-fn c))
1515 (push (cons (concat " " d) c) menu))
1517 (push (car d) menu))))
1518 (setq menu (list prompt (push "title" menu)))
1519 (x-popup-menu (if (fboundp 'posn-at-point)
1520 (let ((x-y (posn-x-y (posn-at-point (point)))))
1521 (list (list (+ (car x-y) 10)
1529 (defun yas--x-pretty-prompt-templates (prompt templates)
1530 "Display TEMPLATES, grouping neatly by table name."
1531 (let ((organized (make-hash-table :test #'equal))
1535 (dolist (tl templates)
1536 (puthash (yas--template-table tl)
1538 (gethash (yas--template-table tl) organized))
1540 (setq more-than-one-table (> (hash-table-count organized) 1))
1541 (setq prefix (if more-than-one-table
1543 (if more-than-one-table
1544 (maphash #'(lambda (table templates)
1545 (push (yas--table-name table) menu)
1546 (dolist (tl templates)
1547 (push (cons (concat prefix (yas--template-name tl)) tl) menu))) organized)
1548 (setq menu (mapcar #'(lambda (tl) (cons (concat prefix (yas--template-name tl)) tl)) templates)))
1550 (setq menu (nreverse menu))
1551 (or (x-popup-menu (if (fboundp 'posn-at-point)
1552 (let ((x-y (posn-x-y (posn-at-point (point)))))
1553 (list (list (+ (car x-y) 10)
1557 (list prompt (push "title" menu)))
1560 (defun yas-ido-prompt (prompt choices &optional display-fn)
1561 (when (and (fboundp 'ido-completing-read)
1562 (or (>= emacs-major-version 24)
1564 (yas-completing-prompt prompt choices display-fn #'ido-completing-read)))
1566 (eval-when-compile (require 'dropdown-list nil t))
1567 (defun yas-dropdown-prompt (prompt choices &optional display-fn)
1568 (when (featurep 'dropdown-list)
1569 (let (formatted-choices
1573 (dolist (choice choices)
1574 (setq d (or (and display-fn (funcall display-fn choice))
1577 (push d formatted-choices)
1578 (push choice filtered-choices)))
1580 (setq n (and formatted-choices (dropdown-list formatted-choices)))
1582 (nth n filtered-choices)
1585 (defun yas-completing-prompt (prompt choices &optional display-fn completion-fn)
1586 (let (formatted-choices
1590 (completion-fn (or completion-fn
1591 #'completing-read)))
1592 (dolist (choice choices)
1593 (setq d (or (and display-fn (funcall display-fn choice))
1596 (push d formatted-choices)
1597 (push choice filtered-choices)))
1598 (setq chosen (and formatted-choices
1599 (funcall completion-fn prompt
1605 (let ((position (or (and chosen
1606 (position chosen formatted-choices :test #'string=))
1608 (nth position filtered-choices))))
1610 (defun yas-no-prompt (prompt choices &optional display-fn)
1613 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1614 ;; Loading snippets from files
1616 (defun yas--load-yas-setup-file (file)
1617 (load file 'noerror))
1619 (defun yas-load-directory (top-level-dir &optional use-jit)
1620 "Load snippets in directory hierarchy TOP-LEVEL-DIR.
1622 Below TOP-LEVEL-DIR each directory should be a mode name.
1624 Optional USE-JIT use jit-loading of snippets."
1625 (interactive "DSelect the root directory: ")
1626 (unless yas-snippet-dirs
1627 (setq yas-snippet-dirs top-level-dir))
1628 (dolist (dir (yas--subdirs top-level-dir))
1629 (let* ((major-mode-and-parents (yas--compute-major-mode-and-parents
1630 (concat dir "/dummy")))
1631 (mode-sym (car major-mode-and-parents))
1632 (parents (cdr major-mode-and-parents)))
1633 ;; Attention: The parents and the menus are already defined
1634 ;; here, even if the snippets are later jit-loaded.
1636 ;; * We need to know the parents at this point since entering a
1637 ;; given mode should jit load for its parents
1638 ;; immediately. This could be reviewed, the parents could be
1639 ;; discovered just-in-time-as well
1641 ;; * We need to create the menus here to support the `full'
1642 ;; option to `yas-use-menu' (all known snippet menus are shown to the user)
1644 (yas--define-parents mode-sym parents)
1645 (yas--menu-keymap-get-create mode-sym)
1646 (let ((form `(yas--load-directory-1 ,dir
1650 (not (some #'(lambda (buffer)
1651 (with-current-buffer buffer
1652 (when (eq major-mode mode-sym)
1653 (yas--message 3 "Discovered there was already %s in %s" buffer mode-sym)
1656 (yas--schedule-jit mode-sym form)
1658 (when (yas--called-interactively-p 'interactive)
1659 (yas--message 3 "Loaded snippets from %s." top-level-dir)))
1661 (defun yas--load-directory-1 (directory mode-sym parents &optional no-compiled-snippets)
1662 "Recursively load snippet templates from DIRECTORY."
1663 (unless (file-exists-p (concat directory "/" ".yas-skip"))
1664 (if (and (not no-compiled-snippets)
1665 (progn (yas--message 2 "Loading compiled snippets from %s" directory) t)
1666 (load (expand-file-name ".yas-compiled-snippets" directory) 'noerror (<= yas-verbosity 3)))
1667 (yas--message 2 "Loading snippet files from %s" directory)
1668 (yas--load-directory-2 directory mode-sym))))
1670 (defun yas--load-directory-2 (directory mode-sym)
1671 ;; Load .yas-setup.el files wherever we find them
1673 (yas--load-yas-setup-file (expand-file-name ".yas-setup" directory))
1674 (let* ((default-directory directory)
1676 ;; load the snippet files
1679 (dolist (file (yas--subdirs directory 'no-subdirs-just-files))
1680 (when (file-readable-p file)
1681 (insert-file-contents file nil nil nil t)
1682 (push (yas--parse-template file)
1685 (yas-define-snippets mode-sym
1687 ;; now recurse to a lower level
1689 (dolist (subdir (yas--subdirs directory))
1690 (yas--load-directory-2 subdir
1693 (defun yas--load-snippet-dirs (&optional nojit)
1694 "Reload the directories listed in `yas-snippet-dirs' or
1695 prompt the user to select one."
1697 (if yas-snippet-dirs
1698 (dolist (directory (reverse (yas-snippet-dirs)))
1699 (cond ((file-directory-p directory)
1700 (yas-load-directory directory (not nojit))
1702 (yas--message 3 "Loaded %s" directory)
1703 (yas--message 3 "Prepared just-in-time loading for %s" directory)))
1705 (push (yas--message 0 "Check your `yas-snippet-dirs': %s is not a directory" directory) errors))))
1706 (call-interactively 'yas-load-directory))
1709 (defun yas-reload-all (&optional interactive)
1710 "Reload all snippets and rebuild the YASnippet menu.
1712 When called interactively force immediate reload of all known
1713 snippets under `yas-snippet-dirs', otherwise use just-in-time
1718 (snippet-editing-buffers
1719 (remove-if-not #'(lambda (buffer)
1720 (with-current-buffer buffer yas--editing-template))
1722 ;; Warn if there are buffers visiting snippets, since reloading will break
1723 ;; any on-line editing of those buffers.
1725 (when snippet-editing-buffers
1727 (if (y-or-n-p "Some buffers editing live snippets, close them and proceed with reload? ")
1728 (mapc #'kill-buffer snippet-editing-buffers)
1729 (yas--message 1 "Aborted reload...")
1731 ;; in a non-interactive use, at least set
1732 ;; `yas--editing-template' to nil, make it guess it next time around
1733 (mapc #'(lambda (buffer) (setq yas--editing-template nil)) (buffer-list))))
1735 ;; Empty all snippet tables, parenting info and all menu tables
1737 (setq yas--tables (make-hash-table))
1738 (setq yas--parents (make-hash-table))
1739 (setq yas--menu-table (make-hash-table))
1741 ;; Cancel all pending 'yas--scheduled-jit-loads'
1743 (setq yas--scheduled-jit-loads (make-hash-table))
1745 ;; Init the `yas-minor-mode-map', taking care not to break the
1748 (setcdr yas-minor-mode-map (cdr (yas--init-minor-keymap)))
1750 ;; Reload the directories listed in `yas-snippet-dirs' or prompt
1751 ;; the user to select one.
1753 (setq errors (yas--load-snippet-dirs interactive))
1754 ;; Reload the direct keybindings
1756 (yas-direct-keymaps-reload)
1758 (yas--message 3 "Reloaded everything%s...%s."
1759 (if interactive "" " (snippets will load just-in-time)")
1760 (if errors " (some errors, check *Messages*)" "")))))
1762 (defun yas--load-pending-jits ()
1763 (dolist (mode (yas--modes-to-activate))
1764 (let ((forms (reverse (gethash mode yas--scheduled-jit-loads))))
1765 ;; must reverse to maintain coherence with `yas-snippet-dirs'
1766 (dolist (form forms)
1767 (yas--message 3 "Loading for `%s', just-in-time: %s!" mode form)
1769 (remhash mode yas--scheduled-jit-loads))))
1771 ;; (when (<= emacs-major-version 22)
1772 ;; (add-hook 'after-change-major-mode-hook 'yas--load-pending-jits))
1774 (defun yas--quote-string (string)
1775 "Escape and quote STRING.
1776 foo\"bar\\! -> \"foo\\\"bar\\\\!\""
1778 (replace-regexp-in-string "[\\\"]"
1783 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1784 ;;; Snippet compilation function
1786 (defun yas--initialize ()
1787 "For backward compatibility, enable `yas-minor-mode' globally."
1788 (yas-global-mode 1))
1790 (defun yas-compile-directory (top-level-dir)
1791 "Create .yas-compiled-snippets.el files under subdirs of TOP-LEVEL-DIR.
1793 This works by stubbing a few functions, then calling
1794 `yas-load-directory'."
1795 (interactive "DTop level snippet directory?")
1796 (cl-flet ((yas--load-yas-setup-file
1798 (let ((elfile (concat file ".el")))
1799 (when (file-exists-p elfile)
1800 (insert ";;; .yas-setup.el support file if any:\n;;;\n")
1801 (insert-file-contents elfile)
1802 (goto-char (point-max))
1804 (yas-define-snippets
1806 (insert ";;; Snippet definitions:\n;;;\n")
1807 (let ((literal-snippets (list))
1809 (dolist (snippet snippets)
1810 (let ((key (first snippet))
1811 (template-content (second snippet))
1812 (name (third snippet))
1813 (condition (fourth snippet))
1814 (group (fifth snippet))
1815 (expand-env (sixth snippet))
1816 (file nil) ;; (seventh snippet)) ;; omit on purpose
1817 (binding (eighth snippet))
1818 (uuid (ninth snippet)))
1829 (insert (pp-to-string `(yas-define-snippets ',mode ',literal-snippets)))
1831 (yas--load-directory-1
1832 (dir mode parents &rest ignore)
1833 (let ((output-file (concat (file-name-as-directory dir) ".yas-compiled-snippets.el")))
1834 (with-temp-file output-file
1835 (insert (format ";;; Compiled snippets and support files for `%s'\n" mode))
1836 (yas--load-directory-2 dir mode)
1837 (insert (format ";;; Do not edit! File generated at %s\n" (current-time-string)))))))
1838 (yas-load-directory top-level-dir nil)))
1840 (defun yas-recompile-all ()
1841 "Compile every dir in `yas-snippet-dirs'."
1843 (mapc #'yas-compile-directory (yas-snippet-dirs)))
1849 (defvar yas--scheduled-jit-loads (make-hash-table)
1850 "Alist of mode-symbols to forms to be evaled when `yas-minor-mode' kicks in.")
1852 (defun yas--schedule-jit (mode form)
1855 (gethash mode yas--scheduled-jit-loads))
1856 yas--scheduled-jit-loads))
1859 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1860 ;;; Some user level functions
1865 (message (concat "yasnippet (version "
1867 ") -- pluskid <pluskid@gmail.com>/joaotavora <joaotavora@gmail.com>")))
1869 (defun yas--define-parents (mode parents)
1870 "Add PARENTS to the list of MODE's parents."
1871 (puthash mode (remove-duplicates
1873 (gethash mode yas--parents)))
1876 (defun yas-define-snippets (mode snippets)
1877 "Define SNIPPETS for MODE.
1879 SNIPPETS is a list of snippet definitions, each taking the
1882 (KEY TEMPLATE NAME CONDITION GROUP EXPAND-ENV FILE KEYBINDING UUID)
1884 Within these, only KEY and TEMPLATE are actually mandatory.
1886 TEMPLATE might be a lisp form or a string, depending on whether
1887 this is a snippet or a snippet-command.
1889 CONDITION, EXPAND-ENV and KEYBINDING are lisp forms, they have
1890 been `yas--read-lisp'-ed and will eventually be
1891 `yas--eval-lisp'-ed.
1893 The remaining elements are strings.
1895 FILE is probably of very little use if you're programatically
1898 UUID is the snippets \"unique-id\". Loading a second snippet file
1899 with the same uuid replaced the previous snippet.
1901 You can use `yas--parse-template' to return such lists based on
1902 the current buffers contents."
1903 (let ((snippet-table (yas--table-get-create mode))
1905 (dolist (snippet snippets)
1906 (setq template (yas-define-snippets-1 snippet
1910 (defun yas-define-snippets-1 (snippet snippet-table)
1911 "Helper for `yas-define-snippets'."
1912 ;; X) Calculate some more defaults on the values returned by
1913 ;; `yas--parse-template'.
1915 (let* ((file (seventh snippet))
1917 (name (or (third snippet)
1919 (file-name-directory file))))
1920 (condition (fourth snippet))
1921 (group (fifth snippet))
1922 (keybinding (yas--read-keybinding (eighth snippet)))
1923 (uuid (or (ninth snippet)
1925 (template (or (gethash uuid (yas--table-uuidhash snippet-table))
1926 (yas--make-blank-template))))
1927 ;; X) populate the template object
1929 (yas--populate-template template
1930 :table snippet-table
1932 :content (second snippet)
1935 :condition condition
1936 :expand-env (sixth snippet)
1937 :file (seventh snippet)
1938 :keybinding keybinding
1940 ;; X) Update this template in the appropriate table. This step
1941 ;; also will take care of adding the key indicators in the
1942 ;; templates menu entry, if any
1944 (yas--update-template snippet-table template)
1945 ;; X) Return the template
1951 ;;; Apropos snippet menu:
1953 ;; The snippet menu keymaps are store by mode in hash table called
1954 ;; `yas--menu-table'. They are linked to the main menu in
1955 ;; `yas--menu-keymap-get-create' and are initially created empty,
1956 ;; reflecting the table hierarchy.
1958 ;; They can be populated in two mutually exclusive ways: (1) by
1959 ;; reading `yas--template-group', which in turn is populated by the "#
1960 ;; group:" directives of the snippets or the ".yas-make-groups" file
1961 ;; or (2) by using a separate `yas-define-menu' call, which declares a
1962 ;; menu structure based on snippets uuids.
1964 ;; Both situations are handled in `yas--update-template-menu', which
1965 ;; uses the predicate `yas--template-menu-managed-by-yas-define-menu'
1966 ;; that can tell between the two situations.
1970 ;; * if `yas-define-menu' is used it must run before
1971 ;; `yas-define-snippets' and the UUIDS must match, otherwise we get
1972 ;; duplicate entries. The `yas--template' objects are created in
1973 ;; `yas-define-menu', holding nothing but the menu entry,
1974 ;; represented by a pair of ((menu-item NAME :keys KEYS) TYPE) and
1975 ;; stored in `yas--template-menu-binding-pair'. The (menu-item ...)
1976 ;; part is then stored in the menu keymap itself which make the item
1977 ;; appear to the user. These limitations could probably be revised.
1979 ;; * The `yas--template-perm-group' slot is only used in
1980 ;; `yas-describe-tables'.
1982 (defun yas--template-menu-binding-pair-get-create (template &optional type)
1983 "Get TEMPLATE's menu binding or assign it a new one.
1985 TYPE may be `:stay', signaling this menu binding should be
1986 static in the menu."
1987 (or (yas--template-menu-binding-pair template)
1988 (let ((key (yas--template-key template))
1989 (keybinding (yas--template-keybinding template)))
1990 (setf (yas--template-menu-binding-pair template)
1991 (cons `(menu-item ,(or (yas--template-name template)
1992 (yas--template-uuid template))
1993 ,(yas--make-menu-binding template)
1996 (defun yas--template-menu-managed-by-yas-define-menu (template)
1997 "Non-nil if TEMPLATE's menu entry was included in a `yas-define-menu' call."
1998 (cdr (yas--template-menu-binding-pair template)))
2001 (defun yas--show-menu-p (mode)
2002 (cond ((eq yas-use-menu 'abbreviate)
2004 (mapcar #'(lambda (table)
2005 (yas--table-mode table))
2006 (yas--get-snippet-tables))))
2007 ((eq yas-use-menu 'full)
2009 ((eq yas-use-menu t)
2012 (defun yas--delete-from-keymap (keymap uuid)
2013 "Recursively delete items with UUID from KEYMAP and its submenus."
2015 ;; XXX: This used to skip any submenus named \"parent mode\"
2017 ;; First of all, recursively enter submenus, i.e. the tree is
2018 ;; searched depth first so that stale submenus can be found in the
2021 (mapc #'(lambda (item)
2022 (when (and (listp (cdr item))
2023 (keymapp (third (cdr item))))
2024 (yas--delete-from-keymap (third (cdr item)) uuid)))
2026 ;; Set the uuid entry to nil
2028 (define-key keymap (vector (make-symbol uuid)) nil)
2029 ;; Destructively modify keymap
2031 (setcdr keymap (delete-if #'(lambda (item)
2032 (or (null (cdr item))
2033 (and (keymapp (third (cdr item)))
2034 (null (cdr (third (cdr item)))))))
2037 (defun yas-define-menu (mode menu &optional omit-items)
2038 "Define a snippet menu for MODE according to MENU, omitting OMIT-ITEMS.
2040 MENU is a list, its elements can be:
2042 - (yas-item UUID) : Creates an entry the snippet identified with
2043 UUID. The menu entry for a snippet thus identified is
2044 permanent, i.e. it will never move (be reordered) in the menu.
2046 - (yas-separator) : Creates a separator
2048 - (yas-submenu NAME SUBMENU) : Creates a submenu with NAME,
2049 SUBMENU has the same form as MENU. NAME is also added to the
2050 list of groups of the snippets defined thereafter.
2052 OMIT-ITEMS is a list of snippet uuid's that will always be
2053 omitted from MODE's menu, even if they're manually loaded.
2055 This function does nothing if `yas-use-menu' is nil."
2057 (let* ((table (yas--table-get-create mode))
2058 (hash (yas--table-uuidhash table)))
2059 (yas--define-menu-1 table
2060 (yas--menu-keymap-get-create mode)
2063 (dolist (uuid omit-items)
2064 (let ((template (or (gethash uuid hash)
2065 (yas--populate-template (puthash uuid
2066 (yas--make-blank-template)
2070 (setf (yas--template-menu-binding-pair template) (cons nil :none)))))))
2072 (defun yas--define-menu-1 (table menu-keymap menu uuidhash &optional group-list)
2073 "Helper for `yas-define-menu'."
2074 (dolist (e (reverse menu))
2075 (cond ((eq (first e) 'yas-item)
2076 (let ((template (or (gethash (second e) uuidhash)
2077 (yas--populate-template (puthash (second e)
2078 (yas--make-blank-template)
2081 :perm-group group-list
2082 :uuid (second e)))))
2083 (define-key menu-keymap (vector (gensym))
2084 (car (yas--template-menu-binding-pair-get-create template :stay)))))
2085 ((eq (first e) 'yas-submenu)
2086 (let ((subkeymap (make-sparse-keymap)))
2087 (define-key menu-keymap (vector (gensym))
2088 `(menu-item ,(second e) ,subkeymap))
2089 (yas--define-menu-1 table
2093 (append group-list (list (second e))))))
2094 ((eq (first e) 'yas-separator)
2095 (define-key menu-keymap (vector (gensym))
2096 '(menu-item "----")))
2098 (yas--message 3 "Don't know anything about menu entry %s" (first e))))))
2100 (defun yas--define (mode key template &optional name condition group)
2101 "Define a snippet. Expanding KEY into TEMPLATE.
2103 NAME is a description to this template. Also update the menu if
2104 `yas-use-menu' is t. CONDITION is the condition attached to
2105 this snippet. If you attach a condition to a snippet, then it
2106 will only be expanded when the condition evaluated to non-nil."
2107 (yas-define-snippets mode
2108 (list (list key template name condition group))))
2110 (defun yas-hippie-try-expand (first-time?)
2111 "Integrate with hippie expand.
2113 Just put this function in `hippie-expand-try-functions-list'."
2114 (when yas-minor-mode
2115 (if (not first-time?)
2116 (let ((yas-fallback-behavior 'return-nil))
2122 ;;; Apropos condition-cache:
2127 (defvar yas--condition-cache-timestamp nil)
2128 (defmacro yas-define-condition-cache (func doc &rest body)
2129 "Define a function FUNC with doc DOC and body BODY, BODY is
2130 executed at most once every snippet expansion attempt, to check
2131 expansion conditions.
2133 It doesn't make any sense to call FUNC programatically."
2134 `(defun ,func () ,(if (and doc
2137 "\n\nFor use in snippets' conditions. Within each
2138 snippet-expansion routine like `yas-expand', computes actual
2139 value for the first time then always returns a cached value.")
2140 (setq body (cons doc body))
2142 (let ((timestamp-and-value (get ',func 'yas--condition-cache)))
2143 (if (equal (car timestamp-and-value) yas--condition-cache-timestamp)
2144 (cdr timestamp-and-value)
2145 (let ((new-value (progn
2148 (put ',func 'yas--condition-cache (cons yas--condition-cache-timestamp new-value))
2151 (defalias 'yas-expand 'yas-expand-from-trigger-key)
2152 (defun yas-expand-from-trigger-key (&optional field)
2153 "Expand a snippet before point.
2155 If no snippet expansion is possible, fall back to the behaviour
2156 defined in `yas-fallback-behavior'.
2158 Optional argument FIELD is for non-interactive use and is an
2159 object satisfying `yas--field-p' to restrict the expansion to."
2161 (setq yas--condition-cache-timestamp (current-time))
2162 (let (templates-and-pos)
2163 (unless (and yas-expand-only-for-last-commands
2164 (not (member last-command yas-expand-only-for-last-commands)))
2165 (setq templates-and-pos (if field
2167 (narrow-to-region (yas--field-start field)
2168 (yas--field-end field))
2170 (yas--current-key))))
2171 (if (and templates-and-pos
2172 (first templates-and-pos))
2173 (yas--expand-or-prompt-for-template (first templates-and-pos)
2174 (second templates-and-pos)
2175 (third templates-and-pos))
2176 (yas--fallback 'trigger-key))))
2178 (defun yas-expand-from-keymap ()
2179 "Directly expand some snippets, searching `yas--direct-keymaps'.
2181 If expansion fails, execute the previous binding for this key"
2183 (setq yas--condition-cache-timestamp (current-time))
2184 (let* ((yas--prefix current-prefix-arg)
2185 (vec (subseq (this-command-keys-vector) (if current-prefix-arg
2186 universal-argument-num-events
2188 (templates (mapcan #'(lambda (table)
2189 (yas--fetch table vec))
2190 (yas--get-snippet-tables))))
2192 (yas--expand-or-prompt-for-template templates)
2193 (let ((yas-fallback-behavior 'call-other-command))
2196 (defun yas--expand-or-prompt-for-template (templates &optional start end)
2197 "Expand one of TEMPLATES from START to END.
2199 Prompt the user if TEMPLATES has more than one element, else
2200 expand immediately. Common gateway for
2201 `yas-expand-from-trigger-key' and `yas-expand-from-keymap'."
2202 (let ((yas--current-template (or (and (rest templates) ;; more than one
2203 (yas--prompt-for-template (mapcar #'cdr templates)))
2205 (when yas--current-template
2206 (yas-expand-snippet (yas--template-content yas--current-template)
2209 (yas--template-expand-env yas--current-template)))))
2211 ;; Apropos the trigger key and the fallback binding:
2213 ;; When `yas-minor-mode-map' binds <tab>, that correctly overrides
2214 ;; org-mode's <tab>, for example and searching for fallbacks correctly
2215 ;; returns `org-cycle'. However, most other modes bind "TAB". TODO,
2216 ;; improve this explanation.
2218 (defun yas--fallback (&optional from-trigger-key-p)
2219 "Fallback after expansion has failed.
2221 Common gateway for `yas-expand-from-trigger-key' and
2222 `yas-expand-from-keymap'."
2223 (cond ((eq yas-fallback-behavior 'return-nil)
2226 ((eq yas-fallback-behavior 'call-other-command)
2227 (let* ((beyond-yasnippet (yas--keybinding-beyond-yasnippet)))
2228 (yas--message 4 "Falling back to %s" beyond-yasnippet)
2229 (assert (or (null beyond-yasnippet) (commandp beyond-yasnippet)))
2230 (setq this-original-command beyond-yasnippet)
2231 (call-interactively beyond-yasnippet)))
2232 ((and (listp yas-fallback-behavior)
2233 (cdr yas-fallback-behavior)
2234 (eq 'apply (car yas-fallback-behavior)))
2235 (if (cddr yas-fallback-behavior)
2236 (apply (cadr yas-fallback-behavior)
2237 (cddr yas-fallback-behavior))
2238 (when (commandp (cadr yas-fallback-behavior))
2239 (setq this-command (cadr yas-fallback-behavior))
2240 (call-interactively (cadr yas-fallback-behavior)))))
2242 ;; also return nil if all the other fallbacks have failed
2245 (defun yas--keybinding-beyond-yasnippet ()
2247 (let* ((yas-minor-mode nil)
2248 (yas--direct-keymaps nil)
2249 (keys (this-single-command-keys)))
2250 (or (key-binding keys t)
2251 (key-binding (yas--fallback-translate-input keys) t))))
2253 (defun yas--fallback-translate-input (keys)
2254 "Emulate `read-key-sequence', at least what I think it does.
2256 Keys should be an untranslated key vector. Returns a translated
2257 vector of keys. FIXME not thoroughly tested"
2260 (while (< i (length keys))
2262 (translated local-function-key-map))
2263 (while (and (< j (length keys))
2265 (keymapp translated))
2266 (setq translated (aget (remove 'keymap translated) (aref keys j))
2268 (setq retval (vconcat retval (cond ((symbolp translated)
2270 ((vectorp translated)
2273 (substring keys i j)))))
2278 ;;; Utils for snippet development:
2280 (defun yas--all-templates (tables)
2281 "Get `yas--template' objects in TABLES, applicable for buffer and point.
2283 Honours `yas-choose-tables-first', `yas-choose-keys-first' and
2284 `yas-buffer-local-condition'"
2285 (when yas-choose-tables-first
2286 (setq tables (list (yas--prompt-for-table tables))))
2288 (if yas-choose-keys-first
2289 (let ((key (yas--prompt-for-keys
2290 (mapcan #'yas--table-all-keys tables))))
2292 (mapcan #'(lambda (table)
2293 (yas--fetch table key))
2295 (remove-duplicates (mapcan #'yas--table-templates tables)
2298 (defun yas-insert-snippet (&optional no-condition)
2299 "Choose a snippet to expand, pop-up a list of choices according
2300 to `yas--prompt-function'.
2302 With prefix argument NO-CONDITION, bypass filtering of snippets
2305 (setq yas--condition-cache-timestamp (current-time))
2306 (let* ((yas-buffer-local-condition (or (and no-condition
2308 yas-buffer-local-condition))
2309 (templates (yas--all-templates (yas--get-snippet-tables)))
2310 (yas--current-template (and templates
2311 (or (and (rest templates) ;; more than one template for same key
2312 (yas--prompt-for-template templates))
2314 (where (if (region-active-p)
2315 (cons (region-beginning) (region-end))
2316 (cons (point) (point)))))
2317 (if yas--current-template
2318 (yas-expand-snippet (yas--template-content yas--current-template)
2321 (yas--template-expand-env yas--current-template))
2322 (yas--message 3 "No snippets can be inserted here!"))))
2324 (defun yas-visit-snippet-file ()
2325 "Choose a snippet to edit, selection like `yas-insert-snippet'.
2327 Only success if selected snippet was loaded from a file. Put the
2328 visited file in `snippet-mode'."
2330 (let* ((yas-buffer-local-condition 'always)
2331 (templates (yas--all-templates (yas--get-snippet-tables)))
2332 (yas-prompt-functions '(yas-ido-prompt yas-completing-prompt))
2333 (template (and templates
2334 (or (yas--prompt-for-template templates
2335 "Choose a snippet template to edit: ")
2339 (yas--visit-snippet-file-1 template)
2340 (message "No snippets tables active!"))))
2342 (defun yas--visit-snippet-file-1 (template)
2343 "Helper for `yas-visit-snippet-file'."
2344 (let ((file (yas--template-file template)))
2345 (cond ((and file (file-readable-p file))
2346 (find-file-other-window file)
2348 (set (make-local-variable 'yas--editing-template) template))
2350 (message "Original file %s no longer exists!" file))
2352 (switch-to-buffer (format "*%s*"(yas--template-name template)))
2353 (let ((type 'snippet))
2354 (when (listp (yas--template-content template))
2355 (insert (format "# type: command\n"))
2356 (setq type 'command))
2357 (insert (format "# key: %s\n" (yas--template-key template)))
2358 (insert (format "# name: %s\n" (yas--template-name template)))
2359 (when (yas--template-keybinding template)
2360 (insert (format "# binding: %s\n" (yas--template-keybinding template))))
2361 (when (yas--template-expand-env template)
2362 (insert (format "# expand-env: %s\n" (yas--template-expand-env template))))
2363 (when (yas--template-condition template)
2364 (insert (format "# condition: %s\n" (yas--template-condition template))))
2366 (insert (if (eq type 'command)
2367 (pp-to-string (yas--template-content template))
2368 (yas--template-content template))))
2370 (set (make-local-variable 'yas--editing-template) template)))))
2372 (defun yas--guess-snippet-directories-1 (table)
2373 "Guesses possible snippet subdirectories for TABLE."
2374 (cons (yas--table-name table)
2375 (mapcan #'(lambda (parent)
2376 (yas--guess-snippet-directories-1
2378 (yas--table-parents table))))
2380 (defun yas--guess-snippet-directories (&optional table)
2381 "Try to guess suitable directories based on the current active
2382 tables (or optional TABLE).
2384 Returns a list of elements (TABLE . DIRS) where TABLE is a
2385 `yas--table' object and DIRS is a list of all possible directories
2386 where snippets of table might exist."
2387 (let ((main-dir (replace-regexp-in-string
2389 (or (first (or (yas-snippet-dirs)
2390 (setq yas-snippet-dirs '("~/.emacs.d/snippets")))))))
2391 (tables (or (and table
2393 (yas--get-snippet-tables))))
2394 ;; HACK! the snippet table created here is actually registered!
2396 (unless (or table (gethash major-mode yas--tables))
2397 (push (yas--table-get-create major-mode)
2400 (mapcar #'(lambda (table)
2402 (mapcar #'(lambda (subdir)
2403 (concat main-dir "/" subdir))
2404 (yas--guess-snippet-directories-1 table))))
2407 (defun yas--make-directory-maybe (table-and-dirs &optional main-table-string)
2408 "Returns a dir inside TABLE-AND-DIRS, prompts for creation if none exists."
2409 (or (some #'(lambda (dir) (when (file-directory-p dir) dir)) (cdr table-and-dirs))
2410 (let ((candidate (first (cdr table-and-dirs))))
2411 (unless (file-writable-p (file-name-directory candidate))
2412 (error (yas--format "%s is not writable." candidate)))
2413 (if (y-or-n-p (format "Guessed directory (%s) for%s%s table \"%s\" does not exist! Create? "
2415 (if (gethash (yas--table-mode (car table-and-dirs))
2419 (or main-table-string
2421 (yas--table-name (car table-and-dirs))))
2423 (make-directory candidate 'also-make-parents)
2424 ;; create the .yas-parents file here...
2427 (defun yas-new-snippet (&optional no-template)
2428 "Pops a new buffer for writing a snippet.
2430 Expands a snippet-writing snippet, unless the optional prefix arg
2431 NO-TEMPLATE is non-nil."
2433 (let ((guessed-directories (yas--guess-snippet-directories)))
2435 (switch-to-buffer "*new snippet*")
2437 (kill-all-local-variables)
2440 (set (make-local-variable 'yas--guessed-modes) (mapcar #'(lambda (d)
2441 (yas--table-mode (car d)))
2442 guessed-directories))
2443 (unless no-template (yas-expand-snippet "\
2444 # -*- mode: snippet -*-
2446 # key: ${2:${1:$(replace-regexp-in-string \"\\\\\\\\(\\\\\\\\w+\\\\\\\\).*\" \"\\\\\\\\1\" yas-text)}}${3:
2447 # binding: ${4:direct-keybinding}}${5:
2448 # expand-env: ((${6:some-var} ${7:some-value}))}${8:
2453 (defun yas--compute-major-mode-and-parents (file)
2454 "Given FILE, find the nearest snippet directory for a given mode.
2456 Returns a list (MODE-SYM PARENTS), the mode's symbol and a list
2457 representing one or more of the mode's parents.
2459 Note that MODE-SYM need not be the symbol of a real major mode,
2460 neither do the elements of PARENTS."
2461 (let* ((file-dir (and file
2462 (directory-file-name (or (some #'(lambda (special)
2463 (locate-dominating-file file special))
2467 (directory-file-name (file-name-directory file))))))
2468 (parents-file-name (concat file-dir "/.yas-parents"))
2469 (major-mode-name (and file-dir
2470 (file-name-nondirectory file-dir)))
2471 (major-mode-sym (or (and major-mode-name
2472 (intern major-mode-name))))
2473 (parents (when (file-readable-p parents-file-name)
2477 (insert-file-contents parents-file-name)
2478 (buffer-substring-no-properties (point-min)
2480 (when major-mode-sym
2481 (cons major-mode-sym parents))))
2483 (defvar yas--editing-template nil
2484 "Supporting variable for `yas-load-snippet-buffer' and `yas--visit-snippet'.")
2486 (defvar yas--current-template nil
2487 "Holds the current template being expanded into a snippet.")
2489 (defvar yas--guessed-modes nil
2490 "List of guessed modes supporting `yas-load-snippet-buffer'.")
2492 (defun yas--read-table ()
2493 "Ask user for a snippet table, help with some guessing."
2494 (let ((prompt (if (and (featurep 'ido)
2496 'ido-completing-read 'completing-read)))
2497 (unless yas--guessed-modes
2498 (set (make-local-variable 'yas--guessed-modes)
2499 (or (yas--compute-major-mode-and-parents buffer-file-name))))
2501 (funcall prompt (format "Choose or enter a table (yas guesses %s): "
2502 (if yas--guessed-modes
2503 (first yas--guessed-modes)
2505 (mapcar #'symbol-name yas--guessed-modes)
2510 (if (first yas--guessed-modes)
2511 (symbol-name (first yas--guessed-modes)))))))
2513 (defun yas-load-snippet-buffer (table &optional interactive)
2514 "Parse and load current buffer's snippet definition into TABLE.
2516 TABLE is a symbol naming a passed to `yas--table-get-create'.
2518 When called interactively, prompt for the table name and
2519 whether (and where) to save the snippet, then quit the window."
2520 (interactive (list (yas--read-table) t))
2522 ;; We have `yas--editing-template', this buffer's content comes from a
2523 ;; template which is already loaded and neatly positioned,...
2525 (yas--editing-template
2526 (yas-define-snippets-1 (yas--parse-template (yas--template-file yas--editing-template))
2527 (yas--template-table yas--editing-template)))
2528 ;; Try to use `yas--guessed-modes'. If we don't have that use the
2529 ;; value from `yas--compute-major-mode-and-parents'
2532 (unless yas--guessed-modes
2533 (set (make-local-variable 'yas--guessed-modes) (or (yas--compute-major-mode-and-parents buffer-file-name))))
2534 (let* ((table (yas--table-get-create table)))
2535 (set (make-local-variable 'yas--editing-template)
2536 (yas-define-snippets-1 (yas--parse-template buffer-file-name)
2539 (when (and interactive
2541 ;; Only offer to save this if it looks like a library or new
2542 ;; snippet (loaded from elisp, from a dir in `yas-snippet-dirs'
2543 ;; which is not the first, or from an unwritable file)
2545 (not (yas--template-file yas--editing-template))
2546 (not (file-writable-p (yas--template-file yas--editing-template)))
2547 (and (listp yas-snippet-dirs)
2548 (second yas-snippet-dirs)
2549 (not (string-match (expand-file-name (first yas-snippet-dirs))
2550 (yas--template-file yas--editing-template)))))
2551 (y-or-n-p (yas--format "Looks like a library or new snippet. Save to new file? ")))
2552 (let* ((option (first (yas--guess-snippet-directories (yas--template-table yas--editing-template))))
2554 (yas--make-directory-maybe option))))
2556 (let ((default-file-name (or (and (yas--template-file yas--editing-template)
2557 (file-name-nondirectory (yas--template-file yas--editing-template)))
2558 (yas--template-name yas--editing-template))))
2559 (write-file (concat chosen "/"
2560 (read-from-minibuffer (format "File name to create in %s? " chosen)
2561 default-file-name)))
2562 (setf (yas--template-file yas--editing-template) buffer-file-name)))))
2564 (yas--message 3 "Snippet \"%s\" loaded for %s."
2565 (yas--template-name yas--editing-template)
2566 (yas--table-name (yas--template-table yas--editing-template)))
2567 (quit-window interactive)))
2569 (defun yas-tryout-snippet (&optional debug)
2570 "Test current buffer's snippet template in other buffer."
2572 (let* ((major-mode-and-parent (yas--compute-major-mode-and-parents buffer-file-name))
2573 (parsed (yas--parse-template))
2574 (test-mode (or (and (car major-mode-and-parent)
2575 (fboundp (car major-mode-and-parent))
2576 (car major-mode-and-parent))
2577 (first yas--guessed-modes)
2578 (intern (read-from-minibuffer (yas--format "Please input a mode: ")))))
2579 (yas--current-template
2582 (yas--populate-template (yas--make-blank-template)
2583 :table nil ;; no tables for ephemeral snippets
2585 :content (second parsed)
2586 :name (third parsed)
2587 :expand-env (sixth parsed)))))
2588 (cond (yas--current-template
2589 (let ((buffer-name (format "*testing snippet: %s*" (yas--template-name yas--current-template))))
2590 (kill-buffer (get-buffer-create buffer-name))
2591 (switch-to-buffer (get-buffer-create buffer-name))
2592 (setq buffer-undo-list nil)
2593 (condition-case nil (funcall test-mode) (error nil))
2595 (setq buffer-read-only nil)
2596 (yas-expand-snippet (yas--template-content yas--current-template)
2599 (yas--template-expand-env yas--current-template))
2601 (require 'yasnippet-debug nil t))
2602 (add-hook 'post-command-hook 'yas-debug-snippet-vars nil t))))
2604 (yas--message 3 "Cannot test snippet for unknown major mode")))))
2606 (defun yas-active-keys ()
2607 "Return all active trigger keys for current buffer and point."
2608 (remove-duplicates (mapcan #'yas--table-all-keys (yas--get-snippet-tables))
2611 (defun yas--template-fine-group (template)
2612 (car (last (or (yas--template-group template)
2613 (yas--template-perm-group template)))))
2615 (defun yas-describe-tables (&optional choose)
2616 "Display snippets for each table."
2618 (let* ((by-name-hash (and choose
2619 (y-or-n-p "Show by namehash? ")))
2620 (buffer (get-buffer-create "*YASnippet tables*"))
2621 (active-tables (yas--get-snippet-tables))
2622 (remain-tables (let ((all))
2623 (maphash #'(lambda (k v)
2624 (unless (find v active-tables)
2628 (table-lists (list active-tables remain-tables))
2629 (original-buffer (current-buffer))
2631 (yas--condition-cache-timestamp (current-time)))
2632 (with-current-buffer buffer
2633 (setq buffer-read-only nil)
2635 (cond ((not by-name-hash)
2636 (insert "YASnippet tables: \n")
2637 (while (and table-lists
2639 (dolist (table (car table-lists))
2640 (yas--describe-pretty-table table original-buffer))
2641 (setq table-lists (cdr table-lists))
2643 (yas--create-snippet-xrefs)
2644 (display-buffer buffer)
2645 (setq continue (and choose (y-or-n-p "Show also non-active tables? ")))))
2646 (yas--create-snippet-xrefs)
2650 (insert "\n\nYASnippet tables by NAMEHASH: \n")
2651 (dolist (table (append active-tables remain-tables))
2652 (insert (format "\nSnippet table `%s':\n\n" (yas--table-name table)))
2654 (maphash #'(lambda (k v)
2656 (yas--table-hash table))
2658 (insert (format " key %s maps snippets: %s\n" key
2660 (maphash #'(lambda (k v)
2662 (gethash key (yas--table-hash table)))
2665 (setq buffer-read-only t))
2666 (display-buffer buffer)))
2668 (defun yas--describe-pretty-table (table &optional original-buffer)
2669 (insert (format "\nSnippet table `%s'"
2670 (yas--table-name table)))
2671 (if (yas--table-parents table)
2672 (insert (format " parents: %s\n"
2673 (mapcar #'yas--table-name
2674 (yas--table-parents table))))
2676 (insert (make-string 100 ?-) "\n")
2677 (insert "group state name key binding\n")
2678 (let ((groups-hash (make-hash-table :test #'equal)))
2679 (maphash #'(lambda (k v)
2680 (let ((group (or (yas--template-fine-group v)
2682 (when (yas--template-name v)
2684 (cons v (gethash group groups-hash))
2686 (yas--table-uuidhash table))
2688 #'(lambda (group templates)
2689 (setq group (truncate-string-to-width group 25 0 ? "..."))
2690 (insert (make-string 100 ?-) "\n")
2691 (dolist (p templates)
2692 (let ((name (truncate-string-to-width (propertize (format "\\\\snippet `%s'" (yas--template-name p))
2696 (setq group (make-string (length group) ? ))))
2697 (condition-string (let ((condition (yas--template-condition p)))
2700 (with-current-buffer original-buffer
2701 (if (yas--eval-condition condition)
2706 (insert condition-string " ")
2708 (if (string-match "\\.\\.\\.$" name)
2712 (insert (truncate-string-to-width (or (yas--template-key p) "")
2714 (insert (truncate-string-to-width (key-description (yas--template-keybinding p))
2721 ;;; User convenience functions, for using in snippet definitions
2723 (defvar yas-modified-p nil
2724 "Non-nil if field has been modified by user or transformation.")
2726 (defvar yas-moving-away-p nil
2727 "Non-nil if user is about to exit field.")
2729 (defvar yas-text nil
2730 "Contains current field text.")
2732 (defun yas-substr (str pattern &optional subexp)
2733 "Search PATTERN in STR and return SUBEXPth match.
2735 If found, the content of subexp group SUBEXP (default 0) is
2736 returned, or else the original STR will be returned."
2737 (let ((grp (or subexp 0)))
2739 (if (string-match pattern str)
2740 (match-string-no-properties grp str)
2743 (defun yas-choose-value (&rest possibilities)
2744 "Prompt for a string in POSSIBILITIES and return it.
2746 The last element of POSSIBILITIES may be a list of strings."
2747 (unless (or yas-moving-away-p
2749 (setq possibilities (nreverse possibilities))
2750 (setq possibilities (if (listp (car possibilities))
2751 (append (reverse (car possibilities)) (rest possibilities))
2753 (some #'(lambda (fn)
2754 (funcall fn "Choose: " possibilities))
2755 yas-prompt-functions)))
2757 (defun yas-key-to-value (alist)
2758 (unless (or yas-moving-away-p
2760 (let ((key (read-key-sequence "")))
2762 (or (cdr (find key alist :key #'car :test #'string=))
2765 (defun yas-throw (text)
2766 "Throw a yas--exception with TEXT as the reason."
2767 (throw 'yas--exception (cons 'yas--exception text)))
2769 (defun yas-verify-value (possibilities)
2770 "Verify that the current field value is in POSSIBILITIES.
2772 Otherwise throw exception."
2773 (when (and yas-moving-away-p (notany #'(lambda (pos) (string= pos yas-text)) possibilities))
2774 (yas-throw (yas--format "Field only allows %s" possibilities))))
2776 (defun yas-field-value (number)
2777 "Get the string for field with NUMBER.
2779 Use this in primary and mirror transformations to tget."
2780 (let* ((snippet (car (yas--snippets-at-point)))
2782 (yas--snippet-find-field snippet number))))
2784 (yas--field-text-for-display field))))
2787 "Return `yas-text' if that exists and is non-empty, else nil."
2789 (not (string= "" yas-text)))
2792 (defun yas-selected-text ()
2793 "Return `yas-selected-text' if that exists and is non-empty, else nil."
2794 (if (and yas-selected-text
2795 (not (string= "" yas-selected-text)))
2798 (defun yas--get-field-once (number &optional transform-fn)
2799 (unless yas-modified-p
2801 (funcall transform-fn (yas-field-value number))
2802 (yas-field-value number))))
2804 (defun yas-default-from-field (number)
2805 (unless yas-modified-p
2806 (yas-field-value number)))
2808 (defun yas-inside-string ()
2809 "Return non-nil if the point is inside a string according to font-lock."
2810 (equal 'font-lock-string-face (get-char-property (1- (point)) 'face)))
2812 (defun yas-unimplemented (&optional missing-feature)
2813 (if yas--current-template
2814 (if (y-or-n-p (format "This snippet is unimplemented (missing %s) Visit the snippet definition? "
2817 (yas--visit-snippet-file-1 yas--current-template))
2818 (message "No implementation. Missing %s" (or missing-feature "something"))))
2821 ;;; Snippet expansion and field management
2823 (defvar yas--active-field-overlay nil
2824 "Overlays the currently active field.")
2826 (defvar yas--field-protection-overlays nil
2827 "Two overlays protect the current active field.")
2829 (defconst yas--prefix nil
2830 "A prefix argument for expansion direct from keybindings.")
2832 (defvar yas-selected-text nil
2833 "The selected region deleted on the last snippet expansion.")
2835 (defvar yas--start-column nil
2836 "The column where the snippet expansion started.")
2838 (make-variable-buffer-local 'yas--active-field-overlay)
2839 (make-variable-buffer-local 'yas--field-protection-overlays)
2840 (put 'yas--active-field-overlay 'permanent-local t)
2841 (put 'yas--field-protection-overlays 'permanent-local t)
2843 (defstruct (yas--snippet (:constructor yas--make-snippet ()))
2849 (id (yas--snippet-next-id) :read-only t)
2850 (control-overlay nil)
2852 ;; stacked expansion: the `previous-active-field' slot saves the
2853 ;; active field where the child expansion took place
2854 previous-active-field
2857 (defstruct (yas--field (:constructor yas--make-field (number start end parent-field)))
2867 (defstruct (yas--mirror (:constructor yas--make-mirror (start end transform)))
2874 (defstruct (yas--exit (:constructor yas--make-exit (marker)))
2878 (defun yas--apply-transform (field-or-mirror field &optional empty-on-nil-p)
2879 "Calculate transformed string for FIELD-OR-MIRROR from FIELD.
2881 If there is no transform for ht field, return nil.
2883 If there is a transform but it returns nil, return the empty
2884 string iff EMPTY-ON-NIL-P is true."
2885 (let* ((yas-text (yas--field-text-for-display field))
2887 (yas-modified-p (yas--field-modified-p field))
2888 (yas-moving-away-p nil)
2889 (transform (if (yas--mirror-p field-or-mirror)
2890 (yas--mirror-transform field-or-mirror)
2891 (yas--field-transform field-or-mirror)))
2892 (start-point (if (yas--mirror-p field-or-mirror)
2893 (yas--mirror-start field-or-mirror)
2894 (yas--field-start field-or-mirror)))
2895 (transformed (and transform
2897 (goto-char start-point)
2898 (let ((ret (yas--eval-lisp transform)))
2899 (or ret (and empty-on-nil-p "")))))))
2902 (defsubst yas--replace-all (from to &optional text)
2903 "Replace all occurrences from FROM to TO.
2905 With optional string TEXT do it in that string."
2907 (replace-regexp-in-string (regexp-quote from) to text t t)
2908 (goto-char (point-min))
2909 (while (search-forward from nil t)
2910 (replace-match to t t text))))
2912 (defun yas--snippet-find-field (snippet number)
2913 (find-if #'(lambda (field)
2914 (eq number (yas--field-number field)))
2915 (yas--snippet-fields snippet)))
2917 (defun yas--snippet-sort-fields (snippet)
2918 "Sort the fields of SNIPPET in navigation order."
2919 (setf (yas--snippet-fields snippet)
2920 (sort (yas--snippet-fields snippet)
2921 #'yas--snippet-field-compare)))
2923 (defun yas--snippet-field-compare (field1 field2)
2924 "Compare FIELD1 and FIELD2.
2926 The field with a number is sorted first. If they both have a
2927 number, compare through the number. If neither have, compare
2928 through the field's start point"
2929 (let ((n1 (yas--field-number field1))
2930 (n2 (yas--field-number field2)))
2933 (or (zerop n2) (and (not (zerop n1))
2938 (< (yas--field-start field1)
2939 (yas--field-start field2))))))
2941 (defun yas--field-probably-deleted-p (snippet field)
2942 "Guess if SNIPPET's FIELD should be skipped."
2944 ;; field must be zero length
2946 (zerop (- (yas--field-start field) (yas--field-end field)))
2949 ;; 1) is a nested field and it's been modified
2951 (and (yas--field-parent-field field)
2952 (yas--field-modified-p field))
2953 ;; 2) ends just before the snippet end
2955 (and (eq field (car (last (yas--snippet-fields snippet))))
2956 (= (yas--field-start field) (overlay-end (yas--snippet-control-overlay snippet)))))
2957 ;; the field numbered 0, just before the exit marker, should
2960 (not (zerop (yas--field-number field)))))
2962 (defun yas--snippets-at-point (&optional all-snippets)
2963 "Return a sorted list of snippets at point.
2965 The most recently-inserted snippets are returned first."
2967 (remove nil (remove-duplicates (mapcar #'(lambda (ov)
2968 (overlay-get ov 'yas--snippet))
2970 (overlays-in (point-min) (point-max))
2971 (nconc (overlays-at (point)) (overlays-at (1- (point))))))))
2973 (<= (yas--snippet-id s2) (yas--snippet-id s1)))))
2975 (defun yas-next-field-or-maybe-expand ()
2976 "Try to expand a snippet at a key before point.
2978 Otherwise delegate to `yas-next-field'."
2980 (if yas-triggers-in-field
2981 (let ((yas-fallback-behavior 'return-nil)
2982 (active-field (overlay-get yas--active-field-overlay 'yas--field)))
2984 (unless (yas-expand-from-trigger-key active-field)
2988 (defun yas-next-field (&optional arg)
2989 "Navigate to the ARGth next field.
2991 If there's none, exit the snippet."
2995 (snippet (first (yas--snippets-at-point)))
2996 (active-field (overlay-get yas--active-field-overlay 'yas--field))
2997 (live-fields (remove-if #'(lambda (field)
2998 (and (not (eq field active-field))
2999 (yas--field-probably-deleted-p snippet field)))
3000 (yas--snippet-fields snippet)))
3001 (active-field-pos (position active-field live-fields))
3002 (target-pos (and active-field-pos (+ arg active-field-pos)))
3003 (target-field (and target-pos (nth target-pos live-fields))))
3004 ;; First check if we're moving out of a field with a transform
3006 (when (and active-field
3007 (yas--field-transform active-field))
3008 (let* ((yas-moving-away-p t)
3009 (yas-text (yas--field-text-for-display active-field))
3011 (yas-modified-p (yas--field-modified-p active-field)))
3012 ;; primary field transform: exit call to field-transform
3013 (yas--eval-lisp (yas--field-transform active-field))))
3014 ;; Now actually move...
3015 (cond ((and target-pos (>= target-pos (length live-fields)))
3016 (yas-exit-snippet snippet))
3018 (yas--move-to-field snippet target-field))
3022 (defun yas--place-overlays (snippet field)
3023 "Correctly place overlays for SNIPPET's FIELD."
3024 (yas--make-move-field-protection-overlays snippet field)
3025 (yas--make-move-active-field-overlay snippet field))
3027 (defun yas--move-to-field (snippet field)
3028 "Update SNIPPET to move to field FIELD.
3030 Also create some protection overlays"
3031 (goto-char (yas--field-start field))
3032 (yas--place-overlays snippet field)
3033 (overlay-put yas--active-field-overlay 'yas--field field)
3034 (let ((number (yas--field-number field)))
3035 ;; check for the special ${0: ...} field
3036 (if (and number (zerop number))
3038 (set-mark (yas--field-end field))
3039 (setf (yas--snippet-force-exit snippet)
3040 (or (yas--field-transform field)
3042 ;; make this field active
3043 (setf (yas--snippet-active-field snippet) field)
3044 ;; primary field transform: first call to snippet transform
3045 (unless (yas--field-modified-p field)
3046 (if (yas--field-update-display field snippet)
3047 (yas--update-mirrors snippet)
3048 (setf (yas--field-modified-p field) nil))))))
3050 (defun yas-prev-field ()
3051 "Navigate to prev field. If there's none, exit the snippet."
3053 (yas-next-field -1))
3055 (defun yas-abort-snippet (&optional snippet)
3057 (let ((snippet (or snippet
3058 (car (yas--snippets-at-point)))))
3060 (setf (yas--snippet-force-exit snippet) t))))
3062 (defun yas-exit-snippet (snippet)
3063 "Goto exit-marker of SNIPPET."
3064 (interactive (list (first (yas--snippets-at-point))))
3066 (setf (yas--snippet-force-exit snippet) t)
3067 (goto-char (if (yas--snippet-exit snippet)
3068 (yas--exit-marker (yas--snippet-exit snippet))
3069 (overlay-end (yas--snippet-control-overlay snippet))))))
3071 (defun yas-exit-all-snippets ()
3072 "Exit all snippets."
3074 (mapc #'(lambda (snippet)
3075 (yas-exit-snippet snippet)
3076 (yas--check-commit-snippet))
3077 (yas--snippets-at-point 'all-snippets)))
3080 ;;; Some low level snippet-routines:
3082 (defmacro yas--inhibit-overlay-hooks (&rest body)
3083 "Run BODY with `yas--inhibit-overlay-hooks' set to t."
3084 (declare (indent 0))
3085 `(let ((yas--inhibit-overlay-hooks t))
3088 (defvar yas-snippet-beg nil "Beginning position of the last snippet committed.")
3089 (defvar yas-snippet-end nil "End position of the last snippet committed.")
3091 (defun yas--commit-snippet (snippet)
3092 "Commit SNIPPET, but leave point as it is.
3094 This renders the snippet as ordinary text."
3096 (let ((control-overlay (yas--snippet-control-overlay snippet)))
3098 ;; Save the end of the moribund snippet in case we need to revive it
3099 ;; its original expansion.
3101 (when (and control-overlay
3102 (overlay-buffer control-overlay))
3103 (setq yas-snippet-beg (overlay-start control-overlay))
3104 (setq yas-snippet-end (overlay-end control-overlay))
3105 (delete-overlay control-overlay))
3107 (yas--inhibit-overlay-hooks
3108 (when yas--active-field-overlay
3109 (delete-overlay yas--active-field-overlay))
3110 (when yas--field-protection-overlays
3111 (mapc #'delete-overlay yas--field-protection-overlays)))
3113 ;; stacked expansion: if the original expansion took place from a
3114 ;; field, make sure we advance it here at least to
3115 ;; `yas-snippet-end'...
3117 (let ((previous-field (yas--snippet-previous-active-field snippet)))
3118 (when (and yas-snippet-end previous-field)
3119 (yas--advance-end-maybe previous-field yas-snippet-end)))
3121 ;; Convert all markers to points,
3123 (yas--markers-to-points snippet)
3125 ;; Take care of snippet revival
3127 (if yas-snippet-revival
3128 (push `(apply yas--snippet-revive ,yas-snippet-beg ,yas-snippet-end ,snippet)
3130 ;; Dismember the snippet... this is useful if we get called
3131 ;; again from `yas--take-care-of-redo'....
3132 (setf (yas--snippet-fields snippet) nil)))
3134 (yas--message 3 "Snippet %s exited." (yas--snippet-id snippet)))
3136 (defun yas--safely-run-hooks (hook-var)
3137 (condition-case error
3138 (run-hooks hook-var)
3140 (yas--message 3 "%s error: %s" hook-var (error-message-string error)))))
3143 (defun yas--check-commit-snippet ()
3144 "Checks if point exited the currently active field of the snippet.
3146 If so cleans up the whole snippet up."
3147 (let* ((snippets (yas--snippets-at-point 'all-snippets))
3148 (snippets-left snippets)
3149 (snippet-exit-transform))
3150 (dolist (snippet snippets)
3151 (let ((active-field (yas--snippet-active-field snippet)))
3152 (setq snippet-exit-transform (yas--snippet-force-exit snippet))
3153 (cond ((or snippet-exit-transform
3154 (not (and active-field (yas--field-contains-point-p active-field))))
3155 (setq snippets-left (delete snippet snippets-left))
3156 (setf (yas--snippet-force-exit snippet) nil)
3157 (yas--commit-snippet snippet))
3159 (or (not yas--active-field-overlay)
3160 (not (overlay-buffer yas--active-field-overlay))))
3162 ;; stacked expansion: this case is mainly for recent
3163 ;; snippet exits that place us back int the field of
3167 (yas--move-to-field snippet active-field)
3168 (yas--update-mirrors snippet)))
3171 (unless (or (null snippets) snippets-left)
3172 (if snippet-exit-transform
3173 (yas--eval-lisp-no-saves snippet-exit-transform))
3174 (yas--safely-run-hooks 'yas-after-exit-snippet-hook))))
3176 ;; Apropos markers-to-points:
3178 ;; This was found useful for performance reasons, so that an
3179 ;; excessive number of live markers aren't kept around in the
3180 ;; `buffer-undo-list'. However, in `markers-to-points', the
3181 ;; set-to-nil markers can't simply be discarded and replaced with
3182 ;; fresh ones in `points-to-markers'. The original marker that was
3183 ;; just set to nil has to be reused.
3185 ;; This shouldn't bring horrible problems with undo/redo, but it
3188 (defun yas--markers-to-points (snippet)
3189 "Convert all markers in SNIPPET to a cons (POINT . MARKER)
3190 where POINT is the original position of the marker and MARKER is
3191 the original marker object with the position set to nil."
3192 (dolist (field (yas--snippet-fields snippet))
3193 (let ((start (marker-position (yas--field-start field)))
3194 (end (marker-position (yas--field-end field))))
3195 (set-marker (yas--field-start field) nil)
3196 (set-marker (yas--field-end field) nil)
3197 (setf (yas--field-start field) (cons start (yas--field-start field)))
3198 (setf (yas--field-end field) (cons end (yas--field-end field))))
3199 (dolist (mirror (yas--field-mirrors field))
3200 (let ((start (marker-position (yas--mirror-start mirror)))
3201 (end (marker-position (yas--mirror-end mirror))))
3202 (set-marker (yas--mirror-start mirror) nil)
3203 (set-marker (yas--mirror-end mirror) nil)
3204 (setf (yas--mirror-start mirror) (cons start (yas--mirror-start mirror)))
3205 (setf (yas--mirror-end mirror) (cons end (yas--mirror-end mirror))))))
3206 (let ((snippet-exit (yas--snippet-exit snippet)))
3208 (let ((exit (marker-position (yas--exit-marker snippet-exit))))
3209 (set-marker (yas--exit-marker snippet-exit) nil)
3210 (setf (yas--exit-marker snippet-exit) (cons exit (yas--exit-marker snippet-exit)))))))
3212 (defun yas--points-to-markers (snippet)
3213 "Convert all cons (POINT . MARKER) in SNIPPET to markers.
3215 This is done by setting MARKER to POINT with `set-marker'."
3216 (dolist (field (yas--snippet-fields snippet))
3217 (setf (yas--field-start field) (set-marker (cdr (yas--field-start field))
3218 (car (yas--field-start field))))
3219 (setf (yas--field-end field) (set-marker (cdr (yas--field-end field))
3220 (car (yas--field-end field))))
3221 (dolist (mirror (yas--field-mirrors field))
3222 (setf (yas--mirror-start mirror) (set-marker (cdr (yas--mirror-start mirror))
3223 (car (yas--mirror-start mirror))))
3224 (setf (yas--mirror-end mirror) (set-marker (cdr (yas--mirror-end mirror))
3225 (car (yas--mirror-end mirror))))))
3226 (let ((snippet-exit (yas--snippet-exit snippet)))
3228 (setf (yas--exit-marker snippet-exit) (set-marker (cdr (yas--exit-marker snippet-exit))
3229 (car (yas--exit-marker snippet-exit)))))))
3231 (defun yas--field-contains-point-p (field &optional point)
3232 (let ((point (or point
3234 (and (>= point (yas--field-start field))
3235 (<= point (yas--field-end field)))))
3237 (defun yas--field-text-for-display (field)
3238 "Return the propertized display text for field FIELD."
3239 (buffer-substring (yas--field-start field) (yas--field-end field)))
3241 (defun yas--undo-in-progress ()
3242 "True if some kind of undo is in progress."
3243 (or undo-in-progress
3244 (eq this-command 'undo)
3245 (eq this-command 'redo)))
3247 (defun yas--make-control-overlay (snippet start end)
3248 "Creates the control overlay that surrounds the snippet and
3250 (let ((overlay (make-overlay start
3255 (overlay-put overlay 'keymap yas-keymap)
3256 (overlay-put overlay 'priority 100)
3257 (overlay-put overlay 'yas--snippet snippet)
3260 (defun yas-skip-and-clear-or-delete-char (&optional field)
3261 "Clears unmodified field if at field start, skips to next tab.
3263 Otherwise deletes a character normally by calling `delete-char'."
3265 (let ((field (or field
3266 (and yas--active-field-overlay
3267 (overlay-buffer yas--active-field-overlay)
3268 (overlay-get yas--active-field-overlay 'yas--field)))))
3270 (not (yas--field-modified-p field))
3271 (eq (point) (marker-position (yas--field-start field))))
3272 (yas--skip-and-clear field)
3275 (call-interactively 'delete-char)))))
3277 (defun yas--skip-and-clear (field)
3278 "Deletes the region of FIELD and sets it's modified state to t."
3279 ;; Just before skipping-and-clearing the field, mark its children
3280 ;; fields as modified, too. If the children have mirrors-in-fields
3281 ;; this prevents them from updating erroneously (we're skipping and
3284 (yas--mark-this-and-children-modified field)
3285 (delete-region (yas--field-start field) (yas--field-end field)))
3287 (defun yas--mark-this-and-children-modified (field)
3288 (setf (yas--field-modified-p field) t)
3289 (let ((fom (yas--field-next field)))
3291 (yas--fom-parent-field fom))
3292 (when (and (eq (yas--fom-parent-field fom) field)
3294 (yas--mark-this-and-children-modified fom))
3295 (setq fom (yas--fom-next fom)))))
3297 (defun yas--make-move-active-field-overlay (snippet field)
3298 "Place the active field overlay in SNIPPET's FIELD.
3300 Move the overlay, or create it if it does not exit."
3301 (if (and yas--active-field-overlay
3302 (overlay-buffer yas--active-field-overlay))
3303 (move-overlay yas--active-field-overlay
3304 (yas--field-start field)
3305 (yas--field-end field))
3306 (setq yas--active-field-overlay
3307 (make-overlay (yas--field-start field)
3308 (yas--field-end field)
3310 (overlay-put yas--active-field-overlay 'priority 100)
3311 (overlay-put yas--active-field-overlay 'face 'yas-field-highlight-face)
3312 (overlay-put yas--active-field-overlay 'yas--snippet snippet)
3313 (overlay-put yas--active-field-overlay 'modification-hooks '(yas--on-field-overlay-modification))
3314 (overlay-put yas--active-field-overlay 'insert-in-front-hooks
3315 '(yas--on-field-overlay-modification))
3316 (overlay-put yas--active-field-overlay 'insert-behind-hooks
3317 '(yas--on-field-overlay-modification))))
3319 (defvar yas--inhibit-overlay-hooks nil
3320 "Bind this temporarily to non-nil to prevent running `yas--on-*-modification'.")
3322 (defun yas--on-field-overlay-modification (overlay after? beg end &optional length)
3323 "Clears the field and updates mirrors, conditionally.
3325 Only clears the field if it hasn't been modified and it point it
3326 at field start. This hook doesn't do anything if an undo is in
3328 (unless (or yas--inhibit-overlay-hooks
3329 (yas--undo-in-progress))
3330 (let* ((field (overlay-get overlay 'yas--field))
3331 (number (and field (yas--field-number field)))
3332 (snippet (overlay-get yas--active-field-overlay 'yas--snippet)))
3334 (yas--advance-end-maybe field (overlay-end overlay))
3336 (yas--field-update-display field snippet))
3337 (yas--update-mirrors snippet))
3339 (when (and (not after?)
3340 (not (yas--field-modified-p field))
3341 (eq (point) (if (markerp (yas--field-start field))
3342 (marker-position (yas--field-start field))
3343 (yas--field-start field))))
3344 (yas--skip-and-clear field))
3345 (setf (yas--field-modified-p field) t))))))
3347 ;;; Apropos protection overlays:
3349 ;; These exist for nasty users who will try to delete parts of the
3350 ;; snippet outside the active field. Actual protection happens in
3351 ;; `yas--on-protection-overlay-modification'.
3353 ;; Currently this signals an error which inhibits the command. For
3354 ;; commands that move point (like `kill-line'), point is restored in
3355 ;; the `yas--post-command-handler' using a global
3356 ;; `yas--protection-violation' variable.
3358 ;; Alternatively, I've experimented with an implementation that
3359 ;; commits the snippet before actually calling `this-command'
3360 ;; interactively, and then signals an error, which is ignored. but
3361 ;; blocks all other million modification hooks. This presented some
3362 ;; problems with stacked expansion.
3364 (defun yas--make-move-field-protection-overlays (snippet field)
3365 "Place protection overlays surrounding SNIPPET's FIELD.
3367 Move the overlays, or create them if they do not exit."
3368 (let ((start (yas--field-start field))
3369 (end (yas--field-end field)))
3370 ;; First check if the (1+ end) is contained in the buffer,
3371 ;; otherwise we'll have to do a bit of cheating and silently
3372 ;; insert a newline. the `(1+ (buffer-size))' should prevent this
3373 ;; when using stacked expansion
3375 (when (< (buffer-size) end)
3377 (yas--inhibit-overlay-hooks
3378 (goto-char (point-max))
3380 ;; go on to normal overlay creation/moving
3382 (cond ((and yas--field-protection-overlays
3383 (every #'overlay-buffer yas--field-protection-overlays))
3384 (move-overlay (first yas--field-protection-overlays) (1- start) start)
3385 (move-overlay (second yas--field-protection-overlays) end (1+ end)))
3387 (setq yas--field-protection-overlays
3388 (list (make-overlay (1- start) start nil t nil)
3389 (make-overlay end (1+ end) nil t nil)))
3390 (dolist (ov yas--field-protection-overlays)
3391 (overlay-put ov 'face 'yas--field-debug-face)
3392 (overlay-put ov 'yas--snippet snippet)
3393 ;; (overlay-put ov 'evaporate t)
3394 (overlay-put ov 'modification-hooks '(yas--on-protection-overlay-modification)))))))
3396 (defvar yas--protection-violation nil
3397 "When non-nil, signals attempts to erroneously exit or modify the snippet.
3399 Functions in the `post-command-hook', for example
3400 `yas--post-command-handler' can check it and reset its value to
3401 nil. The variables value is the point where the violation
3404 (defun yas--on-protection-overlay-modification (overlay after? beg end &optional length)
3405 "Signals a snippet violation, then issues error.
3407 The error should be ignored in `debug-ignored-errors'"
3408 (unless yas--inhibit-overlay-hooks
3409 (cond ((not (or after?
3410 (yas--undo-in-progress)))
3411 (setq yas--protection-violation (point))
3412 (error "Exit the snippet first!")))))
3414 (add-to-list 'debug-ignored-errors "^Exit the snippet first!$")
3417 ;; Snippet expansion and "stacked" expansion:
3419 ;; Stacked expansion is when you try to expand a snippet when already
3420 ;; inside a snippet expansion.
3422 ;; The parent snippet does not run its fields modification hooks
3423 ;; (`yas--on-field-overlay-modification' and
3424 ;; `yas--on-protection-overlay-modification') while the child snippet
3425 ;; is active. This means, among other things, that the mirrors of the
3426 ;; parent snippet are not updated, this only happening when one exits
3427 ;; the child snippet.
3429 ;; Unfortunately, this also puts some ugly (and not fully-tested)
3430 ;; bits of code in `yas-expand-snippet' and
3431 ;; `yas--commit-snippet'. I've tried to mark them with "stacked
3434 ;; This was thought to be safer in an undo/redo perspective, but
3435 ;; maybe the correct implementation is to make the globals
3436 ;; `yas--active-field-overlay' and `yas--field-protection-overlays' be
3437 ;; snippet-local and be active even while the child snippet is
3438 ;; running. This would mean a lot of overlay modification hooks
3439 ;; running, but if managed correctly (including overlay priorities)
3440 ;; they should account for all situations...
3442 (defun yas-expand-snippet (content &optional start end expand-env)
3443 "Expand snippet CONTENT at current point.
3445 Text between START and END will be deleted before inserting
3446 template. EXPAND-ENV is are let-style variable to value bindings
3447 considered when expanding the snippet."
3448 (run-hooks 'yas-before-expand-snippet-hook)
3451 (let* ((yas-selected-text (or yas-selected-text
3452 (and (region-active-p)
3453 (buffer-substring-no-properties (region-beginning)
3456 (and (region-active-p)
3460 (and (region-active-p)
3463 (to-delete (and start
3465 (buffer-substring-no-properties start end)))
3468 (setq yas--indent-original-column (current-column))
3469 ;; Delete the region to delete, this *does* get undo-recorded.
3471 (when (and to-delete
3473 (delete-region start end))
3475 (cond ((listp content)
3476 ;; x) This is a snippet-command
3478 (yas--eval-lisp-no-saves content))
3480 ;; x) This is a snippet-snippet :-)
3482 ;; Narrow the region down to the content, shoosh the
3483 ;; `buffer-undo-list', and create the snippet, the new
3484 ;; snippet updates its mirrors once, so we are left with
3485 ;; some plain text. The undo action for deleting this
3486 ;; plain text will get recorded at the end.
3488 ;; stacked expansion: also shoosh the overlay modification hooks
3490 (narrow-to-region start start)
3491 (let ((buffer-undo-list t))
3492 ;; snippet creation might evaluate users elisp, which
3493 ;; might generate errors, so we have to be ready to catch
3494 ;; them mostly to make the undo information
3496 (setq yas--start-column (save-restriction (widen) (current-column)))
3497 (yas--inhibit-overlay-hooks
3500 (eval `(let* ,expand-env
3502 (yas--snippet-create (point-min) (point-max))))
3504 (yas--snippet-create (point-min) (point-max)))))))
3506 ;; stacked-expansion: This checks for stacked expansion, save the
3507 ;; `yas--previous-active-field' and advance its boundary.
3509 (let ((existing-field (and yas--active-field-overlay
3510 (overlay-buffer yas--active-field-overlay)
3511 (overlay-get yas--active-field-overlay 'yas--field))))
3512 (when existing-field
3513 (setf (yas--snippet-previous-active-field snippet) existing-field)
3514 (yas--advance-end-maybe existing-field (overlay-end yas--active-field-overlay))))
3516 ;; Exit the snippet immediately if no fields
3518 (unless (yas--snippet-fields snippet)
3519 (yas-exit-snippet snippet))
3521 ;; Push two undo actions: the deletion of the inserted contents of
3522 ;; the new snippet (without the "key") followed by an apply of
3523 ;; `yas--take-care-of-redo' on the newly inserted snippet boundaries
3525 ;; A small exception, if `yas-also-auto-indent-first-line'
3526 ;; is t and `yas--indent' decides to indent the line to a
3527 ;; point before the actual expansion point, undo would be
3528 ;; messed up. We call the early point "newstart"". case,
3529 ;; and attempt to fix undo.
3531 (let ((newstart (overlay-start (yas--snippet-control-overlay snippet)))
3532 (end (overlay-end (yas--snippet-control-overlay snippet))))
3533 (when (< newstart start)
3534 (push (cons (make-string (- start newstart) ? ) newstart) buffer-undo-list))
3535 (push (cons newstart end) buffer-undo-list)
3536 (push `(apply yas--take-care-of-redo ,start ,end ,snippet)
3538 ;; Now, schedule a move to the first field
3540 (let ((first-field (car (yas--snippet-fields snippet))))
3542 (sit-for 0) ;; fix issue 125
3543 (yas--move-to-field snippet first-field)))
3544 (yas--message 3 "snippet expanded.")
3547 (defun yas--take-care-of-redo (beg end snippet)
3548 "Commits SNIPPET, which in turn pushes an undo action for reviving it.
3550 Meant to exit in the `buffer-undo-list'."
3551 ;; slightly optimize: this action is only needed for snippets with
3552 ;; at least one field
3553 (when (yas--snippet-fields snippet)
3554 (yas--commit-snippet snippet)))
3556 (defun yas--snippet-revive (beg end snippet)
3557 "Revives SNIPPET and creates a control overlay from BEG to END.
3559 BEG and END are, we hope, the original snippets boundaries. All
3560 the markers/points exiting existing inside SNIPPET should point
3561 to their correct locations *at the time the snippet is revived*.
3563 After revival, push the `yas--take-care-of-redo' in the
3565 ;; Reconvert all the points to markers
3567 (yas--points-to-markers snippet)
3568 ;; When at least one editable field existed in the zombie snippet,
3569 ;; try to revive the whole thing...
3571 (let ((target-field (or (yas--snippet-active-field snippet)
3572 (car (yas--snippet-fields snippet)))))
3574 (setf (yas--snippet-control-overlay snippet) (yas--make-control-overlay snippet beg end))
3575 (overlay-put (yas--snippet-control-overlay snippet) 'yas--snippet snippet)
3577 (yas--move-to-field snippet target-field)
3579 (push `(apply yas--take-care-of-redo ,beg ,end ,snippet)
3580 buffer-undo-list))))
3582 (defun yas--snippet-create (begin end)
3583 "Creates a snippet from an template inserted between BEGIN and END.
3585 Returns the newly created snippet."
3586 (let ((snippet (yas--make-snippet)))
3588 (yas--snippet-parse-create snippet)
3590 ;; Sort and link each field
3591 (yas--snippet-sort-fields snippet)
3593 ;; Create keymap overlay for snippet
3594 (setf (yas--snippet-control-overlay snippet)
3595 (yas--make-control-overlay snippet (point-min) (point-max)))
3598 (goto-char (point-max))
3603 ;;; Apropos adjacencies and "fom's":
3605 ;; Once the $-constructs bits like "$n" and "${:n" are deleted in the
3606 ;; recently expanded snippet, we might actually have many fields,
3607 ;; mirrors (and the snippet exit) in the very same position in the
3608 ;; buffer. Therefore we need to single-link the
3609 ;; fields-or-mirrors-or-exit (which I have abbreviated to "fom")
3610 ;; according to their original positions in the buffer.
3612 ;; Then we have operation `yas--advance-end-maybe' and
3613 ;; `yas--advance-start-maybe', which conditionally push the starts and
3614 ;; ends of these foms down the chain.
3616 ;; This allows for like the printf with the magic ",":
3618 ;; printf ("${1:%s}\\n"${1:$(if (string-match "%" text) "," "\);")} \
3619 ;; $2${1:$(if (string-match "%" text) "\);" "")}$0
3621 (defun yas--fom-start (fom)
3622 (cond ((yas--field-p fom)
3623 (yas--field-start fom))
3624 ((yas--mirror-p fom)
3625 (yas--mirror-start fom))
3627 (yas--exit-marker fom))))
3629 (defun yas--fom-end (fom)
3630 (cond ((yas--field-p fom)
3631 (yas--field-end fom))
3632 ((yas--mirror-p fom)
3633 (yas--mirror-end fom))
3635 (yas--exit-marker fom))))
3637 (defun yas--fom-next (fom)
3638 (cond ((yas--field-p fom)
3639 (yas--field-next fom))
3640 ((yas--mirror-p fom)
3641 (yas--mirror-next fom))
3643 (yas--exit-next fom))))
3645 (defun yas--fom-parent-field (fom)
3646 (cond ((yas--field-p fom)
3647 (yas--field-parent-field fom))
3648 ((yas--mirror-p fom)
3649 (yas--mirror-parent-field fom))
3653 (defun yas--calculate-adjacencies (snippet)
3654 "Calculate adjacencies for fields or mirrors of SNIPPET.
3656 This is according to their relative positions in the buffer, and
3657 has to be called before the $-constructs are deleted."
3658 (cl-flet ((yas--fom-set-next-fom (fom nextfom)
3659 (cond ((yas--field-p fom)
3660 (setf (yas--field-next fom) nextfom))
3661 ((yas--mirror-p fom)
3662 (setf (yas--mirror-next fom) nextfom))
3664 (setf (yas--exit-next fom) nextfom))))
3665 (yas--compare-fom-begs (fom1 fom2)
3666 (if (= (yas--fom-start fom2) (yas--fom-start fom1))
3667 (yas--mirror-p fom2)
3668 (>= (yas--fom-start fom2) (yas--fom-start fom1))))
3669 (yas--link-foms (fom1 fom2)
3670 (yas--fom-set-next-fom fom1 fom2)))
3671 ;; make some yas--field, yas--mirror and yas--exit soup
3673 (when (yas--snippet-exit snippet)
3674 (push (yas--snippet-exit snippet) soup))
3675 (dolist (field (yas--snippet-fields snippet))
3677 (dolist (mirror (yas--field-mirrors field))
3678 (push mirror soup)))
3681 #'yas--compare-fom-begs))
3683 (reduce #'yas--link-foms soup)))))
3685 (defun yas--calculate-mirrors-in-fields (snippet mirror)
3686 "Attempt to assign a parent field of SNIPPET to the mirror MIRROR.
3688 Use the tightest containing field if more than one field contains
3689 the mirror. Intended to be called *before* the dollar-regions are
3691 (let ((min (point-min))
3693 (dolist (field (yas--snippet-fields snippet))
3694 (when (and (<= (yas--field-start field) (yas--mirror-start mirror))
3695 (<= (yas--mirror-end mirror) (yas--field-end field))
3696 (< min (yas--field-start field))
3697 (< (yas--field-end field) max))
3698 (setq min (yas--field-start field)
3699 max (yas--field-end field))
3700 (setf (yas--mirror-parent-field mirror) field)))))
3702 (defun yas--advance-end-maybe (fom newend)
3703 "Maybe advance FOM's end to NEWEND if it needs it.
3707 * call `yas--advance-start-maybe' on FOM's next fom.
3709 * in case FOM is field call `yas--advance-end-maybe' on its parent
3712 Also, if FOM is an exit-marker, always call
3713 `yas--advance-start-maybe' on its next fom. This is because
3714 exit-marker have identical start and end markers."
3715 (cond ((and fom (< (yas--fom-end fom) newend))
3716 (set-marker (yas--fom-end fom) newend)
3717 (yas--advance-start-maybe (yas--fom-next fom) newend)
3718 (yas--advance-end-of-parents-maybe (yas--fom-parent-field fom) newend))
3720 (yas--advance-start-maybe (yas--fom-next fom) newend))))
3722 (defun yas--advance-start-maybe (fom newstart)
3723 "Maybe advance FOM's start to NEWSTART if it needs it.
3725 If it does, also call `yas--advance-end-maybe' on FOM."
3726 (when (and fom (< (yas--fom-start fom) newstart))
3727 (set-marker (yas--fom-start fom) newstart)
3728 (yas--advance-end-maybe fom newstart)))
3730 (defun yas--advance-end-of-parents-maybe (field newend)
3731 "Like `yas--advance-end-maybe' but for parent fields.
3733 Only works for fields and doesn't care about the start of the
3734 next FOM. Works its way up recursively for parents of parents."
3736 (< (yas--field-end field) newend))
3737 (set-marker (yas--field-end field) newend)
3738 (yas--advance-end-of-parents-maybe (yas--field-parent-field field) newend)))
3740 (defvar yas--dollar-regions nil
3741 "When expanding the snippet the \"parse-create\" functions add
3742 cons cells to this var.")
3744 (defvar yas--backquote-markers-and-strings nil
3745 "List of (MARKER . STRING) marking where the values from
3746 backquoted lisp expressions should be inserted at the end of
3749 (defun yas--snippet-parse-create (snippet)
3750 "Parse a recently inserted snippet template, creating all
3751 necessary fields, mirrors and exit points.
3753 Meant to be called in a narrowed buffer, does various passes"
3754 (let ((parse-start (point)))
3755 ;; Reset the yas--dollar-regions
3757 (setq yas--dollar-regions nil)
3758 ;; protect just the backquotes
3760 (yas--protect-escapes nil '(?`))
3761 ;; replace all backquoted expressions
3763 (goto-char parse-start)
3764 (yas--save-backquotes)
3765 ;; protect escaped characters
3767 (yas--protect-escapes)
3768 ;; parse fields with {}
3770 (goto-char parse-start)
3771 (yas--field-parse-create snippet)
3772 ;; parse simple mirrors and fields
3774 (goto-char parse-start)
3775 (yas--simple-mirror-parse-create snippet)
3776 ;; parse mirror transforms
3778 (goto-char parse-start)
3779 (yas--transform-mirror-parse-create snippet)
3780 ;; calculate adjacencies of fields and mirrors
3782 (yas--calculate-adjacencies snippet)
3783 ;; Delete $-constructs
3785 (yas--delete-regions yas--dollar-regions)
3786 ;; restore backquoted expression values
3788 (yas--restore-backquotes)
3791 (goto-char parse-start)
3792 (yas--restore-escapes)
3793 ;; update mirrors for the first time
3795 (yas--update-mirrors snippet)
3796 ;; indent the best we can
3798 (goto-char parse-start)
3799 (yas--indent snippet)))
3801 (defun yas--indent-according-to-mode (snippet-markers)
3802 "Indent current line according to mode, preserving SNIPPET-MARKERS."
3803 ;;; Apropos indenting problems....
3805 ;; `indent-according-to-mode' uses whatever `indent-line-function'
3806 ;; is available. Some implementations of these functions delete text
3807 ;; before they insert. If there happens to be a marker just after
3808 ;; the text being deleted, the insertion actually happens after the
3809 ;; marker, which misplaces it.
3811 ;; This would also happen if we had used overlays with the
3812 ;; `front-advance' property set to nil.
3814 ;; This is why I have these `trouble-markers', they are the ones at
3815 ;; they are the ones at the first non-whitespace char at the line
3816 ;; (i.e. at `yas--real-line-beginning'. After indentation takes place
3817 ;; we should be at the correct to restore them to. All other
3818 ;; non-trouble-markers have been *pushed* and don't need special
3821 (goto-char (yas--real-line-beginning))
3822 (let ((trouble-markers (remove-if-not #'(lambda (marker)
3828 (indent-according-to-mode)
3829 (error (yas--message 3 "Warning: `yas--indent-according-to-mode' having problems running %s" indent-line-function)
3831 (mapc #'(lambda (marker)
3832 (set-marker marker (point)))
3835 (defvar yas--indent-original-column nil)
3836 (defun yas--indent (snippet)
3837 (let ((snippet-markers (yas--collect-snippet-markers snippet)))
3838 ;; Look for those $>
3840 (while (re-search-forward "$>" nil t)
3841 (delete-region (match-beginning 0) (match-end 0))
3842 (when (not (eq yas-indent-line 'auto))
3843 (yas--indent-according-to-mode snippet-markers))))
3844 ;; Now do stuff for 'fixed and 'auto
3846 (cond ((eq yas-indent-line 'fixed)
3847 (while (and (zerop (forward-line))
3848 (zerop (current-column)))
3849 (indent-to-column yas--indent-original-column)))
3850 ((eq yas-indent-line 'auto)
3851 (let ((end (set-marker (make-marker) (point-max)))
3852 (indent-first-line-p yas-also-auto-indent-first-line))
3853 (while (and (zerop (if indent-first-line-p
3856 (setq indent-first-line-p nil))
3860 (yas--indent-according-to-mode snippet-markers))))
3864 (defun yas--collect-snippet-markers (snippet)
3865 "Make a list of all the markers used by SNIPPET."
3867 (dolist (field (yas--snippet-fields snippet))
3868 (push (yas--field-start field) markers)
3869 (push (yas--field-end field) markers)
3870 (dolist (mirror (yas--field-mirrors field))
3871 (push (yas--mirror-start mirror) markers)
3872 (push (yas--mirror-end mirror) markers)))
3873 (let ((snippet-exit (yas--snippet-exit snippet)))
3874 (when (and snippet-exit
3875 (marker-buffer (yas--exit-marker snippet-exit)))
3876 (push (yas--exit-marker snippet-exit) markers)))
3879 (defun yas--real-line-beginning ()
3880 (let ((c (char-after (line-beginning-position)))
3881 (n (line-beginning-position)))
3882 (while (or (eql c ?\ )
3885 (setq c (char-after n)))
3888 (defun yas--escape-string (escaped)
3889 (concat "YASESCAPE" (format "%d" escaped) "PROTECTGUARD"))
3891 (defun yas--protect-escapes (&optional text escaped)
3892 "Protect all escaped characters with their numeric ASCII value.
3894 With optional string TEXT do it in string instead of buffer."
3895 (let ((changed-text text)
3896 (text-provided-p text))
3897 (mapc #'(lambda (escaped)
3899 (yas--replace-all (concat "\\" (char-to-string escaped))
3900 (yas--escape-string escaped)
3901 (when text-provided-p changed-text))))
3902 (or escaped yas--escaped-characters))
3905 (defun yas--restore-escapes (&optional text escaped)
3906 "Restore all escaped characters from their numeric ASCII value.
3908 With optional string TEXT do it in string instead of the buffer."
3909 (let ((changed-text text)
3910 (text-provided-p text))
3911 (mapc #'(lambda (escaped)
3913 (yas--replace-all (yas--escape-string escaped)
3914 (char-to-string escaped)
3915 (when text-provided-p changed-text))))
3916 (or escaped yas--escaped-characters))
3919 (defun yas--save-backquotes ()
3920 "Save all the \"`(lisp-expression)`\"-style expressions
3921 with their evaluated value into `yas--backquote-markers-and-strings'."
3922 (while (re-search-forward yas--backquote-lisp-expression-regexp nil t)
3923 (let ((current-string (match-string-no-properties 1)) transformed)
3924 (delete-region (match-beginning 0) (match-end 0))
3925 (setq transformed (yas--eval-lisp (yas--read-lisp (yas--restore-escapes current-string '(?`)))))
3926 (goto-char (match-beginning 0))
3928 (let ((marker (make-marker)))
3929 (insert "Y") ;; quite horrendous, I love it :)
3930 (set-marker marker (point))
3932 (push (cons marker transformed) yas--backquote-markers-and-strings))))))
3934 (defun yas--restore-backquotes ()
3935 "Replace markers in `yas--backquote-markers-and-strings' with their values."
3936 (while yas--backquote-markers-and-strings
3937 (let* ((marker-and-string (pop yas--backquote-markers-and-strings))
3938 (marker (car marker-and-string))
3939 (string (cdr marker-and-string)))
3945 (set-marker marker nil)))))
3947 (defun yas--scan-sexps (from count)
3949 (with-syntax-table (standard-syntax-table)
3950 (scan-sexps from count))
3954 (defun yas--make-marker (pos)
3955 "Create a marker at POS with nil `marker-insertion-type'."
3956 (let ((marker (set-marker (make-marker) pos)))
3957 (set-marker-insertion-type marker nil)
3960 (defun yas--field-parse-create (snippet &optional parent-field)
3961 "Parse most field expressions in SNIPPET, except for the simple one \"$n\".
3963 The following count as a field:
3965 * \"${n: text}\", for a numbered field with default text, as long as N is not 0;
3967 * \"${n: text$(expression)}, the same with a lisp expression;
3968 this is caught with the curiously named `yas--multi-dollar-lisp-expression-regexp'
3970 * the same as above but unnumbered, (no N:) and number is calculated automatically.
3972 When multiple expressions are found, only the last one counts."
3975 (while (re-search-forward yas--field-regexp nil t)
3976 (let* ((real-match-end-0 (yas--scan-sexps (1+ (match-beginning 0)) 1))
3977 (number (and (match-string-no-properties 1)
3978 (string-to-number (match-string-no-properties 1))))
3979 (brand-new-field (and real-match-end-0
3980 ;; break if on "$(" immediately
3981 ;; after the ":", this will be
3982 ;; caught as a mirror with
3984 (not (save-match-data
3985 (eq (string-match "$[ \t\n]*("
3986 (match-string-no-properties 2)) 0)))
3987 ;; allow ${0: some exit text}
3988 ;; (not (and number (zerop number)))
3989 (yas--make-field number
3990 (yas--make-marker (match-beginning 2))
3991 (yas--make-marker (1- real-match-end-0))
3993 (when brand-new-field
3994 (goto-char real-match-end-0)
3995 (push (cons (1- real-match-end-0) real-match-end-0)
3996 yas--dollar-regions)
3997 (push (cons (match-beginning 0) (match-beginning 2))
3998 yas--dollar-regions)
3999 (push brand-new-field (yas--snippet-fields snippet))
4002 (narrow-to-region (yas--field-start brand-new-field) (yas--field-end brand-new-field))
4003 (goto-char (point-min))
4004 (yas--field-parse-create snippet brand-new-field)))))))
4005 ;; if we entered from a parent field, now search for the
4006 ;; `yas--multi-dollar-lisp-expression-regexp'. This is used for
4007 ;; primary field transformations
4011 (while (re-search-forward yas--multi-dollar-lisp-expression-regexp nil t)
4012 (let* ((real-match-end-1 (yas--scan-sexps (match-beginning 1) 1)))
4013 ;; commit the primary field transformation if:
4015 ;; 1. we don't find it in yas--dollar-regions (a subnested
4016 ;; field) might have already caught it.
4018 ;; 2. we really make sure we have either two '$' or some
4019 ;; text and a '$' after the colon ':'. This is a FIXME: work
4020 ;; my regular expressions and end these ugly hacks.
4022 (when (and real-match-end-1
4023 (not (member (cons (match-beginning 0)
4025 yas--dollar-regions))
4027 (char-before (1- (match-beginning 1))))))
4028 (let ((lisp-expression-string (buffer-substring-no-properties (match-beginning 1)
4030 (setf (yas--field-transform parent-field)
4031 (yas--read-lisp (yas--restore-escapes lisp-expression-string))))
4032 (push (cons (match-beginning 0) real-match-end-1)
4033 yas--dollar-regions)))))))
4035 (defun yas--transform-mirror-parse-create (snippet)
4036 "Parse the \"${n:$(lisp-expression)}\" mirror transformations in SNIPPET."
4037 (while (re-search-forward yas--transform-mirror-regexp nil t)
4038 (let* ((real-match-end-0 (yas--scan-sexps (1+ (match-beginning 0)) 1))
4039 (number (string-to-number (match-string-no-properties 1)))
4041 (not (zerop number))
4042 (yas--snippet-find-field snippet number)))
4044 (and real-match-end-0
4046 (yas--make-mirror (yas--make-marker (match-beginning 0))
4047 (yas--make-marker (match-beginning 0))
4049 (yas--restore-escapes
4050 (buffer-substring-no-properties (match-beginning 2)
4051 (1- real-match-end-0))))))))
4052 (when brand-new-mirror
4053 (push brand-new-mirror
4054 (yas--field-mirrors field))
4055 (yas--calculate-mirrors-in-fields snippet brand-new-mirror)
4056 (push (cons (match-beginning 0) real-match-end-0) yas--dollar-regions)))))
4058 (defun yas--simple-mirror-parse-create (snippet)
4059 "Parse the simple \"$n\" fields/mirrors/exitmarkers in SNIPPET."
4060 (while (re-search-forward yas--simple-mirror-regexp nil t)
4061 (let ((number (string-to-number (match-string-no-properties 1))))
4062 (cond ((zerop number)
4064 (setf (yas--snippet-exit snippet)
4065 (yas--make-exit (yas--make-marker (match-end 0))))
4067 (goto-char (match-beginning 0))
4068 (when yas-wrap-around-region
4069 (cond (yas-selected-text
4070 (insert yas-selected-text))
4071 ((and (eq yas-wrap-around-region 'cua)
4074 (insert (prog1 (get-register ?0)
4075 (set-register ?0 nil))))))
4076 (push (cons (point) (yas--exit-marker (yas--snippet-exit snippet)))
4077 yas--dollar-regions)))
4079 (let ((field (yas--snippet-find-field snippet number)))
4081 (let ((brand-new-mirror (yas--make-mirror
4082 (yas--make-marker (match-beginning 0))
4083 (yas--make-marker (match-beginning 0))
4085 (push brand-new-mirror
4086 (yas--field-mirrors field))
4087 (yas--calculate-mirrors-in-fields snippet brand-new-mirror))
4088 (push (yas--make-field number
4089 (yas--make-marker (match-beginning 0))
4090 (yas--make-marker (match-beginning 0))
4092 (yas--snippet-fields snippet))))
4093 (push (cons (match-beginning 0) (match-end 0))
4094 yas--dollar-regions))))))
4096 (defun yas--delete-regions (regions)
4097 "Sort disjuct REGIONS by start point, then delete from the back."
4098 (mapc #'(lambda (reg)
4099 (delete-region (car reg) (cdr reg)))
4102 (>= (car r1) (car r2))))))
4104 (defun yas--update-mirrors (snippet)
4105 "Updates all the mirrors of SNIPPET."
4107 (dolist (field-and-mirror (sort
4108 ;; make a list of ((F1 . M1) (F1 . M2) (F2 . M3) (F2 . M4) ...)
4109 ;; where F is the field that M is mirroring
4111 (mapcan #'(lambda (field)
4112 (mapcar #'(lambda (mirror)
4113 (cons field mirror))
4114 (yas--field-mirrors field)))
4115 (yas--snippet-fields snippet))
4116 ;; then sort this list so that entries with mirrors with parent
4117 ;; fields appear before. This was important for fixing #290, and
4118 ;; luckily also handles the case where a mirror in a field causes
4119 ;; another mirror to need reupdating
4121 #'(lambda (field-and-mirror1 field-and-mirror2)
4122 (yas--mirror-parent-field (cdr field-and-mirror1)))))
4123 (let* ((field (car field-and-mirror))
4124 (mirror (cdr field-and-mirror))
4125 (parent-field (yas--mirror-parent-field mirror)))
4126 ;; before updating a mirror with a parent-field, maybe advance
4130 (yas--advance-start-maybe mirror (yas--fom-start parent-field)))
4131 ;; update this mirror
4133 (yas--mirror-update-display mirror field)
4134 ;; `yas--place-overlays' is needed if the active field and
4135 ;; protected overlays have been changed because of insertions
4136 ;; in `yas--mirror-update-display'
4138 (when (eq field (yas--snippet-active-field snippet))
4139 (yas--place-overlays snippet field))))))
4141 (defun yas--mirror-update-display (mirror field)
4142 "Update MIRROR according to FIELD (and mirror transform)."
4144 (let* ((mirror-parent-field (yas--mirror-parent-field mirror))
4145 (reflection (and (not (and mirror-parent-field
4146 (yas--field-modified-p mirror-parent-field)))
4147 (or (yas--apply-transform mirror field 'empty-on-nil)
4148 (yas--field-text-for-display field)))))
4149 (when (and reflection
4150 (not (string= reflection (buffer-substring-no-properties (yas--mirror-start mirror)
4151 (yas--mirror-end mirror)))))
4152 (goto-char (yas--mirror-start mirror))
4153 (yas--inhibit-overlay-hooks
4154 (insert reflection))
4155 (if (> (yas--mirror-end mirror) (point))
4156 (delete-region (point) (yas--mirror-end mirror))
4157 (set-marker (yas--mirror-end mirror) (point))
4158 (yas--advance-start-maybe (yas--mirror-next mirror) (point))
4159 ;; super-special advance
4160 (yas--advance-end-of-parents-maybe mirror-parent-field (point))))))
4162 (defun yas--field-update-display (field snippet)
4163 "Much like `yas--mirror-update-display', but for fields."
4164 (when (yas--field-transform field)
4165 (let ((transformed (and (not (eq (yas--field-number field) 0))
4166 (yas--apply-transform field field)))
4168 (when (and transformed
4169 (not (string= transformed (buffer-substring-no-properties (yas--field-start field)
4170 (yas--field-end field)))))
4171 (setf (yas--field-modified-p field) t)
4172 (goto-char (yas--field-start field))
4173 (yas--inhibit-overlay-hooks
4174 (insert transformed)
4175 (if (> (yas--field-end field) (point))
4176 (delete-region (point) (yas--field-end field))
4177 (set-marker (yas--field-end field) (point))
4178 (yas--advance-start-maybe (yas--field-next field) (point)))
4182 ;;; Post-command hook:
4184 (defun yas--post-command-handler ()
4185 "Handles various yasnippet conditions after each command."
4186 (cond (yas--protection-violation
4187 (goto-char yas--protection-violation)
4188 (setq yas--protection-violation nil))
4189 ((eq 'undo this-command)
4191 ;; After undo revival the correct field is sometimes not
4192 ;; restored correctly, this condition handles that
4194 (let* ((snippet (car (yas--snippets-at-point)))
4195 (target-field (and snippet
4196 (find-if-not #'(lambda (field)
4197 (yas--field-probably-deleted-p snippet field))
4199 (cons (yas--snippet-active-field snippet)
4200 (yas--snippet-fields snippet)))))))
4202 (yas--move-to-field snippet target-field))))
4203 ((not (yas--undo-in-progress))
4204 ;; When not in an undo, check if we must commit the snippet
4205 ;; (user exited it).
4206 (yas--check-commit-snippet))))
4210 ;; The docstrings for some functions are generated dynamically
4211 ;; depending on the context.
4213 (put 'yas-expand 'function-documentation
4214 '(yas--expand-from-trigger-key-doc))
4215 (defun yas--expand-from-trigger-key-doc ()
4216 "A doc synthesizer for `yas--expand-from-trigger-key-doc'."
4217 (let ((fallback-description
4218 (cond ((eq yas-fallback-behavior 'call-other-command)
4219 (let* ((fallback (yas--keybinding-beyond-yasnippet)))
4221 (format " call command `%s'." (pp-to-string fallback)))
4222 " do nothing (`yas-expand' doesn't shadow\nanything)")))
4223 ((eq yas-fallback-behavior 'return-nil)
4226 ", defer to `yas-fallback-behaviour' (which see)"))))
4227 (concat "Expand a snippet before point. If no snippet
4228 expansion is possible,"
4229 fallback-description
4230 "\n\nOptional argument FIELD is for non-interactive use and is an
4231 object satisfying `yas--field-p' to restrict the expansion to.")))
4233 (put 'yas-expand-from-keymap 'function-documentation '(yas--expand-from-keymap-doc))
4234 (defun yas--expand-from-keymap-doc ()
4235 "A doc synthesizer for `yas--expand-from-keymap-doc'."
4236 (add-hook 'temp-buffer-show-hook 'yas--snippet-description-finish-runonce)
4237 (concat "Expand/run snippets from keymaps, possibly falling back to original binding.\n"
4238 (when (eq this-command 'describe-key)
4239 (let* ((vec (this-single-command-keys))
4240 (templates (mapcan #'(lambda (table)
4241 (yas--fetch table vec))
4242 (yas--get-snippet-tables)))
4243 (yas--direct-keymaps nil)
4244 (fallback (key-binding vec)))
4245 (concat "In this case, "
4247 (concat "these snippets are bound to this key:\n"
4248 (yas--template-pretty-list templates)
4249 "\n\nIf none of these expands, "))
4251 (format "fallback `%s' will be called." (pp-to-string fallback)))
4252 "no fallback keybinding is called."))))))
4254 (defun yas--template-pretty-list (templates)
4256 (yas-buffer-local-condition 'always))
4257 (dolist (plate templates)
4258 (setq acc (concat acc "\n*) "
4259 (propertize (concat "\\\\snippet `" (car plate) "'")
4260 'yasnippet (cdr plate)))))
4263 (define-button-type 'help-snippet-def
4264 :supertype 'help-xref
4265 'help-function (lambda (template) (yas--visit-snippet-file-1 template))
4266 'help-echo (purecopy "mouse-2, RET: find snippets's definition"))
4268 (defun yas--snippet-description-finish-runonce ()
4269 "Final adjustments for the help buffer when snippets are concerned."
4270 (yas--create-snippet-xrefs)
4271 (remove-hook 'temp-buffer-show-hook 'yas--snippet-description-finish-runonce))
4273 (defun yas--create-snippet-xrefs ()
4275 (goto-char (point-min))
4276 (while (search-forward-regexp "\\\\\\\\snippet[ \s\t]+`\\([^']+\\)'" nil t)
4277 (let ((template (get-text-property (match-beginning 1)
4280 (help-xref-button 1 'help-snippet-def template)
4281 (kill-region (match-end 1) (match-end 0))
4282 (kill-region (match-beginning 0) (match-beginning 1)))))))
4284 (defun yas--expand-uuid (mode-symbol uuid &optional start end expand-env)
4285 "Expand a snippet registered in MODE-SYMBOL's table with UUID.
4287 Remaining args as in `yas-expand-snippet'."
4288 (let* ((table (gethash mode-symbol yas--tables))
4289 (yas--current-template (and table
4290 (gethash uuid (yas--table-uuidhash table)))))
4291 (when yas--current-template
4292 (yas-expand-snippet (yas--template-content yas--current-template)))))
4296 (defvar yas-verbosity 4
4297 "Log level for `yas--message' 4 means trace most anything, 0 means nothing.")
4299 (defun yas--message (level message &rest args)
4300 "When LEVEL is above `yas-verbosity-level', log MESSAGE and ARGS."
4301 (when (> yas-verbosity level)
4302 (message (apply #'yas--format message args))))
4304 (defun yas--format (format-control &rest format-args)
4305 (apply #'format (concat "[yas] " format-control) format-args))
4312 ;; `locate-dominating-file'
4313 ;; `region-active-p'
4315 ;; added for compatibility in emacsen < 23
4316 (unless (>= emacs-major-version 23)
4317 (unless (fboundp 'region-active-p)
4318 (defun region-active-p () (and transient-mark-mode mark-active)))
4320 (unless (fboundp 'locate-dominating-file)
4321 (defvar locate-dominating-stop-dir-regexp
4322 "\\`\\(?:[\\/][\\/][^\\/]+[\\/]\\|/\\(?:net\\|afs\\|\\.\\.\\.\\)/\\)\\'"
4323 "Regexp of directory names which stop the search in `locate-dominating-file'.
4324 Any directory whose name matches this regexp will be treated like
4325 a kind of root directory by `locate-dominating-file' which will stop its search
4326 when it bumps into it.
4327 The default regexp prevents fruitless and time-consuming attempts to find
4328 special files in directories in which filenames are interpreted as hostnames,
4329 or mount points potentially requiring authentication as a different user.")
4331 (defun locate-dominating-file (file name)
4332 "Look up the directory hierarchy from FILE for a file named NAME.
4333 Stop at the first parent directory containing a file NAME,
4334 and return the directory. Return nil if not found."
4335 ;; We used to use the above locate-dominating-files code, but the
4336 ;; directory-files call is very costly, so we're much better off doing
4337 ;; multiple calls using the code in here.
4339 ;; Represent /home/luser/foo as ~/foo so that we don't try to look for
4340 ;; `name' in /home or in /.
4341 (setq file (abbreviate-file-name file))
4344 ;; `user' is not initialized outside the loop because
4345 ;; `file' may not exist, so we may have to walk up part of the
4346 ;; hierarchy before we find the "initial UUID".
4349 (while (not (or root
4351 ;; FIXME: Disabled this heuristic because it is sometimes
4353 ;; As a heuristic, we stop looking up the hierarchy of
4354 ;; directories as soon as we find a directory belonging
4355 ;; to another user. This should save us from looking in
4356 ;; things like /net and /afs. This assumes that all the
4357 ;; files inside a project belong to the same user.
4358 ;; (let ((prev-user user))
4359 ;; (setq user (nth 2 (file-attributes file)))
4360 ;; (and prev-user (not (equal user prev-user))))
4361 (string-match locate-dominating-stop-dir-regexp file)))
4362 (setq try (file-exists-p (expand-file-name name file)))
4363 (cond (try (setq root file))
4364 ((equal file (setq prev-file file
4365 file (file-name-directory
4366 (directory-file-name file))))
4370 ;; `c-neutralize-syntax-in-CPP` sometimes fires "End of Buffer" error
4371 ;; (when it execute forward-char) and interrupt the after change
4372 ;; hook. Thus prevent the insert-behind hook of yasnippet to be
4373 ;; invoked. Here's a way to reproduce it:
4375 ;; # open a *new* Emacs.
4376 ;; # load yasnippet.
4377 ;; # open a *new* .cpp file.
4378 ;; # input "inc" and press TAB to expand the snippet.
4379 ;; # select the `#include <...>` snippet.
4380 ;; # type inside `<>`
4382 (defadvice c-neutralize-syntax-in-CPP
4383 (around yas--mp/c-neutralize-syntax-in-CPP activate)
4384 "Adviced `c-neutralize-syntax-in-CPP' to properly
4385 handle the end-of-buffer error fired in it by calling
4386 `forward-char' at the end of buffer."
4389 (error (message (error-message-string err)))))
4391 ;; disable c-electric-* serial command in YAS fields
4392 (add-hook 'c-mode-common-hook
4394 (dolist (k '(":" ">" ";" "<" "{" "}"))
4395 (define-key (symbol-value (make-local-variable 'yas-keymap))
4396 k 'self-insert-command))))
4398 ;;; Backward compatibility to yasnippet <= 0.7
4399 (defvar yas--exported-syms '(;; `defcustom's
4402 yas-prompt-functions
4404 yas-also-auto-indent-first-line
4406 yas-triggers-in-field
4407 yas-fallback-behavior
4408 yas-choose-keys-first
4409 yas-choose-tables-first
4412 yas-wrap-around-region
4415 yas-expand-only-for-last-commands
4416 yas-field-highlight-face
4418 ;; these vars can be customized as well
4424 yas-after-exit-snippet-hook
4425 yas-before-expand-snippet-hook
4426 yas-buffer-local-condition
4429 ;; prompting functions
4434 yas-completing-prompt
4437 ;; interactive functions
4442 yas-direct-keymaps-reload
4446 yas-compile-directory
4449 yas-expand-from-trigger-key
4450 yas-expand-from-keymap
4452 yas-visit-snippet-file
4454 yas-load-snippet-buffer
4457 yas-next-field-or-maybe-expand
4462 yas-exit-all-snippets
4463 yas-skip-and-clear-or-delete-char
4465 ;; symbols that I "exported" for use
4466 ;; in snippets and hookage
4484 yas-default-from-field
4487 yas-define-condition-cache
4488 yas-hippie-try-expand
4491 ;; debug definitions
4492 ;; yas-debug-snippet-vars
4493 ;; yas-exterminate-package
4496 ;; testing definitions
4497 ;; yas-should-expand
4498 ;; yas-should-not-expand
4500 ;; yas-make-file-or-dirs
4502 ;; yas-saving-variables
4503 ;; yas-call-with-snippet-dirs
4504 ;; yas-with-snippet-dirs
4506 "Exported yasnippet symbols.
4508 i.e. ones that I will try to keep in future yasnippet versions
4509 and ones that other elisp libraries can more or less safely rely
4512 (defvar yas--dont-backport '(yas-active-keys)
4513 "Exported symbols that don't map back to \"yas/*\" variants.")
4515 (dolist (sym (set-difference yas--exported-syms yas--dont-backport))
4516 (let ((backported (intern (replace-regexp-in-string "^yas-" "yas/" (symbol-name sym)))))
4518 (make-obsolete-variable backported sym "yasnippet 0.8")
4519 (defvaralias backported sym))
4521 (make-obsolete backported sym "yasnippet 0.8")
4522 (defalias backported sym))))
4525 (provide 'yasnippet)
4527 ;;; yasnippet.el ends here
4530 ;; byte-compile-warnings: (not cl-functions)