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 ;;; User-visible variables
380 (defvar yas-keymap (let ((map (make-sparse-keymap)))
381 (define-key map [(tab)] 'yas-next-field-or-maybe-expand)
382 (define-key map (kbd "TAB") 'yas-next-field-or-maybe-expand)
383 (define-key map [(shift tab)] 'yas-prev-field)
384 (define-key map [backtab] 'yas-prev-field)
385 (define-key map (kbd "C-g") 'yas-abort-snippet)
386 (define-key map (kbd "C-d") 'yas-skip-and-clear-or-delete-char)
388 "The active keymap while a snippet expansion is in progress.")
390 (defvar yas-key-syntaxes (list "w" "w_" "w_." "w_.()" "^ ")
391 "List of character syntaxes used to find a trigger key before point.
392 The list is tried in the order while scanning characters
393 backwards from point. For example, if the list is '(\"w\" \"w_\")
394 first look for trigger keys which are composed exclusively of
395 \"word\"-syntax characters, and then, if that fails, look for
396 keys which are either of \"word\" or \"symbol\"
397 syntax. Triggering after
401 will, according to the \"w\" element first try \"bar\". If that
402 isn't a trigger key, \"foo-bar\" is tried, respecting a second
405 (defvar yas-after-exit-snippet-hook
407 "Hooks to run after a snippet exited.
409 The hooks will be run in an environment where some variables bound to
412 `yas-snippet-beg' : The beginning of the region of the snippet.
414 `yas-snippet-end' : Similar to beg.
416 Attention: These hooks are not run when exiting nested/stacked snippet expansion!")
418 (defvar yas-before-expand-snippet-hook
420 "Hooks to run just before expanding a snippet.")
422 (defvar yas-buffer-local-condition
423 '(if (and (or (fourth (syntax-ppss))
424 (fifth (syntax-ppss)))
425 (eq (symbol-function this-command) 'yas-expand-from-trigger-key))
426 '(require-snippet-condition . force-in-comment)
428 "Snippet expanding condition.
430 This variable is a Lisp form which is evaluated every time a
431 snippet expansion is attempted:
433 * If it evaluates to nil, no snippets can be expanded.
435 * If it evaluates to the a cons (require-snippet-condition
438 * Snippets bearing no \"# condition:\" directive are not
441 * Snippets bearing conditions that evaluate to nil (or
442 produce an error) won't be considered.
444 * If the snippet has a condition that evaluates to non-nil
447 * If REQUIREMENT is t, the snippet is considered
449 * If REQUIREMENT is `eq' RESULT, the snippet is
452 * Otherwise, the snippet is not considered.
454 * If it evaluates to the symbol 'always, all snippets are
455 considered for expansion, regardless of any conditions.
457 * If it evaluates to t or some other non-nil value
459 * Snippet bearing no conditions, or conditions that
460 evaluate to non-nil, are considered for expansion.
462 * Otherwise, the snippet is not considered.
464 Here's an example preventing snippets from being expanded from
465 inside comments, in `python-mode' only, with the exception of
466 snippets returning the symbol 'force-in-comment in their
469 (add-hook 'python-mode-hook
471 (setq yas-buffer-local-condition
472 '(if (python-in-string/comment)
473 '(require-snippet-condition . force-in-comment)
476 The default value is similar, it filters out potential snippet
477 expansions inside comments and string literals, unless the
478 snippet itself contains a condition that returns the symbol
479 `force-in-comment'.")
482 ;;; Internal variables
484 (defvar yas--version "0.8.0 (beta)")
486 (defvar yas--menu-table (make-hash-table)
487 "A hash table of MAJOR-MODE symbols to menu keymaps.")
489 (defvar yas--known-modes
490 '(ruby-mode rst-mode markdown-mode)
491 "A list of mode which is well known but not part of Emacs.")
493 (defvar yas--escaped-characters
494 '(?\\ ?` ?\" ?' ?$ ?} ?{ ?\( ?\))
495 "List of characters which *might* need to be escaped.")
497 (defconst yas--field-regexp
498 "${\\([0-9]+:\\)?\\([^}]*\\)}"
499 "A regexp to *almost* recognize a field.")
501 (defconst yas--multi-dollar-lisp-expression-regexp
502 "$+[ \t\n]*\\(([^)]*)\\)"
503 "A regexp to *almost* recognize a \"$(...)\" expression.")
505 (defconst yas--backquote-lisp-expression-regexp
507 "A regexp to recognize a \"`lisp-expression`\" expression." )
509 (defconst yas--transform-mirror-regexp
510 "${\\(?:\\([0-9]+\\):\\)?$\\([ \t\n]*([^}]*\\)"
511 "A regexp to *almost* recognize a mirror with a transform.")
513 (defconst yas--simple-mirror-regexp
515 "A regexp to recognize a simple mirror.")
517 (defvar yas--snippet-id-seed 0
518 "Contains the next id for a snippet.")
520 (defun yas--snippet-next-id ()
521 (let ((id yas--snippet-id-seed))
522 (incf yas--snippet-id-seed)
528 ;; XXX: `last-buffer-undo-list' is somehow needed in Carbon Emacs for MacOSX
529 (defvar last-buffer-undo-list nil)
531 (defvar yas--minor-mode-menu nil
532 "Holds the YASnippet menu.")
534 (defun yas--init-minor-keymap ()
535 "Set up the `yas-minor-mode' keymap."
536 (let ((map (make-sparse-keymap)))
538 (easy-menu-define yas--minor-mode-menu
540 "Menu used when `yas-minor-mode' is active."
543 ["Expand trigger" yas-expand
544 :help "Possibly expand tab trigger before point"]
545 ["Insert at point..." yas-insert-snippet
546 :help "Prompt for an expandable snippet and expand it at point"]
547 ["New snippet..." yas-new-snippet
548 :help "Create a new snippet in an appropriate directory"]
549 ["Visit snippet file..." yas-visit-snippet-file
550 :help "Prompt for an expandable snippet and find its file"]
552 ("Snippet menu behaviour"
553 ["Visit snippets" (setq yas-visit-from-menu t)
554 :help "Visit snippets from the menu"
555 :active t :style radio :selected yas-visit-from-menu]
556 ["Expand snippets" (setq yas-visit-from-menu nil)
557 :help "Expand snippets from the menu"
558 :active t :style radio :selected (not yas-visit-from-menu)]
560 ["Show all known modes" (setq yas-use-menu 'full)
561 :help "Show one snippet submenu for each loaded table"
562 :active t :style radio :selected (eq yas-use-menu 'full)]
563 ["Abbreviate according to current mode" (setq yas-use-menu 'abbreviate)
564 :help "Show only snippet submenus for the current active modes"
565 :active t :style radio :selected (eq yas-use-menu 'abbreviate)])
567 ["Auto" (setq yas-indent-line 'auto)
568 :help "Indent each line of the snippet with `indent-according-to-mode'"
569 :active t :style radio :selected (eq yas-indent-line 'auto)]
570 ["Fixed" (setq yas-indent-line 'fixed)
571 :help "Indent the snippet to the current column"
572 :active t :style radio :selected (eq yas-indent-line 'fixed)]
573 ["None" (setq yas-indent-line 'none)
574 :help "Don't apply any particular snippet indentation after expansion"
575 :active t :style radio :selected (not (member yas-indent-line '(fixed auto)))]
577 ["Also auto indent first line" (setq yas-also-auto-indent-first-line
578 (not yas-also-auto-indent-first-line))
579 :help "When auto-indenting also, auto indent the first line menu"
580 :active (eq yas-indent-line 'auto)
581 :style toggle :selected yas-also-auto-indent-first-line]
584 ["System X-widget" (setq yas-prompt-functions
586 (remove 'yas-x-prompt
587 yas-prompt-functions)))
588 :help "Use your windowing system's (gtk, mac, windows, etc...) default menu"
589 :active t :style radio :selected (eq (car yas-prompt-functions)
591 ["Dropdown-list" (setq yas-prompt-functions
592 (cons 'yas-dropdown-prompt
593 (remove 'yas-dropdown-prompt
594 yas-prompt-functions)))
595 :help "Use a special dropdown list"
596 :active t :style radio :selected (eq (car yas-prompt-functions)
597 'yas-dropdown-prompt)]
598 ["Ido" (setq yas-prompt-functions
599 (cons 'yas-ido-prompt
600 (remove 'yas-ido-prompt
601 yas-prompt-functions)))
602 :help "Use an ido-style minibuffer prompt"
603 :active t :style radio :selected (eq (car yas-prompt-functions)
605 ["Completing read" (setq yas-prompt-functions
606 (cons 'yas-completing-prompt
607 (remove 'yas-completing-prompt
608 yas-prompt-functions)))
609 :help "Use a normal minibuffer prompt"
610 :active t :style radio :selected (eq (car yas-prompt-functions)
611 'yas-completing-prompt)]
614 ["Wrap region in exit marker"
615 (setq yas-wrap-around-region
616 (not yas-wrap-around-region))
617 :help "If non-nil automatically wrap the selected text in the $0 snippet exit"
618 :style toggle :selected yas-wrap-around-region]
619 ["Allow stacked expansions "
620 (setq yas-triggers-in-field
621 (not yas-triggers-in-field))
622 :help "If non-nil allow snippets to be triggered inside other snippet fields"
623 :style toggle :selected yas-triggers-in-field]
624 ["Revive snippets on undo "
625 (setq yas-snippet-revival
626 (not yas-snippet-revival))
627 :help "If non-nil allow snippets to become active again after undo"
628 :style toggle :selected yas-snippet-revival]
631 (not yas-good-grace))
632 :help "If non-nil don't raise errors in bad embedded elisp in snippets"
633 :style toggle :selected yas-good-grace]
636 ["Load snippets..." yas-load-directory
637 :help "Load snippets from a specific directory"]
638 ["Reload everything" yas-reload-all
639 :help "Cleanup stuff, reload snippets, rebuild menus"]
641 :help "Display some information about YASnippet"])))
643 ;; Now for the stuff that has direct keybindings
645 (define-key map [(tab)] 'yas-expand)
646 (define-key map (kbd "TAB") 'yas-expand)
647 (define-key map "\C-c&\C-s" 'yas-insert-snippet)
648 (define-key map "\C-c&\C-n" 'yas-new-snippet)
649 (define-key map "\C-c&\C-v" 'yas-visit-snippet-file)
652 (defvar yas-minor-mode-map (yas--init-minor-keymap)
653 "The keymap used when `yas-minor-mode' is active.")
655 (defvar yas--tables (make-hash-table)
656 "A hash table of mode symbols to `yas--table' objects.")
658 (defvar yas--parents (make-hash-table)
659 "A hash table of mode symbols do lists of direct parent mode symbols.
661 This list is populated when reading the \".yas-parents\" files
662 found when traversing snippet directories with
663 `yas-load-directory'.
665 There might be additional parenting information stored in the
666 `derived-mode-parent' property of some mode symbols, but that is
669 (defvar yas--direct-keymaps (list)
670 "Keymap alist supporting direct snippet keybindings.
672 This variable is placed in `emulation-mode-map-alists'.
674 Its elements looks like (TABLE-NAME . KEYMAP). They're
675 instantiated on `yas-reload-all' but KEYMAP is added to only when
676 loading snippets. `yas--direct-TABLE-NAME' is then a variable set
677 buffer-locally when entering `yas-minor-mode'. KEYMAP binds all
678 defined direct keybindings to the command
679 `yas-expand-from-keymap' which then which snippet to expand.")
681 (defun yas-direct-keymaps-reload ()
682 "Force reload the direct keybinding for active snippet tables."
684 (setq yas--direct-keymaps nil)
685 (maphash #'(lambda (name table)
686 (push (cons (intern (format "yas--direct-%s" name))
687 (yas--table-direct-keymap table))
688 yas--direct-keymaps))
691 (defun yas--modes-to-activate ()
692 "Compute list of mode symbols that are active for `yas-expand'
694 (let ((modes-to-activate (list major-mode))
696 (while (setq mode (get mode 'derived-mode-parent))
697 (push mode modes-to-activate))
698 (dolist (mode (yas-extra-modes))
699 (push mode modes-to-activate))
701 (append modes-to-activate
702 (mapcan #'(lambda (mode)
703 (yas--all-parents mode))
704 modes-to-activate)))))
706 (defvar yas-minor-mode-hook nil
707 "Hook run when `yas-minor-mode' is turned on.")
710 (define-minor-mode yas-minor-mode
711 "Toggle YASnippet mode.
713 When YASnippet mode is enabled, `yas-expand', normally bound to
714 the TAB key, expands snippets of code depending on the major
717 With no argument, this command toggles the mode.
718 positive prefix argument turns on the mode.
719 Negative prefix argument turns off the mode.
722 \\{yas-minor-mode-map}"
724 ;; The indicator for the mode line.
727 (cond (yas-minor-mode
728 ;; Install the direct keymaps in `emulation-mode-map-alists'
729 ;; (we use `add-hook' even though it's not technically a hook,
730 ;; but it works). Then define variables named after modes to
731 ;; index `yas--direct-keymaps'.
733 ;; Also install the post-command-hook.
735 (add-hook 'emulation-mode-map-alists 'yas--direct-keymaps)
736 (add-hook 'post-command-hook 'yas--post-command-handler nil t)
737 ;; Set the `yas--direct-%s' vars for direct keymap expansion
739 (dolist (mode (yas--modes-to-activate))
740 (let ((name (intern (format "yas--direct-%s" mode))))
741 (set-default name nil)
742 (set (make-local-variable name) t)))
745 (yas--load-pending-jits))
747 ;; Uninstall the direct keymaps and the post-command hook
749 (remove-hook 'post-command-hook 'yas--post-command-handler t)
750 (remove-hook 'emulation-mode-map-alists 'yas--direct-keymaps))))
752 (defvar yas-dont-activate '(minibufferp)
753 "If non-nil don't let `yas-minor-mode-on' activate for this buffer.
755 If a function, then its result is used.
757 If a list of functions, then all functions must return nil to
758 activate yas for this buffer.
760 `yas-minor-mode-on' is usually called by `yas-global-mode' so
761 this effectively lets you define exceptions to the \"global\"
762 behaviour. Can also be a function of zero arguments.")
763 (make-variable-buffer-local 'yas-dont-activate)
765 (defun yas-minor-mode-on ()
766 "Turn on YASnippet minor mode.
768 Honour `yas-dont-activate', which see."
770 ;; Check `yas-dont-activate'
771 (unless (cond ((functionp yas-dont-activate)
772 (funcall yas-dont-activate))
773 ((consp yas-dont-activate)
774 (some #'funcall yas-dont-activate))
779 (define-globalized-minor-mode yas-global-mode yas-minor-mode yas-minor-mode-on
783 (defun yas--global-mode-reload-with-jit-maybe ()
784 "Run `yas-reload-all' when `yas-global-mode' is on."
785 (when yas-global-mode (yas-reload-all)))
787 (add-hook 'yas-global-mode-hook 'yas--global-mode-reload-with-jit-maybe)
792 (defvar yas--font-lock-keywords
793 (append '(("^#.*$" . font-lock-comment-face))
794 lisp-font-lock-keywords
795 lisp-font-lock-keywords-1
796 lisp-font-lock-keywords-2
798 (0 font-lock-keyword-face)
799 (1 font-lock-string-face t))
801 (0 font-lock-keyword-face)
802 (1 font-lock-warning-face t))
803 ("${" font-lock-keyword-face)
804 ("$[0-9]+?" font-lock-preprocessor-face)
805 ("\\(\\$(\\)" 1 font-lock-preprocessor-face)
807 (0 font-lock-keyword-face)))))
809 (defun yas--init-major-keymap ()
810 "Setup YASnippet major-mode keymap."
811 (let ((map (make-sparse-keymap)))
812 (easy-menu-define nil
814 "Menu used when snippet-mode is active."
816 (mapcar #'(lambda (ent)
818 (define-key map (third ent) (second ent)))
819 (vector (first ent) (second ent) t))
821 (list "Load this snippet" 'yas-load-snippet-buffer "\C-c\C-c")
822 (list "Try out this snippet" 'yas-tryout-snippet "\C-c\C-t")))))
825 (defvar snippet-mode-map
826 (yas--init-major-keymap)
827 "The keymap used when `snippet-mode' is active.")
830 (define-derived-mode snippet-mode text-mode "Snippet"
831 "A mode for editing yasnippets"
832 (setq font-lock-defaults '(yas--font-lock-keywords))
833 (set (make-local-variable 'require-final-newline) nil)
834 (set (make-local-variable 'comment-start) "#")
835 (set (make-local-variable 'comment-start-skip) "#+[\t ]*"))
839 ;;; Internal structs for template management
841 (defstruct (yas--template (:constructor yas--make-blank-template))
842 "A template for a snippet."
852 group ;; as dictated by the #group: directive or .yas-make-groups
853 perm-group ;; as dictated by `yas-define-menu'
857 (defun yas--populate-template (template &rest args)
858 "Helper function to populate TEMPLATE with properties."
862 (position (intern (substring (symbol-name (car args)) 1))
863 (mapcar #'car (get 'yas--template 'cl-struct-slots)))
865 (setq args (cddr args)))
868 (defstruct (yas--table (:constructor yas--make-snippet-table (name)))
869 "A table to store snippets for a particular mode.
871 Has the following fields:
875 A symbol name normally corresponding to a major mode, but can
876 also be a pseudo major-mode to be referenced in
877 `yas-extra-modes', for example.
881 A hash table (KEY . NAMEHASH), known as the \"keyhash\". KEY is
882 a string or a vector, where the former is the snippet's trigger
883 and the latter means it's a direct keybinding. NAMEHASH is yet
884 another hash of (NAME . TEMPLATE) where NAME is the snippet's
885 name and TEMPLATE is a `yas--template' object.
887 `yas--table-direct-keymap'
889 A keymap for the snippets in this table that have direct
890 keybindings. This is kept in sync with the keyhash, i.e., all
891 the elements of the keyhash that are vectors appear here as
892 bindings to `yas-expand-from-keymap'.
894 `yas--table-uuidhash'
896 A hash table mapping snippets uuid's to the same `yas--template'
897 objects. A snippet uuid defaults to the snippet's name.
900 (hash (make-hash-table :test 'equal))
901 (uuidhash (make-hash-table :test 'equal))
903 (direct-keymap (make-sparse-keymap)))
905 (defun yas--get-template-by-uuid (mode uuid)
906 "Find the snippet template in MODE by its UUID."
907 (let* ((table (gethash mode yas--tables mode)))
909 (gethash uuid (yas--table-uuidhash table)))))
911 ;; Apropos storing/updating in TABLE, this works in two steps:
913 ;; 1. `yas--remove-template-by-uuid' removes any
914 ;; keyhash-namehash-template mappings from TABLE, grabbing the
915 ;; snippet by its uuid. Also removes mappings from TABLE's
916 ;; `yas--table-direct-keymap' (FIXME: and should probably take care
917 ;; of potentially stale menu bindings right?.)
919 ;; 2. `yas--add-template' adds this all over again.
921 ;; Create a new or add to an existing keyhash-namehash mapping.
923 ;; For reference on understanding this, consider three snippet
926 ;; A: # name: The Foo
928 ;; # binding: C-c M-l
930 ;; B: # name: Mrs Foo
933 ;; C: # name: The Bar
934 ;; # binding: C-c M-l
939 ;; keyhash namehashes(3) yas--template structs(4)
940 ;; -----------------------------------------------------
943 ;; "foo" ---> "The Foo" ---> [yas--template A] |
944 ;; "Mrs Foo" ---> [yas--template B] |
946 ;; [C-c M-l] ---> "The Foo" -------------------------/
947 ;; "The Bar" ---> [yas--template C]
949 ;; "baz" ---> "Baz" ---> [yas--template D]
951 ;; Additionally, since uuid defaults to the name, we have a
952 ;; `yas--table-uuidhash' for TABLE
954 ;; uuidhash yas--template structs
955 ;; -------------------------------
956 ;; "The Foo" ---> [yas--template A]
957 ;; "Mrs Foo" ---> [yas--template B]
958 ;; "The Bar" ---> [yas--template C]
959 ;; "Baz" ---> [yas--template D]
961 ;; FIXME: the more I look at this data-structure the more I think I'm
962 ;; stupid. There has to be an easier way (but beware lots of code
965 (defun yas--remove-template-by-uuid (table uuid)
966 "Remove from TABLE a template identified by UUID."
967 (let ((template (gethash uuid (yas--table-uuidhash table))))
969 (let* ((name (yas--template-name template))
971 ;; Remove the name from each of the targeted namehashes
973 (maphash #'(lambda (k v)
974 (let ((template (gethash name v)))
976 (eq uuid (yas--template-uuid template)))
978 (when (zerop (hash-table-count v))
979 (push k empty-keys)))))
980 (yas--table-hash table))
981 ;; Remove the namehash themselves if they've become empty
983 (dolist (key empty-keys)
985 (define-key (yas--table-direct-keymap table) key nil))
986 (remhash key (yas--table-hash table)))
988 ;; Finally, remove the uuid from the uuidhash
990 (remhash uuid (yas--table-uuidhash table))))))
992 (defun yas--add-template (table template)
993 "Store in TABLE the snippet template TEMPLATE.
995 KEY can be a string (trigger key) of a vector (direct
997 (let ((name (yas--template-name template))
998 (key (yas--template-key template))
999 (keybinding (yas--template-keybinding template))
1000 (menu-binding-pair (yas--template-menu-binding-pair-get-create template)))
1001 (dolist (k (remove nil (list key keybinding)))
1005 (yas--table-hash table))
1007 (make-hash-table :test 'equal)
1008 (yas--table-hash table))))
1010 (define-key (yas--table-direct-keymap table) k 'yas-expand-from-keymap)))
1012 ;; Update TABLE's `yas--table-uuidhash'
1013 (puthash (yas--template-uuid template)
1015 (yas--table-uuidhash table))))
1017 (defun yas--update-template (table template)
1018 "Add or update TEMPLATE in TABLE.
1020 Also takes care of adding and updating to the associated menu."
1021 ;; Remove from table by uuid
1023 (yas--remove-template-by-uuid table (yas--template-uuid template))
1024 ;; Add to table again
1026 (yas--add-template table template)
1027 ;; Take care of the menu
1030 (yas--update-template-menu table template)))
1032 (defun yas--update-template-menu (table template)
1033 "Update every menu-related for TEMPLATE."
1034 (let ((menu-binding-pair (yas--template-menu-binding-pair-get-create template))
1035 (key (yas--template-key template))
1036 (keybinding (yas--template-keybinding template)))
1037 ;; The snippet might have changed name or keys, so update
1038 ;; user-visible strings
1040 (unless (eq (cdr menu-binding-pair) :none)
1041 ;; the menu item name
1043 (setf (cadar menu-binding-pair) (yas--template-name template))
1044 ;; the :keys information (also visible to the user)
1045 (setf (getf (cdr (car menu-binding-pair)) :keys)
1046 (or (and keybinding (key-description keybinding))
1047 (and key (concat key yas-trigger-symbol))))))
1048 (unless (yas--template-menu-managed-by-yas-define-menu template)
1050 (yas--menu-keymap-get-create (yas--table-mode table)
1051 (mapcar #'yas--table-mode
1052 (yas--table-parents table))))
1053 (group (yas--template-group template)))
1054 ;; Remove from menu keymap
1056 (assert menu-keymap)
1057 (yas--delete-from-keymap menu-keymap (yas--template-uuid template))
1059 ;; Add necessary subgroups as necessary.
1061 (dolist (subgroup group)
1062 (let ((subgroup-keymap (lookup-key menu-keymap (vector (make-symbol subgroup)))))
1063 (unless (and subgroup-keymap
1064 (keymapp subgroup-keymap))
1065 (setq subgroup-keymap (make-sparse-keymap))
1066 (define-key menu-keymap (vector (make-symbol subgroup))
1067 `(menu-item ,subgroup ,subgroup-keymap)))
1068 (setq menu-keymap subgroup-keymap)))
1070 ;; Add this entry to the keymap
1072 (define-key menu-keymap
1073 (vector (make-symbol (yas--template-uuid template)))
1074 (car (yas--template-menu-binding-pair template))))))
1076 (defun yas--namehash-templates-alist (namehash)
1077 "Return NAMEHASH as an alist."
1079 (maphash #'(lambda (k v)
1080 (push (cons k v) alist))
1084 (defun yas--fetch (table key)
1085 "Fetch templates in TABLE by KEY.
1087 Return a list of cons (NAME . TEMPLATE) where NAME is a
1088 string and TEMPLATE is a `yas--template' structure."
1089 (let* ((keyhash (yas--table-hash table))
1090 (namehash (and keyhash (gethash key keyhash))))
1092 (yas--filter-templates-by-condition (yas--namehash-templates-alist namehash)))))
1095 ;;; Filtering/condition logic
1097 (defun yas--eval-condition (condition)
1104 (yas--message 1 "Error in condition evaluation: %s" (error-message-string err))
1108 (defun yas--filter-templates-by-condition (templates)
1109 "Filter the templates using the applicable condition.
1111 TEMPLATES is a list of cons (NAME . TEMPLATE) where NAME is a
1112 string and TEMPLATE is a `yas--template' structure.
1114 This function implements the rules described in
1115 `yas-buffer-local-condition'. See that variables documentation."
1116 (let ((requirement (yas--require-template-specific-condition-p)))
1117 (if (eq requirement 'always)
1119 (remove-if-not #'(lambda (pair)
1120 (yas--template-can-expand-p
1121 (yas--template-condition (cdr pair)) requirement))
1124 (defun yas--require-template-specific-condition-p ()
1125 "Decides if this buffer requests/requires snippet-specific
1126 conditions to filter out potential expansions."
1127 (if (eq 'always yas-buffer-local-condition)
1129 (let ((local-condition (or (and (consp yas-buffer-local-condition)
1130 (yas--eval-condition yas-buffer-local-condition))
1131 yas-buffer-local-condition)))
1132 (when local-condition
1133 (if (eq local-condition t)
1135 (and (consp local-condition)
1136 (eq 'require-snippet-condition (car local-condition))
1137 (symbolp (cdr local-condition))
1138 (cdr local-condition)))))))
1140 (defun yas--template-can-expand-p (condition requirement)
1141 "Evaluates CONDITION and REQUIREMENT and returns a boolean."
1142 (let* ((result (or (null condition)
1143 (yas--eval-condition condition))))
1144 (cond ((eq requirement t)
1147 (eq requirement result)))))
1149 (defun yas--all-parents (mode)
1150 "Returns a list of all parent modes of MODE."
1151 (let ((parents (gethash mode yas--parents)))
1153 (mapcan #'yas--all-parents parents))))
1155 (defun yas--table-templates (table)
1158 (maphash #'(lambda (key namehash)
1159 (maphash #'(lambda (name template)
1160 (push (cons name template) acc))
1162 (yas--table-hash table))
1163 (yas--filter-templates-by-condition acc))))
1165 (defun yas--current-key ()
1166 "Get the key under current position. A key is used to find
1167 the template of a snippet in the current snippet-table."
1168 (let ((start (point))
1170 (syntaxes yas-key-syntaxes)
1174 (while (and (not done) syntaxes)
1175 (setq syntax (car syntaxes))
1176 (setq syntaxes (cdr syntaxes))
1178 (skip-syntax-backward syntax)
1179 (setq start (point)))
1181 (mapcan #'(lambda (table)
1182 (yas--fetch table (buffer-substring-no-properties start end)))
1183 (yas--get-snippet-tables)))
1192 (defun yas--table-all-keys (table)
1193 "Get trigger keys of all active snippets in TABLE."
1195 (maphash #'(lambda (key namehash)
1196 (when (yas--filter-templates-by-condition (yas--namehash-templates-alist namehash))
1198 (yas--table-hash table))
1201 (defun yas--table-mode (table)
1202 (intern (yas--table-name table)))
1205 ;;; Internal functions and macros:
1207 (defun yas--real-mode? (mode)
1208 "Try to find out if MODE is a real mode.
1210 The MODE bound to a function (like `c-mode') is considered real
1211 mode. Other well known mode like `ruby-mode' which is not part of
1212 Emacs might not bound to a function until it is loaded. So
1213 yasnippet keeps a list of modes like this to help the judgment."
1215 (find mode yas--known-modes)))
1217 (defun yas--eval-lisp (form)
1218 "Evaluate FORM and convert the result to string."
1219 (let ((retval (catch 'yas--exception
1225 (let ((result (eval form)))
1227 (format "%s" result))))))
1228 (error (if yas-good-grace
1229 (yas--format "elisp error! %s" (error-message-string err))
1230 (error (yas--format "elisp error: %s"
1231 (error-message-string err)))))))))
1232 (when (and (consp retval)
1233 (eq 'yas--exception (car retval)))
1234 (error (cdr retval)))
1237 (defun yas--eval-lisp-no-saves (form)
1240 (error (if yas-good-grace
1241 (yas--format "elisp error! %s" (error-message-string err))
1242 (error (yas--format "elisp error: %s"
1243 (error-message-string err)))))))
1245 (defun yas--read-lisp (string &optional nil-on-error)
1246 "Read STRING as a elisp expression and return it.
1248 In case STRING in an invalid expression and NIL-ON-ERROR is nil,
1249 return an expression that when evaluated will issue an error."
1252 (error (and (not nil-on-error)
1253 `(error (error-message-string ,err))))))
1255 (defun yas--read-keybinding (keybinding)
1256 "Read KEYBINDING as a snippet keybinding, return a vector."
1257 (when (and keybinding
1258 (not (string-match "keybinding" keybinding)))
1260 (let ((res (or (and (string-match "^\\[.*\\]$" keybinding)
1262 (read-kbd-macro keybinding 'need-vector))))
1265 (yas--message 3 "warning: keybinding \"%s\" invalid since %s."
1266 keybinding (error-message-string err))
1269 (defvar yas-extra-modes nil
1270 "If non-nil, also lookup snippets for this/these modes.
1272 Can be a symbol or a list of symbols.
1274 This variable probably makes more sense as buffer-local, so
1275 ensure your use `make-local-variable' when you set it.")
1276 (defun yas-extra-modes ()
1277 (if (listp yas-extra-modes) yas-extra-modes (list yas-extra-modes)))
1278 (defvaralias 'yas/mode-symbol 'yas-extra-modes)
1280 (defun yas--table-get-create (mode)
1281 "Get or create the snippet table corresponding to MODE."
1282 (let ((table (gethash mode
1285 (setq table (yas--make-snippet-table (symbol-name mode)))
1286 (puthash mode table yas--tables)
1287 (push (cons (intern (format "yas--direct-%s" mode))
1288 (yas--table-direct-keymap table))
1289 yas--direct-keymaps))
1292 (defun yas--get-snippet-tables ()
1293 "Get snippet tables for current buffer.
1295 Return a list of `yas--table' objects. The list of modes to
1296 consider is returned by `yas--modes-to-activate'"
1298 (mapcar #'(lambda (mode-name)
1299 (gethash mode-name yas--tables))
1300 (yas--modes-to-activate))))
1302 (defun yas--menu-keymap-get-create (mode &optional parents)
1303 "Get or create the menu keymap for MODE and its PARENTS.
1305 This may very well create a plethora of menu keymaps and arrange
1306 them all in `yas--menu-table'"
1307 (let* ((menu-keymap (or (gethash mode yas--menu-table)
1308 (puthash mode (make-sparse-keymap) yas--menu-table))))
1309 (mapc #'yas--menu-keymap-get-create parents)
1310 (define-key yas--minor-mode-menu (vector mode)
1311 `(menu-item ,(symbol-name mode) ,menu-keymap
1312 :visible (yas--show-menu-p ',mode)))
1315 (defmacro yas--called-interactively-p (&optional kind)
1316 "A backward-compatible version of `called-interactively-p'.
1318 Optional KIND is as documented at `called-interactively-p'
1319 in GNU Emacs 24.1 or higher."
1320 (if (eq 0 (cdr (subr-arity (symbol-function 'called-interactively-p))))
1321 '(called-interactively-p)
1322 `(called-interactively-p ,kind)))
1325 ;;; Template-related and snippet loading functions
1327 (defun yas--parse-template (&optional file)
1328 "Parse the template in the current buffer.
1330 Optional FILE is the absolute file name of the file being
1333 Optional GROUP is the group where the template is to go,
1334 otherwise we attempt to calculate it from FILE.
1336 Return a snippet-definition, i.e. a list
1338 (KEY TEMPLATE NAME CONDITION GROUP VARS FILE KEYBINDING UUID)
1340 If the buffer contains a line of \"# --\" then the contents above
1341 this line are ignored. Directives can set most of these with the syntax:
1343 # directive-name : directive-value
1345 Here's a list of currently recognized directives:
1356 (goto-char (point-min))
1357 (let* ((type 'snippet)
1359 (file-name-nondirectory file)))
1365 (yas--calculate-group file)))
1369 (if (re-search-forward "^# --\n" nil t)
1370 (progn (setq template
1371 (buffer-substring-no-properties (point)
1373 (setq bound (point))
1374 (goto-char (point-min))
1375 (while (re-search-forward "^# *\\([^ ]+?\\) *: *\\(.*\\)$" bound t)
1376 (when (string= "uuid" (match-string-no-properties 1))
1377 (setq uuid (match-string-no-properties 2)))
1378 (when (string= "type" (match-string-no-properties 1))
1379 (setq type (if (string= "command" (match-string-no-properties 2))
1382 (when (string= "key" (match-string-no-properties 1))
1383 (setq key (match-string-no-properties 2)))
1384 (when (string= "name" (match-string-no-properties 1))
1385 (setq name (match-string-no-properties 2)))
1386 (when (string= "condition" (match-string-no-properties 1))
1387 (setq condition (yas--read-lisp (match-string-no-properties 2))))
1388 (when (string= "group" (match-string-no-properties 1))
1389 (setq group (match-string-no-properties 2)))
1390 (when (string= "expand-env" (match-string-no-properties 1))
1391 (setq expand-env (yas--read-lisp (match-string-no-properties 2)
1393 (when (string= "binding" (match-string-no-properties 1))
1394 (setq binding (match-string-no-properties 2)))))
1396 (buffer-substring-no-properties (point-min) (point-max))))
1397 (unless (or key binding)
1398 (setq key (and file (file-name-nondirectory file))))
1399 (when (eq type 'command)
1400 (setq template (yas--read-lisp (concat "(progn" template ")"))))
1402 (setq group (split-string group "\\.")))
1403 (list key template name condition group expand-env file binding uuid)))
1405 (defun yas--calculate-group (file)
1406 "Calculate the group for snippet file path FILE."
1407 (let* ((dominating-dir (locate-dominating-file file
1408 ".yas-make-groups"))
1409 (extra-path (and dominating-dir
1410 (replace-regexp-in-string (concat "^"
1411 (expand-file-name dominating-dir))
1413 (expand-file-name file))))
1414 (extra-dir (and extra-path
1415 (file-name-directory extra-path)))
1416 (group (and extra-dir
1417 (replace-regexp-in-string "/"
1419 (directory-file-name extra-dir)))))
1422 (defun yas--subdirs (directory &optional filep)
1423 "Return subdirs or files of DIRECTORY according to FILEP."
1424 (remove-if (lambda (file)
1425 (or (string-match "^\\."
1426 (file-name-nondirectory file))
1427 (string-match "^#.*#$"
1428 (file-name-nondirectory file))
1430 (file-name-nondirectory file))
1432 (file-directory-p file)
1433 (not (file-directory-p file)))))
1434 (directory-files directory t)))
1436 (defun yas--make-menu-binding (template)
1437 (let ((mode (yas--table-mode (yas--template-table template))))
1438 `(lambda () (interactive) (yas--expand-or-visit-from-menu ',mode ,(yas--template-uuid template)))))
1440 (defun yas--expand-or-visit-from-menu (mode uuid)
1441 (let* ((table (yas--table-get-create mode))
1442 (yas--current-template (and table
1443 (gethash uuid (yas--table-uuidhash table)))))
1444 (when yas--current-template
1445 (if yas-visit-from-menu
1446 (yas--visit-snippet-file-1 yas--current-template)
1447 (let ((where (if (region-active-p)
1448 (cons (region-beginning) (region-end))
1449 (cons (point) (point)))))
1450 (yas-expand-snippet (yas--template-content yas--current-template)
1453 (yas--template-expand-env yas--current-template)))))))
1456 ;;; Popping up for keys and templates
1458 (defvar yas--x-pretty-prompt-templates nil
1459 "If non-nil, attempt to prompt for templates like TextMate.")
1462 (defun yas--prompt-for-template (templates &optional prompt)
1463 "Interactively choose a template from the list TEMPLATES.
1465 TEMPLATES is a list of `yas--template'.
1467 Optional PROMPT sets the prompt to use."
1470 (sort templates #'(lambda (t1 t2)
1471 (< (length (yas--template-name t1))
1472 (length (yas--template-name t2))))))
1473 (if yas--x-pretty-prompt-templates
1474 (yas--x-pretty-prompt-templates "Choose a snippet" templates)
1475 (some #'(lambda (fn)
1476 (funcall fn (or prompt "Choose a snippet: ")
1478 #'yas--template-name))
1479 yas-prompt-functions))))
1481 (defun yas--prompt-for-keys (keys &optional prompt)
1482 "Interactively choose a template key from the list KEYS.
1484 Optional PROMPT sets the prompt to use."
1486 (some #'(lambda (fn)
1487 (funcall fn (or prompt "Choose a snippet key: ") keys))
1488 yas-prompt-functions)))
1490 (defun yas--prompt-for-table (tables &optional prompt)
1491 "Interactively choose a table from the list TABLES.
1493 Optional PROMPT sets the prompt to use."
1495 (some #'(lambda (fn)
1496 (funcall fn (or prompt "Choose a snippet table: ")
1499 yas-prompt-functions)))
1501 (defun yas-x-prompt (prompt choices &optional display-fn)
1502 "Display choices in a x-window prompt."
1503 ;; FIXME: HACK: if we notice that one of the objects in choices is
1504 ;; actually a `yas--template', defer to `yas--x-prompt-pretty-templates'
1506 ;; This would be better implemented by passing CHOICES as a
1507 ;; structured tree rather than a list. Modifications would go as far
1508 ;; up as `yas--all-templates' I think.
1510 (when (and window-system choices)
1512 (let (menu d) ;; d for display
1514 (setq d (or (and display-fn (funcall display-fn c))
1517 (push (cons (concat " " d) c) menu))
1519 (push (car d) menu))))
1520 (setq menu (list prompt (push "title" menu)))
1521 (x-popup-menu (if (fboundp 'posn-at-point)
1522 (let ((x-y (posn-x-y (posn-at-point (point)))))
1523 (list (list (+ (car x-y) 10)
1531 (defun yas--x-pretty-prompt-templates (prompt templates)
1532 "Display TEMPLATES, grouping neatly by table name."
1533 (let ((organized (make-hash-table :test #'equal))
1537 (dolist (tl templates)
1538 (puthash (yas--template-table tl)
1540 (gethash (yas--template-table tl) organized))
1542 (setq more-than-one-table (> (hash-table-count organized) 1))
1543 (setq prefix (if more-than-one-table
1545 (if more-than-one-table
1546 (maphash #'(lambda (table templates)
1547 (push (yas--table-name table) menu)
1548 (dolist (tl templates)
1549 (push (cons (concat prefix (yas--template-name tl)) tl) menu))) organized)
1550 (setq menu (mapcar #'(lambda (tl) (cons (concat prefix (yas--template-name tl)) tl)) templates)))
1552 (setq menu (nreverse menu))
1553 (or (x-popup-menu (if (fboundp 'posn-at-point)
1554 (let ((x-y (posn-x-y (posn-at-point (point)))))
1555 (list (list (+ (car x-y) 10)
1559 (list prompt (push "title" menu)))
1562 (defun yas-ido-prompt (prompt choices &optional display-fn)
1563 (when (and (fboundp 'ido-completing-read)
1564 (or (>= emacs-major-version 24)
1566 (yas-completing-prompt prompt choices display-fn #'ido-completing-read)))
1568 (eval-when-compile (require 'dropdown-list nil t))
1569 (defun yas-dropdown-prompt (prompt choices &optional display-fn)
1570 (when (featurep 'dropdown-list)
1571 (let (formatted-choices
1575 (dolist (choice choices)
1576 (setq d (or (and display-fn (funcall display-fn choice))
1579 (push d formatted-choices)
1580 (push choice filtered-choices)))
1582 (setq n (and formatted-choices (dropdown-list formatted-choices)))
1584 (nth n filtered-choices)
1587 (defun yas-completing-prompt (prompt choices &optional display-fn completion-fn)
1588 (let (formatted-choices
1592 (completion-fn (or completion-fn
1593 #'completing-read)))
1594 (dolist (choice choices)
1595 (setq d (or (and display-fn (funcall display-fn choice))
1598 (push d formatted-choices)
1599 (push choice filtered-choices)))
1600 (setq chosen (and formatted-choices
1601 (funcall completion-fn prompt
1607 (let ((position (or (and chosen
1608 (position chosen formatted-choices :test #'string=))
1610 (nth position filtered-choices))))
1612 (defun yas-no-prompt (prompt choices &optional display-fn)
1616 ;;; Defining snippets
1617 ;; This consists of creating and registering `yas--template' objects in the
1621 (defun yas-define-snippets-1 (snippet snippet-table)
1622 "Helper for `yas-define-snippets'."
1623 ;; X) Calculate some more defaults on the values returned by
1624 ;; `yas--parse-template'.
1626 (let* ((file (seventh snippet))
1628 (name (or (third snippet)
1630 (file-name-directory file))))
1631 (condition (fourth snippet))
1632 (group (fifth snippet))
1633 (keybinding (yas--read-keybinding (eighth snippet)))
1634 (uuid (or (ninth snippet)
1636 (template (or (gethash uuid (yas--table-uuidhash snippet-table))
1637 (yas--make-blank-template))))
1638 ;; X) populate the template object
1640 (yas--populate-template template
1641 :table snippet-table
1643 :content (second snippet)
1646 :condition condition
1647 :expand-env (sixth snippet)
1648 :file (seventh snippet)
1649 :keybinding keybinding
1651 ;; X) Update this template in the appropriate table. This step
1652 ;; also will take care of adding the key indicators in the
1653 ;; templates menu entry, if any
1655 (yas--update-template snippet-table template)
1656 ;; X) Return the template
1661 (defun yas-define-snippets (mode snippets)
1662 "Define SNIPPETS for MODE.
1664 SNIPPETS is a list of snippet definitions, each taking the
1667 (KEY TEMPLATE NAME CONDITION GROUP EXPAND-ENV FILE KEYBINDING UUID)
1669 Within these, only KEY and TEMPLATE are actually mandatory.
1671 TEMPLATE might be a lisp form or a string, depending on whether
1672 this is a snippet or a snippet-command.
1674 CONDITION, EXPAND-ENV and KEYBINDING are lisp forms, they have
1675 been `yas--read-lisp'-ed and will eventually be
1676 `yas--eval-lisp'-ed.
1678 The remaining elements are strings.
1680 FILE is probably of very little use if you're programatically
1683 UUID is the snippets \"unique-id\". Loading a second snippet file
1684 with the same uuid replaced the previous snippet.
1686 You can use `yas--parse-template' to return such lists based on
1687 the current buffers contents."
1688 (let ((snippet-table (yas--table-get-create mode))
1690 (dolist (snippet snippets)
1691 (setq template (yas-define-snippets-1 snippet
1696 ;;; Loading snippets from files
1698 (defun yas--load-yas-setup-file (file)
1699 (load file 'noerror))
1701 (defun yas--define-parents (mode parents)
1702 "Add PARENTS to the list of MODE's parents."
1703 (puthash mode (remove-duplicates
1705 (gethash mode yas--parents)))
1708 (defun yas-load-directory (top-level-dir &optional use-jit)
1709 "Load snippets in directory hierarchy TOP-LEVEL-DIR.
1711 Below TOP-LEVEL-DIR each directory should be a mode name.
1713 Optional USE-JIT use jit-loading of snippets."
1714 (interactive "DSelect the root directory: ")
1715 (unless yas-snippet-dirs
1716 (setq yas-snippet-dirs top-level-dir))
1717 (dolist (dir (yas--subdirs top-level-dir))
1718 (let* ((major-mode-and-parents (yas--compute-major-mode-and-parents
1719 (concat dir "/dummy")))
1720 (mode-sym (car major-mode-and-parents))
1721 (parents (cdr major-mode-and-parents)))
1722 ;; Attention: The parents and the menus are already defined
1723 ;; here, even if the snippets are later jit-loaded.
1725 ;; * We need to know the parents at this point since entering a
1726 ;; given mode should jit load for its parents
1727 ;; immediately. This could be reviewed, the parents could be
1728 ;; discovered just-in-time-as well
1730 ;; * We need to create the menus here to support the `full'
1731 ;; option to `yas-use-menu' (all known snippet menus are shown to the user)
1733 (yas--define-parents mode-sym parents)
1734 (yas--menu-keymap-get-create mode-sym)
1735 (let ((form `(yas--load-directory-1 ,dir
1739 (not (some #'(lambda (buffer)
1740 (with-current-buffer buffer
1741 (when (eq major-mode mode-sym)
1742 (yas--message 3 "Discovered there was already %s in %s" buffer mode-sym)
1745 (yas--schedule-jit mode-sym form)
1747 (when (yas--called-interactively-p 'interactive)
1748 (yas--message 3 "Loaded snippets from %s." top-level-dir)))
1750 (defun yas--load-directory-1 (directory mode-sym parents &optional no-compiled-snippets)
1751 "Recursively load snippet templates from DIRECTORY."
1752 (unless (file-exists-p (concat directory "/" ".yas-skip"))
1753 (if (and (not no-compiled-snippets)
1754 (progn (yas--message 2 "Loading compiled snippets from %s" directory) t)
1755 (load (expand-file-name ".yas-compiled-snippets" directory) 'noerror (<= yas-verbosity 3)))
1756 (yas--message 2 "Loading snippet files from %s" directory)
1757 (yas--load-directory-2 directory mode-sym))))
1759 (defun yas--load-directory-2 (directory mode-sym)
1760 ;; Load .yas-setup.el files wherever we find them
1762 (yas--load-yas-setup-file (expand-file-name ".yas-setup" directory))
1763 (let* ((default-directory directory)
1765 ;; load the snippet files
1768 (dolist (file (yas--subdirs directory 'no-subdirs-just-files))
1769 (when (file-readable-p file)
1770 (insert-file-contents file nil nil nil t)
1771 (push (yas--parse-template file)
1774 (yas-define-snippets mode-sym
1776 ;; now recurse to a lower level
1778 (dolist (subdir (yas--subdirs directory))
1779 (yas--load-directory-2 subdir
1782 (defun yas--load-snippet-dirs (&optional nojit)
1783 "Reload the directories listed in `yas-snippet-dirs' or
1784 prompt the user to select one."
1786 (if yas-snippet-dirs
1787 (dolist (directory (reverse (yas-snippet-dirs)))
1788 (cond ((file-directory-p directory)
1789 (yas-load-directory directory (not nojit))
1791 (yas--message 3 "Loaded %s" directory)
1792 (yas--message 3 "Prepared just-in-time loading for %s" directory)))
1794 (push (yas--message 0 "Check your `yas-snippet-dirs': %s is not a directory" directory) errors))))
1795 (call-interactively 'yas-load-directory))
1798 (defun yas-reload-all (&optional interactive)
1799 "Reload all snippets and rebuild the YASnippet menu.
1801 When called interactively force immediate reload of all known
1802 snippets under `yas-snippet-dirs', otherwise use just-in-time
1807 (snippet-editing-buffers
1808 (remove-if-not #'(lambda (buffer)
1809 (with-current-buffer buffer yas--editing-template))
1811 ;; Warn if there are buffers visiting snippets, since reloading will break
1812 ;; any on-line editing of those buffers.
1814 (when snippet-editing-buffers
1816 (if (y-or-n-p "Some buffers editing live snippets, close them and proceed with reload? ")
1817 (mapc #'kill-buffer snippet-editing-buffers)
1818 (yas--message 1 "Aborted reload...")
1820 ;; in a non-interactive use, at least set
1821 ;; `yas--editing-template' to nil, make it guess it next time around
1822 (mapc #'(lambda (buffer) (setq yas--editing-template nil)) (buffer-list))))
1824 ;; Empty all snippet tables, parenting info and all menu tables
1826 (setq yas--tables (make-hash-table))
1827 (setq yas--parents (make-hash-table))
1828 (setq yas--menu-table (make-hash-table))
1830 ;; Cancel all pending 'yas--scheduled-jit-loads'
1832 (setq yas--scheduled-jit-loads (make-hash-table))
1834 ;; Init the `yas-minor-mode-map', taking care not to break the
1837 (setcdr yas-minor-mode-map (cdr (yas--init-minor-keymap)))
1839 ;; Reload the directories listed in `yas-snippet-dirs' or prompt
1840 ;; the user to select one.
1842 (setq errors (yas--load-snippet-dirs interactive))
1843 ;; Reload the direct keybindings
1845 (yas-direct-keymaps-reload)
1847 (yas--message 3 "Reloaded everything%s...%s."
1848 (if interactive "" " (snippets will load just-in-time)")
1849 (if errors " (some errors, check *Messages*)" "")))))
1851 (defun yas--load-pending-jits ()
1852 (dolist (mode (yas--modes-to-activate))
1853 (let ((forms (reverse (gethash mode yas--scheduled-jit-loads))))
1854 ;; must reverse to maintain coherence with `yas-snippet-dirs'
1855 (dolist (form forms)
1856 (yas--message 3 "Loading for `%s', just-in-time: %s!" mode form)
1858 (remhash mode yas--scheduled-jit-loads))))
1860 ;; (when (<= emacs-major-version 22)
1861 ;; (add-hook 'after-change-major-mode-hook 'yas--load-pending-jits))
1863 (defun yas--quote-string (string)
1864 "Escape and quote STRING.
1865 foo\"bar\\! -> \"foo\\\"bar\\\\!\""
1867 (replace-regexp-in-string "[\\\"]"
1873 ;;; Snippet compilation function
1875 (defun yas--initialize ()
1876 "For backward compatibility, enable `yas-minor-mode' globally."
1877 (yas-global-mode 1))
1879 (defun yas-compile-directory (top-level-dir)
1880 "Create .yas-compiled-snippets.el files under subdirs of TOP-LEVEL-DIR.
1882 This works by stubbing a few functions, then calling
1883 `yas-load-directory'."
1884 (interactive "DTop level snippet directory?")
1885 (cl-flet ((yas--load-yas-setup-file
1887 (let ((elfile (concat file ".el")))
1888 (when (file-exists-p elfile)
1889 (insert ";;; .yas-setup.el support file if any:\n;;;\n")
1890 (insert-file-contents elfile)
1891 (goto-char (point-max))
1893 (yas-define-snippets
1895 (insert ";;; Snippet definitions:\n;;;\n")
1896 (let ((literal-snippets (list))
1898 (dolist (snippet snippets)
1899 (let ((key (first snippet))
1900 (template-content (second snippet))
1901 (name (third snippet))
1902 (condition (fourth snippet))
1903 (group (fifth snippet))
1904 (expand-env (sixth snippet))
1905 (file nil) ;; (seventh snippet)) ;; omit on purpose
1906 (binding (eighth snippet))
1907 (uuid (ninth snippet)))
1918 (insert (pp-to-string `(yas-define-snippets ',mode ',literal-snippets)))
1920 (yas--load-directory-1
1921 (dir mode parents &rest ignore)
1922 (let ((output-file (concat (file-name-as-directory dir) ".yas-compiled-snippets.el")))
1923 (with-temp-file output-file
1924 (insert (format ";;; Compiled snippets and support files for `%s'\n" mode))
1925 (yas--load-directory-2 dir mode)
1926 (insert (format ";;; Do not edit! File generated at %s\n" (current-time-string)))))))
1927 (yas-load-directory top-level-dir nil)))
1929 (defun yas-recompile-all ()
1930 "Compile every dir in `yas-snippet-dirs'."
1932 (mapc #'yas-compile-directory (yas-snippet-dirs)))
1938 (defvar yas--scheduled-jit-loads (make-hash-table)
1939 "Alist of mode-symbols to forms to be evaled when `yas-minor-mode' kicks in.")
1941 (defun yas--schedule-jit (mode form)
1944 (gethash mode yas--scheduled-jit-loads))
1945 yas--scheduled-jit-loads))
1949 ;;; Some user level functions
1953 (message (concat "yasnippet (version "
1955 ") -- pluskid <pluskid@gmail.com>/joaotavora <joaotavora@gmail.com>")))
1958 ;;; Apropos snippet menu:
1960 ;; The snippet menu keymaps are store by mode in hash table called
1961 ;; `yas--menu-table'. They are linked to the main menu in
1962 ;; `yas--menu-keymap-get-create' and are initially created empty,
1963 ;; reflecting the table hierarchy.
1965 ;; They can be populated in two mutually exclusive ways: (1) by
1966 ;; reading `yas--template-group', which in turn is populated by the "#
1967 ;; group:" directives of the snippets or the ".yas-make-groups" file
1968 ;; or (2) by using a separate `yas-define-menu' call, which declares a
1969 ;; menu structure based on snippets uuids.
1971 ;; Both situations are handled in `yas--update-template-menu', which
1972 ;; uses the predicate `yas--template-menu-managed-by-yas-define-menu'
1973 ;; that can tell between the two situations.
1977 ;; * if `yas-define-menu' is used it must run before
1978 ;; `yas-define-snippets' and the UUIDS must match, otherwise we get
1979 ;; duplicate entries. The `yas--template' objects are created in
1980 ;; `yas-define-menu', holding nothing but the menu entry,
1981 ;; represented by a pair of ((menu-item NAME :keys KEYS) TYPE) and
1982 ;; stored in `yas--template-menu-binding-pair'. The (menu-item ...)
1983 ;; part is then stored in the menu keymap itself which make the item
1984 ;; appear to the user. These limitations could probably be revised.
1986 ;; * The `yas--template-perm-group' slot is only used in
1987 ;; `yas-describe-tables'.
1989 (defun yas--template-menu-binding-pair-get-create (template &optional type)
1990 "Get TEMPLATE's menu binding or assign it a new one.
1992 TYPE may be `:stay', signaling this menu binding should be
1993 static in the menu."
1994 (or (yas--template-menu-binding-pair template)
1995 (let ((key (yas--template-key template))
1996 (keybinding (yas--template-keybinding template)))
1997 (setf (yas--template-menu-binding-pair template)
1998 (cons `(menu-item ,(or (yas--template-name template)
1999 (yas--template-uuid template))
2000 ,(yas--make-menu-binding template)
2003 (defun yas--template-menu-managed-by-yas-define-menu (template)
2004 "Non-nil if TEMPLATE's menu entry was included in a `yas-define-menu' call."
2005 (cdr (yas--template-menu-binding-pair template)))
2008 (defun yas--show-menu-p (mode)
2009 (cond ((eq yas-use-menu 'abbreviate)
2011 (mapcar #'(lambda (table)
2012 (yas--table-mode table))
2013 (yas--get-snippet-tables))))
2014 ((eq yas-use-menu 'full)
2016 ((eq yas-use-menu t)
2019 (defun yas--delete-from-keymap (keymap uuid)
2020 "Recursively delete items with UUID from KEYMAP and its submenus."
2022 ;; XXX: This used to skip any submenus named \"parent mode\"
2024 ;; First of all, recursively enter submenus, i.e. the tree is
2025 ;; searched depth first so that stale submenus can be found in the
2028 (mapc #'(lambda (item)
2029 (when (and (listp (cdr item))
2030 (keymapp (third (cdr item))))
2031 (yas--delete-from-keymap (third (cdr item)) uuid)))
2033 ;; Set the uuid entry to nil
2035 (define-key keymap (vector (make-symbol uuid)) nil)
2036 ;; Destructively modify keymap
2038 (setcdr keymap (delete-if #'(lambda (item)
2039 (or (null (cdr item))
2040 (and (keymapp (third (cdr item)))
2041 (null (cdr (third (cdr item)))))))
2044 (defun yas-define-menu (mode menu &optional omit-items)
2045 "Define a snippet menu for MODE according to MENU, omitting OMIT-ITEMS.
2047 MENU is a list, its elements can be:
2049 - (yas-item UUID) : Creates an entry the snippet identified with
2050 UUID. The menu entry for a snippet thus identified is
2051 permanent, i.e. it will never move (be reordered) in the menu.
2053 - (yas-separator) : Creates a separator
2055 - (yas-submenu NAME SUBMENU) : Creates a submenu with NAME,
2056 SUBMENU has the same form as MENU. NAME is also added to the
2057 list of groups of the snippets defined thereafter.
2059 OMIT-ITEMS is a list of snippet uuid's that will always be
2060 omitted from MODE's menu, even if they're manually loaded.
2062 This function does nothing if `yas-use-menu' is nil."
2064 (let* ((table (yas--table-get-create mode))
2065 (hash (yas--table-uuidhash table)))
2066 (yas--define-menu-1 table
2067 (yas--menu-keymap-get-create mode)
2070 (dolist (uuid omit-items)
2071 (let ((template (or (gethash uuid hash)
2072 (yas--populate-template (puthash uuid
2073 (yas--make-blank-template)
2077 (setf (yas--template-menu-binding-pair template) (cons nil :none)))))))
2079 (defun yas--define-menu-1 (table menu-keymap menu uuidhash &optional group-list)
2080 "Helper for `yas-define-menu'."
2081 (dolist (e (reverse menu))
2082 (cond ((eq (first e) 'yas-item)
2083 (let ((template (or (gethash (second e) uuidhash)
2084 (yas--populate-template (puthash (second e)
2085 (yas--make-blank-template)
2088 :perm-group group-list
2089 :uuid (second e)))))
2090 (define-key menu-keymap (vector (gensym))
2091 (car (yas--template-menu-binding-pair-get-create template :stay)))))
2092 ((eq (first e) 'yas-submenu)
2093 (let ((subkeymap (make-sparse-keymap)))
2094 (define-key menu-keymap (vector (gensym))
2095 `(menu-item ,(second e) ,subkeymap))
2096 (yas--define-menu-1 table
2100 (append group-list (list (second e))))))
2101 ((eq (first e) 'yas-separator)
2102 (define-key menu-keymap (vector (gensym))
2103 '(menu-item "----")))
2105 (yas--message 3 "Don't know anything about menu entry %s" (first e))))))
2107 (defun yas--define (mode key template &optional name condition group)
2108 "Define a snippet. Expanding KEY into TEMPLATE.
2110 NAME is a description to this template. Also update the menu if
2111 `yas-use-menu' is t. CONDITION is the condition attached to
2112 this snippet. If you attach a condition to a snippet, then it
2113 will only be expanded when the condition evaluated to non-nil."
2114 (yas-define-snippets mode
2115 (list (list key template name condition group))))
2117 (defun yas-hippie-try-expand (first-time?)
2118 "Integrate with hippie expand.
2120 Just put this function in `hippie-expand-try-functions-list'."
2121 (when yas-minor-mode
2122 (if (not first-time?)
2123 (let ((yas-fallback-behavior 'return-nil))
2129 ;;; Apropos condition-cache:
2134 (defvar yas--condition-cache-timestamp nil)
2135 (defmacro yas-define-condition-cache (func doc &rest body)
2136 "Define a function FUNC with doc DOC and body BODY, BODY is
2137 executed at most once every snippet expansion attempt, to check
2138 expansion conditions.
2140 It doesn't make any sense to call FUNC programatically."
2141 `(defun ,func () ,(if (and doc
2144 "\n\nFor use in snippets' conditions. Within each
2145 snippet-expansion routine like `yas-expand', computes actual
2146 value for the first time then always returns a cached value.")
2147 (setq body (cons doc body))
2149 (let ((timestamp-and-value (get ',func 'yas--condition-cache)))
2150 (if (equal (car timestamp-and-value) yas--condition-cache-timestamp)
2151 (cdr timestamp-and-value)
2152 (let ((new-value (progn
2155 (put ',func 'yas--condition-cache (cons yas--condition-cache-timestamp new-value))
2158 (defalias 'yas-expand 'yas-expand-from-trigger-key)
2159 (defun yas-expand-from-trigger-key (&optional field)
2160 "Expand a snippet before point.
2162 If no snippet expansion is possible, fall back to the behaviour
2163 defined in `yas-fallback-behavior'.
2165 Optional argument FIELD is for non-interactive use and is an
2166 object satisfying `yas--field-p' to restrict the expansion to."
2168 (setq yas--condition-cache-timestamp (current-time))
2169 (let (templates-and-pos)
2170 (unless (and yas-expand-only-for-last-commands
2171 (not (member last-command yas-expand-only-for-last-commands)))
2172 (setq templates-and-pos (if field
2174 (narrow-to-region (yas--field-start field)
2175 (yas--field-end field))
2177 (yas--current-key))))
2178 (if (and templates-and-pos
2179 (first templates-and-pos))
2180 (yas--expand-or-prompt-for-template (first templates-and-pos)
2181 (second templates-and-pos)
2182 (third templates-and-pos))
2183 (yas--fallback 'trigger-key))))
2185 (defun yas-expand-from-keymap ()
2186 "Directly expand some snippets, searching `yas--direct-keymaps'.
2188 If expansion fails, execute the previous binding for this key"
2190 (setq yas--condition-cache-timestamp (current-time))
2191 (let* ((yas--prefix current-prefix-arg)
2192 (vec (subseq (this-command-keys-vector) (if current-prefix-arg
2193 universal-argument-num-events
2195 (templates (mapcan #'(lambda (table)
2196 (yas--fetch table vec))
2197 (yas--get-snippet-tables))))
2199 (yas--expand-or-prompt-for-template templates)
2200 (let ((yas-fallback-behavior 'call-other-command))
2203 (defun yas--expand-or-prompt-for-template (templates &optional start end)
2204 "Expand one of TEMPLATES from START to END.
2206 Prompt the user if TEMPLATES has more than one element, else
2207 expand immediately. Common gateway for
2208 `yas-expand-from-trigger-key' and `yas-expand-from-keymap'."
2209 (let ((yas--current-template (or (and (rest templates) ;; more than one
2210 (yas--prompt-for-template (mapcar #'cdr templates)))
2212 (when yas--current-template
2213 (yas-expand-snippet (yas--template-content yas--current-template)
2216 (yas--template-expand-env yas--current-template)))))
2218 ;; Apropos the trigger key and the fallback binding:
2220 ;; When `yas-minor-mode-map' binds <tab>, that correctly overrides
2221 ;; org-mode's <tab>, for example and searching for fallbacks correctly
2222 ;; returns `org-cycle'. However, most other modes bind "TAB". TODO,
2223 ;; improve this explanation.
2225 (defun yas--fallback (&optional from-trigger-key-p)
2226 "Fallback after expansion has failed.
2228 Common gateway for `yas-expand-from-trigger-key' and
2229 `yas-expand-from-keymap'."
2230 (cond ((eq yas-fallback-behavior 'return-nil)
2233 ((eq yas-fallback-behavior 'call-other-command)
2234 (let* ((beyond-yasnippet (yas--keybinding-beyond-yasnippet)))
2235 (yas--message 4 "Falling back to %s" beyond-yasnippet)
2236 (assert (or (null beyond-yasnippet) (commandp beyond-yasnippet)))
2237 (setq this-original-command beyond-yasnippet)
2238 (call-interactively beyond-yasnippet)))
2239 ((and (listp yas-fallback-behavior)
2240 (cdr yas-fallback-behavior)
2241 (eq 'apply (car yas-fallback-behavior)))
2242 (if (cddr yas-fallback-behavior)
2243 (apply (cadr yas-fallback-behavior)
2244 (cddr yas-fallback-behavior))
2245 (when (commandp (cadr yas-fallback-behavior))
2246 (setq this-command (cadr yas-fallback-behavior))
2247 (call-interactively (cadr yas-fallback-behavior)))))
2249 ;; also return nil if all the other fallbacks have failed
2252 (defun yas--keybinding-beyond-yasnippet ()
2254 (let* ((yas-minor-mode nil)
2255 (yas--direct-keymaps nil)
2256 (keys (this-single-command-keys)))
2257 (or (key-binding keys t)
2258 (key-binding (yas--fallback-translate-input keys) t))))
2260 (defun yas--fallback-translate-input (keys)
2261 "Emulate `read-key-sequence', at least what I think it does.
2263 Keys should be an untranslated key vector. Returns a translated
2264 vector of keys. FIXME not thoroughly tested"
2267 (while (< i (length keys))
2269 (translated local-function-key-map))
2270 (while (and (< j (length keys))
2272 (keymapp translated))
2273 (setq translated (aget (remove 'keymap translated) (aref keys j))
2275 (setq retval (vconcat retval (cond ((symbolp translated)
2277 ((vectorp translated)
2280 (substring keys i j)))))
2285 ;;; Utils for snippet development:
2287 (defun yas--all-templates (tables)
2288 "Get `yas--template' objects in TABLES, applicable for buffer and point.
2290 Honours `yas-choose-tables-first', `yas-choose-keys-first' and
2291 `yas-buffer-local-condition'"
2292 (when yas-choose-tables-first
2293 (setq tables (list (yas--prompt-for-table tables))))
2295 (if yas-choose-keys-first
2296 (let ((key (yas--prompt-for-keys
2297 (mapcan #'yas--table-all-keys tables))))
2299 (mapcan #'(lambda (table)
2300 (yas--fetch table key))
2302 (remove-duplicates (mapcan #'yas--table-templates tables)
2305 (defun yas-insert-snippet (&optional no-condition)
2306 "Choose a snippet to expand, pop-up a list of choices according
2307 to `yas--prompt-function'.
2309 With prefix argument NO-CONDITION, bypass filtering of snippets
2312 (setq yas--condition-cache-timestamp (current-time))
2313 (let* ((yas-buffer-local-condition (or (and no-condition
2315 yas-buffer-local-condition))
2316 (templates (yas--all-templates (yas--get-snippet-tables)))
2317 (yas--current-template (and templates
2318 (or (and (rest templates) ;; more than one template for same key
2319 (yas--prompt-for-template templates))
2321 (where (if (region-active-p)
2322 (cons (region-beginning) (region-end))
2323 (cons (point) (point)))))
2324 (if yas--current-template
2325 (yas-expand-snippet (yas--template-content yas--current-template)
2328 (yas--template-expand-env yas--current-template))
2329 (yas--message 3 "No snippets can be inserted here!"))))
2331 (defun yas-visit-snippet-file ()
2332 "Choose a snippet to edit, selection like `yas-insert-snippet'.
2334 Only success if selected snippet was loaded from a file. Put the
2335 visited file in `snippet-mode'."
2337 (let* ((yas-buffer-local-condition 'always)
2338 (templates (yas--all-templates (yas--get-snippet-tables)))
2339 (yas-prompt-functions '(yas-ido-prompt yas-completing-prompt))
2340 (template (and templates
2341 (or (yas--prompt-for-template templates
2342 "Choose a snippet template to edit: ")
2346 (yas--visit-snippet-file-1 template)
2347 (message "No snippets tables active!"))))
2349 (defun yas--visit-snippet-file-1 (template)
2350 "Helper for `yas-visit-snippet-file'."
2351 (let ((file (yas--template-file template)))
2352 (cond ((and file (file-readable-p file))
2353 (find-file-other-window file)
2355 (set (make-local-variable 'yas--editing-template) template))
2357 (message "Original file %s no longer exists!" file))
2359 (switch-to-buffer (format "*%s*"(yas--template-name template)))
2360 (let ((type 'snippet))
2361 (when (listp (yas--template-content template))
2362 (insert (format "# type: command\n"))
2363 (setq type 'command))
2364 (insert (format "# key: %s\n" (yas--template-key template)))
2365 (insert (format "# name: %s\n" (yas--template-name template)))
2366 (when (yas--template-keybinding template)
2367 (insert (format "# binding: %s\n" (yas--template-keybinding template))))
2368 (when (yas--template-expand-env template)
2369 (insert (format "# expand-env: %s\n" (yas--template-expand-env template))))
2370 (when (yas--template-condition template)
2371 (insert (format "# condition: %s\n" (yas--template-condition template))))
2373 (insert (if (eq type 'command)
2374 (pp-to-string (yas--template-content template))
2375 (yas--template-content template))))
2377 (set (make-local-variable 'yas--editing-template) template)))))
2379 (defun yas--guess-snippet-directories-1 (table)
2380 "Guesses possible snippet subdirectories for TABLE."
2381 (cons (yas--table-name table)
2382 (mapcan #'(lambda (parent)
2383 (yas--guess-snippet-directories-1
2385 (yas--table-parents table))))
2387 (defun yas--guess-snippet-directories (&optional table)
2388 "Try to guess suitable directories based on the current active
2389 tables (or optional TABLE).
2391 Returns a list of elements (TABLE . DIRS) where TABLE is a
2392 `yas--table' object and DIRS is a list of all possible directories
2393 where snippets of table might exist."
2394 (let ((main-dir (replace-regexp-in-string
2396 (or (first (or (yas-snippet-dirs)
2397 (setq yas-snippet-dirs '("~/.emacs.d/snippets")))))))
2398 (tables (or (and table
2400 (yas--get-snippet-tables))))
2401 ;; HACK! the snippet table created here is actually registered!
2403 (unless (or table (gethash major-mode yas--tables))
2404 (push (yas--table-get-create major-mode)
2407 (mapcar #'(lambda (table)
2409 (mapcar #'(lambda (subdir)
2410 (concat main-dir "/" subdir))
2411 (yas--guess-snippet-directories-1 table))))
2414 (defun yas--make-directory-maybe (table-and-dirs &optional main-table-string)
2415 "Returns a dir inside TABLE-AND-DIRS, prompts for creation if none exists."
2416 (or (some #'(lambda (dir) (when (file-directory-p dir) dir)) (cdr table-and-dirs))
2417 (let ((candidate (first (cdr table-and-dirs))))
2418 (unless (file-writable-p (file-name-directory candidate))
2419 (error (yas--format "%s is not writable." candidate)))
2420 (if (y-or-n-p (format "Guessed directory (%s) for%s%s table \"%s\" does not exist! Create? "
2422 (if (gethash (yas--table-mode (car table-and-dirs))
2426 (or main-table-string
2428 (yas--table-name (car table-and-dirs))))
2430 (make-directory candidate 'also-make-parents)
2431 ;; create the .yas-parents file here...
2434 (defun yas-new-snippet (&optional no-template)
2435 "Pops a new buffer for writing a snippet.
2437 Expands a snippet-writing snippet, unless the optional prefix arg
2438 NO-TEMPLATE is non-nil."
2440 (let ((guessed-directories (yas--guess-snippet-directories)))
2442 (switch-to-buffer "*new snippet*")
2444 (kill-all-local-variables)
2447 (set (make-local-variable 'yas--guessed-modes) (mapcar #'(lambda (d)
2448 (yas--table-mode (car d)))
2449 guessed-directories))
2450 (unless no-template (yas-expand-snippet "\
2451 # -*- mode: snippet -*-
2453 # key: ${2:${1:$(replace-regexp-in-string \"\\\\\\\\(\\\\\\\\w+\\\\\\\\).*\" \"\\\\\\\\1\" yas-text)}}${3:
2454 # binding: ${4:direct-keybinding}}${5:
2455 # expand-env: ((${6:some-var} ${7:some-value}))}${8:
2460 (defun yas--compute-major-mode-and-parents (file)
2461 "Given FILE, find the nearest snippet directory for a given mode.
2463 Returns a list (MODE-SYM PARENTS), the mode's symbol and a list
2464 representing one or more of the mode's parents.
2466 Note that MODE-SYM need not be the symbol of a real major mode,
2467 neither do the elements of PARENTS."
2468 (let* ((file-dir (and file
2469 (directory-file-name (or (some #'(lambda (special)
2470 (locate-dominating-file file special))
2474 (directory-file-name (file-name-directory file))))))
2475 (parents-file-name (concat file-dir "/.yas-parents"))
2476 (major-mode-name (and file-dir
2477 (file-name-nondirectory file-dir)))
2478 (major-mode-sym (or (and major-mode-name
2479 (intern major-mode-name))))
2480 (parents (when (file-readable-p parents-file-name)
2484 (insert-file-contents parents-file-name)
2485 (buffer-substring-no-properties (point-min)
2487 (when major-mode-sym
2488 (cons major-mode-sym parents))))
2490 (defvar yas--editing-template nil
2491 "Supporting variable for `yas-load-snippet-buffer' and `yas--visit-snippet'.")
2493 (defvar yas--current-template nil
2494 "Holds the current template being expanded into a snippet.")
2496 (defvar yas--guessed-modes nil
2497 "List of guessed modes supporting `yas-load-snippet-buffer'.")
2499 (defun yas--read-table ()
2500 "Ask user for a snippet table, help with some guessing."
2501 (let ((prompt (if (and (featurep 'ido)
2503 'ido-completing-read 'completing-read)))
2504 (unless yas--guessed-modes
2505 (set (make-local-variable 'yas--guessed-modes)
2506 (or (yas--compute-major-mode-and-parents buffer-file-name))))
2508 (funcall prompt (format "Choose or enter a table (yas guesses %s): "
2509 (if yas--guessed-modes
2510 (first yas--guessed-modes)
2512 (mapcar #'symbol-name yas--guessed-modes)
2517 (if (first yas--guessed-modes)
2518 (symbol-name (first yas--guessed-modes)))))))
2520 (defun yas-load-snippet-buffer (table &optional interactive)
2521 "Parse and load current buffer's snippet definition into TABLE.
2523 TABLE is a symbol naming a passed to `yas--table-get-create'.
2525 When called interactively, prompt for the table name and
2526 whether (and where) to save the snippet, then quit the window."
2527 (interactive (list (yas--read-table) t))
2529 ;; We have `yas--editing-template', this buffer's content comes from a
2530 ;; template which is already loaded and neatly positioned,...
2532 (yas--editing-template
2533 (yas-define-snippets-1 (yas--parse-template (yas--template-file yas--editing-template))
2534 (yas--template-table yas--editing-template)))
2535 ;; Try to use `yas--guessed-modes'. If we don't have that use the
2536 ;; value from `yas--compute-major-mode-and-parents'
2539 (unless yas--guessed-modes
2540 (set (make-local-variable 'yas--guessed-modes) (or (yas--compute-major-mode-and-parents buffer-file-name))))
2541 (let* ((table (yas--table-get-create table)))
2542 (set (make-local-variable 'yas--editing-template)
2543 (yas-define-snippets-1 (yas--parse-template buffer-file-name)
2546 (when (and interactive
2548 ;; Only offer to save this if it looks like a library or new
2549 ;; snippet (loaded from elisp, from a dir in `yas-snippet-dirs'
2550 ;; which is not the first, or from an unwritable file)
2552 (not (yas--template-file yas--editing-template))
2553 (not (file-writable-p (yas--template-file yas--editing-template)))
2554 (and (listp yas-snippet-dirs)
2555 (second yas-snippet-dirs)
2556 (not (string-match (expand-file-name (first yas-snippet-dirs))
2557 (yas--template-file yas--editing-template)))))
2558 (y-or-n-p (yas--format "Looks like a library or new snippet. Save to new file? ")))
2559 (let* ((option (first (yas--guess-snippet-directories (yas--template-table yas--editing-template))))
2561 (yas--make-directory-maybe option))))
2563 (let ((default-file-name (or (and (yas--template-file yas--editing-template)
2564 (file-name-nondirectory (yas--template-file yas--editing-template)))
2565 (yas--template-name yas--editing-template))))
2566 (write-file (concat chosen "/"
2567 (read-from-minibuffer (format "File name to create in %s? " chosen)
2568 default-file-name)))
2569 (setf (yas--template-file yas--editing-template) buffer-file-name)))))
2571 (yas--message 3 "Snippet \"%s\" loaded for %s."
2572 (yas--template-name yas--editing-template)
2573 (yas--table-name (yas--template-table yas--editing-template)))
2574 (quit-window interactive)))
2576 (defun yas-tryout-snippet (&optional debug)
2577 "Test current buffer's snippet template in other buffer."
2579 (let* ((major-mode-and-parent (yas--compute-major-mode-and-parents buffer-file-name))
2580 (parsed (yas--parse-template))
2581 (test-mode (or (and (car major-mode-and-parent)
2582 (fboundp (car major-mode-and-parent))
2583 (car major-mode-and-parent))
2584 (first yas--guessed-modes)
2585 (intern (read-from-minibuffer (yas--format "Please input a mode: ")))))
2586 (yas--current-template
2589 (yas--populate-template (yas--make-blank-template)
2590 :table nil ;; no tables for ephemeral snippets
2592 :content (second parsed)
2593 :name (third parsed)
2594 :expand-env (sixth parsed)))))
2595 (cond (yas--current-template
2596 (let ((buffer-name (format "*testing snippet: %s*" (yas--template-name yas--current-template))))
2597 (kill-buffer (get-buffer-create buffer-name))
2598 (switch-to-buffer (get-buffer-create buffer-name))
2599 (setq buffer-undo-list nil)
2600 (condition-case nil (funcall test-mode) (error nil))
2602 (setq buffer-read-only nil)
2603 (yas-expand-snippet (yas--template-content yas--current-template)
2606 (yas--template-expand-env yas--current-template))
2608 (require 'yasnippet-debug nil t))
2609 (add-hook 'post-command-hook 'yas-debug-snippet-vars nil t))))
2611 (yas--message 3 "Cannot test snippet for unknown major mode")))))
2613 (defun yas-active-keys ()
2614 "Return all active trigger keys for current buffer and point."
2615 (remove-duplicates (mapcan #'yas--table-all-keys (yas--get-snippet-tables))
2618 (defun yas--template-fine-group (template)
2619 (car (last (or (yas--template-group template)
2620 (yas--template-perm-group template)))))
2622 (defun yas-describe-tables (&optional choose)
2623 "Display snippets for each table."
2625 (let* ((by-name-hash (and choose
2626 (y-or-n-p "Show by namehash? ")))
2627 (buffer (get-buffer-create "*YASnippet tables*"))
2628 (active-tables (yas--get-snippet-tables))
2629 (remain-tables (let ((all))
2630 (maphash #'(lambda (k v)
2631 (unless (find v active-tables)
2635 (table-lists (list active-tables remain-tables))
2636 (original-buffer (current-buffer))
2638 (yas--condition-cache-timestamp (current-time)))
2639 (with-current-buffer buffer
2640 (setq buffer-read-only nil)
2642 (cond ((not by-name-hash)
2643 (insert "YASnippet tables: \n")
2644 (while (and table-lists
2646 (dolist (table (car table-lists))
2647 (yas--describe-pretty-table table original-buffer))
2648 (setq table-lists (cdr table-lists))
2650 (yas--create-snippet-xrefs)
2651 (display-buffer buffer)
2652 (setq continue (and choose (y-or-n-p "Show also non-active tables? ")))))
2653 (yas--create-snippet-xrefs)
2657 (insert "\n\nYASnippet tables by NAMEHASH: \n")
2658 (dolist (table (append active-tables remain-tables))
2659 (insert (format "\nSnippet table `%s':\n\n" (yas--table-name table)))
2661 (maphash #'(lambda (k v)
2663 (yas--table-hash table))
2665 (insert (format " key %s maps snippets: %s\n" key
2667 (maphash #'(lambda (k v)
2669 (gethash key (yas--table-hash table)))
2672 (setq buffer-read-only t))
2673 (display-buffer buffer)))
2675 (defun yas--describe-pretty-table (table &optional original-buffer)
2676 (insert (format "\nSnippet table `%s'"
2677 (yas--table-name table)))
2678 (if (yas--table-parents table)
2679 (insert (format " parents: %s\n"
2680 (mapcar #'yas--table-name
2681 (yas--table-parents table))))
2683 (insert (make-string 100 ?-) "\n")
2684 (insert "group state name key binding\n")
2685 (let ((groups-hash (make-hash-table :test #'equal)))
2686 (maphash #'(lambda (k v)
2687 (let ((group (or (yas--template-fine-group v)
2689 (when (yas--template-name v)
2691 (cons v (gethash group groups-hash))
2693 (yas--table-uuidhash table))
2695 #'(lambda (group templates)
2696 (setq group (truncate-string-to-width group 25 0 ? "..."))
2697 (insert (make-string 100 ?-) "\n")
2698 (dolist (p templates)
2699 (let ((name (truncate-string-to-width (propertize (format "\\\\snippet `%s'" (yas--template-name p))
2703 (setq group (make-string (length group) ? ))))
2704 (condition-string (let ((condition (yas--template-condition p)))
2707 (with-current-buffer original-buffer
2708 (if (yas--eval-condition condition)
2713 (insert condition-string " ")
2715 (if (string-match "\\.\\.\\.$" name)
2719 (insert (truncate-string-to-width (or (yas--template-key p) "")
2721 (insert (truncate-string-to-width (key-description (yas--template-keybinding p))
2728 ;;; User convenience functions, for using in snippet definitions
2730 (defvar yas-modified-p nil
2731 "Non-nil if field has been modified by user or transformation.")
2733 (defvar yas-moving-away-p nil
2734 "Non-nil if user is about to exit field.")
2736 (defvar yas-text nil
2737 "Contains current field text.")
2739 (defun yas-substr (str pattern &optional subexp)
2740 "Search PATTERN in STR and return SUBEXPth match.
2742 If found, the content of subexp group SUBEXP (default 0) is
2743 returned, or else the original STR will be returned."
2744 (let ((grp (or subexp 0)))
2746 (if (string-match pattern str)
2747 (match-string-no-properties grp str)
2750 (defun yas-choose-value (&rest possibilities)
2751 "Prompt for a string in POSSIBILITIES and return it.
2753 The last element of POSSIBILITIES may be a list of strings."
2754 (unless (or yas-moving-away-p
2756 (setq possibilities (nreverse possibilities))
2757 (setq possibilities (if (listp (car possibilities))
2758 (append (reverse (car possibilities)) (rest possibilities))
2760 (some #'(lambda (fn)
2761 (funcall fn "Choose: " possibilities))
2762 yas-prompt-functions)))
2764 (defun yas-key-to-value (alist)
2765 (unless (or yas-moving-away-p
2767 (let ((key (read-key-sequence "")))
2769 (or (cdr (find key alist :key #'car :test #'string=))
2772 (defun yas-throw (text)
2773 "Throw a yas--exception with TEXT as the reason."
2774 (throw 'yas--exception (cons 'yas--exception text)))
2776 (defun yas-verify-value (possibilities)
2777 "Verify that the current field value is in POSSIBILITIES.
2779 Otherwise throw exception."
2780 (when (and yas-moving-away-p (notany #'(lambda (pos) (string= pos yas-text)) possibilities))
2781 (yas-throw (yas--format "Field only allows %s" possibilities))))
2783 (defun yas-field-value (number)
2784 "Get the string for field with NUMBER.
2786 Use this in primary and mirror transformations to tget."
2787 (let* ((snippet (car (yas--snippets-at-point)))
2789 (yas--snippet-find-field snippet number))))
2791 (yas--field-text-for-display field))))
2794 "Return `yas-text' if that exists and is non-empty, else nil."
2796 (not (string= "" yas-text)))
2799 (defun yas-selected-text ()
2800 "Return `yas-selected-text' if that exists and is non-empty, else nil."
2801 (if (and yas-selected-text
2802 (not (string= "" yas-selected-text)))
2805 (defun yas--get-field-once (number &optional transform-fn)
2806 (unless yas-modified-p
2808 (funcall transform-fn (yas-field-value number))
2809 (yas-field-value number))))
2811 (defun yas-default-from-field (number)
2812 (unless yas-modified-p
2813 (yas-field-value number)))
2815 (defun yas-inside-string ()
2816 "Return non-nil if the point is inside a string according to font-lock."
2817 (equal 'font-lock-string-face (get-char-property (1- (point)) 'face)))
2819 (defun yas-unimplemented (&optional missing-feature)
2820 (if yas--current-template
2821 (if (y-or-n-p (format "This snippet is unimplemented (missing %s) Visit the snippet definition? "
2824 (yas--visit-snippet-file-1 yas--current-template))
2825 (message "No implementation. Missing %s" (or missing-feature "something"))))
2828 ;;; Snippet expansion and field management
2830 (defvar yas--active-field-overlay nil
2831 "Overlays the currently active field.")
2833 (defvar yas--field-protection-overlays nil
2834 "Two overlays protect the current active field.")
2836 (defconst yas--prefix nil
2837 "A prefix argument for expansion direct from keybindings.")
2839 (defvar yas-selected-text nil
2840 "The selected region deleted on the last snippet expansion.")
2842 (defvar yas--start-column nil
2843 "The column where the snippet expansion started.")
2845 (make-variable-buffer-local 'yas--active-field-overlay)
2846 (make-variable-buffer-local 'yas--field-protection-overlays)
2847 (put 'yas--active-field-overlay 'permanent-local t)
2848 (put 'yas--field-protection-overlays 'permanent-local t)
2850 (defstruct (yas--snippet (:constructor yas--make-snippet ()))
2856 (id (yas--snippet-next-id) :read-only t)
2857 (control-overlay nil)
2859 ;; stacked expansion: the `previous-active-field' slot saves the
2860 ;; active field where the child expansion took place
2861 previous-active-field
2864 (defstruct (yas--field (:constructor yas--make-field (number start end parent-field)))
2874 (defstruct (yas--mirror (:constructor yas--make-mirror (start end transform)))
2881 (defstruct (yas--exit (:constructor yas--make-exit (marker)))
2885 (defun yas--apply-transform (field-or-mirror field &optional empty-on-nil-p)
2886 "Calculate transformed string for FIELD-OR-MIRROR from FIELD.
2888 If there is no transform for ht field, return nil.
2890 If there is a transform but it returns nil, return the empty
2891 string iff EMPTY-ON-NIL-P is true."
2892 (let* ((yas-text (yas--field-text-for-display field))
2894 (yas-modified-p (yas--field-modified-p field))
2895 (yas-moving-away-p nil)
2896 (transform (if (yas--mirror-p field-or-mirror)
2897 (yas--mirror-transform field-or-mirror)
2898 (yas--field-transform field-or-mirror)))
2899 (start-point (if (yas--mirror-p field-or-mirror)
2900 (yas--mirror-start field-or-mirror)
2901 (yas--field-start field-or-mirror)))
2902 (transformed (and transform
2904 (goto-char start-point)
2905 (let ((ret (yas--eval-lisp transform)))
2906 (or ret (and empty-on-nil-p "")))))))
2909 (defsubst yas--replace-all (from to &optional text)
2910 "Replace all occurrences from FROM to TO.
2912 With optional string TEXT do it in that string."
2914 (replace-regexp-in-string (regexp-quote from) to text t t)
2915 (goto-char (point-min))
2916 (while (search-forward from nil t)
2917 (replace-match to t t text))))
2919 (defun yas--snippet-find-field (snippet number)
2920 (find-if #'(lambda (field)
2921 (eq number (yas--field-number field)))
2922 (yas--snippet-fields snippet)))
2924 (defun yas--snippet-sort-fields (snippet)
2925 "Sort the fields of SNIPPET in navigation order."
2926 (setf (yas--snippet-fields snippet)
2927 (sort (yas--snippet-fields snippet)
2928 #'yas--snippet-field-compare)))
2930 (defun yas--snippet-field-compare (field1 field2)
2931 "Compare FIELD1 and FIELD2.
2933 The field with a number is sorted first. If they both have a
2934 number, compare through the number. If neither have, compare
2935 through the field's start point"
2936 (let ((n1 (yas--field-number field1))
2937 (n2 (yas--field-number field2)))
2940 (or (zerop n2) (and (not (zerop n1))
2945 (< (yas--field-start field1)
2946 (yas--field-start field2))))))
2948 (defun yas--field-probably-deleted-p (snippet field)
2949 "Guess if SNIPPET's FIELD should be skipped."
2951 ;; field must be zero length
2953 (zerop (- (yas--field-start field) (yas--field-end field)))
2956 ;; 1) is a nested field and it's been modified
2958 (and (yas--field-parent-field field)
2959 (yas--field-modified-p field))
2960 ;; 2) ends just before the snippet end
2962 (and (eq field (car (last (yas--snippet-fields snippet))))
2963 (= (yas--field-start field) (overlay-end (yas--snippet-control-overlay snippet)))))
2964 ;; the field numbered 0, just before the exit marker, should
2967 (not (zerop (yas--field-number field)))))
2969 (defun yas--snippets-at-point (&optional all-snippets)
2970 "Return a sorted list of snippets at point.
2972 The most recently-inserted snippets are returned first."
2974 (remove nil (remove-duplicates (mapcar #'(lambda (ov)
2975 (overlay-get ov 'yas--snippet))
2977 (overlays-in (point-min) (point-max))
2978 (nconc (overlays-at (point)) (overlays-at (1- (point))))))))
2980 (<= (yas--snippet-id s2) (yas--snippet-id s1)))))
2982 (defun yas-next-field-or-maybe-expand ()
2983 "Try to expand a snippet at a key before point.
2985 Otherwise delegate to `yas-next-field'."
2987 (if yas-triggers-in-field
2988 (let ((yas-fallback-behavior 'return-nil)
2989 (active-field (overlay-get yas--active-field-overlay 'yas--field)))
2991 (unless (yas-expand-from-trigger-key active-field)
2995 (defun yas-next-field (&optional arg)
2996 "Navigate to the ARGth next field.
2998 If there's none, exit the snippet."
3002 (snippet (first (yas--snippets-at-point)))
3003 (active-field (overlay-get yas--active-field-overlay 'yas--field))
3004 (live-fields (remove-if #'(lambda (field)
3005 (and (not (eq field active-field))
3006 (yas--field-probably-deleted-p snippet field)))
3007 (yas--snippet-fields snippet)))
3008 (active-field-pos (position active-field live-fields))
3009 (target-pos (and active-field-pos (+ arg active-field-pos)))
3010 (target-field (and target-pos (nth target-pos live-fields))))
3011 ;; First check if we're moving out of a field with a transform
3013 (when (and active-field
3014 (yas--field-transform active-field))
3015 (let* ((yas-moving-away-p t)
3016 (yas-text (yas--field-text-for-display active-field))
3018 (yas-modified-p (yas--field-modified-p active-field)))
3019 ;; primary field transform: exit call to field-transform
3020 (yas--eval-lisp (yas--field-transform active-field))))
3021 ;; Now actually move...
3022 (cond ((and target-pos (>= target-pos (length live-fields)))
3023 (yas-exit-snippet snippet))
3025 (yas--move-to-field snippet target-field))
3029 (defun yas--place-overlays (snippet field)
3030 "Correctly place overlays for SNIPPET's FIELD."
3031 (yas--make-move-field-protection-overlays snippet field)
3032 (yas--make-move-active-field-overlay snippet field))
3034 (defun yas--move-to-field (snippet field)
3035 "Update SNIPPET to move to field FIELD.
3037 Also create some protection overlays"
3038 (goto-char (yas--field-start field))
3039 (yas--place-overlays snippet field)
3040 (overlay-put yas--active-field-overlay 'yas--field field)
3041 (let ((number (yas--field-number field)))
3042 ;; check for the special ${0: ...} field
3043 (if (and number (zerop number))
3045 (set-mark (yas--field-end field))
3046 (setf (yas--snippet-force-exit snippet)
3047 (or (yas--field-transform field)
3049 ;; make this field active
3050 (setf (yas--snippet-active-field snippet) field)
3051 ;; primary field transform: first call to snippet transform
3052 (unless (yas--field-modified-p field)
3053 (if (yas--field-update-display field snippet)
3054 (yas--update-mirrors snippet)
3055 (setf (yas--field-modified-p field) nil))))))
3057 (defun yas-prev-field ()
3058 "Navigate to prev field. If there's none, exit the snippet."
3060 (yas-next-field -1))
3062 (defun yas-abort-snippet (&optional snippet)
3064 (let ((snippet (or snippet
3065 (car (yas--snippets-at-point)))))
3067 (setf (yas--snippet-force-exit snippet) t))))
3069 (defun yas-exit-snippet (snippet)
3070 "Goto exit-marker of SNIPPET."
3071 (interactive (list (first (yas--snippets-at-point))))
3073 (setf (yas--snippet-force-exit snippet) t)
3074 (goto-char (if (yas--snippet-exit snippet)
3075 (yas--exit-marker (yas--snippet-exit snippet))
3076 (overlay-end (yas--snippet-control-overlay snippet))))))
3078 (defun yas-exit-all-snippets ()
3079 "Exit all snippets."
3081 (mapc #'(lambda (snippet)
3082 (yas-exit-snippet snippet)
3083 (yas--check-commit-snippet))
3084 (yas--snippets-at-point 'all-snippets)))
3087 ;;; Some low level snippet-routines:
3089 (defmacro yas--inhibit-overlay-hooks (&rest body)
3090 "Run BODY with `yas--inhibit-overlay-hooks' set to t."
3091 (declare (indent 0))
3092 `(let ((yas--inhibit-overlay-hooks t))
3095 (defvar yas-snippet-beg nil "Beginning position of the last snippet committed.")
3096 (defvar yas-snippet-end nil "End position of the last snippet committed.")
3098 (defun yas--commit-snippet (snippet)
3099 "Commit SNIPPET, but leave point as it is.
3101 This renders the snippet as ordinary text."
3103 (let ((control-overlay (yas--snippet-control-overlay snippet)))
3105 ;; Save the end of the moribund snippet in case we need to revive it
3106 ;; its original expansion.
3108 (when (and control-overlay
3109 (overlay-buffer control-overlay))
3110 (setq yas-snippet-beg (overlay-start control-overlay))
3111 (setq yas-snippet-end (overlay-end control-overlay))
3112 (delete-overlay control-overlay))
3114 (yas--inhibit-overlay-hooks
3115 (when yas--active-field-overlay
3116 (delete-overlay yas--active-field-overlay))
3117 (when yas--field-protection-overlays
3118 (mapc #'delete-overlay yas--field-protection-overlays)))
3120 ;; stacked expansion: if the original expansion took place from a
3121 ;; field, make sure we advance it here at least to
3122 ;; `yas-snippet-end'...
3124 (let ((previous-field (yas--snippet-previous-active-field snippet)))
3125 (when (and yas-snippet-end previous-field)
3126 (yas--advance-end-maybe previous-field yas-snippet-end)))
3128 ;; Convert all markers to points,
3130 (yas--markers-to-points snippet)
3132 ;; Take care of snippet revival
3134 (if yas-snippet-revival
3135 (push `(apply yas--snippet-revive ,yas-snippet-beg ,yas-snippet-end ,snippet)
3137 ;; Dismember the snippet... this is useful if we get called
3138 ;; again from `yas--take-care-of-redo'....
3139 (setf (yas--snippet-fields snippet) nil)))
3141 (yas--message 3 "Snippet %s exited." (yas--snippet-id snippet)))
3143 (defun yas--safely-run-hooks (hook-var)
3144 (condition-case error
3145 (run-hooks hook-var)
3147 (yas--message 3 "%s error: %s" hook-var (error-message-string error)))))
3150 (defun yas--check-commit-snippet ()
3151 "Checks if point exited the currently active field of the snippet.
3153 If so cleans up the whole snippet up."
3154 (let* ((snippets (yas--snippets-at-point 'all-snippets))
3155 (snippets-left snippets)
3156 (snippet-exit-transform))
3157 (dolist (snippet snippets)
3158 (let ((active-field (yas--snippet-active-field snippet)))
3159 (setq snippet-exit-transform (yas--snippet-force-exit snippet))
3160 (cond ((or snippet-exit-transform
3161 (not (and active-field (yas--field-contains-point-p active-field))))
3162 (setq snippets-left (delete snippet snippets-left))
3163 (setf (yas--snippet-force-exit snippet) nil)
3164 (yas--commit-snippet snippet))
3166 (or (not yas--active-field-overlay)
3167 (not (overlay-buffer yas--active-field-overlay))))
3169 ;; stacked expansion: this case is mainly for recent
3170 ;; snippet exits that place us back int the field of
3174 (yas--move-to-field snippet active-field)
3175 (yas--update-mirrors snippet)))
3178 (unless (or (null snippets) snippets-left)
3179 (if snippet-exit-transform
3180 (yas--eval-lisp-no-saves snippet-exit-transform))
3181 (yas--safely-run-hooks 'yas-after-exit-snippet-hook))))
3183 ;; Apropos markers-to-points:
3185 ;; This was found useful for performance reasons, so that an
3186 ;; excessive number of live markers aren't kept around in the
3187 ;; `buffer-undo-list'. However, in `markers-to-points', the
3188 ;; set-to-nil markers can't simply be discarded and replaced with
3189 ;; fresh ones in `points-to-markers'. The original marker that was
3190 ;; just set to nil has to be reused.
3192 ;; This shouldn't bring horrible problems with undo/redo, but it
3195 (defun yas--markers-to-points (snippet)
3196 "Convert all markers in SNIPPET to a cons (POINT . MARKER)
3197 where POINT is the original position of the marker and MARKER is
3198 the original marker object with the position set to nil."
3199 (dolist (field (yas--snippet-fields snippet))
3200 (let ((start (marker-position (yas--field-start field)))
3201 (end (marker-position (yas--field-end field))))
3202 (set-marker (yas--field-start field) nil)
3203 (set-marker (yas--field-end field) nil)
3204 (setf (yas--field-start field) (cons start (yas--field-start field)))
3205 (setf (yas--field-end field) (cons end (yas--field-end field))))
3206 (dolist (mirror (yas--field-mirrors field))
3207 (let ((start (marker-position (yas--mirror-start mirror)))
3208 (end (marker-position (yas--mirror-end mirror))))
3209 (set-marker (yas--mirror-start mirror) nil)
3210 (set-marker (yas--mirror-end mirror) nil)
3211 (setf (yas--mirror-start mirror) (cons start (yas--mirror-start mirror)))
3212 (setf (yas--mirror-end mirror) (cons end (yas--mirror-end mirror))))))
3213 (let ((snippet-exit (yas--snippet-exit snippet)))
3215 (let ((exit (marker-position (yas--exit-marker snippet-exit))))
3216 (set-marker (yas--exit-marker snippet-exit) nil)
3217 (setf (yas--exit-marker snippet-exit) (cons exit (yas--exit-marker snippet-exit)))))))
3219 (defun yas--points-to-markers (snippet)
3220 "Convert all cons (POINT . MARKER) in SNIPPET to markers.
3222 This is done by setting MARKER to POINT with `set-marker'."
3223 (dolist (field (yas--snippet-fields snippet))
3224 (setf (yas--field-start field) (set-marker (cdr (yas--field-start field))
3225 (car (yas--field-start field))))
3226 (setf (yas--field-end field) (set-marker (cdr (yas--field-end field))
3227 (car (yas--field-end field))))
3228 (dolist (mirror (yas--field-mirrors field))
3229 (setf (yas--mirror-start mirror) (set-marker (cdr (yas--mirror-start mirror))
3230 (car (yas--mirror-start mirror))))
3231 (setf (yas--mirror-end mirror) (set-marker (cdr (yas--mirror-end mirror))
3232 (car (yas--mirror-end mirror))))))
3233 (let ((snippet-exit (yas--snippet-exit snippet)))
3235 (setf (yas--exit-marker snippet-exit) (set-marker (cdr (yas--exit-marker snippet-exit))
3236 (car (yas--exit-marker snippet-exit)))))))
3238 (defun yas--field-contains-point-p (field &optional point)
3239 (let ((point (or point
3241 (and (>= point (yas--field-start field))
3242 (<= point (yas--field-end field)))))
3244 (defun yas--field-text-for-display (field)
3245 "Return the propertized display text for field FIELD."
3246 (buffer-substring (yas--field-start field) (yas--field-end field)))
3248 (defun yas--undo-in-progress ()
3249 "True if some kind of undo is in progress."
3250 (or undo-in-progress
3251 (eq this-command 'undo)
3252 (eq this-command 'redo)))
3254 (defun yas--make-control-overlay (snippet start end)
3255 "Creates the control overlay that surrounds the snippet and
3257 (let ((overlay (make-overlay start
3262 (overlay-put overlay 'keymap yas-keymap)
3263 (overlay-put overlay 'priority 100)
3264 (overlay-put overlay 'yas--snippet snippet)
3267 (defun yas-skip-and-clear-or-delete-char (&optional field)
3268 "Clears unmodified field if at field start, skips to next tab.
3270 Otherwise deletes a character normally by calling `delete-char'."
3272 (let ((field (or field
3273 (and yas--active-field-overlay
3274 (overlay-buffer yas--active-field-overlay)
3275 (overlay-get yas--active-field-overlay 'yas--field)))))
3277 (not (yas--field-modified-p field))
3278 (eq (point) (marker-position (yas--field-start field))))
3279 (yas--skip-and-clear field)
3282 (call-interactively 'delete-char)))))
3284 (defun yas--skip-and-clear (field)
3285 "Deletes the region of FIELD and sets it's modified state to t."
3286 ;; Just before skipping-and-clearing the field, mark its children
3287 ;; fields as modified, too. If the children have mirrors-in-fields
3288 ;; this prevents them from updating erroneously (we're skipping and
3291 (yas--mark-this-and-children-modified field)
3292 (delete-region (yas--field-start field) (yas--field-end field)))
3294 (defun yas--mark-this-and-children-modified (field)
3295 (setf (yas--field-modified-p field) t)
3296 (let ((fom (yas--field-next field)))
3298 (yas--fom-parent-field fom))
3299 (when (and (eq (yas--fom-parent-field fom) field)
3301 (yas--mark-this-and-children-modified fom))
3302 (setq fom (yas--fom-next fom)))))
3304 (defun yas--make-move-active-field-overlay (snippet field)
3305 "Place the active field overlay in SNIPPET's FIELD.
3307 Move the overlay, or create it if it does not exit."
3308 (if (and yas--active-field-overlay
3309 (overlay-buffer yas--active-field-overlay))
3310 (move-overlay yas--active-field-overlay
3311 (yas--field-start field)
3312 (yas--field-end field))
3313 (setq yas--active-field-overlay
3314 (make-overlay (yas--field-start field)
3315 (yas--field-end field)
3317 (overlay-put yas--active-field-overlay 'priority 100)
3318 (overlay-put yas--active-field-overlay 'face 'yas-field-highlight-face)
3319 (overlay-put yas--active-field-overlay 'yas--snippet snippet)
3320 (overlay-put yas--active-field-overlay 'modification-hooks '(yas--on-field-overlay-modification))
3321 (overlay-put yas--active-field-overlay 'insert-in-front-hooks
3322 '(yas--on-field-overlay-modification))
3323 (overlay-put yas--active-field-overlay 'insert-behind-hooks
3324 '(yas--on-field-overlay-modification))))
3326 (defvar yas--inhibit-overlay-hooks nil
3327 "Bind this temporarily to non-nil to prevent running `yas--on-*-modification'.")
3329 (defun yas--on-field-overlay-modification (overlay after? beg end &optional length)
3330 "Clears the field and updates mirrors, conditionally.
3332 Only clears the field if it hasn't been modified and it point it
3333 at field start. This hook doesn't do anything if an undo is in
3335 (unless (or yas--inhibit-overlay-hooks
3336 (yas--undo-in-progress))
3337 (let* ((field (overlay-get overlay 'yas--field))
3338 (number (and field (yas--field-number field)))
3339 (snippet (overlay-get yas--active-field-overlay 'yas--snippet)))
3341 (yas--advance-end-maybe field (overlay-end overlay))
3343 (yas--field-update-display field snippet))
3344 (yas--update-mirrors snippet))
3346 (when (and (not after?)
3347 (not (yas--field-modified-p field))
3348 (eq (point) (if (markerp (yas--field-start field))
3349 (marker-position (yas--field-start field))
3350 (yas--field-start field))))
3351 (yas--skip-and-clear field))
3352 (setf (yas--field-modified-p field) t))))))
3354 ;;; Apropos protection overlays:
3356 ;; These exist for nasty users who will try to delete parts of the
3357 ;; snippet outside the active field. Actual protection happens in
3358 ;; `yas--on-protection-overlay-modification'.
3360 ;; Currently this signals an error which inhibits the command. For
3361 ;; commands that move point (like `kill-line'), point is restored in
3362 ;; the `yas--post-command-handler' using a global
3363 ;; `yas--protection-violation' variable.
3365 ;; Alternatively, I've experimented with an implementation that
3366 ;; commits the snippet before actually calling `this-command'
3367 ;; interactively, and then signals an error, which is ignored. but
3368 ;; blocks all other million modification hooks. This presented some
3369 ;; problems with stacked expansion.
3371 (defun yas--make-move-field-protection-overlays (snippet field)
3372 "Place protection overlays surrounding SNIPPET's FIELD.
3374 Move the overlays, or create them if they do not exit."
3375 (let ((start (yas--field-start field))
3376 (end (yas--field-end field)))
3377 ;; First check if the (1+ end) is contained in the buffer,
3378 ;; otherwise we'll have to do a bit of cheating and silently
3379 ;; insert a newline. the `(1+ (buffer-size))' should prevent this
3380 ;; when using stacked expansion
3382 (when (< (buffer-size) end)
3384 (yas--inhibit-overlay-hooks
3385 (goto-char (point-max))
3387 ;; go on to normal overlay creation/moving
3389 (cond ((and yas--field-protection-overlays
3390 (every #'overlay-buffer yas--field-protection-overlays))
3391 (move-overlay (first yas--field-protection-overlays) (1- start) start)
3392 (move-overlay (second yas--field-protection-overlays) end (1+ end)))
3394 (setq yas--field-protection-overlays
3395 (list (make-overlay (1- start) start nil t nil)
3396 (make-overlay end (1+ end) nil t nil)))
3397 (dolist (ov yas--field-protection-overlays)
3398 (overlay-put ov 'face 'yas--field-debug-face)
3399 (overlay-put ov 'yas--snippet snippet)
3400 ;; (overlay-put ov 'evaporate t)
3401 (overlay-put ov 'modification-hooks '(yas--on-protection-overlay-modification)))))))
3403 (defvar yas--protection-violation nil
3404 "When non-nil, signals attempts to erroneously exit or modify the snippet.
3406 Functions in the `post-command-hook', for example
3407 `yas--post-command-handler' can check it and reset its value to
3408 nil. The variables value is the point where the violation
3411 (defun yas--on-protection-overlay-modification (overlay after? beg end &optional length)
3412 "Signals a snippet violation, then issues error.
3414 The error should be ignored in `debug-ignored-errors'"
3415 (unless yas--inhibit-overlay-hooks
3416 (cond ((not (or after?
3417 (yas--undo-in-progress)))
3418 (setq yas--protection-violation (point))
3419 (error "Exit the snippet first!")))))
3421 (add-to-list 'debug-ignored-errors "^Exit the snippet first!$")
3424 ;;; Snippet expansion and "stacked" expansion:
3426 ;; Stacked expansion is when you try to expand a snippet when already
3427 ;; inside a snippet expansion.
3429 ;; The parent snippet does not run its fields modification hooks
3430 ;; (`yas--on-field-overlay-modification' and
3431 ;; `yas--on-protection-overlay-modification') while the child snippet
3432 ;; is active. This means, among other things, that the mirrors of the
3433 ;; parent snippet are not updated, this only happening when one exits
3434 ;; the child snippet.
3436 ;; Unfortunately, this also puts some ugly (and not fully-tested)
3437 ;; bits of code in `yas-expand-snippet' and
3438 ;; `yas--commit-snippet'. I've tried to mark them with "stacked
3441 ;; This was thought to be safer in an undo/redo perspective, but
3442 ;; maybe the correct implementation is to make the globals
3443 ;; `yas--active-field-overlay' and `yas--field-protection-overlays' be
3444 ;; snippet-local and be active even while the child snippet is
3445 ;; running. This would mean a lot of overlay modification hooks
3446 ;; running, but if managed correctly (including overlay priorities)
3447 ;; they should account for all situations...
3449 (defun yas-expand-snippet (content &optional start end expand-env)
3450 "Expand snippet CONTENT at current point.
3452 Text between START and END will be deleted before inserting
3453 template. EXPAND-ENV is are let-style variable to value bindings
3454 considered when expanding the snippet."
3455 (run-hooks 'yas-before-expand-snippet-hook)
3458 (let* ((yas-selected-text (or yas-selected-text
3459 (and (region-active-p)
3460 (buffer-substring-no-properties (region-beginning)
3463 (and (region-active-p)
3467 (and (region-active-p)
3470 (to-delete (and start
3472 (buffer-substring-no-properties start end)))
3475 (setq yas--indent-original-column (current-column))
3476 ;; Delete the region to delete, this *does* get undo-recorded.
3478 (when (and to-delete
3480 (delete-region start end))
3482 (cond ((listp content)
3483 ;; x) This is a snippet-command
3485 (yas--eval-lisp-no-saves content))
3487 ;; x) This is a snippet-snippet :-)
3489 ;; Narrow the region down to the content, shoosh the
3490 ;; `buffer-undo-list', and create the snippet, the new
3491 ;; snippet updates its mirrors once, so we are left with
3492 ;; some plain text. The undo action for deleting this
3493 ;; plain text will get recorded at the end.
3495 ;; stacked expansion: also shoosh the overlay modification hooks
3497 (narrow-to-region start start)
3498 (let ((buffer-undo-list t))
3499 ;; snippet creation might evaluate users elisp, which
3500 ;; might generate errors, so we have to be ready to catch
3501 ;; them mostly to make the undo information
3503 (setq yas--start-column (save-restriction (widen) (current-column)))
3504 (yas--inhibit-overlay-hooks
3507 (eval `(let* ,expand-env
3509 (yas--snippet-create (point-min) (point-max))))
3511 (yas--snippet-create (point-min) (point-max)))))))
3513 ;; stacked-expansion: This checks for stacked expansion, save the
3514 ;; `yas--previous-active-field' and advance its boundary.
3516 (let ((existing-field (and yas--active-field-overlay
3517 (overlay-buffer yas--active-field-overlay)
3518 (overlay-get yas--active-field-overlay 'yas--field))))
3519 (when existing-field
3520 (setf (yas--snippet-previous-active-field snippet) existing-field)
3521 (yas--advance-end-maybe existing-field (overlay-end yas--active-field-overlay))))
3523 ;; Exit the snippet immediately if no fields
3525 (unless (yas--snippet-fields snippet)
3526 (yas-exit-snippet snippet))
3528 ;; Push two undo actions: the deletion of the inserted contents of
3529 ;; the new snippet (without the "key") followed by an apply of
3530 ;; `yas--take-care-of-redo' on the newly inserted snippet boundaries
3532 ;; A small exception, if `yas-also-auto-indent-first-line'
3533 ;; is t and `yas--indent' decides to indent the line to a
3534 ;; point before the actual expansion point, undo would be
3535 ;; messed up. We call the early point "newstart"". case,
3536 ;; and attempt to fix undo.
3538 (let ((newstart (overlay-start (yas--snippet-control-overlay snippet)))
3539 (end (overlay-end (yas--snippet-control-overlay snippet))))
3540 (when (< newstart start)
3541 (push (cons (make-string (- start newstart) ? ) newstart) buffer-undo-list))
3542 (push (cons newstart end) buffer-undo-list)
3543 (push `(apply yas--take-care-of-redo ,start ,end ,snippet)
3545 ;; Now, schedule a move to the first field
3547 (let ((first-field (car (yas--snippet-fields snippet))))
3549 (sit-for 0) ;; fix issue 125
3550 (yas--move-to-field snippet first-field)))
3551 (yas--message 3 "snippet expanded.")
3554 (defun yas--take-care-of-redo (beg end snippet)
3555 "Commits SNIPPET, which in turn pushes an undo action for reviving it.
3557 Meant to exit in the `buffer-undo-list'."
3558 ;; slightly optimize: this action is only needed for snippets with
3559 ;; at least one field
3560 (when (yas--snippet-fields snippet)
3561 (yas--commit-snippet snippet)))
3563 (defun yas--snippet-revive (beg end snippet)
3564 "Revives SNIPPET and creates a control overlay from BEG to END.
3566 BEG and END are, we hope, the original snippets boundaries. All
3567 the markers/points exiting existing inside SNIPPET should point
3568 to their correct locations *at the time the snippet is revived*.
3570 After revival, push the `yas--take-care-of-redo' in the
3572 ;; Reconvert all the points to markers
3574 (yas--points-to-markers snippet)
3575 ;; When at least one editable field existed in the zombie snippet,
3576 ;; try to revive the whole thing...
3578 (let ((target-field (or (yas--snippet-active-field snippet)
3579 (car (yas--snippet-fields snippet)))))
3581 (setf (yas--snippet-control-overlay snippet) (yas--make-control-overlay snippet beg end))
3582 (overlay-put (yas--snippet-control-overlay snippet) 'yas--snippet snippet)
3584 (yas--move-to-field snippet target-field)
3586 (push `(apply yas--take-care-of-redo ,beg ,end ,snippet)
3587 buffer-undo-list))))
3589 (defun yas--snippet-create (begin end)
3590 "Creates a snippet from an template inserted between BEGIN and END.
3592 Returns the newly created snippet."
3593 (let ((snippet (yas--make-snippet)))
3595 (yas--snippet-parse-create snippet)
3597 ;; Sort and link each field
3598 (yas--snippet-sort-fields snippet)
3600 ;; Create keymap overlay for snippet
3601 (setf (yas--snippet-control-overlay snippet)
3602 (yas--make-control-overlay snippet (point-min) (point-max)))
3605 (goto-char (point-max))
3610 ;;; Apropos adjacencies and "fom's":
3612 ;; Once the $-constructs bits like "$n" and "${:n" are deleted in the
3613 ;; recently expanded snippet, we might actually have many fields,
3614 ;; mirrors (and the snippet exit) in the very same position in the
3615 ;; buffer. Therefore we need to single-link the
3616 ;; fields-or-mirrors-or-exit (which I have abbreviated to "fom")
3617 ;; according to their original positions in the buffer.
3619 ;; Then we have operation `yas--advance-end-maybe' and
3620 ;; `yas--advance-start-maybe', which conditionally push the starts and
3621 ;; ends of these foms down the chain.
3623 ;; This allows for like the printf with the magic ",":
3625 ;; printf ("${1:%s}\\n"${1:$(if (string-match "%" text) "," "\);")} \
3626 ;; $2${1:$(if (string-match "%" text) "\);" "")}$0
3628 (defun yas--fom-start (fom)
3629 (cond ((yas--field-p fom)
3630 (yas--field-start fom))
3631 ((yas--mirror-p fom)
3632 (yas--mirror-start fom))
3634 (yas--exit-marker fom))))
3636 (defun yas--fom-end (fom)
3637 (cond ((yas--field-p fom)
3638 (yas--field-end fom))
3639 ((yas--mirror-p fom)
3640 (yas--mirror-end fom))
3642 (yas--exit-marker fom))))
3644 (defun yas--fom-next (fom)
3645 (cond ((yas--field-p fom)
3646 (yas--field-next fom))
3647 ((yas--mirror-p fom)
3648 (yas--mirror-next fom))
3650 (yas--exit-next fom))))
3652 (defun yas--fom-parent-field (fom)
3653 (cond ((yas--field-p fom)
3654 (yas--field-parent-field fom))
3655 ((yas--mirror-p fom)
3656 (yas--mirror-parent-field fom))
3660 (defun yas--calculate-adjacencies (snippet)
3661 "Calculate adjacencies for fields or mirrors of SNIPPET.
3663 This is according to their relative positions in the buffer, and
3664 has to be called before the $-constructs are deleted."
3665 (cl-flet ((yas--fom-set-next-fom (fom nextfom)
3666 (cond ((yas--field-p fom)
3667 (setf (yas--field-next fom) nextfom))
3668 ((yas--mirror-p fom)
3669 (setf (yas--mirror-next fom) nextfom))
3671 (setf (yas--exit-next fom) nextfom))))
3672 (yas--compare-fom-begs (fom1 fom2)
3673 (if (= (yas--fom-start fom2) (yas--fom-start fom1))
3674 (yas--mirror-p fom2)
3675 (>= (yas--fom-start fom2) (yas--fom-start fom1))))
3676 (yas--link-foms (fom1 fom2)
3677 (yas--fom-set-next-fom fom1 fom2)))
3678 ;; make some yas--field, yas--mirror and yas--exit soup
3680 (when (yas--snippet-exit snippet)
3681 (push (yas--snippet-exit snippet) soup))
3682 (dolist (field (yas--snippet-fields snippet))
3684 (dolist (mirror (yas--field-mirrors field))
3685 (push mirror soup)))
3688 #'yas--compare-fom-begs))
3690 (reduce #'yas--link-foms soup)))))
3692 (defun yas--calculate-mirrors-in-fields (snippet mirror)
3693 "Attempt to assign a parent field of SNIPPET to the mirror MIRROR.
3695 Use the tightest containing field if more than one field contains
3696 the mirror. Intended to be called *before* the dollar-regions are
3698 (let ((min (point-min))
3700 (dolist (field (yas--snippet-fields snippet))
3701 (when (and (<= (yas--field-start field) (yas--mirror-start mirror))
3702 (<= (yas--mirror-end mirror) (yas--field-end field))
3703 (< min (yas--field-start field))
3704 (< (yas--field-end field) max))
3705 (setq min (yas--field-start field)
3706 max (yas--field-end field))
3707 (setf (yas--mirror-parent-field mirror) field)))))
3709 (defun yas--advance-end-maybe (fom newend)
3710 "Maybe advance FOM's end to NEWEND if it needs it.
3714 * call `yas--advance-start-maybe' on FOM's next fom.
3716 * in case FOM is field call `yas--advance-end-maybe' on its parent
3719 Also, if FOM is an exit-marker, always call
3720 `yas--advance-start-maybe' on its next fom. This is because
3721 exit-marker have identical start and end markers."
3722 (cond ((and fom (< (yas--fom-end fom) newend))
3723 (set-marker (yas--fom-end fom) newend)
3724 (yas--advance-start-maybe (yas--fom-next fom) newend)
3725 (yas--advance-end-of-parents-maybe (yas--fom-parent-field fom) newend))
3727 (yas--advance-start-maybe (yas--fom-next fom) newend))))
3729 (defun yas--advance-start-maybe (fom newstart)
3730 "Maybe advance FOM's start to NEWSTART if it needs it.
3732 If it does, also call `yas--advance-end-maybe' on FOM."
3733 (when (and fom (< (yas--fom-start fom) newstart))
3734 (set-marker (yas--fom-start fom) newstart)
3735 (yas--advance-end-maybe fom newstart)))
3737 (defun yas--advance-end-of-parents-maybe (field newend)
3738 "Like `yas--advance-end-maybe' but for parent fields.
3740 Only works for fields and doesn't care about the start of the
3741 next FOM. Works its way up recursively for parents of parents."
3743 (< (yas--field-end field) newend))
3744 (set-marker (yas--field-end field) newend)
3745 (yas--advance-end-of-parents-maybe (yas--field-parent-field field) newend)))
3747 (defvar yas--dollar-regions nil
3748 "When expanding the snippet the \"parse-create\" functions add
3749 cons cells to this var.")
3751 (defvar yas--backquote-markers-and-strings nil
3752 "List of (MARKER . STRING) marking where the values from
3753 backquoted lisp expressions should be inserted at the end of
3756 (defun yas--snippet-parse-create (snippet)
3757 "Parse a recently inserted snippet template, creating all
3758 necessary fields, mirrors and exit points.
3760 Meant to be called in a narrowed buffer, does various passes"
3761 (let ((parse-start (point)))
3762 ;; Reset the yas--dollar-regions
3764 (setq yas--dollar-regions nil)
3765 ;; protect just the backquotes
3767 (yas--protect-escapes nil '(?`))
3768 ;; replace all backquoted expressions
3770 (goto-char parse-start)
3771 (yas--save-backquotes)
3772 ;; protect escaped characters
3774 (yas--protect-escapes)
3775 ;; parse fields with {}
3777 (goto-char parse-start)
3778 (yas--field-parse-create snippet)
3779 ;; parse simple mirrors and fields
3781 (goto-char parse-start)
3782 (yas--simple-mirror-parse-create snippet)
3783 ;; parse mirror transforms
3785 (goto-char parse-start)
3786 (yas--transform-mirror-parse-create snippet)
3787 ;; calculate adjacencies of fields and mirrors
3789 (yas--calculate-adjacencies snippet)
3790 ;; Delete $-constructs
3792 (yas--delete-regions yas--dollar-regions)
3793 ;; restore backquoted expression values
3795 (yas--restore-backquotes)
3798 (goto-char parse-start)
3799 (yas--restore-escapes)
3800 ;; update mirrors for the first time
3802 (yas--update-mirrors snippet)
3803 ;; indent the best we can
3805 (goto-char parse-start)
3806 (yas--indent snippet)))
3808 (defun yas--indent-according-to-mode (snippet-markers)
3809 "Indent current line according to mode, preserving SNIPPET-MARKERS."
3810 ;;; Apropos indenting problems....
3812 ;; `indent-according-to-mode' uses whatever `indent-line-function'
3813 ;; is available. Some implementations of these functions delete text
3814 ;; before they insert. If there happens to be a marker just after
3815 ;; the text being deleted, the insertion actually happens after the
3816 ;; marker, which misplaces it.
3818 ;; This would also happen if we had used overlays with the
3819 ;; `front-advance' property set to nil.
3821 ;; This is why I have these `trouble-markers', they are the ones at
3822 ;; they are the ones at the first non-whitespace char at the line
3823 ;; (i.e. at `yas--real-line-beginning'. After indentation takes place
3824 ;; we should be at the correct to restore them to. All other
3825 ;; non-trouble-markers have been *pushed* and don't need special
3828 (goto-char (yas--real-line-beginning))
3829 (let ((trouble-markers (remove-if-not #'(lambda (marker)
3835 (indent-according-to-mode)
3836 (error (yas--message 3 "Warning: `yas--indent-according-to-mode' having problems running %s" indent-line-function)
3838 (mapc #'(lambda (marker)
3839 (set-marker marker (point)))
3842 (defvar yas--indent-original-column nil)
3843 (defun yas--indent (snippet)
3844 (let ((snippet-markers (yas--collect-snippet-markers snippet)))
3845 ;; Look for those $>
3847 (while (re-search-forward "$>" nil t)
3848 (delete-region (match-beginning 0) (match-end 0))
3849 (when (not (eq yas-indent-line 'auto))
3850 (yas--indent-according-to-mode snippet-markers))))
3851 ;; Now do stuff for 'fixed and 'auto
3853 (cond ((eq yas-indent-line 'fixed)
3854 (while (and (zerop (forward-line))
3855 (zerop (current-column)))
3856 (indent-to-column yas--indent-original-column)))
3857 ((eq yas-indent-line 'auto)
3858 (let ((end (set-marker (make-marker) (point-max)))
3859 (indent-first-line-p yas-also-auto-indent-first-line))
3860 (while (and (zerop (if indent-first-line-p
3863 (setq indent-first-line-p nil))
3867 (yas--indent-according-to-mode snippet-markers))))
3871 (defun yas--collect-snippet-markers (snippet)
3872 "Make a list of all the markers used by SNIPPET."
3874 (dolist (field (yas--snippet-fields snippet))
3875 (push (yas--field-start field) markers)
3876 (push (yas--field-end field) markers)
3877 (dolist (mirror (yas--field-mirrors field))
3878 (push (yas--mirror-start mirror) markers)
3879 (push (yas--mirror-end mirror) markers)))
3880 (let ((snippet-exit (yas--snippet-exit snippet)))
3881 (when (and snippet-exit
3882 (marker-buffer (yas--exit-marker snippet-exit)))
3883 (push (yas--exit-marker snippet-exit) markers)))
3886 (defun yas--real-line-beginning ()
3887 (let ((c (char-after (line-beginning-position)))
3888 (n (line-beginning-position)))
3889 (while (or (eql c ?\ )
3892 (setq c (char-after n)))
3895 (defun yas--escape-string (escaped)
3896 (concat "YASESCAPE" (format "%d" escaped) "PROTECTGUARD"))
3898 (defun yas--protect-escapes (&optional text escaped)
3899 "Protect all escaped characters with their numeric ASCII value.
3901 With optional string TEXT do it in string instead of buffer."
3902 (let ((changed-text text)
3903 (text-provided-p text))
3904 (mapc #'(lambda (escaped)
3906 (yas--replace-all (concat "\\" (char-to-string escaped))
3907 (yas--escape-string escaped)
3908 (when text-provided-p changed-text))))
3909 (or escaped yas--escaped-characters))
3912 (defun yas--restore-escapes (&optional text escaped)
3913 "Restore all escaped characters from their numeric ASCII value.
3915 With optional string TEXT do it in string instead of the buffer."
3916 (let ((changed-text text)
3917 (text-provided-p text))
3918 (mapc #'(lambda (escaped)
3920 (yas--replace-all (yas--escape-string escaped)
3921 (char-to-string escaped)
3922 (when text-provided-p changed-text))))
3923 (or escaped yas--escaped-characters))
3926 (defun yas--save-backquotes ()
3927 "Save all the \"`(lisp-expression)`\"-style expressions
3928 with their evaluated value into `yas--backquote-markers-and-strings'."
3929 (while (re-search-forward yas--backquote-lisp-expression-regexp nil t)
3930 (let ((current-string (match-string-no-properties 1)) transformed)
3931 (delete-region (match-beginning 0) (match-end 0))
3932 (setq transformed (yas--eval-lisp (yas--read-lisp (yas--restore-escapes current-string '(?`)))))
3933 (goto-char (match-beginning 0))
3935 (let ((marker (make-marker)))
3936 (insert "Y") ;; quite horrendous, I love it :)
3937 (set-marker marker (point))
3939 (push (cons marker transformed) yas--backquote-markers-and-strings))))))
3941 (defun yas--restore-backquotes ()
3942 "Replace markers in `yas--backquote-markers-and-strings' with their values."
3943 (while yas--backquote-markers-and-strings
3944 (let* ((marker-and-string (pop yas--backquote-markers-and-strings))
3945 (marker (car marker-and-string))
3946 (string (cdr marker-and-string)))
3952 (set-marker marker nil)))))
3954 (defun yas--scan-sexps (from count)
3956 (with-syntax-table (standard-syntax-table)
3957 (scan-sexps from count))
3961 (defun yas--make-marker (pos)
3962 "Create a marker at POS with nil `marker-insertion-type'."
3963 (let ((marker (set-marker (make-marker) pos)))
3964 (set-marker-insertion-type marker nil)
3967 (defun yas--field-parse-create (snippet &optional parent-field)
3968 "Parse most field expressions in SNIPPET, except for the simple one \"$n\".
3970 The following count as a field:
3972 * \"${n: text}\", for a numbered field with default text, as long as N is not 0;
3974 * \"${n: text$(expression)}, the same with a lisp expression;
3975 this is caught with the curiously named `yas--multi-dollar-lisp-expression-regexp'
3977 * the same as above but unnumbered, (no N:) and number is calculated automatically.
3979 When multiple expressions are found, only the last one counts."
3982 (while (re-search-forward yas--field-regexp nil t)
3983 (let* ((real-match-end-0 (yas--scan-sexps (1+ (match-beginning 0)) 1))
3984 (number (and (match-string-no-properties 1)
3985 (string-to-number (match-string-no-properties 1))))
3986 (brand-new-field (and real-match-end-0
3987 ;; break if on "$(" immediately
3988 ;; after the ":", this will be
3989 ;; caught as a mirror with
3991 (not (save-match-data
3992 (eq (string-match "$[ \t\n]*("
3993 (match-string-no-properties 2)) 0)))
3994 ;; allow ${0: some exit text}
3995 ;; (not (and number (zerop number)))
3996 (yas--make-field number
3997 (yas--make-marker (match-beginning 2))
3998 (yas--make-marker (1- real-match-end-0))
4000 (when brand-new-field
4001 (goto-char real-match-end-0)
4002 (push (cons (1- real-match-end-0) real-match-end-0)
4003 yas--dollar-regions)
4004 (push (cons (match-beginning 0) (match-beginning 2))
4005 yas--dollar-regions)
4006 (push brand-new-field (yas--snippet-fields snippet))
4009 (narrow-to-region (yas--field-start brand-new-field) (yas--field-end brand-new-field))
4010 (goto-char (point-min))
4011 (yas--field-parse-create snippet brand-new-field)))))))
4012 ;; if we entered from a parent field, now search for the
4013 ;; `yas--multi-dollar-lisp-expression-regexp'. This is used for
4014 ;; primary field transformations
4018 (while (re-search-forward yas--multi-dollar-lisp-expression-regexp nil t)
4019 (let* ((real-match-end-1 (yas--scan-sexps (match-beginning 1) 1)))
4020 ;; commit the primary field transformation if:
4022 ;; 1. we don't find it in yas--dollar-regions (a subnested
4023 ;; field) might have already caught it.
4025 ;; 2. we really make sure we have either two '$' or some
4026 ;; text and a '$' after the colon ':'. This is a FIXME: work
4027 ;; my regular expressions and end these ugly hacks.
4029 (when (and real-match-end-1
4030 (not (member (cons (match-beginning 0)
4032 yas--dollar-regions))
4034 (char-before (1- (match-beginning 1))))))
4035 (let ((lisp-expression-string (buffer-substring-no-properties (match-beginning 1)
4037 (setf (yas--field-transform parent-field)
4038 (yas--read-lisp (yas--restore-escapes lisp-expression-string))))
4039 (push (cons (match-beginning 0) real-match-end-1)
4040 yas--dollar-regions)))))))
4042 (defun yas--transform-mirror-parse-create (snippet)
4043 "Parse the \"${n:$(lisp-expression)}\" mirror transformations in SNIPPET."
4044 (while (re-search-forward yas--transform-mirror-regexp nil t)
4045 (let* ((real-match-end-0 (yas--scan-sexps (1+ (match-beginning 0)) 1))
4046 (number (string-to-number (match-string-no-properties 1)))
4048 (not (zerop number))
4049 (yas--snippet-find-field snippet number)))
4051 (and real-match-end-0
4053 (yas--make-mirror (yas--make-marker (match-beginning 0))
4054 (yas--make-marker (match-beginning 0))
4056 (yas--restore-escapes
4057 (buffer-substring-no-properties (match-beginning 2)
4058 (1- real-match-end-0))))))))
4059 (when brand-new-mirror
4060 (push brand-new-mirror
4061 (yas--field-mirrors field))
4062 (yas--calculate-mirrors-in-fields snippet brand-new-mirror)
4063 (push (cons (match-beginning 0) real-match-end-0) yas--dollar-regions)))))
4065 (defun yas--simple-mirror-parse-create (snippet)
4066 "Parse the simple \"$n\" fields/mirrors/exitmarkers in SNIPPET."
4067 (while (re-search-forward yas--simple-mirror-regexp nil t)
4068 (let ((number (string-to-number (match-string-no-properties 1))))
4069 (cond ((zerop number)
4071 (setf (yas--snippet-exit snippet)
4072 (yas--make-exit (yas--make-marker (match-end 0))))
4074 (goto-char (match-beginning 0))
4075 (when yas-wrap-around-region
4076 (cond (yas-selected-text
4077 (insert yas-selected-text))
4078 ((and (eq yas-wrap-around-region 'cua)
4081 (insert (prog1 (get-register ?0)
4082 (set-register ?0 nil))))))
4083 (push (cons (point) (yas--exit-marker (yas--snippet-exit snippet)))
4084 yas--dollar-regions)))
4086 (let ((field (yas--snippet-find-field snippet number)))
4088 (let ((brand-new-mirror (yas--make-mirror
4089 (yas--make-marker (match-beginning 0))
4090 (yas--make-marker (match-beginning 0))
4092 (push brand-new-mirror
4093 (yas--field-mirrors field))
4094 (yas--calculate-mirrors-in-fields snippet brand-new-mirror))
4095 (push (yas--make-field number
4096 (yas--make-marker (match-beginning 0))
4097 (yas--make-marker (match-beginning 0))
4099 (yas--snippet-fields snippet))))
4100 (push (cons (match-beginning 0) (match-end 0))
4101 yas--dollar-regions))))))
4103 (defun yas--delete-regions (regions)
4104 "Sort disjuct REGIONS by start point, then delete from the back."
4105 (mapc #'(lambda (reg)
4106 (delete-region (car reg) (cdr reg)))
4109 (>= (car r1) (car r2))))))
4111 (defun yas--update-mirrors (snippet)
4112 "Updates all the mirrors of SNIPPET."
4114 (dolist (field-and-mirror (sort
4115 ;; make a list of ((F1 . M1) (F1 . M2) (F2 . M3) (F2 . M4) ...)
4116 ;; where F is the field that M is mirroring
4118 (mapcan #'(lambda (field)
4119 (mapcar #'(lambda (mirror)
4120 (cons field mirror))
4121 (yas--field-mirrors field)))
4122 (yas--snippet-fields snippet))
4123 ;; then sort this list so that entries with mirrors with parent
4124 ;; fields appear before. This was important for fixing #290, and
4125 ;; luckily also handles the case where a mirror in a field causes
4126 ;; another mirror to need reupdating
4128 #'(lambda (field-and-mirror1 field-and-mirror2)
4129 (yas--mirror-parent-field (cdr field-and-mirror1)))))
4130 (let* ((field (car field-and-mirror))
4131 (mirror (cdr field-and-mirror))
4132 (parent-field (yas--mirror-parent-field mirror)))
4133 ;; before updating a mirror with a parent-field, maybe advance
4137 (yas--advance-start-maybe mirror (yas--fom-start parent-field)))
4138 ;; update this mirror
4140 (yas--mirror-update-display mirror field)
4141 ;; `yas--place-overlays' is needed if the active field and
4142 ;; protected overlays have been changed because of insertions
4143 ;; in `yas--mirror-update-display'
4145 (when (eq field (yas--snippet-active-field snippet))
4146 (yas--place-overlays snippet field))))))
4148 (defun yas--mirror-update-display (mirror field)
4149 "Update MIRROR according to FIELD (and mirror transform)."
4151 (let* ((mirror-parent-field (yas--mirror-parent-field mirror))
4152 (reflection (and (not (and mirror-parent-field
4153 (yas--field-modified-p mirror-parent-field)))
4154 (or (yas--apply-transform mirror field 'empty-on-nil)
4155 (yas--field-text-for-display field)))))
4156 (when (and reflection
4157 (not (string= reflection (buffer-substring-no-properties (yas--mirror-start mirror)
4158 (yas--mirror-end mirror)))))
4159 (goto-char (yas--mirror-start mirror))
4160 (yas--inhibit-overlay-hooks
4161 (insert reflection))
4162 (if (> (yas--mirror-end mirror) (point))
4163 (delete-region (point) (yas--mirror-end mirror))
4164 (set-marker (yas--mirror-end mirror) (point))
4165 (yas--advance-start-maybe (yas--mirror-next mirror) (point))
4166 ;; super-special advance
4167 (yas--advance-end-of-parents-maybe mirror-parent-field (point))))))
4169 (defun yas--field-update-display (field snippet)
4170 "Much like `yas--mirror-update-display', but for fields."
4171 (when (yas--field-transform field)
4172 (let ((transformed (and (not (eq (yas--field-number field) 0))
4173 (yas--apply-transform field field)))
4175 (when (and transformed
4176 (not (string= transformed (buffer-substring-no-properties (yas--field-start field)
4177 (yas--field-end field)))))
4178 (setf (yas--field-modified-p field) t)
4179 (goto-char (yas--field-start field))
4180 (yas--inhibit-overlay-hooks
4181 (insert transformed)
4182 (if (> (yas--field-end field) (point))
4183 (delete-region (point) (yas--field-end field))
4184 (set-marker (yas--field-end field) (point))
4185 (yas--advance-start-maybe (yas--field-next field) (point)))
4189 ;;; Post-command hook:
4191 (defun yas--post-command-handler ()
4192 "Handles various yasnippet conditions after each command."
4193 (cond (yas--protection-violation
4194 (goto-char yas--protection-violation)
4195 (setq yas--protection-violation nil))
4196 ((eq 'undo this-command)
4198 ;; After undo revival the correct field is sometimes not
4199 ;; restored correctly, this condition handles that
4201 (let* ((snippet (car (yas--snippets-at-point)))
4202 (target-field (and snippet
4203 (find-if-not #'(lambda (field)
4204 (yas--field-probably-deleted-p snippet field))
4206 (cons (yas--snippet-active-field snippet)
4207 (yas--snippet-fields snippet)))))))
4209 (yas--move-to-field snippet target-field))))
4210 ((not (yas--undo-in-progress))
4211 ;; When not in an undo, check if we must commit the snippet
4212 ;; (user exited it).
4213 (yas--check-commit-snippet))))
4217 ;; The docstrings for some functions are generated dynamically
4218 ;; depending on the context.
4220 (put 'yas-expand 'function-documentation
4221 '(yas--expand-from-trigger-key-doc))
4222 (defun yas--expand-from-trigger-key-doc ()
4223 "A doc synthesizer for `yas--expand-from-trigger-key-doc'."
4224 (let ((fallback-description
4225 (cond ((eq yas-fallback-behavior 'call-other-command)
4226 (let* ((fallback (yas--keybinding-beyond-yasnippet)))
4228 (format " call command `%s'." (pp-to-string fallback)))
4229 " do nothing (`yas-expand' doesn't shadow\nanything)")))
4230 ((eq yas-fallback-behavior 'return-nil)
4233 ", defer to `yas-fallback-behaviour' (which see)"))))
4234 (concat "Expand a snippet before point. If no snippet
4235 expansion is possible,"
4236 fallback-description
4237 "\n\nOptional argument FIELD is for non-interactive use and is an
4238 object satisfying `yas--field-p' to restrict the expansion to.")))
4240 (put 'yas-expand-from-keymap 'function-documentation '(yas--expand-from-keymap-doc))
4241 (defun yas--expand-from-keymap-doc ()
4242 "A doc synthesizer for `yas--expand-from-keymap-doc'."
4243 (add-hook 'temp-buffer-show-hook 'yas--snippet-description-finish-runonce)
4244 (concat "Expand/run snippets from keymaps, possibly falling back to original binding.\n"
4245 (when (eq this-command 'describe-key)
4246 (let* ((vec (this-single-command-keys))
4247 (templates (mapcan #'(lambda (table)
4248 (yas--fetch table vec))
4249 (yas--get-snippet-tables)))
4250 (yas--direct-keymaps nil)
4251 (fallback (key-binding vec)))
4252 (concat "In this case, "
4254 (concat "these snippets are bound to this key:\n"
4255 (yas--template-pretty-list templates)
4256 "\n\nIf none of these expands, "))
4258 (format "fallback `%s' will be called." (pp-to-string fallback)))
4259 "no fallback keybinding is called."))))))
4261 (defun yas--template-pretty-list (templates)
4263 (yas-buffer-local-condition 'always))
4264 (dolist (plate templates)
4265 (setq acc (concat acc "\n*) "
4266 (propertize (concat "\\\\snippet `" (car plate) "'")
4267 'yasnippet (cdr plate)))))
4270 (define-button-type 'help-snippet-def
4271 :supertype 'help-xref
4272 'help-function (lambda (template) (yas--visit-snippet-file-1 template))
4273 'help-echo (purecopy "mouse-2, RET: find snippets's definition"))
4275 (defun yas--snippet-description-finish-runonce ()
4276 "Final adjustments for the help buffer when snippets are concerned."
4277 (yas--create-snippet-xrefs)
4278 (remove-hook 'temp-buffer-show-hook 'yas--snippet-description-finish-runonce))
4280 (defun yas--create-snippet-xrefs ()
4282 (goto-char (point-min))
4283 (while (search-forward-regexp "\\\\\\\\snippet[ \s\t]+`\\([^']+\\)'" nil t)
4284 (let ((template (get-text-property (match-beginning 1)
4287 (help-xref-button 1 'help-snippet-def template)
4288 (kill-region (match-end 1) (match-end 0))
4289 (kill-region (match-beginning 0) (match-beginning 1)))))))
4291 (defun yas--expand-uuid (mode-symbol uuid &optional start end expand-env)
4292 "Expand a snippet registered in MODE-SYMBOL's table with UUID.
4294 Remaining args as in `yas-expand-snippet'."
4295 (let* ((table (gethash mode-symbol yas--tables))
4296 (yas--current-template (and table
4297 (gethash uuid (yas--table-uuidhash table)))))
4298 (when yas--current-template
4299 (yas-expand-snippet (yas--template-content yas--current-template)))))
4303 (defvar yas-verbosity 4
4304 "Log level for `yas--message' 4 means trace most anything, 0 means nothing.")
4306 (defun yas--message (level message &rest args)
4307 "When LEVEL is above `yas-verbosity-level', log MESSAGE and ARGS."
4308 (when (> yas-verbosity level)
4309 (message (apply #'yas--format message args))))
4311 (defun yas--format (format-control &rest format-args)
4312 (apply #'format (concat "[yas] " format-control) format-args))
4319 ;; `locate-dominating-file'
4320 ;; `region-active-p'
4322 ;; added for compatibility in emacsen < 23
4323 (unless (>= emacs-major-version 23)
4324 (unless (fboundp 'region-active-p)
4325 (defun region-active-p () (and transient-mark-mode mark-active)))
4327 (unless (fboundp 'locate-dominating-file)
4328 (defvar locate-dominating-stop-dir-regexp
4329 "\\`\\(?:[\\/][\\/][^\\/]+[\\/]\\|/\\(?:net\\|afs\\|\\.\\.\\.\\)/\\)\\'"
4330 "Regexp of directory names which stop the search in `locate-dominating-file'.
4331 Any directory whose name matches this regexp will be treated like
4332 a kind of root directory by `locate-dominating-file' which will stop its search
4333 when it bumps into it.
4334 The default regexp prevents fruitless and time-consuming attempts to find
4335 special files in directories in which filenames are interpreted as hostnames,
4336 or mount points potentially requiring authentication as a different user.")
4338 (defun locate-dominating-file (file name)
4339 "Look up the directory hierarchy from FILE for a file named NAME.
4340 Stop at the first parent directory containing a file NAME,
4341 and return the directory. Return nil if not found."
4342 ;; We used to use the above locate-dominating-files code, but the
4343 ;; directory-files call is very costly, so we're much better off doing
4344 ;; multiple calls using the code in here.
4346 ;; Represent /home/luser/foo as ~/foo so that we don't try to look for
4347 ;; `name' in /home or in /.
4348 (setq file (abbreviate-file-name file))
4351 ;; `user' is not initialized outside the loop because
4352 ;; `file' may not exist, so we may have to walk up part of the
4353 ;; hierarchy before we find the "initial UUID".
4356 (while (not (or root
4358 ;; FIXME: Disabled this heuristic because it is sometimes
4360 ;; As a heuristic, we stop looking up the hierarchy of
4361 ;; directories as soon as we find a directory belonging
4362 ;; to another user. This should save us from looking in
4363 ;; things like /net and /afs. This assumes that all the
4364 ;; files inside a project belong to the same user.
4365 ;; (let ((prev-user user))
4366 ;; (setq user (nth 2 (file-attributes file)))
4367 ;; (and prev-user (not (equal user prev-user))))
4368 (string-match locate-dominating-stop-dir-regexp file)))
4369 (setq try (file-exists-p (expand-file-name name file)))
4370 (cond (try (setq root file))
4371 ((equal file (setq prev-file file
4372 file (file-name-directory
4373 (directory-file-name file))))
4377 ;; `c-neutralize-syntax-in-CPP` sometimes fires "End of Buffer" error
4378 ;; (when it execute forward-char) and interrupt the after change
4379 ;; hook. Thus prevent the insert-behind hook of yasnippet to be
4380 ;; invoked. Here's a way to reproduce it:
4382 ;; # open a *new* Emacs.
4383 ;; # load yasnippet.
4384 ;; # open a *new* .cpp file.
4385 ;; # input "inc" and press TAB to expand the snippet.
4386 ;; # select the `#include <...>` snippet.
4387 ;; # type inside `<>`
4389 (defadvice c-neutralize-syntax-in-CPP
4390 (around yas--mp/c-neutralize-syntax-in-CPP activate)
4391 "Adviced `c-neutralize-syntax-in-CPP' to properly
4392 handle the end-of-buffer error fired in it by calling
4393 `forward-char' at the end of buffer."
4396 (error (message (error-message-string err)))))
4398 ;; disable c-electric-* serial command in YAS fields
4399 (add-hook 'c-mode-common-hook
4401 (dolist (k '(":" ">" ";" "<" "{" "}"))
4402 (define-key (symbol-value (make-local-variable 'yas-keymap))
4403 k 'self-insert-command))))
4405 ;;; Backward compatibility to yasnippet <= 0.7
4407 (defvar yas--exported-syms '(;; `defcustom's
4410 yas-prompt-functions
4412 yas-also-auto-indent-first-line
4414 yas-triggers-in-field
4415 yas-fallback-behavior
4416 yas-choose-keys-first
4417 yas-choose-tables-first
4420 yas-wrap-around-region
4423 yas-expand-only-for-last-commands
4424 yas-field-highlight-face
4426 ;; these vars can be customized as well
4432 yas-after-exit-snippet-hook
4433 yas-before-expand-snippet-hook
4434 yas-buffer-local-condition
4437 ;; prompting functions
4442 yas-completing-prompt
4445 ;; interactive functions
4450 yas-direct-keymaps-reload
4454 yas-compile-directory
4457 yas-expand-from-trigger-key
4458 yas-expand-from-keymap
4460 yas-visit-snippet-file
4462 yas-load-snippet-buffer
4465 yas-next-field-or-maybe-expand
4470 yas-exit-all-snippets
4471 yas-skip-and-clear-or-delete-char
4473 ;; symbols that I "exported" for use
4474 ;; in snippets and hookage
4492 yas-default-from-field
4495 yas-define-condition-cache
4496 yas-hippie-try-expand
4499 ;; debug definitions
4500 ;; yas-debug-snippet-vars
4501 ;; yas-exterminate-package
4504 ;; testing definitions
4505 ;; yas-should-expand
4506 ;; yas-should-not-expand
4508 ;; yas-make-file-or-dirs
4510 ;; yas-saving-variables
4511 ;; yas-call-with-snippet-dirs
4512 ;; yas-with-snippet-dirs
4514 "Exported yasnippet symbols.
4516 i.e. ones that I will try to keep in future yasnippet versions
4517 and ones that other elisp libraries can more or less safely rely
4520 (defvar yas--dont-backport '(yas-active-keys)
4521 "Exported symbols that don't map back to \"yas/*\" variants.")
4523 (dolist (sym (set-difference yas--exported-syms yas--dont-backport))
4524 (let ((backported (intern (replace-regexp-in-string "^yas-" "yas/" (symbol-name sym)))))
4526 (make-obsolete-variable backported sym "yasnippet 0.8")
4527 (defvaralias backported sym))
4529 (make-obsolete backported sym "yasnippet 0.8")
4530 (defalias backported sym))))
4533 (provide 'yasnippet)
4535 ;;; yasnippet.el ends here
4538 ;; byte-compile-warnings: (not cl-functions)