1 ;;; yasnippet.el --- Yet another snippet extension for Emacs.
3 ;; Copyright (C) 2008-2012 Free Software Foundation, Inc.
4 ;; Authors: pluskid <pluskid@gmail.com>, João Távora <joaotavora@gmail.com>
6 ;; Package-version: 0.8.0
7 ;; X-URL: http://github.com/capitaomorte/yasnippet
8 ;; Keywords: convenience, emulation
9 ;; URL: http://github.com/capitaomorte/yasnippet
10 ;; EmacsWiki: YaSnippetMode
12 ;; This program is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; This program is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
27 ;; Basic steps to setup:
29 ;; (add-to-list 'load-path
30 ;; "~/path-to-yasnippet")
31 ;; (require 'yasnippet)
32 ;; (yas-global-mode 1)
35 ;; Interesting variables are:
39 ;; The directory where user-created snippets are to be
40 ;; stored. Can also be a list of directories. In that case,
41 ;; when used for bulk (re)loading of snippets (at startup or
42 ;; via `yas-reload-all'), directories appearing earlier in
43 ;; the list shadow other dir's snippets. Also, the first
44 ;; directory is taken as the default for storing the user's
47 ;; The deprecated `yas/root-directory' aliases this variable
48 ;; for backward-compatibility.
52 ;; A local variable that you can set in a hook to override
53 ;; snippet-lookup based on major mode. It is a a symbol (or
54 ;; list of symbols) that correspond to subdirectories of
55 ;; `yas-snippet-dirs' and is used for deciding which
56 ;; snippets to consider for the active buffer.
58 ;; Deprecated `yas/mode-symbol' aliases this variable for
59 ;; backward-compatibility.
61 ;; Major commands are:
65 ;; Try to expand snippets before point. In `yas-minor-mode',
66 ;; this is bound to `yas-trigger-key' which you can customize.
68 ;; M-x yas-load-directory
70 ;; Prompts you for a directory hierarchy of snippets to load.
72 ;; M-x yas-insert-snippet
74 ;; Prompts you for possible snippet expansion if that is
75 ;; possible according to buffer-local and snippet-local
76 ;; expansion conditions. With prefix argument, ignore these
79 ;; M-x yas-visit-snippet-file
81 ;; Prompts you for possible snippet expansions like
82 ;; `yas-insert-snippet', but instead of expanding it, takes
83 ;; you directly to the snippet definition's file, if it
86 ;; M-x yas-new-snippet
88 ;; Lets you create a new snippet file in the correct
89 ;; subdirectory of `yas-snippet-dirs', according to the
92 ;; M-x yas-load-snippet-buffer
94 ;; When editing a snippet, this loads the snippet. This is
95 ;; bound to "C-c C-c" while in the `snippet-mode' editing
98 ;; M-x yas-tryout-snippet
100 ;; When editing a snippet, this opens a new empty buffer,
101 ;; sets it to the appropriate major mode and inserts the
102 ;; snippet there, so you can see what it looks like. This is
103 ;; bound to "C-c C-t" while in `snippet-mode'.
105 ;; M-x yas-describe-tables
107 ;; Lists known snippets in a separate buffer. User is
108 ;; prompted as to whether only the currently active tables
109 ;; are to be displayed, or all the tables for all major
112 ;; The `dropdown-list.el' extension is bundled with YASnippet, you
113 ;; can optionally use it the preferred "prompting method", puting in
114 ;; your .emacs file, for example:
116 ;; (require 'dropdown-list)
117 ;; (setq yas-prompt-functions '(yas-dropdown-prompt
119 ;; yas-completing-prompt))
121 ;; Also check out the customization group
123 ;; M-x customize-group RET yasnippet RET
125 ;; If you use the customization group to set variables
126 ;; `yas-snippet-dirs' or `yas-global-mode', make sure the path to
127 ;; "yasnippet.el" is present in the `load-path' *before* the
128 ;; `custom-set-variables' is executed in your .emacs file.
130 ;; For more information and detailed usage, refer to the project page:
131 ;; http://github.com/capitaomorte/yasnippet
140 ;;; User customizable variables
142 (defgroup yasnippet nil
143 "Yet Another Snippet extension"
146 (defvar yas--load-file-name load-file-name
147 "Store the filename that yasnippet.el was originally loaded from.")
149 (defcustom yas-snippet-dirs (remove nil
150 (list "~/.emacs.d/snippets"
151 (when yas--load-file-name
152 (concat (file-name-directory yas--load-file-name) "snippets"))))
153 "Directory or list of snippet dirs for each major mode.
155 The directory where user-created snippets are to be stored. Can
156 also be a list of directories. In that case, when used for
157 bulk (re)loading of snippets (at startup or via
158 `yas-reload-all'), directories appearing earlier in the list
159 shadow other dir's snippets. Also, the first directory is taken
160 as the default for storing the user's new snippets."
161 :type '(choice (string :tag "Single directory (string)")
162 (repeat :args (string) :tag "List of directories (strings)"))
165 :set #'(lambda (symbol new)
166 (let ((old (and (boundp symbol)
167 (symbol-value symbol))))
168 (set-default symbol new)
169 (unless (or (not (fboundp 'yas-reload-all))
173 (defun yas-snippet-dirs ()
174 "Returns `yas-snippet-dirs' (which see) as a list."
175 (if (listp yas-snippet-dirs) yas-snippet-dirs (list yas-snippet-dirs)))
177 (defvaralias 'yas/root-directory 'yas-snippet-dirs)
179 (defcustom yas-prompt-functions '(yas-x-prompt
181 yas-completing-prompt
184 "Functions to prompt for keys, templates, etc interactively.
186 These functions are called with the following arguments:
188 - PROMPT: A string to prompt the user
190 - CHOICES: a list of strings or objects.
192 - optional DISPLAY-FN : A function that, when applied to each of
193 the objects in CHOICES will return a string.
195 The return value of any function you put here should be one of
196 the objects in CHOICES, properly formatted with DISPLAY-FN (if
199 - To signal that your particular style of prompting is
200 unavailable at the moment, you can also have the function return
203 - To signal that the user quit the prompting process, you can
206 (signal 'quit \"user quit!\")."
207 :type '(repeat function)
210 (defcustom yas-indent-line 'auto
211 "Controls indenting applied to a recent snippet expansion.
213 The following values are possible:
215 - `fixed' Indent the snippet to the current column;
217 - `auto' Indent each line of the snippet with `indent-according-to-mode'
219 Every other value means don't apply any snippet-side indendation
220 after expansion (the manual per-line \"$>\" indentation still
222 :type '(choice (const :tag "Nothing" nothing)
223 (const :tag "Fixed" fixed)
224 (const :tag "Auto" auto))
227 (defcustom yas-also-auto-indent-first-line nil
228 "Non-nil means also auto indent first line according to mode.
230 Naturally this is only valid when `yas-indent-line' is `auto'"
234 (defcustom yas-snippet-revival t
235 "Non-nil means re-activate snippet fields after undo/redo."
239 (defcustom yas-trigger-key "TAB"
240 "The key bound to `yas-expand' when function `yas-minor-mode' is active.
242 Value is a string that is converted to the internal Emacs key
243 representation using `read-kbd-macro'."
246 :set #'(lambda (symbol key)
247 (let ((old (and (boundp symbol)
248 (symbol-value symbol))))
249 (set-default symbol key)
250 ;; On very first loading of this defcustom,
251 ;; `yas-trigger-key' is *not* loaded.
252 (if (fboundp 'yas--trigger-key-reload)
253 (yas--trigger-key-reload old)))))
255 (defcustom yas-next-field-key '("TAB" "<tab>")
256 "The key to navigate to next field when a snippet is active.
258 Value is a string that is converted to the internal Emacs key
259 representation using `read-kbd-macro'.
261 Can also be a list of strings."
262 :type '(choice (string :tag "String")
263 (repeat :args (string) :tag "List of strings"))
265 :set #'(lambda (symbol val)
266 (set-default symbol val)
267 (if (fboundp 'yas--init-yas-in-snippet-keymap)
268 (yas--init-yas-in-snippet-keymap))))
271 (defcustom yas-prev-field-key '("<backtab>" "<S-tab>")
272 "The key to navigate to previous field when a snippet is active.
274 Value is a string that is converted to the internal Emacs key
275 representation using `read-kbd-macro'.
277 Can also be a list of strings."
278 :type '(choice (string :tag "String")
279 (repeat :args (string) :tag "List of strings"))
281 :set #'(lambda (symbol val)
282 (set-default symbol val)
283 (if (fboundp 'yas--init-yas-in-snippet-keymap)
284 (yas--init-yas-in-snippet-keymap))))
286 (defcustom yas-skip-and-clear-key '("C-d" "<delete>" "<deletechar>")
287 "The key to clear the currently active field.
289 Value is a string that is converted to the internal Emacs key
290 representation using `read-kbd-macro'.
292 Can also be a list of strings."
293 :type '(choice (string :tag "String")
294 (repeat :args (string) :tag "List of strings"))
296 :set #'(lambda (symbol val)
297 (set-default symbol val)
298 (if (fboundp 'yas--init-yas-in-snippet-keymap)
299 (yas--init-yas-in-snippet-keymap))))
301 (defcustom yas-triggers-in-field nil
302 "If non-nil, `yas-next-field-key' can trigger stacked expansions.
304 Otherwise, `yas-next-field-key' just tries to move on to the next
309 (defcustom yas-fallback-behavior 'call-other-command
310 "How to act when `yas-trigger-key' does *not* expand a snippet.
312 - `call-other-command' means try to temporarily disable YASnippet
313 and call the next command bound to `yas-trigger-key'.
315 - nil or the symbol `return-nil' mean do nothing. (and
316 `yas-expand' returns nil)
318 - A lisp form (apply COMMAND . ARGS) means interactively call
319 COMMAND, if ARGS is non-nil, call COMMAND non-interactively
320 with ARGS as arguments."
321 :type '(choice (const :tag "Call previous command" call-other-command)
322 (const :tag "Do nothing" return-nil))
325 (defcustom yas-choose-keys-first nil
326 "If non-nil, prompt for snippet key first, then for template.
328 Otherwise prompts for all possible snippet names.
330 This affects `yas-insert-snippet' and `yas-visit-snippet-file'."
334 (defcustom yas-choose-tables-first nil
335 "If non-nil, and multiple eligible snippet tables, prompts user for tables first.
337 Otherwise, user chooses between the merging together of all
340 This affects `yas-insert-snippet', `yas-visit-snippet-file'"
344 (defcustom yas-use-menu 'abbreviate
345 "Display a YASnippet menu in the menu bar.
347 When non-nil, submenus for each snippet table will be listed
348 under the menu \"Yasnippet\".
350 - If set to `abbreviate', only the current major-mode
351 menu and the modes set in `yas-extra-modes' are listed.
353 - If set to `full', every submenu is listed
355 - It set to nil, don't display a menu at all (this requires a
356 `yas-reload-all' call if the menu is already visible).
358 Any other non-nil value, every submenu is listed."
359 :type '(choice (const :tag "Full" full)
360 (const :tag "Abbreviate" abbreviate)
361 (const :tag "No menu" nil))
364 (defcustom yas-trigger-symbol (if (eq window-system 'mac)
365 (char-to-string ?\x21E5) ;; little ->| sign
367 "The text that will be used in menu to represent the trigger."
371 (defcustom yas-wrap-around-region nil
372 "If non-nil, snippet expansion wraps around selected region.
374 The wrapping occurs just before the snippet's exit marker. This
375 can be overriden on a per-snippet basis."
379 (defcustom yas-good-grace t
380 "If non-nil, don't raise errors in inline elisp evaluation.
382 An error string \"[yas] error\" is returned instead."
386 (defcustom yas-visit-from-menu nil
387 "If non-nil visit snippets's files from menu, instead of expanding them.
389 This cafn only work when snippets are loaded from files."
393 (defcustom yas-expand-only-for-last-commands nil
394 "List of `last-command' values to restrict tab-triggering to, or nil.
396 Leave this set at nil (the default) to be able to trigger an
397 expansion simply by placing the cursor after a valid tab trigger,
398 using whichever commands.
400 Optionallly, set this to something like '(self-insert-command) if
401 you to wish restrict expansion to only happen when the last
402 letter of the snippet tab trigger was typed immediately before
403 the trigger key itself."
404 :type '(repeat function)
407 ;; Only two faces, and one of them shouldn't even be used...
409 (defface yas-field-highlight-face
410 '((t (:inherit 'region)))
411 "The face used to highlight the currently active field of a snippet"
414 (defface yas--field-debug-face
416 "The face used for debugging some overlays normally hidden"
420 ;;; User can also customize the next defvars
422 (defun yas--define-some-keys (keys keymap definition)
423 "Bind KEYS to DEFINITION in KEYMAP, read with `read-kbd-macro'."
424 (let ((keys (or (and (listp keys) keys)
427 (define-key keymap (read-kbd-macro key) definition))))
430 (let ((map (make-sparse-keymap)))
431 (mapc #'(lambda (binding)
432 (yas--define-some-keys (car binding) map (cdr binding)))
433 `((,yas-next-field-key . yas-next-field-or-maybe-expand)
434 (,yas-prev-field-key . yas-prev-field)
435 ("C-g" . yas-abort-snippet)
436 (,yas-skip-and-clear-key . yas-skip-and-clear-or-delete-char)))
438 "The keymap active while a snippet expansion is in progress.")
440 (defvar yas-key-syntaxes (list "w" "w_" "w_." "w_.()" "^ ")
441 "List of character syntaxes used to find a trigger key before point.
442 The list is tried in the order while scanning characters
443 backwards from point. For example, if the list is '(\"w\" \"w_\")
444 first look for trigger keys which are composed exclusively of
445 \"word\"-syntax characters, and then, if that fails, look for
446 keys which are either of \"word\" or \"symbol\"
447 syntax. Triggering after
451 will, according to the \"w\" element first try \"bar\". If that
452 isn't a trigger key, \"foo-bar\" is tried, respecting a second
455 (defvar yas-after-exit-snippet-hook
457 "Hooks to run after a snippet exited.
459 The hooks will be run in an environment where some variables bound to
462 `yas-snippet-beg' : The beginning of the region of the snippet.
464 `yas-snippet-end' : Similar to beg.
466 Attention: These hooks are not run when exiting nested/stackd snippet expansion!")
468 (defvar yas-before-expand-snippet-hook
470 "Hooks to run just before expanding a snippet.")
472 (defvar yas-buffer-local-condition
473 '(if (and (or (fourth (syntax-ppss))
474 (fifth (syntax-ppss)))
475 (eq (symbol-function this-command) 'yas-expand-from-trigger-key))
476 '(require-snippet-condition . force-in-comment)
478 "Snippet expanding condition.
480 This variable is a lisp form which is evaluated everytime a
481 snippet expansion is attemped:
483 * If it evaluates to nil, no snippets can be expanded.
485 * If it evaluates to the a cons (require-snippet-condition
488 * Snippets bearing no \"# condition:\" directive are not
491 * Snippets bearing conditions that evaluate to nil (or
492 produce an error) won't be onsidered.
494 * If the snippet has a condition that evaluates to non-nil
497 * If REQUIREMENT is t, the snippet is considered
499 * If REQUIREMENT is `eq' RESULT, the snippet is
502 * Otherwise, the snippet is not considered.
504 * If it evaluates to the symbol 'always, all snippets are
505 considered for expansion, regardless of any conditions.
507 * If it evaluates to t or some other non-nil value
509 * Snippet bearing no conditions, or conditions that
510 evaluate to non-nil, are considered for expansion.
512 * Otherwise, the snippet is not considered.
514 Here's an example preventing snippets from being expanded from
515 inside comments, in `python-mode' only, with the exception of
516 snippets returning the symbol 'force-in-comment in their
519 (add-hook 'python-mode-hook
521 (setq yas-buffer-local-condition
522 '(if (python-in-string/comment)
523 '(require-snippet-condition . force-in-comment)
526 The default value is similar, it filters out potential snippet
527 expansions inside comments and string literals, unless the
528 snippet itself contains a condition that returns the symbol
529 `force-in-comment'.")
532 ;;; Internal variables
534 (defvar yas--version "0.8.0 (beta)")
536 (defvar yas--menu-table (make-hash-table)
537 "A hash table of MAJOR-MODE symbols to menu keymaps.")
539 (defvar yas--known-modes
540 '(ruby-mode rst-mode markdown-mode)
541 "A list of mode which is well known but not part of emacs.")
543 (defvar yas--escaped-characters
544 '(?\\ ?` ?\" ?' ?$ ?} ?{ ?\( ?\))
545 "List of characters which *might* need to be escaped.")
547 (defconst yas--field-regexp
548 "${\\([0-9]+:\\)?\\([^}]*\\)}"
549 "A regexp to *almost* recognize a field.")
551 (defconst yas--multi-dollar-lisp-expression-regexp
552 "$+[ \t\n]*\\(([^)]*)\\)"
553 "A regexp to *almost* recognize a \"$(...)\" expression.")
555 (defconst yas--backquote-lisp-expression-regexp
557 "A regexp to recognize a \"`lisp-expression`\" expression." )
559 (defconst yas--transform-mirror-regexp
560 "${\\(?:\\([0-9]+\\):\\)?$\\([ \t\n]*([^}]*\\)"
561 "A regexp to *almost* recognize a mirror with a transform.")
563 (defconst yas--simple-mirror-regexp
565 "A regexp to recognize a simple mirror.")
567 (defvar yas--snippet-id-seed 0
568 "Contains the next id for a snippet.")
570 (defun yas--snippet-next-id ()
571 (let ((id yas--snippet-id-seed))
572 (incf yas--snippet-id-seed)
578 ;; XXX: `last-buffer-undo-list' is somehow needed in Carbon Emacs for MacOSX
579 (defvar last-buffer-undo-list nil)
581 (defvar yas--minor-mode-menu nil
582 "Holds the YASnippet menu")
584 (defun yas--init-minor-keymap ()
585 (let ((map (make-sparse-keymap)))
587 (easy-menu-define yas--minor-mode-menu
589 "Menu used when `yas-minor-mode' is active."
592 ["Expand trigger" yas-expand
593 :help "Possibly expand tab trigger before point"]
594 ["Insert at point..." yas-insert-snippet
595 :help "Prompt for an expandable snippet and expand it at point"]
596 ["New snippet..." yas-new-snippet
597 :help "Create a new snippet in an appropriate directory"]
598 ["Visit snippet file..." yas-visit-snippet-file
599 :help "Prompt for an expandable snippet and find its file"]
601 ("Snippet menu behaviour"
602 ["Visit snippets" (setq yas-visit-from-menu t)
603 :help "Visit snippets from the menu"
604 :active t :style radio :selected yas-visit-from-menu]
605 ["Expand snippets" (setq yas-visit-from-menu nil)
606 :help "Expand snippets from the menu"
607 :active t :style radio :selected (not yas-visit-from-menu)]
609 ["Show all known modes" (setq yas-use-menu 'full)
610 :help "Show one snippet submenu for each loaded table"
611 :active t :style radio :selected (eq yas-use-menu 'full)]
612 ["Abbreviate according to current mode" (setq yas-use-menu 'abbreviate)
613 :help "Show only snippet submenus for the current active modes"
614 :active t :style radio :selected (eq yas-use-menu 'abbreviate)])
616 ["Auto" (setq yas-indent-line 'auto)
617 :help "Indent each line of the snippet with `indent-according-to-mode'"
618 :active t :style radio :selected (eq yas-indent-line 'auto)]
619 ["Fixed" (setq yas-indent-line 'fixed)
620 :help "Indent the snippet to the current column"
621 :active t :style radio :selected (eq yas-indent-line 'fixed)]
622 ["None" (setq yas-indent-line 'none)
623 :help "Don't apply any particular snippet indentation after expansion"
624 :active t :style radio :selected (not (member yas-indent-line '(fixed auto)))]
626 ["Also auto indent first line" (setq yas-also-auto-indent-first-line
627 (not yas-also-auto-indent-first-line))
628 :help "When auto-indenting also, auto indent the first line menu"
629 :active (eq yas-indent-line 'auto)
630 :style toggle :selected yas-also-auto-indent-first-line]
633 ["System X-widget" (setq yas-prompt-functions
635 (remove 'yas-x-prompt
636 yas-prompt-functions)))
637 :help "Use your windowing system's (gtk, mac, windows, etc...) default menu"
638 :active t :style radio :selected (eq (car yas-prompt-functions)
640 ["Dropdown-list" (setq yas-prompt-functions
641 (cons 'yas-dropdown-prompt
642 (remove 'yas-dropdown-prompt
643 yas-prompt-functions)))
644 :help "Use a special dropdown list"
645 :active t :style radio :selected (eq (car yas-prompt-functions)
646 'yas-dropdown-prompt)]
647 ["Ido" (setq yas-prompt-functions
648 (cons 'yas-ido-prompt
649 (remove 'yas-ido-prompt
650 yas-prompt-functions)))
651 :help "Use an ido-style minibuffer prompt"
652 :active t :style radio :selected (eq (car yas-prompt-functions)
654 ["Completing read" (setq yas-prompt-functions
655 (cons 'yas-completing-prompt
656 (remove 'yas-completing-prompt
657 yas-prompt-functions)))
658 :help "Use a normal minibuffer prompt"
659 :active t :style radio :selected (eq (car yas-prompt-functions)
660 'yas-completing-prompt)]
663 ["Wrap region in exit marker"
664 (setq yas-wrap-around-region
665 (not yas-wrap-around-region))
666 :help "If non-nil automatically wrap the selected text in the $0 snippet exit"
667 :style toggle :selected yas-wrap-around-region]
668 ["Allow stacked expansions "
669 (setq yas-triggers-in-field
670 (not yas-triggers-in-field))
671 :help "If non-nil allow snippets to be triggered inside other snippet fields"
672 :style toggle :selected yas-triggers-in-field]
673 ["Revive snippets on undo "
674 (setq yas-snippet-revival
675 (not yas-snippet-revival))
676 :help "If non-nil allow snippets to become active again after undo"
677 :style toggle :selected yas-snippet-revival]
680 (not yas-good-grace))
681 :help "If non-nil don't raise errors in bad embedded eslip in snippets"
682 :style toggle :selected yas-good-grace]
685 ["Load snippets..." yas-load-directory
686 :help "Load snippets from a specific directory"]
687 ["Reload everything" yas-reload-all
688 :help "Cleanup stuff, reload snippets, rebuild menus"]
690 :help "Display some information about YASsnippet"])))
692 ;; Now for the stuff that has direct keybindings
694 (define-key map "\C-c&\C-s" 'yas-insert-snippet)
695 (define-key map "\C-c&\C-n" 'yas-new-snippet)
696 (define-key map "\C-c&\C-v" 'yas-visit-snippet-file)
699 (defvar yas-minor-mode-map (yas--init-minor-keymap)
700 "The keymap used when `yas-minor-mode' is active.")
702 (defun yas--trigger-key-reload (&optional unbind-key)
703 "Rebind `yas-expand' to the new value of `yas-trigger-key'.
705 With optional UNBIND-KEY, try to unbind that key from
706 `yas-minor-mode-map'."
707 (when (and unbind-key
709 (not (string= unbind-key "")))
710 (define-key yas-minor-mode-map (read-kbd-macro unbind-key) nil))
711 (when (and yas-trigger-key
712 (stringp yas-trigger-key)
713 (not (string= yas-trigger-key "")))
714 (define-key yas-minor-mode-map (read-kbd-macro yas-trigger-key) 'yas-expand)))
716 (defvar yas--tables (make-hash-table)
717 "A hash table of mode symbols to `yas--table' objects.")
719 (defvar yas--parents (make-hash-table)
720 "A hash table of mode symbols do lists of direct parent mode symbols.
722 This list is populated when reading the \".yas-parents\" files
723 found when traversing snippet directories with
724 `yas-load-directory'.
726 There might be additionalal parenting information stored in the
727 `derived-mode-parent' property of some mode symbols, but that is
730 (defvar yas--direct-keymaps (list)
731 "Keymap alist supporting direct snippet keybindings.
733 This variable is is placed in `emulation-mode-map-alists'.
735 Its elements looks like (TABLE-NAME . KEYMAP). They're
736 instantiated on `yas-reload-all' but KEYMAP is added to only when
737 loading snippets. `yas--direct-TABLE-NAME' is then a variable set
738 buffer-locally when entering `yas-minor-mode'. KEYMAP binds all
739 defined direct keybindings to the command
740 `yas-expand-from-keymap' which then which snippet to expand.")
742 (defun yas-direct-keymaps-reload ()
743 "Force reload the direct keybinding for active snippet tables."
745 (setq yas--direct-keymaps nil)
746 (maphash #'(lambda (name table)
747 (push (cons (intern (format "yas--direct-%s" name))
748 (yas--table-direct-keymap table))
749 yas--direct-keymaps))
752 (defun yas--modes-to-activate ()
753 "Compute list of mode symbols that are active for `yas-expand'
755 (let ((modes-to-activate (list major-mode))
757 (while (setq mode (get mode 'derived-mode-parent))
758 (push mode modes-to-activate))
759 (dolist (mode (yas-extra-modes))
760 (push mode modes-to-activate))
762 (append modes-to-activate
763 (mapcan #'(lambda (mode)
764 (yas--all-parents mode))
765 modes-to-activate)))))
767 (defvar yas-minor-mode-hook nil
768 "Hook run when yas-minor-mode is turned on")
771 (define-minor-mode yas-minor-mode
772 "Toggle YASnippet mode.
774 When YASnippet mode is enabled, the `yas-trigger-key' key expands
775 snippets of code depending on the major mode.
777 With no argument, this command toggles the mode.
778 positive prefix argument turns on the mode.
779 Negative prefix argument turns off the mode.
781 You can customize the key through `yas-trigger-key'.
784 \\{yas-minor-mode-map}"
786 ;; The indicator for the mode line.
789 (cond (yas-minor-mode
790 ;; Reload the trigger key
792 (yas--trigger-key-reload)
793 ;; Install the direct keymaps in `emulation-mode-map-alists'
794 ;; (we use `add-hook' even though it's not technically a hook,
795 ;; but it works). Then define variables named after modes to
796 ;; index `yas--direct-keymaps'.
798 ;; Also install the post-command-hook.
800 (add-hook 'emulation-mode-map-alists 'yas--direct-keymaps)
801 (add-hook 'post-command-hook 'yas--post-command-handler nil t)
802 ;; Set the `yas--direct-%s' vars for direct keymap expansion
804 (dolist (mode (yas--modes-to-activate))
805 (let ((name (intern (format "yas--direct-%s" mode))))
806 (set-default name nil)
807 (set (make-local-variable name) t)))
810 (yas--load-pending-jits))
812 ;; Uninstall the direct keymaps and the post-command hook
814 (remove-hook 'post-command-hook 'yas--post-command-handler t)
815 (remove-hook 'emulation-mode-map-alists 'yas--direct-keymaps))))
817 (defvar yas--dont-activate '(minibufferp)
818 "If non-nil don't let `yas-minor-mode-on' active yas for this buffer.
820 If a function, then its result is used.
822 If a list of functions, then all functions must return nil to
823 activate yas for this buffer.
825 `yas-minor-mode-on' is usually called by `yas-global-mode' so
826 this effectively lets you define exceptions to the \"global\"
827 behaviour. Can also be a function of zero arguments.")
828 (make-variable-buffer-local 'yas--dont-activate)
830 (defun yas-minor-mode-on ()
831 "Turn on YASnippet minor mode.
833 Do this unless `yas--dont-activate' is truish "
835 (unless (cond ((functionp yas--dont-activate)
836 (funcall yas--dont-activate))
837 ((consp yas--dont-activate)
838 (some #'funcall yas--dont-activate))
839 (yas--dont-activate))
840 ;; Load all snippets definitions unless we still don't have a
841 ;; root-directory or some snippets have already been loaded.
846 (define-globalized-minor-mode yas-global-mode yas-minor-mode yas-minor-mode-on
850 (defadvice yas-global-mode (before yas--reload-with-jit (arg) activate)
854 ;; explicitly enabling
856 ((not yas-global-mode)
860 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
863 (defvar yas--font-lock-keywords
864 (append '(("^#.*$" . font-lock-comment-face))
865 lisp-font-lock-keywords
866 lisp-font-lock-keywords-1
867 lisp-font-lock-keywords-2
869 (0 font-lock-keyword-face)
870 (1 font-lock-string-face t))
872 (0 font-lock-keyword-face)
873 (1 font-lock-warning-face t))
874 ("${" font-lock-keyword-face)
875 ("$[0-9]+?" font-lock-preprocessor-face)
876 ("\\(\\$(\\)" 1 font-lock-preprocessor-face)
878 (0 font-lock-keyword-face)))))
880 (defun yas--init-major-keymap ()
881 (let ((map (make-sparse-keymap)))
882 (easy-menu-define nil
884 "Menu used when snippet-mode is active."
886 (mapcar #'(lambda (ent)
888 (define-key map (third ent) (second ent)))
889 (vector (first ent) (second ent) t))
891 (list "Load this snippet" 'yas-load-snippet-buffer "\C-c\C-c")
892 (list "Try out this snippet" 'yas-tryout-snippet "\C-c\C-t")))))
895 (defvar snippet-mode-map
896 (yas--init-major-keymap)
897 "The keymap used when `snippet-mode' is active")
900 (define-derived-mode snippet-mode text-mode "Snippet"
901 "A mode for editing yasnippets"
902 (setq font-lock-defaults '(yas--font-lock-keywords))
903 (set (make-local-variable 'require-final-newline) nil)
904 (set (make-local-variable 'comment-start) "#")
905 (set (make-local-variable 'comment-start-skip) "#+[\t ]*"))
909 ;;; Internal structs for template management
911 (defstruct (yas--template (:constructor yas--make-blank-template))
912 "A template for a snippet."
922 group ;; as dictated by the #group: directive or .yas-make-groups
923 perm-group ;; as dictated by `yas-define-menu'
927 (defun yas--populate-template (template &rest args)
928 "Helper function to populate a template with properties"
932 (position (intern (substring (symbol-name (car args)) 1))
933 (mapcar #'car (get 'yas--template 'cl-struct-slots)))
935 (setq args (cddr args)))
938 (defstruct (yas--table (:constructor yas--make-snippet-table (name)))
939 "A table to store snippets for a particular mode.
941 Has the following fields:
945 A symbol name normally corresponding to a major mode, but can
946 also be a pseudo major-mode to be referenced in
947 `yas-extra-modes', for example.
951 A hash table (KEY . NAMEHASH), known as the \"keyhash\". KEY is
952 a string or a vector, where the former is the snippet's trigger
953 and the latter means it's a direct keybinding. NAMEHASH is yet
954 another hash of (NAME . TEMPLATE) where NAME is the snippet's
955 name and TEMPLATE is a `yas--template' object.
957 `yas--table-direct-keymap'
959 A keymap for the snippets in this table that have direct
960 keybindings. This is kept in sync with the keyhash, i.e., all
961 the elements of the keyhash that are vectors appear here as
962 bindings to `yas-expand-from-keymap'.
964 `yas--table-uuidhash'
966 A hash table mapping snippets uuid's to the same `yas--template'
967 objects. A snippet uuid defaults to the snippet's name.
970 (hash (make-hash-table :test 'equal))
971 (uuidhash (make-hash-table :test 'equal))
973 (direct-keymap (make-sparse-keymap)))
975 (defun yas--get-template-by-uuid (mode uuid)
976 "Find the snippet template in MODE by its UUID."
977 (let* ((table (gethash mode yas--tables mode)))
979 (gethash uuid (yas--table-uuidhash table)))))
981 ;; Apropos storing/updating in TABLE, this works in two steps:
983 ;; 1. `yas--remove-template-by-uuid' removes any
984 ;; keyhash-namehash-template mappings from TABLE, grabing the
985 ;; snippet by its uuid. Also removes mappings from TABLE's
986 ;; `yas--table-direct-keymap' (FIXME: and should probably take care
987 ;; of potentially stale menu bindings right?.)
989 ;; 2. `yas--add-template' adds this all over again.
991 ;; Create a new or add to an existing keyhash-namehash mapping.
993 ;; For reference on understanding this, consider three snippet
996 ;; A: # name: The Foo
998 ;; # binding: C-c M-l
1000 ;; B: # name: Mrs Foo
1003 ;; C: # name: The Bar
1004 ;; # binding: C-c M-l
1009 ;; keyhash namehashes(3) yas--template structs(4)
1010 ;; -----------------------------------------------------
1013 ;; "foo" ---> "The Foo" ---> [yas--template A] |
1014 ;; "Mrs Foo" ---> [yas--template B] |
1016 ;; [C-c M-l] ---> "The Foo" -------------------------/
1017 ;; "The Bar" ---> [yas--template C]
1019 ;; "baz" ---> "Baz" ---> [yas--template D]
1021 ;; Additionally, since uuid defaults to the name, we have a
1022 ;; `yas--table-uuidhash' for TABLE
1024 ;; uuidhash yas--template structs
1025 ;; -------------------------------
1026 ;; "The Foo" ---> [yas--template A]
1027 ;; "Mrs Foo" ---> [yas--template B]
1028 ;; "The Bar" ---> [yas--template C]
1029 ;; "Baz" ---> [yas--template D]
1031 ;; FIXME: the more I look at this data-structure the more I think I'm
1032 ;; stupid. There has to be an easier way (but beware lots of code
1033 ;; depends on this).
1035 (defun yas--remove-template-by-uuid (table uuid)
1036 "Remove from TABLE a template identified by UUID."
1037 (let ((template (gethash uuid (yas--table-uuidhash table))))
1039 (let* ((name (yas--template-name template))
1041 ;; Remove the name from each of the targeted namehashes
1043 (maphash #'(lambda (k v)
1044 (let ((template (gethash name v)))
1046 (eq uuid (yas--template-uuid template)))
1048 (when (zerop (hash-table-count v))
1049 (push k empty-keys)))))
1050 (yas--table-hash table))
1051 ;; Remove the namehash themselves if they've become empty
1053 (dolist (key empty-keys)
1055 (define-key (yas--table-direct-keymap table) key nil))
1056 (remhash key (yas--table-hash table)))
1058 ;; Finally, remove the uuid from the uuidhash
1060 (remhash uuid (yas--table-uuidhash table))))))
1062 (defun yas--add-template (table template)
1063 "Store in TABLE the snippet template TEMPLATE.
1065 KEY can be a string (trigger key) of a vector (direct
1067 (let ((name (yas--template-name template))
1068 (key (yas--template-key template))
1069 (keybinding (yas--template-keybinding template))
1070 (menu-binding-pair (yas--template-menu-binding-pair-get-create template)))
1071 (dolist (k (remove nil (list key keybinding)))
1075 (yas--table-hash table))
1077 (make-hash-table :test 'equal)
1078 (yas--table-hash table))))
1080 (define-key (yas--table-direct-keymap table) k 'yas-expand-from-keymap)))
1082 ;; Update TABLE's `yas--table-uuidhash'
1083 (puthash (yas--template-uuid template)
1085 (yas--table-uuidhash table))))
1087 (defun yas--update-template (table template)
1088 "Add or update TEMPLATE in TABLE.
1090 Also takes care of adding and updating to the associated menu."
1091 ;; Remove from table by uuid
1093 (yas--remove-template-by-uuid table (yas--template-uuid template))
1094 ;; Add to table again
1096 (yas--add-template table template)
1097 ;; Take care of the menu
1100 (yas--update-template-menu table template)))
1102 (defun yas--update-template-menu (table template)
1103 "Update every menu-related for TEMPLATE"
1104 (let ((menu-binding-pair (yas--template-menu-binding-pair-get-create template))
1105 (key (yas--template-key template))
1106 (keybinding (yas--template-keybinding template)))
1107 ;; The snippet might have changed name or keys, so update
1108 ;; user-visible strings
1110 (unless (eq (cdr menu-binding-pair) :none)
1111 ;; the menu item name
1113 (setf (cadar menu-binding-pair) (yas--template-name template))
1114 ;; the :keys information (also visible to the user)
1115 (setf (getf (cdr (car menu-binding-pair)) :keys)
1116 (or (and keybinding (key-description keybinding))
1117 (and key (concat key yas-trigger-symbol))))))
1118 (unless (yas--template-menu-managed-by-yas-define-menu template)
1120 (yas--menu-keymap-get-create (yas--table-mode table)
1121 (mapcar #'yas--table-mode
1122 (yas--table-parents table))))
1123 (group (yas--template-group template)))
1124 ;; Remove from menu keymap
1126 (assert menu-keymap)
1127 (yas--delete-from-keymap menu-keymap (yas--template-uuid template))
1129 ;; Add necessary subgroups as necessary.
1131 (dolist (subgroup group)
1132 (let ((subgroup-keymap (lookup-key menu-keymap (vector (make-symbol subgroup)))))
1133 (unless (and subgroup-keymap
1134 (keymapp subgroup-keymap))
1135 (setq subgroup-keymap (make-sparse-keymap))
1136 (define-key menu-keymap (vector (make-symbol subgroup))
1137 `(menu-item ,subgroup ,subgroup-keymap)))
1138 (setq menu-keymap subgroup-keymap)))
1140 ;; Add this entry to the keymap
1142 (define-key menu-keymap
1143 (vector (make-symbol (yas--template-uuid template)))
1144 (car (yas--template-menu-binding-pair template))))))
1146 (defun yas--namehash-templates-alist (namehash)
1148 (maphash #'(lambda (k v)
1149 (push (cons k v) alist))
1153 (defun yas--fetch (table key)
1154 "Fetch templates in TABLE by KEY.
1156 Return a list of cons (NAME . TEMPLATE) where NAME is a
1157 string and TEMPLATE is a `yas--template' structure."
1158 (let* ((keyhash (yas--table-hash table))
1159 (namehash (and keyhash (gethash key keyhash))))
1161 (yas--filter-templates-by-condition (yas--namehash-templates-alist namehash)))))
1164 ;;; Filtering/condition logic
1166 (defun yas--eval-condition (condition)
1173 (yas--message 1 "Error in condition evaluation: %s" (error-message-string err))
1177 (defun yas--filter-templates-by-condition (templates)
1178 "Filter the templates using the applicable condition.
1180 TEMPLATES is a list of cons (NAME . TEMPLATE) where NAME is a
1181 string and TEMPLATE is a `yas--template' structure.
1183 This function implements the rules described in
1184 `yas-buffer-local-condition'. See that variables documentation."
1185 (let ((requirement (yas--require-template-specific-condition-p)))
1186 (if (eq requirement 'always)
1188 (remove-if-not #'(lambda (pair)
1189 (yas--template-can-expand-p
1190 (yas--template-condition (cdr pair)) requirement))
1193 (defun yas--require-template-specific-condition-p ()
1194 "Decides if this buffer requests/requires snippet-specific
1195 conditions to filter out potential expansions."
1196 (if (eq 'always yas-buffer-local-condition)
1198 (let ((local-condition (or (and (consp yas-buffer-local-condition)
1199 (yas--eval-condition yas-buffer-local-condition))
1200 yas-buffer-local-condition)))
1201 (when local-condition
1202 (if (eq local-condition t)
1204 (and (consp local-condition)
1205 (eq 'require-snippet-condition (car local-condition))
1206 (symbolp (cdr local-condition))
1207 (cdr local-condition)))))))
1209 (defun yas--template-can-expand-p (condition requirement)
1210 "Evaluates CONDITION and REQUIREMENT and returns a boolean"
1211 (let* ((result (or (null condition)
1212 (yas--eval-condition condition))))
1213 (cond ((eq requirement t)
1216 (eq requirement result)))))
1218 (defun yas--all-parents (mode)
1219 "Returns a list of all parent modes of MODE"
1220 (let ((parents (gethash mode yas--parents)))
1222 (mapcan #'yas--all-parents parents))))
1224 (defun yas--table-templates (table)
1227 (maphash #'(lambda (key namehash)
1228 (maphash #'(lambda (name template)
1229 (push (cons name template) acc))
1231 (yas--table-hash table))
1232 (yas--filter-templates-by-condition acc))))
1234 (defun yas--current-key ()
1235 "Get the key under current position. A key is used to find
1236 the template of a snippet in the current snippet-table."
1237 (let ((start (point))
1239 (syntaxes yas-key-syntaxes)
1243 (while (and (not done) syntaxes)
1244 (setq syntax (car syntaxes))
1245 (setq syntaxes (cdr syntaxes))
1247 (skip-syntax-backward syntax)
1248 (setq start (point)))
1250 (mapcan #'(lambda (table)
1251 (yas--fetch table (buffer-substring-no-properties start end)))
1252 (yas--get-snippet-tables)))
1261 (defun yas--table-all-keys (table)
1264 (maphash #'(lambda (key namehash)
1265 (when (yas--filter-templates-by-condition (yas--namehash-templates-alist namehash))
1267 (yas--table-hash table))
1270 (defun yas--table-mode (table)
1271 (intern (yas--table-name table)))
1274 ;;; Internal functions:
1276 (defun yas--real-mode? (mode)
1277 "Try to find out if MODE is a real mode. The MODE bound to
1278 a function (like `c-mode') is considered real mode. Other well
1279 known mode like `ruby-mode' which is not part of Emacs might
1280 not bound to a function until it is loaded. So yasnippet keeps
1281 a list of modes like this to help the judgement."
1283 (find mode yas--known-modes)))
1285 (defun yas--eval-lisp (form)
1286 "Evaluate FORM and convert the result to string."
1287 (let ((retval (catch 'yas--exception
1293 (let ((result (eval form)))
1295 (format "%s" result))))))
1296 (error (if yas-good-grace
1297 (yas--format "elisp error! %s" (error-message-string err))
1298 (error (yas--format "elisp error: %s"
1299 (error-message-string err)))))))))
1300 (when (and (consp retval)
1301 (eq 'yas--exception (car retval)))
1302 (error (cdr retval)))
1305 (defun yas--eval-lisp-no-saves (form)
1308 (error (if yas-good-grace
1309 (yas--format "elisp error! %s" (error-message-string err))
1310 (error (yas--format "elisp error: %s"
1311 (error-message-string err)))))))
1313 (defun yas--read-lisp (string &optional nil-on-error)
1314 "Read STRING as a elisp expression and return it.
1316 In case STRING in an invalid expression and NIL-ON-ERROR is nil,
1317 return an expression that when evaluated will issue an error."
1320 (error (and (not nil-on-error)
1321 `(error (error-message-string ,err))))))
1323 (defun yas--read-keybinding (keybinding)
1324 "Read KEYBINDING as a snippet keybinding, return a vector."
1325 (when (and keybinding
1326 (not (string-match "keybinding" keybinding)))
1328 (let ((res (or (and (string-match "^\\[.*\\]$" keybinding)
1330 (read-kbd-macro keybinding 'need-vector))))
1333 (yas--message 3 "warning: keybinding \"%s\" invalid since %s."
1334 keybinding (error-message-string err))
1337 (defvar yas-extra-modes nil
1338 "If non-nil, also lookup snippets for this/these modes.
1340 Can be a symbol or a list of symbols.
1342 This variable probably makes more sense as buffer-local, so
1343 ensure your use `make-local-variable' when you set it.")
1344 (defun yas-extra-modes ()
1345 (if (listp yas-extra-modes) yas-extra-modes (list yas-extra-modes)))
1346 (defvaralias 'yas/mode-symbol 'yas-extra-modes)
1348 (defun yas--table-get-create (mode)
1349 "Get or create the snippet table corresponding to MODE."
1350 (let ((table (gethash mode
1353 (setq table (yas--make-snippet-table (symbol-name mode)))
1354 (puthash mode table yas--tables)
1355 (push (cons (intern (format "yas--direct-%s" mode))
1356 (yas--table-direct-keymap table))
1357 yas--direct-keymaps))
1360 (defun yas--get-snippet-tables ()
1361 "Get snippet tables for current buffer.
1363 Return a list of `yas--table' objects. The list of modes to
1364 consider is returned by `yas--modes-to-activate'"
1366 (mapcar #'(lambda (mode-name)
1367 (gethash mode-name yas--tables))
1368 (yas--modes-to-activate))))
1370 (defun yas--menu-keymap-get-create (mode &optional parents)
1371 "Get or create the menu keymap for MODE and its PARENTS.
1373 This may very well create a plethora of menu keymaps and arrange
1374 them all in `yas--menu-table'"
1375 (let* ((menu-keymap (or (gethash mode yas--menu-table)
1376 (puthash mode (make-sparse-keymap) yas--menu-table))))
1377 (mapc #'yas--menu-keymap-get-create parents)
1378 (define-key yas--minor-mode-menu (vector mode)
1379 `(menu-item ,(symbol-name mode) ,menu-keymap
1380 :visible (yas--show-menu-p ',mode)))
1383 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1384 ;;; Template-related and snippet loading functions
1386 (defun yas--parse-template (&optional file)
1387 "Parse the template in the current buffer.
1389 Optional FILE is the absolute file name of the file being
1392 Optional GROUP is the group where the template is to go,
1393 otherwise we attempt to calculate it from FILE.
1395 Return a snippet-definition, i.e. a list
1397 (KEY TEMPLATE NAME CONDITION GROUP VARS FILE KEYBINDING UUID)
1399 If the buffer contains a line of \"# --\" then the contents above
1400 this line are ignored. Directives can set most of these with the syntax:
1402 # directive-name : directive-value
1404 Here's a list of currently recognized directives:
1415 (goto-char (point-min))
1416 (let* ((type 'snippet)
1418 (file-name-nondirectory file)))
1424 (yas--calculate-group file)))
1428 (if (re-search-forward "^# --\n" nil t)
1429 (progn (setq template
1430 (buffer-substring-no-properties (point)
1432 (setq bound (point))
1433 (goto-char (point-min))
1434 (while (re-search-forward "^# *\\([^ ]+?\\) *: *\\(.*\\)$" bound t)
1435 (when (string= "uuid" (match-string-no-properties 1))
1436 (setq uuid (match-string-no-properties 2)))
1437 (when (string= "type" (match-string-no-properties 1))
1438 (setq type (if (string= "command" (match-string-no-properties 2))
1441 (when (string= "key" (match-string-no-properties 1))
1442 (setq key (match-string-no-properties 2)))
1443 (when (string= "name" (match-string-no-properties 1))
1444 (setq name (match-string-no-properties 2)))
1445 (when (string= "condition" (match-string-no-properties 1))
1446 (setq condition (yas--read-lisp (match-string-no-properties 2))))
1447 (when (string= "group" (match-string-no-properties 1))
1448 (setq group (match-string-no-properties 2)))
1449 (when (string= "expand-env" (match-string-no-properties 1))
1450 (setq expand-env (yas--read-lisp (match-string-no-properties 2)
1452 (when (string= "binding" (match-string-no-properties 1))
1453 (setq binding (match-string-no-properties 2)))))
1455 (buffer-substring-no-properties (point-min) (point-max))))
1456 (unless (or key binding)
1457 (setq key (and file (file-name-nondirectory file))))
1458 (when (eq type 'command)
1459 (setq template (yas--read-lisp (concat "(progn" template ")"))))
1461 (setq group (split-string group "\\.")))
1462 (list key template name condition group expand-env file binding uuid)))
1464 (defun yas--calculate-group (file)
1465 "Calculate the group for snippet file path FILE."
1466 (let* ((dominating-dir (locate-dominating-file file
1467 ".yas-make-groups"))
1468 (extra-path (and dominating-dir
1469 (replace-regexp-in-string (concat "^"
1470 (expand-file-name dominating-dir))
1472 (expand-file-name file))))
1473 (extra-dir (and extra-path
1474 (file-name-directory extra-path)))
1475 (group (and extra-dir
1476 (replace-regexp-in-string "/"
1478 (directory-file-name extra-dir)))))
1481 (defun yas--subdirs (directory &optional filep)
1482 "Return subdirs or files of DIRECTORY according to FILEP."
1483 (remove-if (lambda (file)
1484 (or (string-match "^\\."
1485 (file-name-nondirectory file))
1486 (string-match "^#.*#$"
1487 (file-name-nondirectory file))
1489 (file-name-nondirectory file))
1491 (file-directory-p file)
1492 (not (file-directory-p file)))))
1493 (directory-files directory t)))
1495 (defun yas--make-menu-binding (template)
1496 (let ((mode (yas--table-mode (yas--template-table template))))
1497 `(lambda () (interactive) (yas--expand-or-visit-from-menu ',mode ,(yas--template-uuid template)))))
1499 (defun yas--expand-or-visit-from-menu (mode uuid)
1500 (let* ((table (yas--table-get-create mode))
1501 (yas--current-template (and table
1502 (gethash uuid (yas--table-uuidhash table)))))
1503 (when yas--current-template
1504 (if yas-visit-from-menu
1505 (yas--visit-snippet-file-1 yas--current-template)
1506 (let ((where (if (region-active-p)
1507 (cons (region-beginning) (region-end))
1508 (cons (point) (point)))))
1509 (yas-expand-snippet (yas--template-content yas--current-template)
1512 (yas--template-expand-env yas--current-template)))))))
1514 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1515 ;; Popping up for keys and templates
1517 (defvar yas--x-pretty-prompt-templates nil
1518 "If non-nil, attempt to prompt for templates like TextMate.")
1521 (defun yas--prompt-for-template (templates &optional prompt)
1522 "Interactively choose a template from the list TEMPLATES.
1524 TEMPLATES is a list of `yas--template'."
1527 (sort templates #'(lambda (t1 t2)
1528 (< (length (yas--template-name t1))
1529 (length (yas--template-name t2))))))
1530 (if yas--x-pretty-prompt-templates
1531 (yas--x-pretty-prompt-templates "Choose a snippet" templates)
1532 (some #'(lambda (fn)
1533 (funcall fn (or prompt "Choose a snippet: ")
1535 #'yas--template-name))
1536 yas-prompt-functions))))
1538 (defun yas--prompt-for-keys (keys &optional prompt)
1539 "Interactively choose a template key from the list KEYS."
1541 (some #'(lambda (fn)
1542 (funcall fn (or prompt "Choose a snippet key: ") keys))
1543 yas-prompt-functions)))
1545 (defun yas--prompt-for-table (tables &optional prompt)
1547 (some #'(lambda (fn)
1548 (funcall fn (or prompt "Choose a snippet table: ")
1551 yas-prompt-functions)))
1553 (defun yas-x-prompt (prompt choices &optional display-fn)
1554 "Display choices in a x-window prompt."
1555 ;; FIXME: HACK: if we notice that one of the objects in choices is
1556 ;; actually a `yas--template', defer to `yas--x-prompt-pretty-templates'
1558 ;; This would be better implemented by passing CHOICES as a
1559 ;; strucutred tree rather than a list. Modifications would go as far
1560 ;; up as `yas--all-templates' I think.
1562 (when (and window-system choices)
1564 (let (menu d) ;; d for display
1566 (setq d (or (and display-fn (funcall display-fn c))
1569 (push (cons (concat " " d) c) menu))
1571 (push (car d) menu))))
1572 (setq menu (list prompt (push "title" menu)))
1573 (x-popup-menu (if (fboundp 'posn-at-point)
1574 (let ((x-y (posn-x-y (posn-at-point (point)))))
1575 (list (list (+ (car x-y) 10)
1583 (defun yas--x-pretty-prompt-templates (prompt templates)
1584 "Display TEMPLATES, grouping neatly by table name."
1585 (let ((organized (make-hash-table :test #'equal))
1589 (dolist (tl templates)
1590 (puthash (yas--template-table tl)
1592 (gethash (yas--template-table tl) organized))
1594 (setq more-than-one-table (> (hash-table-count organized) 1))
1595 (setq prefix (if more-than-one-table
1597 (if more-than-one-table
1598 (maphash #'(lambda (table templates)
1599 (push (yas--table-name table) menu)
1600 (dolist (tl templates)
1601 (push (cons (concat prefix (yas--template-name tl)) tl) menu))) organized)
1602 (setq menu (mapcar #'(lambda (tl) (cons (concat prefix (yas--template-name tl)) tl)) templates)))
1604 (setq menu (nreverse menu))
1605 (or (x-popup-menu (if (fboundp 'posn-at-point)
1606 (let ((x-y (posn-x-y (posn-at-point (point)))))
1607 (list (list (+ (car x-y) 10)
1611 (list prompt (push "title" menu)))
1614 (defun yas-ido-prompt (prompt choices &optional display-fn)
1615 (when (and (fboundp 'ido-completing-read)
1616 (or (>= emacs-major-version 24)
1618 (yas-completing-prompt prompt choices display-fn #'ido-completing-read)))
1620 (eval-when-compile (require 'dropdown-list nil t))
1621 (defun yas-dropdown-prompt (prompt choices &optional display-fn)
1622 (when (featurep 'dropdown-list)
1623 (let (formatted-choices
1627 (dolist (choice choices)
1628 (setq d (or (and display-fn (funcall display-fn choice))
1631 (push d formatted-choices)
1632 (push choice filtered-choices)))
1634 (setq n (and formatted-choices (dropdown-list formatted-choices)))
1636 (nth n filtered-choices)
1639 (defun yas-completing-prompt (prompt choices &optional display-fn completion-fn)
1640 (let (formatted-choices
1644 (completion-fn (or completion-fn
1645 #'completing-read)))
1646 (dolist (choice choices)
1647 (setq d (or (and display-fn (funcall display-fn choice))
1650 (push d formatted-choices)
1651 (push choice filtered-choices)))
1652 (setq chosen (and formatted-choices
1653 (funcall completion-fn prompt
1659 (let ((position (or (and chosen
1660 (position chosen formatted-choices :test #'string=))
1662 (nth position filtered-choices))))
1664 (defun yas-no-prompt (prompt choices &optional display-fn)
1667 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1668 ;; Loading snippets from files
1670 (defun yas--load-yas-setup-file (file)
1671 (load file 'noerror))
1673 (defun yas-load-directory (top-level-dir &optional use-jit)
1674 "Load snippets in directory hierarchy TOP-LEVEL-DIR.
1676 Below TOP-LEVEL-DIR each directory should be a mode name.
1678 Optional USE-JIT use jit-loading of snippets."
1679 (interactive "DSelect the root directory: ")
1680 (unless yas-snippet-dirs
1681 (setq yas-snippet-dirs top-level-dir))
1682 (dolist (dir (yas--subdirs top-level-dir))
1683 (let* ((major-mode-and-parents (yas--compute-major-mode-and-parents
1684 (concat dir "/dummy")))
1685 (mode-sym (car major-mode-and-parents))
1686 (parents (cdr major-mode-and-parents)))
1687 ;; Attention: The parents and the menus are already defined
1688 ;; here, even if the snippets are later jit-loaded.
1690 ;; * We need to know the parents at this point since entering a
1691 ;; given mode should jit load for its parents
1692 ;; immediately. This could be reviewed, the parents could be
1693 ;; discovered just-in-time-as well
1695 ;; * We need to create the menus here to support the `full'
1696 ;; option to `yas-use-menu' (all known snippet menus are shown to the user)
1698 (yas--define-parents mode-sym parents)
1699 (yas--menu-keymap-get-create mode-sym)
1700 (let ((form `(yas--load-directory-1 ,dir
1704 (yas--schedule-jit mode-sym form)
1706 (when (interactive-p)
1707 (yas--message 3 "Loaded snippets from %s." top-level-dir)))
1709 (defun yas--load-directory-1 (directory mode-sym parents &optional no-compiled-snippets)
1710 "Recursively load snippet templates from DIRECTORY."
1711 (unless (file-exists-p (concat directory "/" ".yas-skip"))
1712 (if (and (not no-compiled-snippets)
1713 (progn (yas--message 2 "Loading compiled snippets from %s" directory) t)
1714 (load (expand-file-name ".yas-compiled-snippets" directory) 'noerror (<= yas-verbosity 3)))
1715 (yas--message 2 "Loading snippet files from %s" directory)
1716 (yas--load-directory-2 directory mode-sym))))
1718 (defun yas--load-directory-2 (directory mode-sym)
1719 ;; Load .yas-setup.el files wherever we find them
1721 (yas--load-yas-setup-file (expand-file-name ".yas-setup" directory))
1722 (let* ((default-directory directory)
1724 ;; load the snippet files
1727 (dolist (file (yas--subdirs directory 'no-subdirs-just-files))
1728 (when (file-readable-p file)
1729 (insert-file-contents file nil nil nil t)
1730 (push (yas--parse-template file)
1733 (yas-define-snippets mode-sym
1735 ;; now recurse to a lower level
1737 (dolist (subdir (yas--subdirs directory))
1738 (yas--load-directory-2 subdir
1741 (defun yas--load-snippet-dirs (&optional nojit)
1742 "Reload the directories listed in `yas-snippet-dirs' or
1743 prompt the user to select one."
1745 (if yas-snippet-dirs
1746 (dolist (directory (reverse (yas-snippet-dirs)))
1747 (cond ((file-directory-p directory)
1748 (yas-load-directory directory (not nojit))
1750 (yas--message 3 "Loaded %s" directory)
1751 (yas--message 3 "Prepared just-in-time loading for %s" directory)))
1753 (push (yas--message 0 "Check your `yas-snippet-dirs': %s is not a directory" directory) errors))))
1754 (call-interactively 'yas-load-directory))
1757 (defun yas-reload-all (&optional interactive)
1758 "Reload all snippets and rebuild the YASnippet menu.
1760 When called interactively force immediate reload of all known
1761 snippets under `yas-snippet-dirs', otherwise use just-in-time
1766 (snippet-editing-buffers
1767 (remove-if-not #'(lambda (buffer)
1768 (with-current-buffer buffer yas--editing-template))
1770 ;; Warn if there are buffers visiting snippets, since reloading will break
1771 ;; any on-line editing of those buffers.
1773 (when snippet-editing-buffers
1775 (if (y-or-n-p "Some buffers editing live snippets, close them and proceed with reload?")
1776 (mapc #'kill-buffer snippet-editing-buffers)
1777 (yas--message 1 "Aborted reload...")
1779 ;; in a non-interactive use, at least set
1780 ;; `yas--editing-template' to nil, make it guess it next time around
1781 (mapc #'(lambda (buffer) (setq yas--editing-template nil)) (buffer-list))))
1783 ;; Empty all snippet tables, parenting info and all menu tables
1785 (setq yas--tables (make-hash-table))
1786 (setq yas--parents (make-hash-table))
1787 (setq yas--menu-table (make-hash-table))
1789 ;; Cancel all pending 'yas--scheduled-jit-loads'
1791 (setq yas--scheduled-jit-loads (make-hash-table))
1793 ;; Init the `yas-minor-mode-map', taking care not to break the
1796 (setcdr yas-minor-mode-map (cdr (yas--init-minor-keymap)))
1798 ;; Reload the directories listed in `yas-snippet-dirs' or prompt
1799 ;; the user to select one.
1801 (setq errors (yas--load-snippet-dirs interactive))
1802 ;; Reload the direct keybindings
1804 (yas-direct-keymaps-reload)
1805 ;; Reload the trigger-key (shoudn't be needed, but see issue #237)
1807 (yas--trigger-key-reload)
1809 (yas--message 3 "Reloaded everything%s...%s."
1810 (if interactive "" " (snippets will load just-in-time)")
1811 (if errors " (some errors, check *Messages*)" "")))))
1813 (defun yas--load-pending-jits ()
1814 (when yas-minor-mode
1815 (dolist (mode (yas--modes-to-activate))
1816 (let ((forms (gethash mode yas--scheduled-jit-loads)))
1817 (dolist (form forms)
1818 (yas--message 3 "Loading for `%s', just-in-time: %s!" mode form)
1820 (remhash mode yas--scheduled-jit-loads)))))
1822 ;; (when (<= emacs-major-version 22)
1823 ;; (add-hook 'after-change-major-mode-hook 'yas--load-pending-jits))
1825 (defun yas--quote-string (string)
1826 "Escape and quote STRING.
1827 foo\"bar\\! -> \"foo\\\"bar\\\\!\""
1829 (replace-regexp-in-string "[\\\"]"
1834 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1835 ;;; Snippet compilation function
1837 (defun yas--initialize ()
1838 "For backward compatibility, enable `yas-minor-mode' globally"
1839 (yas-global-mode 1))
1841 (defun yas-compile-directory (top-level-dir)
1842 "Create .yas-compiled-snippets.el files under subdirs of TOP-LEVEL-DIR.
1844 This works by stubbing a few functions, then calling
1845 `yas-load-directory'."
1846 (interactive "DTop level snippet directory?")
1847 (flet ((yas--load-yas-setup-file
1849 (let ((elfile (concat file ".el")))
1850 (when (file-exists-p elfile)
1851 (insert ";;; .yas-setup.el support file if any:\n;;;\n")
1852 (insert-file-contents elfile)
1855 (yas-define-snippets
1857 (insert ";;; Snippet definitions:\n;;;\n")
1858 (let ((literal-snippets (list))
1860 (dolist (snippet snippets)
1861 (let ((key (first snippet))
1862 (template-content (second snippet))
1863 (name (third snippet))
1864 (condition (fourth snippet))
1865 (group (fifth snippet))
1866 (expand-env (sixth snippet))
1867 (file nil) ;; (seventh snippet)) ;; omit on purpose
1868 (binding (eighth snippet))
1869 (uuid (ninth snippet)))
1880 (insert (pp-to-string `(yas-define-snippets ',mode ',literal-snippets)))
1882 (yas--load-directory-1
1883 (dir mode parents &rest ignore)
1884 (let ((output-file (concat (file-name-as-directory dir) ".yas-compiled-snippets.el")))
1885 (with-temp-file output-file
1886 (insert (format ";;; Compiled snippets and support files for `%s'\n" mode))
1887 (yas--load-directory-2 dir mode)
1888 (insert (format ";;; Do not edit! File generated at %s\n" (current-time-string)))))))
1889 (yas-load-directory top-level-dir nil)))
1891 (defun yas-recompile-all ()
1892 "Compile every dir in `yas-snippet-dirs'."
1894 (mapc #'yas-compile-directory (yas-snippet-dirs)))
1900 (defvar yas--scheduled-jit-loads (make-hash-table)
1901 "Alist of mode-symbols to forms to be evaled when `yas-minor-mode' kicks in.")
1903 (defun yas--schedule-jit (mode form)
1906 (gethash mode yas--scheduled-jit-loads))
1907 yas--scheduled-jit-loads))
1910 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1911 ;;; Some user level functions
1916 (message (concat "yasnippet (version "
1918 ") -- pluskid <pluskid@gmail.com>/joaotavora <joaotavora@gmail.com>")))
1920 (defun yas--define-parents (mode parents)
1921 "Add PARENTS to the list of MODE's parents"
1922 (puthash mode (remove-duplicates
1924 (gethash mode yas--parents)))
1927 (defun yas-define-snippets (mode snippets)
1928 "Define SNIPPETS for MODE.
1930 SNIPPETS is a list of snippet definitions, each taking the
1933 (KEY TEMPLATE NAME CONDITION GROUP EXPAND-ENV FILE KEYBINDING UUID)
1935 Within these, only KEY and TEMPLATE are actually mandatory.
1937 TEMPLATE might be a lisp form or a string, depending on whether
1938 this is a snippet or a snippet-command.
1940 CONDITION, EXPAND-ENV and KEYBINDING are lisp forms, they have
1941 been `yas--read-lisp'-ed and will eventually be
1942 `yas--eval-lisp'-ed.
1944 The remaining elements are strings.
1946 FILE is probably of very little use if you're programatically
1949 UUID is the snippets \"unique-id\". Loading a second snippet file
1950 with the same uuid replaced the previous snippet.
1952 You can use `yas--parse-template' to return such lists based on
1953 the current buffers contents."
1954 (let ((snippet-table (yas--table-get-create mode))
1956 (dolist (snippet snippets)
1957 (setq template (yas-define-snippets-1 snippet
1961 (defun yas-define-snippets-1 (snippet snippet-table)
1962 "Helper for `yas-define-snippets'."
1963 ;; X) Calculate some more defaults on the values returned by
1964 ;; `yas--parse-template'.
1966 (let* ((file (seventh snippet))
1968 (name (or (third snippet)
1970 (file-name-directory file))))
1971 (condition (fourth snippet))
1972 (group (fifth snippet))
1973 (keybinding (yas--read-keybinding (eighth snippet)))
1974 (uuid (or (ninth snippet)
1976 (template (or (gethash uuid (yas--table-uuidhash snippet-table))
1977 (yas--make-blank-template))))
1978 ;; X) populate the template object
1980 (yas--populate-template template
1981 :table snippet-table
1983 :content (second snippet)
1986 :condition condition
1987 :expand-env (sixth snippet)
1988 :file (seventh snippet)
1989 :keybinding keybinding
1991 ;; X) Update this template in the appropriate table. This step
1992 ;; also will take care of adding the key indicators in the
1993 ;; templates menu entry, if any
1995 (yas--update-template snippet-table template)
1996 ;; X) Return the template
2002 ;;; Apropos snippet menu:
2004 ;; The snippet menu keymaps are store by mode in hash table called
2005 ;; `yas--menu-table'. They are linked to the main menu in
2006 ;; `yas--menu-keymap-get-create' and are initially created empty,
2007 ;; reflecting the table hierarchy.
2009 ;; They can be populated in two mutually exclusive ways: (1) by
2010 ;; reading `yas--template-group', which in turn is populated by the "#
2011 ;; group:" directives of the snippets or the ".yas-make-groups" file
2012 ;; or (2) by using a separate `yas-define-menu' call, which declares a
2013 ;; menu structure based on snippets uuids.
2015 ;; Both situations are handled in `yas--update-template-menu', which
2016 ;; uses the predicate `yas--template-menu-managed-by-yas-define-menu'
2017 ;; that can tell between the two situations.
2021 ;; * if `yas-define-menu' is used it must run before
2022 ;; `yas-define-snippets' and the UUIDS must match, otherwise we get
2023 ;; duplicate entries. The `yas--template' objects are created in
2024 ;; `yas-define-menu', holding nothing but the menu entry,
2025 ;; represented by a pair of ((menu-item NAME :keys KEYS) TYPE) and
2026 ;; stored in `yas--template-menu-binding-pair'. The (menu-item ...)
2027 ;; part is then stored in the menu keymap itself which make the item
2028 ;; appear to the user. These limitations could probably be revised.
2030 ;; * The `yas--template-perm-group' slot is only used in
2031 ;; `yas-describe-tables'.
2033 (defun yas--template-menu-binding-pair-get-create (template &optional type)
2034 "Get TEMPLATE's menu binding or assign it a new one.
2036 TYPE may be `:stay', signalling this menu binding should be
2037 static in the menu."
2038 (or (yas--template-menu-binding-pair template)
2039 (let ((key (yas--template-key template))
2040 (keybinding (yas--template-keybinding template)))
2041 (setf (yas--template-menu-binding-pair template)
2042 (cons `(menu-item ,(or (yas--template-name template)
2043 (yas--template-uuid template))
2044 ,(yas--make-menu-binding template)
2047 (defun yas--template-menu-managed-by-yas-define-menu (template)
2048 "Non-nil if TEMPLATE's menu entry was included in a `yas-define-menu' call."
2049 (cdr (yas--template-menu-binding-pair template)))
2052 (defun yas--show-menu-p (mode)
2053 (cond ((eq yas-use-menu 'abbreviate)
2055 (mapcar #'(lambda (table)
2056 (yas--table-mode table))
2057 (yas--get-snippet-tables))))
2058 ((eq yas-use-menu 'full)
2060 ((eq yas-use-menu t)
2063 (defun yas--delete-from-keymap (keymap uuid)
2064 "Recursively delete items with UUID from KEYMAP and its submenus."
2066 ;; XXX: This used to skip any submenus named \"parent mode\"
2068 ;; First of all, recursively enter submenus, i.e. the tree is
2069 ;; searched depth first so that stale submenus can be found in the
2072 (mapc #'(lambda (item)
2073 (when (and (listp (cdr item))
2074 (keymapp (third (cdr item))))
2075 (yas--delete-from-keymap (third (cdr item)) uuid)))
2077 ;; Set the uuid entry to nil
2079 (define-key keymap (vector (make-symbol uuid)) nil)
2080 ;; Destructively modify keymap
2082 (setcdr keymap (delete-if #'(lambda (item)
2083 (or (null (cdr item))
2084 (and (keymapp (third (cdr item)))
2085 (null (cdr (third (cdr item)))))))
2088 (defun yas-define-menu (mode menu &optional omit-items)
2089 "Define a snippet menu for MODE according to MENU, ommitting OMIT-ITEMS.
2091 MENU is a list, its elements can be:
2093 - (yas-item UUID) : Creates an entry the snippet identified with
2094 UUID. The menu entry for a snippet thus identified is
2095 permanent, i.e. it will never move (be reordered) in the menu.
2097 - (yas-separator) : Creates a separator
2099 - (yas-submenu NAME SUBMENU) : Creates a submenu with NAME,
2100 SUBMENU has the same form as MENU. NAME is also added to the
2101 list of groups of the snippets defined thereafter.
2103 OMIT-ITEMS is a list of snippet uuid's that will always be
2104 ommited from MODE's menu, even if they're manually loaded.
2106 This function does nothing if `yas-use-menu' is nil.
2109 (let* ((table (yas--table-get-create mode))
2110 (hash (yas--table-uuidhash table)))
2111 (yas--define-menu-1 table
2112 (yas--menu-keymap-get-create mode)
2115 (dolist (uuid omit-items)
2116 (let ((template (or (gethash uuid hash)
2117 (yas--populate-template (puthash uuid
2118 (yas--make-blank-template)
2122 (setf (yas--template-menu-binding-pair template) (cons nil :none)))))))
2124 (defun yas--define-menu-1 (table menu-keymap menu uuidhash &optional group-list)
2125 (dolist (e (reverse menu))
2126 (cond ((eq (first e) 'yas-item)
2127 (let ((template (or (gethash (second e) uuidhash)
2128 (yas--populate-template (puthash (second e)
2129 (yas--make-blank-template)
2132 :perm-group group-list
2133 :uuid (second e)))))
2134 (define-key menu-keymap (vector (gensym))
2135 (car (yas--template-menu-binding-pair-get-create template :stay)))))
2136 ((eq (first e) 'yas-submenu)
2137 (let ((subkeymap (make-sparse-keymap)))
2138 (define-key menu-keymap (vector (gensym))
2139 `(menu-item ,(second e) ,subkeymap))
2140 (yas--define-menu-1 table
2144 (append group-list (list (second e))))))
2145 ((eq (first e) 'yas-separator)
2146 (define-key menu-keymap (vector (gensym))
2147 '(menu-item "----")))
2149 (yas--message 3 "Don't know anything about menu entry %s" (first e))))))
2151 (defun yas--define (mode key template &optional name condition group)
2152 "Define a snippet. Expanding KEY into TEMPLATE.
2154 NAME is a description to this template. Also update the menu if
2155 `yas-use-menu' is t. CONDITION is the condition attached to
2156 this snippet. If you attach a condition to a snippet, then it
2157 will only be expanded when the condition evaluated to non-nil."
2158 (yas-define-snippets mode
2159 (list (list key template name condition group))))
2161 (defun yas-hippie-try-expand (first-time?)
2162 "Integrate with hippie expand. Just put this function in
2163 `hippie-expand-try-functions-list'."
2164 (when yas-minor-mode
2165 (if (not first-time?)
2166 (let ((yas-fallback-behavior 'return-nil))
2172 ;;; Apropos condition-cache:
2177 (defvar yas--condition-cache-timestamp nil)
2178 (defmacro yas-define-condition-cache (func doc &rest body)
2179 "Define a function FUNC with doc DOC and body BODY, BODY is
2180 executed at most once every snippet expansion attempt, to check
2181 expansion conditions.
2183 It doesn't make any sense to call FUNC programatically."
2184 `(defun ,func () ,(if (and doc
2187 "\n\nFor use in snippets' conditions. Within each
2188 snippet-expansion routine like `yas-expand', computes actual
2189 value for the first time then always returns a cached value.")
2190 (setq body (cons doc body))
2192 (let ((timestamp-and-value (get ',func 'yas--condition-cache)))
2193 (if (equal (car timestamp-and-value) yas--condition-cache-timestamp)
2194 (cdr timestamp-and-value)
2195 (let ((new-value (progn
2198 (put ',func 'yas--condition-cache (cons yas--condition-cache-timestamp new-value))
2201 (defalias 'yas-expand 'yas-expand-from-trigger-key)
2202 (defun yas-expand-from-trigger-key (&optional field)
2203 "Expand a snippet before point.
2205 If no snippet expansion is possible, fall back to the behaviour
2206 defined in `yas-fallback-behavior'.
2208 Optional argument FIELD is for non-interactive use and is an
2209 object satisfying `yas--field-p' to restrict the expansion to."
2211 (setq yas--condition-cache-timestamp (current-time))
2212 (let (templates-and-pos)
2213 (unless (and yas-expand-only-for-last-commands
2214 (not (member last-command yas-expand-only-for-last-commands)))
2215 (setq templates-and-pos (if field
2217 (narrow-to-region (yas--field-start field)
2218 (yas--field-end field))
2220 (yas--current-key))))
2221 (if (and templates-and-pos
2222 (first templates-and-pos))
2223 (yas--expand-or-prompt-for-template (first templates-and-pos)
2224 (second templates-and-pos)
2225 (third templates-and-pos))
2226 (yas--fallback 'trigger-key))))
2228 (defun yas-expand-from-keymap ()
2229 "Directly expand some snippets, searching `yas--direct-keymaps'.
2231 If expansion fails, execute the previous binding for this key"
2233 (setq yas--condition-cache-timestamp (current-time))
2234 (let* ((yas--prefix current-prefix-arg)
2235 (vec (subseq (this-command-keys-vector) (if current-prefix-arg
2236 universal-argument-num-events
2238 (templates (mapcan #'(lambda (table)
2239 (yas--fetch table vec))
2240 (yas--get-snippet-tables))))
2242 (yas--expand-or-prompt-for-template templates)
2243 (let ((yas-fallback-behavior 'call-other-command))
2246 (defun yas--expand-or-prompt-for-template (templates &optional start end)
2247 "Expand one of TEMPLATES from START to END.
2249 Prompt the user if TEMPLATES has more than one element, else
2250 expand immediately. Common gateway for
2251 `yas-expand-from-trigger-key' and `yas-expand-from-keymap'."
2252 (let ((yas--current-template (or (and (rest templates) ;; more than one
2253 (yas--prompt-for-template (mapcar #'cdr templates)))
2255 (when yas--current-template
2256 (yas-expand-snippet (yas--template-content yas--current-template)
2259 (yas--template-expand-env yas--current-template)))))
2261 (defun yas--fallback (&optional from-trigger-key-p)
2262 "Fallback after expansion has failed.
2264 Common gateway for `yas-expand-from-trigger-key' and
2265 `yas-expand-from-keymap'."
2266 (cond ((eq yas-fallback-behavior 'return-nil)
2269 ((eq yas-fallback-behavior 'call-other-command)
2270 (let* ((yas-minor-mode nil)
2271 (yas--direct-keymaps nil)
2272 (keys-1 (this-command-keys-vector))
2273 (keys-2 (and yas-trigger-key
2275 (stringp yas-trigger-key)
2276 (read-kbd-macro yas-trigger-key)))
2277 (command-1 (and keys-1 (key-binding keys-1)))
2278 (command-2 (and keys-2 (key-binding keys-2)))
2279 ;; An (ugly) safety: prevents infinite recursion of
2280 ;; yas-expand* calls.
2281 (command (or (and (symbolp command-1)
2282 (not (string-match "yas-expand" (symbol-name command-1)))
2284 (and (symbolp command-2)
2286 (when (and (commandp command)
2287 (not (string-match "yas-expand" (symbol-name command))))
2288 (setq this-command command)
2289 (call-interactively command))))
2290 ((and (listp yas-fallback-behavior)
2291 (cdr yas-fallback-behavior)
2292 (eq 'apply (car yas-fallback-behavior)))
2293 (if (cddr yas-fallback-behavior)
2294 (apply (cadr yas-fallback-behavior)
2295 (cddr yas-fallback-behavior))
2296 (when (commandp (cadr yas-fallback-behavior))
2297 (setq this-command (cadr yas-fallback-behavior))
2298 (call-interactively (cadr yas-fallback-behavior)))))
2300 ;; also return nil if all the other fallbacks have failed
2305 ;;; Utils for snippet development:
2307 (defun yas--all-templates (tables)
2308 "Return all snippet tables applicable for the current buffer.
2310 Honours `yas-choose-tables-first', `yas-choose-keys-first' and
2311 `yas-buffer-local-condition'"
2312 (when yas-choose-tables-first
2313 (setq tables (list (yas--prompt-for-table tables))))
2315 (if yas-choose-keys-first
2316 (let ((key (yas--prompt-for-keys
2317 (mapcan #'yas--table-all-keys tables))))
2319 (mapcan #'(lambda (table)
2320 (yas--fetch table key))
2322 (remove-duplicates (mapcan #'yas--table-templates tables)
2325 (defun yas-insert-snippet (&optional no-condition)
2326 "Choose a snippet to expand, pop-up a list of choices according
2327 to `yas--prompt-function'.
2329 With prefix argument NO-CONDITION, bypass filtering of snippets
2332 (setq yas--condition-cache-timestamp (current-time))
2333 (let* ((yas-buffer-local-condition (or (and no-condition
2335 yas-buffer-local-condition))
2336 (templates (yas--all-templates (yas--get-snippet-tables)))
2337 (yas--current-template (and templates
2338 (or (and (rest templates) ;; more than one template for same key
2339 (yas--prompt-for-template templates))
2341 (where (if (region-active-p)
2342 (cons (region-beginning) (region-end))
2343 (cons (point) (point)))))
2344 (if yas--current-template
2345 (yas-expand-snippet (yas--template-content yas--current-template)
2348 (yas--template-expand-env yas--current-template))
2349 (yas--message 3 "No snippets can be inserted here!"))))
2351 (defun yas-visit-snippet-file ()
2352 "Choose a snippet to edit, selection like `yas-insert-snippet'.
2354 Only success if selected snippet was loaded from a file. Put the
2355 visited file in `snippet-mode'."
2357 (let* ((yas-buffer-local-condition 'always)
2358 (templates (yas--all-templates (yas--get-snippet-tables)))
2359 (yas-prompt-functions '(yas-ido-prompt yas-completing-prompt))
2360 (template (and templates
2361 (or (yas--prompt-for-template templates
2362 "Choose a snippet template to edit: ")
2366 (yas--visit-snippet-file-1 template)
2367 (message "No snippets tables active!"))))
2369 (defun yas--visit-snippet-file-1 (template)
2370 (let ((file (yas--template-file template)))
2371 (cond ((and file (file-readable-p file))
2372 (find-file-other-window file)
2374 (set (make-local-variable 'yas--editing-template) template))
2376 (message "Original file %s no longer exists!" file))
2378 (switch-to-buffer (format "*%s*"(yas--template-name template)))
2379 (let ((type 'snippet))
2380 (when (listp (yas--template-content template))
2381 (insert (format "# type: command\n"))
2382 (setq type 'command))
2383 (insert (format "# key: %s\n" (yas--template-key template)))
2384 (insert (format "# name: %s\n" (yas--template-name template)))
2385 (when (yas--template-keybinding template)
2386 (insert (format "# binding: %s\n" (yas--template-keybinding template))))
2387 (when (yas--template-expand-env template)
2388 (insert (format "# expand-env: %s\n" (yas--template-expand-env template))))
2389 (when (yas--template-condition template)
2390 (insert (format "# condition: %s\n" (yas--template-condition template))))
2392 (insert (if (eq type 'command)
2393 (pp-to-string (yas--template-content template))
2394 (yas--template-content template))))
2396 (set (make-local-variable 'yas--editing-template) template)))))
2398 (defun yas--guess-snippet-directories-1 (table)
2399 "Guesses possible snippet subdirectories for TABLE."
2400 (cons (yas--table-name table)
2401 (mapcan #'(lambda (parent)
2402 (yas--guess-snippet-directories-1
2404 (yas--table-parents table))))
2406 (defun yas--guess-snippet-directories (&optional table)
2407 "Try to guess suitable directories based on the current active
2408 tables (or optional TABLE).
2410 Returns a list of elemts (TABLE . DIRS) where TABLE is a
2411 `yas--table' object and DIRS is a list of all possible directories
2412 where snippets of table might exist."
2413 (let ((main-dir (replace-regexp-in-string
2415 (or (first (or (yas-snippet-dirs)
2416 (setq yas-snippet-dirs '("~/.emacs.d/snippets")))))))
2417 (tables (or (and table
2419 (yas--get-snippet-tables))))
2420 ;; HACK! the snippet table created here is actually registered!
2422 (unless (or table (gethash major-mode yas--tables))
2423 (push (yas--table-get-create major-mode)
2426 (mapcar #'(lambda (table)
2428 (mapcar #'(lambda (subdir)
2429 (concat main-dir "/" subdir))
2430 (yas--guess-snippet-directories-1 table))))
2433 (defun yas--make-directory-maybe (table-and-dirs &optional main-table-string)
2434 "Returns a dir inside TABLE-AND-DIRS, prompts for creation if none exists."
2435 (or (some #'(lambda (dir) (when (file-directory-p dir) dir)) (cdr table-and-dirs))
2436 (let ((candidate (first (cdr table-and-dirs))))
2437 (unless (file-writable-p (file-name-directory candidate))
2438 (error (yas--format "%s is not writable." candidate)))
2439 (if (y-or-n-p (format "Guessed directory (%s) for%s%s table \"%s\" does not exist! Create? "
2441 (if (gethash (yas--table-mode (car table-and-dirs))
2445 (or main-table-string
2447 (yas--table-name (car table-and-dirs))))
2449 (make-directory candidate 'also-make-parents)
2450 ;; create the .yas-parents file here...
2453 (defun yas-new-snippet (&optional no-template)
2454 "Pops a new buffer for writing a snippet.
2456 Expands a snippet-writing snippet, unless the optional prefix arg
2457 NO-TEMPLATE is non-nil."
2459 (let ((guessed-directories (yas--guess-snippet-directories)))
2461 (switch-to-buffer "*new snippet*")
2463 (kill-all-local-variables)
2466 (set (make-local-variable 'yas--guessed-modes) (mapcar #'(lambda (d)
2467 (yas--table-mode (car d)))
2468 guessed-directories))
2469 (unless no-template (yas-expand-snippet "\
2470 # -*- mode: snippet -*-
2472 # key: ${2:${1:$(replace-regexp-in-string \"\\\\\\\\(\\\\\\\\w+\\\\\\\\).*\" \"\\\\\\\\1\" yas-text)}}${3:
2473 # binding: ${4:direct-keybinding}}${5:
2474 # expand-env: ((${6:some-var} ${7:some-value}))}${8:
2479 (defun yas--compute-major-mode-and-parents (file)
2480 "Given FILE, find the nearest snippet directory for a given
2481 mode, then return a list (MODE-SYM PARENTS), the mode's symbol and a list
2482 representing one or more of the mode's parents.
2484 Note that MODE-SYM need not be the symbol of a real major mode,
2485 neither do the elements of PARENTS."
2486 (let* ((file-dir (and file
2487 (directory-file-name (or (some #'(lambda (special)
2488 (locate-dominating-file file special))
2492 (directory-file-name (file-name-directory file))))))
2493 (parents-file-name (concat file-dir "/.yas-parents"))
2494 (major-mode-name (and file-dir
2495 (file-name-nondirectory file-dir)))
2496 (major-mode-sym (or (and major-mode-name
2497 (intern major-mode-name))))
2498 (parents (when (file-readable-p parents-file-name)
2502 (insert-file-contents parents-file-name)
2503 (buffer-substring-no-properties (point-min)
2505 (when major-mode-sym
2506 (cons major-mode-sym parents))))
2508 (defvar yas--editing-template nil
2509 "Supporting variable for `yas-load-snippet-buffer' and `yas--visit-snippet'")
2511 (defvar yas--current-template nil
2512 "Holds the current template being expanded into a snippet.")
2514 (defvar yas--guessed-modes nil
2515 "List of guessed modes supporting `yas-load-snippet-buffer'.")
2517 (defun yas-load-snippet-buffer (&optional kill)
2518 "Parse and load current buffer's snippet definition.
2520 With optional prefix argument KILL quit the window and buffer."
2523 ;; We have `yas--editing-template', this buffer's
2524 ;; content comes from a template which is already loaded and
2525 ;; neatly positioned,...
2527 (yas--editing-template
2528 (yas-define-snippets-1 (yas--parse-template (yas--template-file yas--editing-template))
2529 (yas--template-table yas--editing-template)))
2530 ;; Try to use `yas--guessed-modes'. If we don't have that use the
2531 ;; value from `yas--compute-major-mode-and-parents'
2534 (unless yas--guessed-modes
2535 (set (make-local-variable 'yas--guessed-modes) (or (yas--compute-major-mode-and-parents buffer-file-name))))
2536 (let* ((prompt (if (and (featurep 'ido)
2538 'ido-completing-read 'completing-read))
2539 (table (yas--table-get-create
2541 (funcall prompt (format "Choose or enter a table (yas guesses %s): "
2542 (if yas--guessed-modes
2543 (first yas--guessed-modes)
2545 (mapcar #'symbol-name yas--guessed-modes)
2550 (if (first yas--guessed-modes)
2551 (symbol-name (first yas--guessed-modes))))))))
2552 (set (make-local-variable 'yas--editing-template)
2553 (yas-define-snippets-1 (yas--parse-template buffer-file-name)
2555 ;; Now, offer to save this iff:
2557 ;; 1) `yas-snippet-dirs' is a list and its first element does not
2558 ;; match this template's file (i.e. this is a library snippet, not
2559 ;; a user snippet) OR
2561 ;; 2) yas--editing-template comes from a file that we cannot write to...
2563 (when (or (not (yas--template-file yas--editing-template))
2564 (not (file-writable-p (yas--template-file yas--editing-template)))
2565 (and (listp yas-snippet-dirs)
2566 (second yas-snippet-dirs)
2567 (not (string-match (expand-file-name (first yas-snippet-dirs))
2568 (yas--template-file yas--editing-template)))))
2570 (when (y-or-n-p (yas--format "Looks like a library or new snippet. Save to new file? "))
2571 (let* ((option (first (yas--guess-snippet-directories (yas--template-table yas--editing-template))))
2573 (yas--make-directory-maybe option))))
2575 (let ((default-file-name (or (and (yas--template-file yas--editing-template)
2576 (file-name-nondirectory (yas--template-file yas--editing-template)))
2577 (yas--template-name yas--editing-template))))
2578 (write-file (concat chosen "/"
2579 (read-from-minibuffer (format "File name to create in %s? " chosen)
2580 default-file-name)))
2581 (setf (yas--template-file yas--editing-template) buffer-file-name))))))
2584 (yas--message 3 "Snippet \"%s\" loaded for %s."
2585 (yas--template-name yas--editing-template)
2586 (yas--table-name (yas--template-table yas--editing-template))))
2589 (defun yas-tryout-snippet (&optional debug)
2590 "Test current buffers's snippet template in other buffer."
2592 (let* ((major-mode-and-parent (yas--compute-major-mode-and-parents buffer-file-name))
2593 (parsed (yas--parse-template))
2594 (test-mode (or (and (car major-mode-and-parent)
2595 (fboundp (car major-mode-and-parent))
2596 (car major-mode-and-parent))
2597 (first yas--guessed-modes)
2598 (intern (read-from-minibuffer (yas--format "Please input a mode: ")))))
2599 (yas--current-template
2602 (yas--populate-template (yas--make-blank-template)
2603 :table nil ;; no tables for ephemeral snippets
2605 :content (second parsed)
2606 :name (third parsed)
2607 :expand-env (sixth parsed)))))
2608 (cond (yas--current-template
2609 (let ((buffer-name (format "*testing snippet: %s*" (yas--template-name yas--current-template))))
2610 (kill-buffer (get-buffer-create buffer-name))
2611 (switch-to-buffer (get-buffer-create buffer-name))
2612 (setq buffer-undo-list nil)
2613 (condition-case nil (funcall test-mode) (error nil))
2614 (setq buffer-read-only nil)
2615 (yas-expand-snippet (yas--template-content yas--current-template)
2618 (yas--template-expand-env yas--current-template))
2620 (require 'yasnippet-debug nil t))
2621 (add-hook 'post-command-hook 'yas-debug-snippet-vars nil t))))
2623 (yas--message 3 "Cannot test snippet for unknown major mode")))))
2625 (defun yas--template-fine-group (template)
2626 (car (last (or (yas--template-group template)
2627 (yas--template-perm-group template)))))
2629 (defun yas-describe-tables (&optional choose)
2630 "Display snippets for each table."
2632 (let* ((by-name-hash (and choose
2633 (y-or-n-p "Show by namehash? ")))
2634 (buffer (get-buffer-create "*YASnippet tables*"))
2635 (active-tables (yas--get-snippet-tables))
2636 (remain-tables (let ((all))
2637 (maphash #'(lambda (k v)
2638 (unless (find v active-tables)
2642 (table-lists (list active-tables remain-tables))
2643 (original-buffer (current-buffer))
2645 (yas--condition-cache-timestamp (current-time)))
2646 (with-current-buffer buffer
2647 (setq buffer-read-only nil)
2649 (cond ((not by-name-hash)
2650 (insert "YASnippet tables: \n")
2651 (while (and table-lists
2653 (dolist (table (car table-lists))
2654 (yas--describe-pretty-table table original-buffer))
2655 (setq table-lists (cdr table-lists))
2657 (yas--create-snippet-xrefs)
2658 (display-buffer buffer)
2659 (setq continue (and choose (y-or-n-p "Show also non-active tables? ")))))
2660 (yas--create-snippet-xrefs)
2664 (insert "\n\nYASnippet tables by NAMEHASH: \n")
2665 (dolist (table (append active-tables remain-tables))
2666 (insert (format "\nSnippet table `%s':\n\n" (yas--table-name table)))
2668 (maphash #'(lambda (k v)
2670 (yas--table-hash table))
2672 (insert (format " key %s maps snippets: %s\n" key
2674 (maphash #'(lambda (k v)
2676 (gethash key (yas--table-hash table)))
2679 (setq buffer-read-only t))
2680 (display-buffer buffer)))
2682 (defun yas--describe-pretty-table (table &optional original-buffer)
2683 (insert (format "\nSnippet table `%s'"
2684 (yas--table-name table)))
2685 (if (yas--table-parents table)
2686 (insert (format " parents: %s\n"
2687 (mapcar #'yas--table-name
2688 (yas--table-parents table))))
2690 (insert (make-string 100 ?-) "\n")
2691 (insert "group state name key binding\n")
2692 (let ((groups-hash (make-hash-table :test #'equal)))
2693 (maphash #'(lambda (k v)
2694 (let ((group (or (yas--template-fine-group v)
2696 (when (yas--template-name v)
2698 (cons v (gethash group groups-hash))
2700 (yas--table-uuidhash table))
2702 #'(lambda (group templates)
2703 (setq group (truncate-string-to-width group 25 0 ? "..."))
2704 (insert (make-string 100 ?-) "\n")
2705 (dolist (p templates)
2706 (let ((name (truncate-string-to-width (propertize (format "\\\\snippet `%s'" (yas--template-name p))
2710 (setq group (make-string (length group) ? ))))
2711 (condition-string (let ((condition (yas--template-condition p)))
2714 (with-current-buffer original-buffer
2715 (if (yas--eval-condition condition)
2720 (insert condition-string " ")
2722 (if (string-match "\\.\\.\\.$" name)
2726 (insert (truncate-string-to-width (or (yas--template-key p) "")
2728 (insert (truncate-string-to-width (key-description (yas--template-keybinding p))
2735 ;;; User convenience functions, for using in snippet definitions
2737 (defvar yas-modified-p nil
2738 "Non-nil if field has been modified by user or transformation.")
2740 (defvar yas-moving-away-p nil
2741 "Non-nil if user is about to exit field.")
2743 (defvar yas-text nil
2744 "Contains current field text.")
2746 (defun yas-substr (str pattern &optional subexp)
2747 "Search PATTERN in STR and return SUBEXPth match.
2749 If found, the content of subexp group SUBEXP (default 0) is
2750 returned, or else the original STR will be returned."
2751 (let ((grp (or subexp 0)))
2753 (if (string-match pattern str)
2754 (match-string-no-properties grp str)
2757 (defun yas-choose-value (possibilities)
2758 "Prompt for a string in the list POSSIBILITIES and return it."
2759 (unless (or yas-moving-away-p
2761 (some #'(lambda (fn)
2762 (funcall fn "Choose: " possibilities))
2763 yas-prompt-functions)))
2765 (defun yas-key-to-value (alist)
2766 "Prompt for a string in the list POSSIBILITIES and return it."
2767 (unless (or yas-moving-away-p
2769 (let ((key (read-key-sequence "")))
2771 (or (cdr (find key alist :key #'car :test #'string=))
2774 (defun yas-throw (text)
2775 "Throw a yas--exception with TEXT as the reason."
2776 (throw 'yas--exception (cons 'yas--exception text)))
2778 (defun yas-verify-value (possibilities)
2779 "Verify that the current field value is in POSSIBILITIES
2781 Otherwise throw exception."
2782 (when (and yas-moving-away-p (notany #'(lambda (pos) (string= pos yas-text)) possibilities))
2783 (yas-throw (yas--format "Field only allows %s" possibilities))))
2785 (defun yas-field-value (number)
2786 "Get the string for field with NUMBER.
2788 Use this in primary and mirror transformations to tget."
2789 (let* ((snippet (car (yas--snippets-at-point)))
2791 (yas--snippet-find-field snippet number))))
2793 (yas--field-text-for-display field))))
2796 "Return `yas-text' if that exists and is non-empty, else nil."
2798 (not (string= "" yas-text)))
2801 ;; (defun yas-selected-text ()
2802 ;; "Return `yas-selected-text' if that exists and is non-empty, else nil."
2803 ;; (if (and yas-selected-text
2804 ;; (not (string= "" yas-selected-text)))
2805 ;; yas-selected-text))
2807 (defun yas--get-field-once (number &optional transform-fn)
2808 (unless yas-modified-p
2810 (funcall transform-fn (yas-field-value number))
2811 (yas-field-value number))))
2813 (defun yas-default-from-field (number)
2814 (unless yas-modified-p
2815 (yas-field-value number)))
2817 (defun yas-inside-string ()
2818 (equal 'font-lock-string-face (get-char-property (1- (point)) 'face)))
2820 (defun yas-unimplemented (&optional missing-feature)
2821 (if yas--current-template
2822 (if (y-or-n-p (format "This snippet is unimplemented (missing %s) Visit the snippet definition? "
2825 (yas--visit-snippet-file-1 yas--current-template))
2826 (message "No implementation. Missing %s" (or missing-feature "something"))))
2829 ;;; Snippet expansion and field management
2831 (defvar yas--active-field-overlay nil
2832 "Overlays the currently active field.")
2834 (defvar yas--field-protection-overlays nil
2835 "Two overlays protect the current active field ")
2837 (defconst yas--prefix nil
2838 "A prefix argument for expansion direct from keybindings")
2840 (defvar yas-selected-text nil
2841 "The selected region deleted on the last snippet expansion.")
2843 (defvar yas--start-column nil
2844 "The column where the snippet expansion started.")
2846 (make-variable-buffer-local 'yas--active-field-overlay)
2847 (make-variable-buffer-local 'yas--field-protection-overlays)
2848 (put 'yas--active-field-overlay 'permanent-local t)
2849 (put 'yas--field-protection-overlays 'permanent-local t)
2851 (defstruct (yas--snippet (:constructor yas--make-snippet ()))
2857 (id (yas--snippet-next-id) :read-only t)
2858 (control-overlay nil)
2860 ;; stacked expansion: the `previous-active-field' slot saves the
2861 ;; active field where the child expansion took place
2862 previous-active-field
2865 (defstruct (yas--field (:constructor yas--make-field (number start end parent-field)))
2875 (defstruct (yas--mirror (:constructor yas--make-mirror (start end transform)))
2882 (defstruct (yas--exit (:constructor yas--make-exit (marker)))
2886 (defun yas--apply-transform (field-or-mirror field &optional empty-on-nil-p)
2887 "Calculate transformed string for FIELD-OR-MIRROR from FIELD.
2889 If there is no transform for ht field, return nil.
2891 If there is a transform but it returns nil, return the empty
2892 string iff EMPTY-ON-NIL-P is true."
2893 (let* ((yas-text (yas--field-text-for-display field))
2895 (yas-modified-p (yas--field-modified-p field))
2896 (yas-moving-away-p nil)
2897 (transform (if (yas--mirror-p field-or-mirror)
2898 (yas--mirror-transform field-or-mirror)
2899 (yas--field-transform field-or-mirror)))
2900 (start-point (if (yas--mirror-p field-or-mirror)
2901 (yas--mirror-start field-or-mirror)
2902 (yas--field-start field-or-mirror)))
2903 (transformed (and transform
2905 (goto-char start-point)
2906 (let ((ret (yas--eval-lisp transform)))
2907 (or ret (and empty-on-nil-p "")))))))
2910 (defsubst yas--replace-all (from to &optional text)
2911 "Replace all occurance from FROM to TO.
2913 With optional string TEXT do it in that string."
2915 (replace-regexp-in-string (regexp-quote from) to text t t)
2916 (goto-char (point-min))
2917 (while (search-forward from nil t)
2918 (replace-match to t t text))))
2920 (defun yas--snippet-find-field (snippet number)
2921 (find-if #'(lambda (field)
2922 (eq number (yas--field-number field)))
2923 (yas--snippet-fields snippet)))
2925 (defun yas--snippet-sort-fields (snippet)
2926 "Sort the fields of SNIPPET in navigation order."
2927 (setf (yas--snippet-fields snippet)
2928 (sort (yas--snippet-fields snippet)
2929 #'yas--snippet-field-compare)))
2931 (defun yas--snippet-field-compare (field1 field2)
2932 "Compare two fields. The field with a number is sorted first.
2933 If they both have a number, compare through the number. If neither
2934 have, compare through the field's start point"
2935 (let ((n1 (yas--field-number field1))
2936 (n2 (yas--field-number field2)))
2939 (or (zerop n2) (and (not (zerop n1))
2944 (< (yas--field-start field1)
2945 (yas--field-start field2))))))
2947 (defun yas--field-probably-deleted-p (snippet field)
2948 "Guess if SNIPPET's FIELD should be skipped."
2950 ;; field must be zero lentgh
2952 (zerop (- (yas--field-start field) (yas--field-end field)))
2955 ;; 1) is a nested field and it's been modified
2957 (and (yas--field-parent-field field)
2958 (yas--field-modified-p field))
2959 ;; 2) ends just before the snippet end
2961 (and (eq field (car (last (yas--snippet-fields snippet))))
2962 (= (yas--field-start field) (overlay-end (yas--snippet-control-overlay snippet)))))
2963 ;; the field numbered 0, just before the exit marker, should
2966 (not (zerop (yas--field-number field)))))
2968 (defun yas--snippets-at-point (&optional all-snippets)
2969 "Return a sorted list of snippets at point, most recently
2972 (remove nil (remove-duplicates (mapcar #'(lambda (ov)
2973 (overlay-get ov 'yas--snippet))
2975 (overlays-in (point-min) (point-max))
2976 (nconc (overlays-at (point)) (overlays-at (1- (point))))))))
2978 (<= (yas--snippet-id s2) (yas--snippet-id s1)))))
2980 (defun yas-next-field-or-maybe-expand ()
2981 "Try to expand a snippet at a key before point, otherwise
2982 delegate to `yas-next-field'."
2984 (if yas-triggers-in-field
2985 (let ((yas-fallback-behavior 'return-nil)
2986 (active-field (overlay-get yas--active-field-overlay 'yas--field)))
2988 (unless (yas-expand-from-trigger-key active-field)
2992 (defun yas-next-field (&optional arg)
2993 "Navigate to next field. If there's none, exit the snippet."
2997 (snippet (first (yas--snippets-at-point)))
2998 (active-field (overlay-get yas--active-field-overlay 'yas--field))
2999 (live-fields (remove-if #'(lambda (field)
3000 (and (not (eq field active-field))
3001 (yas--field-probably-deleted-p snippet field)))
3002 (yas--snippet-fields snippet)))
3003 (active-field-pos (position active-field live-fields))
3004 (target-pos (and active-field-pos (+ arg active-field-pos)))
3005 (target-field (and target-pos (nth target-pos live-fields))))
3006 ;; First check if we're moving out of a field with a transform
3008 (when (and active-field
3009 (yas--field-transform active-field))
3010 (let* ((yas-moving-away-p t)
3011 (yas-text (yas--field-text-for-display active-field))
3013 (yas-modified-p (yas--field-modified-p active-field)))
3014 ;; primary field transform: exit call to field-transform
3015 (yas--eval-lisp (yas--field-transform active-field))))
3016 ;; Now actually move...
3017 (cond ((and target-pos (>= target-pos (length live-fields)))
3018 (yas-exit-snippet snippet))
3020 (yas--move-to-field snippet target-field))
3024 (defun yas--place-overlays (snippet field)
3025 "Correctly place overlays for SNIPPET's FIELD"
3026 (yas--make-move-field-protection-overlays snippet field)
3027 (yas--make-move-active-field-overlay snippet field))
3029 (defun yas--move-to-field (snippet field)
3030 "Update SNIPPET to move to field FIELD.
3032 Also create some protection overlays"
3033 (goto-char (yas--field-start field))
3034 (yas--place-overlays snippet field)
3035 (overlay-put yas--active-field-overlay 'yas--field field)
3036 (let ((number (yas--field-number field)))
3037 ;; check for the special ${0: ...} field
3038 (if (and number (zerop number))
3040 (set-mark (yas--field-end field))
3041 (setf (yas--snippet-force-exit snippet)
3042 (or (yas--field-transform field)
3044 ;; make this field active
3045 (setf (yas--snippet-active-field snippet) field)
3046 ;; primary field transform: first call to snippet transform
3047 (unless (yas--field-modified-p field)
3048 (if (yas--field-update-display field snippet)
3049 (yas--update-mirrors snippet)
3050 (setf (yas--field-modified-p field) nil))))))
3052 (defun yas-prev-field ()
3053 "Navigate to prev field. If there's none, exit the snippet."
3055 (yas-next-field -1))
3057 (defun yas-abort-snippet (&optional snippet)
3059 (let ((snippet (or snippet
3060 (car (yas--snippets-at-point)))))
3062 (setf (yas--snippet-force-exit snippet) t))))
3064 (defun yas-exit-snippet (snippet)
3065 "Goto exit-marker of SNIPPET."
3066 (interactive (list (first (yas--snippets-at-point))))
3068 (setf (yas--snippet-force-exit snippet) t)
3069 (goto-char (if (yas--snippet-exit snippet)
3070 (yas--exit-marker (yas--snippet-exit snippet))
3071 (overlay-end (yas--snippet-control-overlay snippet))))))
3073 (defun yas-exit-all-snippets ()
3074 "Exit all snippets."
3076 (mapc #'(lambda (snippet)
3077 (yas-exit-snippet snippet)
3078 (yas--check-commit-snippet))
3079 (yas--snippets-at-point 'all-snippets)))
3082 ;;; Some low level snippet-routines:
3084 (defmacro yas--inhibit-overlay-hooks (&rest body)
3085 "Run BODY with `yas--inhibit-overlay-hooks' set to t."
3086 (declare (indent 0))
3087 `(let ((yas--inhibit-overlay-hooks t))
3090 (defvar yas-snippet-beg nil "Beginning position of the last snippet commited.")
3091 (defvar yas-snippet-end nil "End position of the last snippet commited.")
3093 (defun yas--commit-snippet (snippet)
3094 "Commit SNIPPET, but leave point as it is. This renders the
3095 snippet as ordinary text."
3097 (let ((control-overlay (yas--snippet-control-overlay snippet)))
3099 ;; Save the end of the moribund snippet in case we need to revive it
3100 ;; its original expansion.
3102 (when (and control-overlay
3103 (overlay-buffer control-overlay))
3104 (setq yas-snippet-beg (overlay-start control-overlay))
3105 (setq yas-snippet-end (overlay-end control-overlay))
3106 (delete-overlay control-overlay))
3108 (yas--inhibit-overlay-hooks
3109 (when yas--active-field-overlay
3110 (delete-overlay yas--active-field-overlay))
3111 (when yas--field-protection-overlays
3112 (mapc #'delete-overlay yas--field-protection-overlays)))
3114 ;; stacked expansion: if the original expansion took place from a
3115 ;; field, make sure we advance it here at least to
3116 ;; `yas-snippet-end'...
3118 (let ((previous-field (yas--snippet-previous-active-field snippet)))
3119 (when (and yas-snippet-end previous-field)
3120 (yas--advance-end-maybe previous-field yas-snippet-end)))
3122 ;; Convert all markers to points,
3124 (yas--markers-to-points snippet)
3126 ;; Take care of snippet revival
3128 (if yas-snippet-revival
3129 (push `(apply yas--snippet-revive ,yas-snippet-beg ,yas-snippet-end ,snippet)
3131 ;; Dismember the snippet... this is useful if we get called
3132 ;; again from `yas--take-care-of-redo'....
3133 (setf (yas--snippet-fields snippet) nil)))
3135 (yas--message 3 "Snippet %s exited." (yas--snippet-id snippet)))
3137 (defun yas--safely-run-hooks (hook-var)
3138 (condition-case error
3139 (run-hooks hook-var)
3141 (yas--message 3 "%s error: %s" hook-var (error-message-string error)))))
3144 (defun yas--check-commit-snippet ()
3145 "Checks if point exited the currently active field of the
3146 snippet, if so cleans up the whole snippet up."
3147 (let* ((snippets (yas--snippets-at-point 'all-snippets))
3148 (snippets-left snippets)
3149 (snippet-exit-transform))
3150 (dolist (snippet snippets)
3151 (let ((active-field (yas--snippet-active-field snippet)))
3152 (setq snippet-exit-transform (yas--snippet-force-exit snippet))
3153 (cond ((or snippet-exit-transform
3154 (not (and active-field (yas--field-contains-point-p active-field))))
3155 (setq snippets-left (delete snippet snippets-left))
3156 (setf (yas--snippet-force-exit snippet) nil)
3157 (yas--commit-snippet snippet))
3159 (or (not yas--active-field-overlay)
3160 (not (overlay-buffer yas--active-field-overlay))))
3162 ;; stacked expansion: this case is mainly for recent
3163 ;; snippet exits that place us back int the field of
3167 (yas--move-to-field snippet active-field)
3168 (yas--update-mirrors snippet)))
3171 (unless (or (null snippets) snippets-left)
3172 (if snippet-exit-transform
3173 (yas--eval-lisp-no-saves snippet-exit-transform))
3174 (yas--safely-run-hooks 'yas-after-exit-snippet-hook))))
3176 ;; Apropos markers-to-points:
3178 ;; This was found useful for performance reasons, so that an
3179 ;; excessive number of live markers aren't kept around in the
3180 ;; `buffer-undo-list'. However, in `markers-to-points', the
3181 ;; set-to-nil markers can't simply be discarded and replaced with
3182 ;; fresh ones in `points-to-markers'. The original marker that was
3183 ;; just set to nil has to be reused.
3185 ;; This shouldn't bring horrible problems with undo/redo, but it
3188 (defun yas--markers-to-points (snippet)
3189 "Convert all markers in SNIPPET to a cons (POINT . MARKER)
3190 where POINT is the original position of the marker and MARKER is
3191 the original marker object with the position set to nil."
3192 (dolist (field (yas--snippet-fields snippet))
3193 (let ((start (marker-position (yas--field-start field)))
3194 (end (marker-position (yas--field-end field))))
3195 (set-marker (yas--field-start field) nil)
3196 (set-marker (yas--field-end field) nil)
3197 (setf (yas--field-start field) (cons start (yas--field-start field)))
3198 (setf (yas--field-end field) (cons end (yas--field-end field))))
3199 (dolist (mirror (yas--field-mirrors field))
3200 (let ((start (marker-position (yas--mirror-start mirror)))
3201 (end (marker-position (yas--mirror-end mirror))))
3202 (set-marker (yas--mirror-start mirror) nil)
3203 (set-marker (yas--mirror-end mirror) nil)
3204 (setf (yas--mirror-start mirror) (cons start (yas--mirror-start mirror)))
3205 (setf (yas--mirror-end mirror) (cons end (yas--mirror-end mirror))))))
3206 (let ((snippet-exit (yas--snippet-exit snippet)))
3208 (let ((exit (marker-position (yas--exit-marker snippet-exit))))
3209 (set-marker (yas--exit-marker snippet-exit) nil)
3210 (setf (yas--exit-marker snippet-exit) (cons exit (yas--exit-marker snippet-exit)))))))
3212 (defun yas--points-to-markers (snippet)
3213 "Convert all cons (POINT . MARKER) in SNIPPET to markers. This
3214 is done by setting MARKER to POINT with `set-marker'."
3215 (dolist (field (yas--snippet-fields snippet))
3216 (setf (yas--field-start field) (set-marker (cdr (yas--field-start field))
3217 (car (yas--field-start field))))
3218 (setf (yas--field-end field) (set-marker (cdr (yas--field-end field))
3219 (car (yas--field-end field))))
3220 (dolist (mirror (yas--field-mirrors field))
3221 (setf (yas--mirror-start mirror) (set-marker (cdr (yas--mirror-start mirror))
3222 (car (yas--mirror-start mirror))))
3223 (setf (yas--mirror-end mirror) (set-marker (cdr (yas--mirror-end mirror))
3224 (car (yas--mirror-end mirror))))))
3225 (let ((snippet-exit (yas--snippet-exit snippet)))
3227 (setf (yas--exit-marker snippet-exit) (set-marker (cdr (yas--exit-marker snippet-exit))
3228 (car (yas--exit-marker snippet-exit)))))))
3230 (defun yas--field-contains-point-p (field &optional point)
3231 (let ((point (or point
3233 (and (>= point (yas--field-start field))
3234 (<= point (yas--field-end field)))))
3236 (defun yas--field-text-for-display (field)
3237 "Return the propertized display text for field FIELD. "
3238 (buffer-substring (yas--field-start field) (yas--field-end field)))
3240 (defun yas--undo-in-progress ()
3241 "True if some kind of undo is in progress"
3242 (or undo-in-progress
3243 (eq this-command 'undo)
3244 (eq this-command 'redo)))
3246 (defun yas--make-control-overlay (snippet start end)
3247 "Creates the control overlay that surrounds the snippet and
3249 (let ((overlay (make-overlay start
3254 (overlay-put overlay 'keymap yas-keymap)
3255 (overlay-put overlay 'priority 100)
3256 (overlay-put overlay 'yas--snippet snippet)
3259 (defun yas-skip-and-clear-or-delete-char (&optional field)
3260 "Clears unmodified field if at field start, skips to next tab.
3262 Otherwise deletes a character normally by calling `delete-char'."
3264 (let ((field (or field
3265 (and yas--active-field-overlay
3266 (overlay-buffer yas--active-field-overlay)
3267 (overlay-get yas--active-field-overlay 'yas--field)))))
3269 (not (yas--field-modified-p field))
3270 (eq (point) (marker-position (yas--field-start field))))
3271 (yas--skip-and-clear field)
3274 (call-interactively 'delete-char)))))
3276 (defun yas--skip-and-clear (field)
3277 "Deletes the region of FIELD and sets it modified state to t"
3278 ;; Just before skipping-and-clearing the field, mark its children
3279 ;; fields as modified, too. If the childen have mirrors-in-fields
3280 ;; this prevents them from updating erroneously (we're skipping and
3283 (yas--mark-this-and-children-modified field)
3284 (delete-region (yas--field-start field) (yas--field-end field)))
3286 (defun yas--mark-this-and-children-modified (field)
3287 (setf (yas--field-modified-p field) t)
3288 (let ((fom (yas--field-next field)))
3290 (yas--fom-parent-field fom))
3291 (when (and (eq (yas--fom-parent-field fom) field)
3293 (yas--mark-this-and-children-modified fom))
3294 (setq fom (yas--fom-next fom)))))
3296 (defun yas--make-move-active-field-overlay (snippet field)
3297 "Place the active field overlay in SNIPPET's FIELD.
3299 Move the overlay, or create it if it does not exit."
3300 (if (and yas--active-field-overlay
3301 (overlay-buffer yas--active-field-overlay))
3302 (move-overlay yas--active-field-overlay
3303 (yas--field-start field)
3304 (yas--field-end field))
3305 (setq yas--active-field-overlay
3306 (make-overlay (yas--field-start field)
3307 (yas--field-end field)
3309 (overlay-put yas--active-field-overlay 'priority 100)
3310 (overlay-put yas--active-field-overlay 'face 'yas-field-highlight-face)
3311 (overlay-put yas--active-field-overlay 'yas--snippet snippet)
3312 (overlay-put yas--active-field-overlay 'modification-hooks '(yas--on-field-overlay-modification))
3313 (overlay-put yas--active-field-overlay 'insert-in-front-hooks
3314 '(yas--on-field-overlay-modification))
3315 (overlay-put yas--active-field-overlay 'insert-behind-hooks
3316 '(yas--on-field-overlay-modification))))
3318 (defvar yas--inhibit-overlay-hooks nil
3319 "Bind this temporarity to non-nil to prevent running `yas--on-*-modification'.")
3321 (defun yas--on-field-overlay-modification (overlay after? beg end &optional length)
3322 "Clears the field and updates mirrors, conditionally.
3324 Only clears the field if it hasn't been modified and it point it
3325 at field start. This hook doesn't do anything if an undo is in
3327 (unless (or yas--inhibit-overlay-hooks
3328 (yas--undo-in-progress))
3329 (let* ((field (overlay-get overlay 'yas--field))
3330 (number (and field (yas--field-number field)))
3331 (snippet (overlay-get yas--active-field-overlay 'yas--snippet)))
3333 (yas--advance-end-maybe field (overlay-end overlay))
3335 (yas--field-update-display field snippet))
3336 (yas--update-mirrors snippet))
3338 (when (and (not after?)
3339 (not (yas--field-modified-p field))
3340 (eq (point) (if (markerp (yas--field-start field))
3341 (marker-position (yas--field-start field))
3342 (yas--field-start field))))
3343 (yas--skip-and-clear field))
3344 (setf (yas--field-modified-p field) t))))))
3346 ;;; Apropos protection overlays:
3348 ;; These exist for nasty users who will try to delete parts of the
3349 ;; snippet outside the active field. Actual protection happens in
3350 ;; `yas--on-protection-overlay-modification'.
3352 ;; Currently this signals an error which inhibits the command. For
3353 ;; commands that move point (like `kill-line'), point is restored in
3354 ;; the `yas--post-command-handler' using a global
3355 ;; `yas--protection-violation' variable.
3357 ;; Alternatively, I've experimented with an implementation that
3358 ;; commits the snippet before actually calling `this-command'
3359 ;; interactively, and then signals an eror, which is ignored. but
3360 ;; blocks all other million modification hooks. This presented some
3361 ;; problems with stacked expansion.
3363 (defun yas--make-move-field-protection-overlays (snippet field)
3364 "Place protection overlays surrounding SNIPPET's FIELD.
3366 Move the overlays, or create them if they do not exit."
3367 (let ((start (yas--field-start field))
3368 (end (yas--field-end field)))
3369 ;; First check if the (1+ end) is contained in the buffer,
3370 ;; otherwise we'll have to do a bit of cheating and silently
3371 ;; insert a newline. the `(1+ (buffer-size))' should prevent this
3372 ;; when using stacked expansion
3374 (when (< (buffer-size) end)
3376 (yas--inhibit-overlay-hooks
3377 (goto-char (point-max))
3379 ;; go on to normal overlay creation/moving
3381 (cond ((and yas--field-protection-overlays
3382 (every #'overlay-buffer yas--field-protection-overlays))
3383 (move-overlay (first yas--field-protection-overlays) (1- start) start)
3384 (move-overlay (second yas--field-protection-overlays) end (1+ end)))
3386 (setq yas--field-protection-overlays
3387 (list (make-overlay (1- start) start nil t nil)
3388 (make-overlay end (1+ end) nil t nil)))
3389 (dolist (ov yas--field-protection-overlays)
3390 (overlay-put ov 'face 'yas--field-debug-face)
3391 (overlay-put ov 'yas--snippet snippet)
3392 ;; (overlay-put ov 'evaporate t)
3393 (overlay-put ov 'modification-hooks '(yas--on-protection-overlay-modification)))))))
3395 (defvar yas--protection-violation nil
3396 "When non-nil, signals attempts to erronesly exit or modify the snippet.
3398 Functions in the `post-command-hook', for example
3399 `yas--post-command-handler' can check it and reset its value to
3400 nil. The variables value is the point where the violation
3403 (defun yas--on-protection-overlay-modification (overlay after? beg end &optional length)
3404 "Signals a snippet violation, then issues error.
3406 The error should be ignored in `debug-ignored-errors'"
3407 (unless yas--inhibit-overlay-hooks
3408 (cond ((not (or after?
3409 (yas--undo-in-progress)))
3410 (setq yas--protection-violation (point))
3411 (error "Exit the snippet first!")))))
3413 (add-to-list 'debug-ignored-errors "^Exit the snippet first!$")
3416 ;; Snippet expansion and "stacked" expansion:
3418 ;; Stacked expansion is when you try to expand a snippet when already
3419 ;; inside a snippet expansion.
3421 ;; The parent snippet does not run its fields modification hooks
3422 ;; (`yas--on-field-overlay-modification' and
3423 ;; `yas--on-protection-overlay-modification') while the child snippet
3424 ;; is active. This means, among other things, that the mirrors of the
3425 ;; parent snippet are not updated, this only happening when one exits
3426 ;; the child snippet.
3428 ;; Unfortunately, this also puts some ugly (and not fully-tested)
3429 ;; bits of code in `yas-expand-snippet' and
3430 ;; `yas--commit-snippet'. I've tried to mark them with "stacked
3433 ;; This was thought to be safer in in an undo/redo perpective, but
3434 ;; maybe the correct implementation is to make the globals
3435 ;; `yas--active-field-overlay' and `yas--field-protection-overlays' be
3436 ;; snippet-local and be active even while the child snippet is
3437 ;; running. This would mean a lot of overlay modification hooks
3438 ;; running, but if managed correctly (including overlay priorities)
3439 ;; they should account for all situations...
3441 (defun yas-expand-snippet (content &optional start end expand-env)
3442 "Expand snippet CONTENT at current point.
3444 Text between START and END will be deleted before inserting
3445 template. EXPAND-ENV is are let-style variable to value bindings
3446 considered when expanding the snippet."
3447 (run-hooks 'yas-before-expand-snippet-hook)
3449 ;; If a region is active, set `yas-selected-text'
3450 (setq yas-selected-text
3451 (when (region-active-p)
3452 (prog1 (buffer-substring-no-properties (region-beginning)
3454 (unless start (setq start (region-beginning))
3455 (unless end (setq end (region-end)))))))
3461 (let ((to-delete (and start end (buffer-substring-no-properties start end)))
3462 (start (or start (point)))
3463 (end (or end (point)))
3465 (setq yas--indent-original-column (current-column))
3466 ;; Delete the region to delete, this *does* get undo-recorded.
3468 (when (and to-delete
3470 (delete-region start end))
3472 (cond ((listp content)
3473 ;; x) This is a snippet-command
3475 (yas--eval-lisp-no-saves content))
3477 ;; x) This is a snippet-snippet :-)
3479 ;; Narrow the region down to the content, shoosh the
3480 ;; `buffer-undo-list', and create the snippet, the new
3481 ;; snippet updates its mirrors once, so we are left with
3482 ;; some plain text. The undo action for deleting this
3483 ;; plain text will get recorded at the end.
3485 ;; stacked expansion: also shoosh the overlay modification hooks
3487 (narrow-to-region start start)
3488 (let ((buffer-undo-list t))
3489 ;; snippet creation might evaluate users elisp, which
3490 ;; might generate errors, so we have to be ready to catch
3491 ;; them mostly to make the undo information
3493 (setq yas--start-column (save-restriction (widen) (current-column)))
3494 (yas--inhibit-overlay-hooks
3497 (eval `(let* ,expand-env
3499 (yas--snippet-create (point-min) (point-max))))
3501 (yas--snippet-create (point-min) (point-max)))))))
3503 ;; stacked-expansion: This checks for stacked expansion, save the
3504 ;; `yas--previous-active-field' and advance its boudary.
3506 (let ((existing-field (and yas--active-field-overlay
3507 (overlay-buffer yas--active-field-overlay)
3508 (overlay-get yas--active-field-overlay 'yas--field))))
3509 (when existing-field
3510 (setf (yas--snippet-previous-active-field snippet) existing-field)
3511 (yas--advance-end-maybe existing-field (overlay-end yas--active-field-overlay))))
3513 ;; Exit the snippet immediately if no fields
3515 (unless (yas--snippet-fields snippet)
3516 (yas-exit-snippet snippet))
3518 ;; Push two undo actions: the deletion of the inserted contents of
3519 ;; the new snippet (without the "key") followed by an apply of
3520 ;; `yas--take-care-of-redo' on the newly inserted snippet boundaries
3522 ;; A small exception, if `yas-also-auto-indent-first-line'
3523 ;; is t and `yas--indent' decides to indent the line to a
3524 ;; point before the actual expansion point, undo would be
3525 ;; messed up. We call the early point "newstart"". case,
3526 ;; and attempt to fix undo.
3528 (let ((newstart (overlay-start (yas--snippet-control-overlay snippet)))
3529 (end (overlay-end (yas--snippet-control-overlay snippet))))
3530 (when (< newstart start)
3531 (push (cons (make-string (- start newstart) ? ) newstart) buffer-undo-list))
3532 (push (cons newstart end) buffer-undo-list)
3533 (push `(apply yas--take-care-of-redo ,start ,end ,snippet)
3535 ;; Now, schedule a move to the first field
3537 (let ((first-field (car (yas--snippet-fields snippet))))
3539 (sit-for 0) ;; fix issue 125
3540 (yas--move-to-field snippet first-field)))
3541 (yas--message 3 "snippet expanded.")
3544 (defun yas--take-care-of-redo (beg end snippet)
3545 "Commits SNIPPET, which in turn pushes an undo action for
3548 Meant to exit in the `buffer-undo-list'."
3549 ;; slightly optimize: this action is only needed for snippets with
3550 ;; at least one field
3551 (when (yas--snippet-fields snippet)
3552 (yas--commit-snippet snippet)))
3554 (defun yas--snippet-revive (beg end snippet)
3555 "Revives the SNIPPET and creates a control overlay from BEG to
3558 BEG and END are, we hope, the original snippets boudaries. All
3559 the markers/points exiting existing inside SNIPPET should point
3560 to their correct locations *at the time the snippet is revived*.
3562 After revival, push the `yas--take-care-of-redo' in the
3564 ;; Reconvert all the points to markers
3566 (yas--points-to-markers snippet)
3567 ;; When at least one editable field existed in the zombie snippet,
3568 ;; try to revive the whole thing...
3570 (let ((target-field (or (yas--snippet-active-field snippet)
3571 (car (yas--snippet-fields snippet)))))
3573 (setf (yas--snippet-control-overlay snippet) (yas--make-control-overlay snippet beg end))
3574 (overlay-put (yas--snippet-control-overlay snippet) 'yas--snippet snippet)
3576 (yas--move-to-field snippet target-field)
3578 (push `(apply yas--take-care-of-redo ,beg ,end ,snippet)
3579 buffer-undo-list))))
3581 (defun yas--snippet-create (begin end)
3582 "Creates a snippet from an template inserted between BEGIN and END.
3584 Returns the newly created snippet."
3585 (let ((snippet (yas--make-snippet)))
3587 (yas--snippet-parse-create snippet)
3589 ;; Sort and link each field
3590 (yas--snippet-sort-fields snippet)
3592 ;; Create keymap overlay for snippet
3593 (setf (yas--snippet-control-overlay snippet)
3594 (yas--make-control-overlay snippet (point-min) (point-max)))
3597 (goto-char (point-max))
3602 ;;; Apropos adjacencies and "fom's":
3604 ;; Once the $-constructs bits like "$n" and "${:n" are deleted in the
3605 ;; recently expanded snippet, we might actually have many fields,
3606 ;; mirrors (and the snippet exit) in the very same position in the
3607 ;; buffer. Therefore we need to single-link the
3608 ;; fields-or-mirrors-or-exit (which I have abbreviated to "fom")
3609 ;; according to their original positions in the buffer.
3611 ;; Then we have operation `yas--advance-end-maybe' and
3612 ;; `yas--advance-start-maybe', which conditionally push the starts and
3613 ;; ends of these foms down the chain.
3615 ;; This allows for like the printf with the magic ",":
3617 ;; printf ("${1:%s}\\n"${1:$(if (string-match "%" text) "," "\);")} \
3618 ;; $2${1:$(if (string-match "%" text) "\);" "")}$0
3620 (defun yas--fom-start (fom)
3621 (cond ((yas--field-p fom)
3622 (yas--field-start fom))
3623 ((yas--mirror-p fom)
3624 (yas--mirror-start fom))
3626 (yas--exit-marker fom))))
3628 (defun yas--fom-end (fom)
3629 (cond ((yas--field-p fom)
3630 (yas--field-end fom))
3631 ((yas--mirror-p fom)
3632 (yas--mirror-end fom))
3634 (yas--exit-marker fom))))
3636 (defun yas--fom-next (fom)
3637 (cond ((yas--field-p fom)
3638 (yas--field-next fom))
3639 ((yas--mirror-p fom)
3640 (yas--mirror-next fom))
3642 (yas--exit-next fom))))
3644 (defun yas--fom-parent-field (fom)
3645 (cond ((yas--field-p fom)
3646 (yas--field-parent-field fom))
3647 ((yas--mirror-p fom)
3648 (yas--mirror-parent-field fom))
3652 (defun yas--calculate-adjacencies (snippet)
3653 "Calculate adjacencies for fields or mirrors of SNIPPET.
3655 This is according to their relative positions in the buffer, and
3656 has to be called before the $-constructs are deleted."
3657 (flet ((yas--fom-set-next-fom (fom nextfom)
3658 (cond ((yas--field-p fom)
3659 (setf (yas--field-next fom) nextfom))
3660 ((yas--mirror-p fom)
3661 (setf (yas--mirror-next fom) nextfom))
3663 (setf (yas--exit-next fom) nextfom))))
3664 (yas--compare-fom-begs (fom1 fom2)
3665 (if (= (yas--fom-start fom2) (yas--fom-start fom1))
3666 (yas--mirror-p fom2)
3667 (>= (yas--fom-start fom2) (yas--fom-start fom1))))
3668 (yas--link-foms (fom1 fom2)
3669 (yas--fom-set-next-fom fom1 fom2)))
3670 ;; make some yas--field, yas--mirror and yas--exit soup
3672 (when (yas--snippet-exit snippet)
3673 (push (yas--snippet-exit snippet) soup))
3674 (dolist (field (yas--snippet-fields snippet))
3676 (dolist (mirror (yas--field-mirrors field))
3677 (push mirror soup)))
3680 #'yas--compare-fom-begs))
3682 (reduce #'yas--link-foms soup)))))
3684 (defun yas--calculate-mirrors-in-fields (snippet mirror)
3685 "Attempt to assign a parent field of SNIPPET to the mirror MIRROR.
3687 Use the tighest containing field if more than one field contains
3688 the mirror. Intended to be called *before* the dollar-regions are
3690 (let ((min (point-min))
3692 (dolist (field (yas--snippet-fields snippet))
3693 (when (and (<= (yas--field-start field) (yas--mirror-start mirror))
3694 (<= (yas--mirror-end mirror) (yas--field-end field))
3695 (< min (yas--field-start field))
3696 (< (yas--field-end field) max))
3697 (setq min (yas--field-start field)
3698 max (yas--field-end field))
3699 (setf (yas--mirror-parent-field mirror) field)))))
3701 (defun yas--advance-end-maybe (fom newend)
3702 "Maybe advance FOM's end to NEWEND if it needs it.
3706 * call `yas--advance-start-maybe' on FOM's next fom.
3708 * in case FOM is field call `yas--advance-end-maybe' on its parent
3711 Also, if FOM is an exit-marker, always call
3712 `yas--advance-start-maybe' on its next fom. This is beacuse
3713 exit-marker have identical start and end markers.
3716 (cond ((and fom (< (yas--fom-end fom) newend))
3717 (set-marker (yas--fom-end fom) newend)
3718 (yas--advance-start-maybe (yas--fom-next fom) newend)
3719 (yas--advance-end-of-parents-maybe (yas--fom-parent-field fom) newend))
3721 (yas--advance-start-maybe (yas--fom-next fom) newend))))
3723 (defun yas--advance-start-maybe (fom newstart)
3724 "Maybe advance FOM's start to NEWSTART if it needs it.
3726 If it does, also call `yas--advance-end-maybe' on FOM."
3727 (when (and fom (< (yas--fom-start fom) newstart))
3728 (set-marker (yas--fom-start fom) newstart)
3729 (yas--advance-end-maybe fom newstart)))
3731 (defun yas--advance-end-of-parents-maybe (field newend)
3732 "Like `yas--advance-end-maybe' but for parent fields.
3734 Only works for fields and doesn't care about the start of the
3735 next FOM. Works its way up recursively for parents of parents."
3737 (< (yas--field-end field) newend))
3738 (set-marker (yas--field-end field) newend)
3739 (yas--advance-end-of-parents-maybe (yas--field-parent-field field) newend)))
3741 (defvar yas--dollar-regions nil
3742 "When expanding the snippet the \"parse-create\" functions add
3743 cons cells to this var")
3745 (defun yas--snippet-parse-create (snippet)
3746 "Parse a recently inserted snippet template, creating all
3747 necessary fields, mirrors and exit points.
3749 Meant to be called in a narrowed buffer, does various passes"
3750 (let ((parse-start (point)))
3751 ;; Reset the yas--dollar-regions
3753 (setq yas--dollar-regions nil)
3754 ;; protect escaped quote, backquotes and backslashes
3756 (yas--protect-escapes nil `(?\\ ?` ?'))
3757 ;; replace all backquoted expressions
3759 (goto-char parse-start)
3760 (yas--replace-backquotes)
3761 ;; protect escapes again since previous steps might have generated
3762 ;; more characters needing escaping
3764 (goto-char parse-start)
3765 (yas--protect-escapes)
3766 ;; parse fields with {}
3768 (goto-char parse-start)
3769 (yas--field-parse-create snippet)
3770 ;; parse simple mirrors and fields
3772 (goto-char parse-start)
3773 (yas--simple-mirror-parse-create snippet)
3774 ;; parse mirror transforms
3776 (goto-char parse-start)
3777 (yas--transform-mirror-parse-create snippet)
3778 ;; calculate adjacencies of fields and mirrors
3780 (yas--calculate-adjacencies snippet)
3781 ;; Delete $-constructs
3783 (yas--delete-regions yas--dollar-regions)
3786 (goto-char parse-start)
3787 (yas--restore-escapes)
3788 ;; update mirrors for the first time
3790 (yas--update-mirrors snippet)
3791 ;; indent the best we can
3793 (goto-char parse-start)
3794 (yas--indent snippet)))
3796 (defun yas--indent-according-to-mode (snippet-markers)
3797 "Indent current line according to mode, preserving
3799 ;;; Apropos indenting problems....
3801 ;; `indent-according-to-mode' uses whatever `indent-line-function'
3802 ;; is available. Some implementations of these functions delete text
3803 ;; before they insert. If there happens to be a marker just after
3804 ;; the text being deleted, the insertion actually happens after the
3805 ;; marker, which misplaces it.
3807 ;; This would also happen if we had used overlays with the
3808 ;; `front-advance' property set to nil.
3810 ;; This is why I have these `trouble-markers', they are the ones at
3811 ;; they are the ones at the first non-whitespace char at the line
3812 ;; (i.e. at `yas--real-line-beginning'. After indentation takes place
3813 ;; we should be at the correct to restore them to. All other
3814 ;; non-trouble-markers have been *pushed* and don't need special
3817 (goto-char (yas--real-line-beginning))
3818 (let ((trouble-markers (remove-if-not #'(lambda (marker)
3824 (indent-according-to-mode)
3825 (error (yas--message 3 "Warning: `yas--indent-according-to-mode' having problems running %s" indent-line-function)
3827 (mapc #'(lambda (marker)
3828 (set-marker marker (point)))
3831 (defvar yas--indent-original-column nil)
3832 (defun yas--indent (snippet)
3833 (let ((snippet-markers (yas--collect-snippet-markers snippet)))
3834 ;; Look for those $>
3836 (while (re-search-forward "$>" nil t)
3837 (delete-region (match-beginning 0) (match-end 0))
3838 (when (not (eq yas-indent-line 'auto))
3839 (yas--indent-according-to-mode snippet-markers))))
3840 ;; Now do stuff for 'fixed and 'auto
3842 (cond ((eq yas-indent-line 'fixed)
3843 (while (and (zerop (forward-line))
3844 (zerop (current-column)))
3845 (indent-to-column yas--indent-original-column)))
3846 ((eq yas-indent-line 'auto)
3847 (let ((end (set-marker (make-marker) (point-max)))
3848 (indent-first-line-p yas-also-auto-indent-first-line))
3849 (while (and (zerop (if indent-first-line-p
3852 (setq indent-first-line-p nil))
3856 (yas--indent-according-to-mode snippet-markers))))
3860 (defun yas--collect-snippet-markers (snippet)
3861 "Make a list of all the markers used by SNIPPET."
3863 (dolist (field (yas--snippet-fields snippet))
3864 (push (yas--field-start field) markers)
3865 (push (yas--field-end field) markers)
3866 (dolist (mirror (yas--field-mirrors field))
3867 (push (yas--mirror-start mirror) markers)
3868 (push (yas--mirror-end mirror) markers)))
3869 (let ((snippet-exit (yas--snippet-exit snippet)))
3870 (when (and snippet-exit
3871 (marker-buffer (yas--exit-marker snippet-exit)))
3872 (push (yas--exit-marker snippet-exit) markers)))
3875 (defun yas--real-line-beginning ()
3876 (let ((c (char-after (line-beginning-position)))
3877 (n (line-beginning-position)))
3878 (while (or (eql c ?\ )
3881 (setq c (char-after n)))
3884 (defun yas--escape-string (escaped)
3885 (concat "YASESCAPE" (format "%d" escaped) "PROTECTGUARD"))
3887 (defun yas--protect-escapes (&optional text escaped)
3888 "Protect all escaped characters with their numeric ASCII value.
3890 With optional string TEXT do it in string instead of buffer."
3891 (let ((changed-text text)
3892 (text-provided-p text))
3893 (mapc #'(lambda (escaped)
3895 (yas--replace-all (concat "\\" (char-to-string escaped))
3896 (yas--escape-string escaped)
3897 (when text-provided-p changed-text))))
3898 (or escaped yas--escaped-characters))
3901 (defun yas--restore-escapes (&optional text escaped)
3902 "Restore all escaped characters from their numeric ASCII value.
3904 With optional string TEXT do it in string instead of the buffer."
3905 (let ((changed-text text)
3906 (text-provided-p text))
3907 (mapc #'(lambda (escaped)
3909 (yas--replace-all (yas--escape-string escaped)
3910 (char-to-string escaped)
3911 (when text-provided-p changed-text))))
3912 (or escaped yas--escaped-characters))
3915 (defun yas--replace-backquotes ()
3916 "Replace all the \"`(lisp-expression)`\"-style expression
3917 with their evaluated value"
3918 (while (re-search-forward yas--backquote-lisp-expression-regexp nil t)
3919 (let ((current-string (match-string 1)) transformed)
3920 (delete-region (match-beginning 0) (match-end 0))
3921 (setq transformed (yas--eval-lisp (yas--read-lisp (yas--restore-escapes current-string))))
3922 (goto-char (match-beginning 0))
3923 (when transformed (insert transformed)))))
3925 (defun yas--scan-sexps (from count)
3927 (with-syntax-table (standard-syntax-table)
3928 (scan-sexps from count))
3932 (defun yas--make-marker (pos)
3933 "Create a marker at POS with `nil' `marker-insertion-type'"
3934 (let ((marker (set-marker (make-marker) pos)))
3935 (set-marker-insertion-type marker nil)
3938 (defun yas--field-parse-create (snippet &optional parent-field)
3939 "Parse most field expressions, except for the simple one \"$n\".
3941 The following count as a field:
3943 * \"${n: text}\", for a numbered field with default text, as long as N is not 0;
3945 * \"${n: text$(expression)}, the same with a lisp expression;
3946 this is caught with the curiously named `yas--multi-dollar-lisp-expression-regexp'
3948 * the same as above but unnumbered, (no N:) and number is calculated automatically.
3950 When multiple expressions are found, only the last one counts."
3953 (while (re-search-forward yas--field-regexp nil t)
3954 (let* ((real-match-end-0 (yas--scan-sexps (1+ (match-beginning 0)) 1))
3955 (number (and (match-string-no-properties 1)
3956 (string-to-number (match-string-no-properties 1))))
3957 (brand-new-field (and real-match-end-0
3958 ;; break if on "$(" immediately
3959 ;; after the ":", this will be
3960 ;; caught as a mirror with
3962 (not (save-match-data
3963 (eq (string-match "$[ \t\n]*("
3964 (match-string-no-properties 2)) 0)))
3965 ;; allow ${0: some exit text}
3966 ;; (not (and number (zerop number)))
3967 (yas--make-field number
3968 (yas--make-marker (match-beginning 2))
3969 (yas--make-marker (1- real-match-end-0))
3971 (when brand-new-field
3972 (goto-char real-match-end-0)
3973 (push (cons (1- real-match-end-0) real-match-end-0)
3974 yas--dollar-regions)
3975 (push (cons (match-beginning 0) (match-beginning 2))
3976 yas--dollar-regions)
3977 (push brand-new-field (yas--snippet-fields snippet))
3980 (narrow-to-region (yas--field-start brand-new-field) (yas--field-end brand-new-field))
3981 (goto-char (point-min))
3982 (yas--field-parse-create snippet brand-new-field)))))))
3983 ;; if we entered from a parent field, now search for the
3984 ;; `yas--multi-dollar-lisp-expression-regexp'. THis is used for
3985 ;; primary field transformations
3989 (while (re-search-forward yas--multi-dollar-lisp-expression-regexp nil t)
3990 (let* ((real-match-end-1 (yas--scan-sexps (match-beginning 1) 1)))
3991 ;; commit the primary field transformation if:
3993 ;; 1. we don't find it in yas--dollar-regions (a subnested
3994 ;; field) might have already caught it.
3996 ;; 2. we really make sure we have either two '$' or some
3997 ;; text and a '$' after the colon ':'. This is a FIXME: work
3998 ;; my regular expressions and end these ugly hacks.
4000 (when (and real-match-end-1
4001 (not (member (cons (match-beginning 0)
4003 yas--dollar-regions))
4005 (char-before (1- (match-beginning 1))))))
4006 (let ((lisp-expression-string (buffer-substring-no-properties (match-beginning 1)
4008 (setf (yas--field-transform parent-field)
4009 (yas--read-lisp (yas--restore-escapes lisp-expression-string))))
4010 (push (cons (match-beginning 0) real-match-end-1)
4011 yas--dollar-regions)))))))
4013 (defun yas--transform-mirror-parse-create (snippet)
4014 "Parse the \"${n:$(lisp-expression)}\" mirror transformations."
4015 (while (re-search-forward yas--transform-mirror-regexp nil t)
4016 (let* ((real-match-end-0 (yas--scan-sexps (1+ (match-beginning 0)) 1))
4017 (number (string-to-number (match-string-no-properties 1)))
4019 (not (zerop number))
4020 (yas--snippet-find-field snippet number)))
4022 (and real-match-end-0
4024 (yas--make-mirror (yas--make-marker (match-beginning 0))
4025 (yas--make-marker (match-beginning 0))
4027 (yas--restore-escapes
4028 (buffer-substring-no-properties (match-beginning 2)
4029 (1- real-match-end-0))))))))
4030 (when brand-new-mirror
4031 (push brand-new-mirror
4032 (yas--field-mirrors field))
4033 (yas--calculate-mirrors-in-fields snippet brand-new-mirror)
4034 (push (cons (match-beginning 0) real-match-end-0) yas--dollar-regions)))))
4036 (defun yas--simple-mirror-parse-create (snippet)
4037 "Parse the simple \"$n\" fields/mirrors/exitmarkers."
4038 (while (re-search-forward yas--simple-mirror-regexp nil t)
4039 (let ((number (string-to-number (match-string-no-properties 1))))
4040 (cond ((zerop number)
4042 (setf (yas--snippet-exit snippet)
4043 (yas--make-exit (yas--make-marker (match-end 0))))
4045 (goto-char (match-beginning 0))
4046 (when yas-wrap-around-region
4047 (cond (yas-selected-text
4048 (insert yas-selected-text))
4049 ((and (eq yas-wrap-around-region 'cua)
4052 (insert (prog1 (get-register ?0)
4053 (set-register ?0 nil))))))
4054 (push (cons (point) (yas--exit-marker (yas--snippet-exit snippet)))
4055 yas--dollar-regions)))
4057 (let ((field (yas--snippet-find-field snippet number)))
4059 (let ((brand-new-mirror (yas--make-mirror
4060 (yas--make-marker (match-beginning 0))
4061 (yas--make-marker (match-beginning 0))
4063 (push brand-new-mirror
4064 (yas--field-mirrors field))
4065 (yas--calculate-mirrors-in-fields snippet brand-new-mirror))
4066 (push (yas--make-field number
4067 (yas--make-marker (match-beginning 0))
4068 (yas--make-marker (match-beginning 0))
4070 (yas--snippet-fields snippet))))
4071 (push (cons (match-beginning 0) (match-end 0))
4072 yas--dollar-regions))))))
4074 (defun yas--delete-regions (regions)
4075 "Sort disjuct REGIONS by start point, then delete from the back."
4076 (mapc #'(lambda (reg)
4077 (delete-region (car reg) (cdr reg)))
4080 (>= (car r1) (car r2))))))
4082 (defun yas--update-mirrors (snippet)
4083 "Updates all the mirrors of SNIPPET."
4085 (let* ((fields (copy-list (yas--snippet-fields snippet)))
4086 (field (car fields)))
4088 (dolist (mirror (yas--field-mirrors field))
4089 (let ((mirror-parent-field (yas--mirror-parent-field mirror)))
4090 ;; updatte this mirror
4092 (yas--mirror-update-display mirror field)
4093 ;; for mirrors-in-fields: schedule a possible
4094 ;; parent field for reupdting later on
4096 (when mirror-parent-field
4097 (add-to-list 'fields mirror-parent-field 'append #'eq))
4098 ;; `yas--place-overlays' is needed if the active field and
4099 ;; protected overlays have been changed because of insertions
4100 ;; in `yas--mirror-update-display'
4102 (when (eq field (yas--snippet-active-field snippet))
4103 (yas--place-overlays snippet field))))
4104 (setq fields (cdr fields))
4105 (setq field (car fields))))))
4107 (defun yas--mirror-update-display (mirror field)
4108 "Update MIRROR according to FIELD (and mirror transform)."
4110 (let* ((mirror-parent-field (yas--mirror-parent-field mirror))
4111 (reflection (and (not (and mirror-parent-field
4112 (yas--field-modified-p mirror-parent-field)))
4113 (or (yas--apply-transform mirror field 'empty-on-nil)
4114 (yas--field-text-for-display field)))))
4115 (when (and reflection
4116 (not (string= reflection (buffer-substring-no-properties (yas--mirror-start mirror)
4117 (yas--mirror-end mirror)))))
4118 (goto-char (yas--mirror-start mirror))
4119 (yas--inhibit-overlay-hooks
4120 (insert reflection))
4121 (if (> (yas--mirror-end mirror) (point))
4122 (delete-region (point) (yas--mirror-end mirror))
4123 (set-marker (yas--mirror-end mirror) (point))
4124 (yas--advance-start-maybe (yas--mirror-next mirror) (point))
4125 ;; super-special advance
4126 (yas--advance-end-of-parents-maybe mirror-parent-field (point))))))
4128 (defun yas--field-update-display (field snippet)
4129 "Much like `yas--mirror-update-display', but for fields"
4130 (when (yas--field-transform field)
4131 (let ((transformed (and (not (eq (yas--field-number field) 0))
4132 (yas--apply-transform field field)))
4134 (when (and transformed
4135 (not (string= transformed (buffer-substring-no-properties (yas--field-start field)
4136 (yas--field-end field)))))
4137 (setf (yas--field-modified-p field) t)
4138 (goto-char (yas--field-start field))
4139 (yas--inhibit-overlay-hooks
4140 (insert transformed)
4141 (if (> (yas--field-end field) (point))
4142 (delete-region (point) (yas--field-end field))
4143 (set-marker (yas--field-end field) (point))
4144 (yas--advance-start-maybe (yas--field-next field) (point)))
4148 ;;; Post-command hook:
4150 (defun yas--post-command-handler ()
4151 "Handles various yasnippet conditions after each command."
4152 (cond (yas--protection-violation
4153 (goto-char yas--protection-violation)
4154 (setq yas--protection-violation nil))
4155 ((eq 'undo this-command)
4157 ;; After undo revival the correct field is sometimes not
4158 ;; restored correctly, this condition handles that
4160 (let* ((snippet (car (yas--snippets-at-point)))
4161 (target-field (and snippet
4162 (find-if-not #'(lambda (field)
4163 (yas--field-probably-deleted-p snippet field))
4165 (cons (yas--snippet-active-field snippet)
4166 (yas--snippet-fields snippet)))))))
4168 (yas--move-to-field snippet target-field))))
4169 ((not (yas--undo-in-progress))
4170 ;; When not in an undo, check if we must commit the snippet
4171 ;; (user exited it).
4172 (yas--check-commit-snippet))))
4176 ;; The docstrings for some functions are generated dynamically
4177 ;; depending on the context.
4179 (put 'yas-expand 'function-documentation
4180 '(yas--expand-from-trigger-key-doc))
4181 (defun yas--expand-from-trigger-key-doc ()
4182 "A doc synthethizer for `yas--expand-from-trigger-key-doc'."
4183 (let ((fallback-description
4184 (cond ((eq yas-fallback-behavior 'call-other-command)
4185 (let* ((yas-minor-mode nil)
4186 (fallback (key-binding (read-kbd-macro yas-trigger-key))))
4188 (format " call command `%s'." (pp-to-string fallback)))
4190 ((eq yas-fallback-behavior 'return-nil)
4193 ", defer to `yas--fallback-behaviour' :-)"))))
4194 (concat "Expand a snippet before point. If no snippet
4195 expansion is possible,"
4196 fallback-description
4197 "\n\nOptional argument FIELD is for non-interactive use and is an
4198 object satisfying `yas--field-p' to restrict the expansion to.")))
4200 (put 'yas-expand-from-keymap 'function-documentation '(yas--expand-from-keymap-doc))
4201 (defun yas--expand-from-keymap-doc ()
4202 "A doc synthethizer for `yas--expand-from-keymap-doc'."
4203 (add-hook 'temp-buffer-show-hook 'yas--snippet-description-finish-runonce)
4204 (concat "Expand/run snippets from keymaps, possibly falling back to original binding.\n"
4205 (when (eq this-command 'describe-key)
4206 (let* ((vec (this-single-command-keys))
4207 (templates (mapcan #'(lambda (table)
4208 (yas--fetch table vec))
4209 (yas--get-snippet-tables)))
4210 (yas--direct-keymaps nil)
4211 (fallback (key-binding vec)))
4212 (concat "In this case, "
4214 (concat "these snippets are bound to this key:\n"
4215 (yas--template-pretty-list templates)
4216 "\n\nIf none of these expands, "))
4218 (format "fallback `%s' will be called." (pp-to-string fallback)))
4219 "no fallback keybinding is called."))))))
4221 (defun yas--template-pretty-list (templates)
4223 (yas-buffer-local-condition 'always))
4224 (dolist (plate templates)
4225 (setq acc (concat acc "\n*) "
4226 (propertize (concat "\\\\snippet `" (car plate) "'")
4227 'yasnippet (cdr plate)))))
4230 (define-button-type 'help-snippet-def
4231 :supertype 'help-xref
4232 'help-function (lambda (template) (yas--visit-snippet-file-1 template))
4233 'help-echo (purecopy "mouse-2, RET: find snippets's definition"))
4235 (defun yas--snippet-description-finish-runonce ()
4236 "Final adjustments for the help buffer when snippets are concerned."
4237 (yas--create-snippet-xrefs)
4238 (remove-hook 'temp-buffer-show-hook 'yas--snippet-description-finish-runonce))
4240 (defun yas--create-snippet-xrefs ()
4242 (goto-char (point-min))
4243 (while (search-forward-regexp "\\\\\\\\snippet[ \s\t]+`\\([^']+\\)'" nil t)
4244 (let ((template (get-text-property (match-beginning 1)
4247 (help-xref-button 1 'help-snippet-def template)
4248 (kill-region (match-end 1) (match-end 0))
4249 (kill-region (match-beginning 0) (match-beginning 1)))))))
4251 (defun yas--expand-uuid (mode-symbol uuid &optional start end expand-env)
4252 "Expand a snippet registered in MODE-SYMBOL's table with UUID.
4254 Remaining args as in `yas-expand-snippet'."
4255 (let* ((table (gethash mode-symbol yas--tables))
4256 (yas--current-template (and table
4257 (gethash uuid (yas--table-uuidhash table)))))
4258 (when yas--current-template
4259 (yas-expand-snippet (yas--template-content yas--current-template)))))
4263 (defvar yas-verbosity 4
4264 "Log level for `yas--message' 4 means trace most anything, 0 means nothing.")
4266 (defun yas--message (level message &rest args)
4267 (when (> yas-verbosity level)
4268 (message (apply #'yas--format message args))))
4270 (defun yas--format (format-control &rest format-args)
4271 (apply #'format (concat "[yas] " format-control) format-args))
4278 ;; `locate-dominating-file'
4279 ;; `region-active-p'
4281 ;; added for compatibility in emacsen < 23
4282 (unless (>= emacs-major-version 23)
4283 (unless (fboundp 'region-active-p)
4284 (defun region-active-p () (and transient-mark-mode mark-active)))
4286 (unless (fboundp 'locate-dominating-file)
4287 (defvar locate-dominating-stop-dir-regexp
4288 "\\`\\(?:[\\/][\\/][^\\/]+[\\/]\\|/\\(?:net\\|afs\\|\\.\\.\\.\\)/\\)\\'"
4289 "Regexp of directory names which stop the search in `locate-dominating-file'.
4290 Any directory whose name matches this regexp will be treated like
4291 a kind of root directory by `locate-dominating-file' which will stop its search
4292 when it bumps into it.
4293 The default regexp prevents fruitless and time-consuming attempts to find
4294 special files in directories in which filenames are interpreted as hostnames,
4295 or mount points potentially requiring authentication as a different user.")
4297 (defun locate-dominating-file (file name)
4298 "Look up the directory hierarchy from FILE for a file named NAME.
4299 Stop at the first parent directory containing a file NAME,
4300 and return the directory. Return nil if not found."
4301 ;; We used to use the above locate-dominating-files code, but the
4302 ;; directory-files call is very costly, so we're much better off doing
4303 ;; multiple calls using the code in here.
4305 ;; Represent /home/luser/foo as ~/foo so that we don't try to look for
4306 ;; `name' in /home or in /.
4307 (setq file (abbreviate-file-name file))
4310 ;; `user' is not initialized outside the loop because
4311 ;; `file' may not exist, so we may have to walk up part of the
4312 ;; hierarchy before we find the "initial UUID".
4315 (while (not (or root
4317 ;; FIXME: Disabled this heuristic because it is sometimes
4319 ;; As a heuristic, we stop looking up the hierarchy of
4320 ;; directories as soon as we find a directory belonging
4321 ;; to another user. This should save us from looking in
4322 ;; things like /net and /afs. This assumes that all the
4323 ;; files inside a project belong to the same user.
4324 ;; (let ((prev-user user))
4325 ;; (setq user (nth 2 (file-attributes file)))
4326 ;; (and prev-user (not (equal user prev-user))))
4327 (string-match locate-dominating-stop-dir-regexp file)))
4328 (setq try (file-exists-p (expand-file-name name file)))
4329 (cond (try (setq root file))
4330 ((equal file (setq prev-file file
4331 file (file-name-directory
4332 (directory-file-name file))))
4336 ;; `c-neutralize-syntax-in-CPP` sometimes fires "End of Buffer" error
4337 ;; (when it execute forward-char) and interrupt the after change
4338 ;; hook. Thus prevent the insert-behind hook of yasnippet to be
4339 ;; invoked. Here's a way to reproduce it:
4341 ;; # open a *new* Emacs.
4342 ;; # load yasnippet.
4343 ;; # open a *new* .cpp file.
4344 ;; # input "inc" and press TAB to expand the snippet.
4345 ;; # select the `#include <...>` snippet.
4346 ;; # type inside `<>`
4348 (defadvice c-neutralize-syntax-in-CPP
4349 (around yas--mp/c-neutralize-syntax-in-CPP activate)
4350 "Adviced `c-neutralize-syntax-in-CPP' to properly
4351 handle the end-of-buffer error fired in it by calling
4352 `forward-char' at the end of buffer."
4355 (error (message (error-message-string err)))))
4357 ;; disable c-electric-* serial command in YAS fields
4358 (add-hook 'c-mode-common-hook
4360 (dolist (k '(":" ">" ";" "<" "{" "}"))
4361 (define-key (symbol-value (make-local-variable 'yas-keymap))
4362 k 'self-insert-command))))
4364 ;;; Backward compatibility to to yasnippet <= 0.7
4365 (defvar yas--exported-syms '(;; `defcustom's
4368 yas-prompt-functions
4370 yas-also-auto-indent-first-line
4375 yas-skip-and-clear-key
4376 yas-triggers-in-field
4377 yas-fallback-behavior
4378 yas-choose-keys-first
4379 yas-choose-tables-first
4382 yas-wrap-around-region
4385 yas-expand-only-for-last-commands
4386 yas-field-highlight-face
4388 ;; these vars can be customized as well
4394 yas-after-exit-snippet-hook
4395 yas-before-expand-snippet-hook
4396 yas-buffer-local-condition
4398 ;; prompting functions
4403 yas-completing-prompt
4406 ;; interactive functions
4411 yas-direct-keymaps-reload
4415 yas-compile-directory
4418 yas-expand-from-trigger-key
4419 yas-expand-from-keymap
4421 yas-visit-snippet-file
4423 yas-load-snippet-buffer
4426 yas-next-field-or-maybe-expand
4431 yas-exit-all-snippets
4432 yas-skip-and-clear-or-delete-char
4434 ;; symbols that I "exported" for use
4435 ;; in snippets and hookage
4453 yas-default-from-field
4456 yas-define-condition-cache
4457 yas-hippie-try-expand
4459 ;; debug definitions
4460 ;; yas-debug-snippet-vars
4461 ;; yas-exterminate-package
4464 ;; testing definitions
4465 ;; yas-should-expand
4466 ;; yas-should-not-expand
4468 ;; yas-make-file-or-dirs
4470 ;; yas-saving-variables
4471 ;; yas-call-with-snippet-dirs
4472 ;; yas-with-snippet-dirs
4475 (dolist (sym yas--exported-syms)
4476 (let ((backported (intern (replace-regexp-in-string "^yas-" "yas/" (symbol-name sym)))))
4478 (make-obsolete-variable backported sym "yasnippet 0.8")
4479 (defvaralias backported sym))
4481 (make-obsolete backported sym "yasnippet 0.8")
4482 (defalias backported sym))))
4485 (provide 'yasnippet)
4487 ;;; yasnippet.el ends here