1 ;;; yasnippet.el --- Yet another snippet extension for Emacs.
3 ;; Copyright (C) 2008-2012 Free Software Foundation, Inc.
4 ;; Authors: pluskid <pluskid@gmail.com>, João Távora <joaotavora@gmail.com>
6 ;; Package-version: 0.8.0
7 ;; X-URL: http://github.com/capitaomorte/yasnippet
8 ;; Keywords: convenience, emulation
9 ;; URL: http://github.com/capitaomorte/yasnippet
10 ;; EmacsWiki: YaSnippetMode
12 ;; This program is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; This program is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
27 ;; Basic steps to setup:
29 ;; (add-to-list 'load-path
30 ;; "~/path-to-yasnippet")
31 ;; (require 'yasnippet)
32 ;; (yas-global-mode 1)
35 ;; Interesting variables are:
39 ;; The directory where user-created snippets are to be
40 ;; stored. Can also be a list of directories. In that case,
41 ;; when used for bulk (re)loading of snippets (at startup or
42 ;; via `yas-reload-all'), directories appearing earlier in
43 ;; the list shadow other dir's snippets. Also, the first
44 ;; directory is taken as the default for storing the user's
47 ;; The deprecated `yas/root-directory' aliases this variable
48 ;; for backward-compatibility.
52 ;; A local variable that you can set in a hook to override
53 ;; snippet-lookup based on major mode. It is a symbol (or
54 ;; list of symbols) that correspond to subdirectories of
55 ;; `yas-snippet-dirs' and is used for deciding which
56 ;; snippets to consider for the active buffer.
58 ;; Deprecated `yas/mode-symbol' aliases this variable for
59 ;; backward-compatibility.
61 ;; Major commands are:
65 ;; Try to expand snippets before point. In `yas-minor-mode',
66 ;; this is normally bound to TAB, but you can customize it in
67 ;; `yas-minor-mode-map'.
69 ;; M-x yas-load-directory
71 ;; Prompts you for a directory hierarchy of snippets to load.
73 ;; M-x yas-insert-snippet
75 ;; Prompts you for possible snippet expansion if that is
76 ;; possible according to buffer-local and snippet-local
77 ;; expansion conditions. With prefix argument, ignore these
80 ;; M-x yas-visit-snippet-file
82 ;; Prompts you for possible snippet expansions like
83 ;; `yas-insert-snippet', but instead of expanding it, takes
84 ;; you directly to the snippet definition's file, if it
87 ;; M-x yas-new-snippet
89 ;; Lets you create a new snippet file in the correct
90 ;; subdirectory of `yas-snippet-dirs', according to the
93 ;; M-x yas-load-snippet-buffer
95 ;; When editing a snippet, this loads the snippet. This is
96 ;; bound to "C-c C-c" while in the `snippet-mode' editing
99 ;; M-x yas-tryout-snippet
101 ;; When editing a snippet, this opens a new empty buffer,
102 ;; sets it to the appropriate major mode and inserts the
103 ;; snippet there, so you can see what it looks like. This is
104 ;; bound to "C-c C-t" while in `snippet-mode'.
106 ;; M-x yas-describe-tables
108 ;; Lists known snippets in a separate buffer. User is
109 ;; prompted as to whether only the currently active tables
110 ;; are to be displayed, or all the tables for all major
113 ;; The `dropdown-list.el' extension is bundled with YASnippet, you
114 ;; can optionally use it the preferred "prompting method", putting in
115 ;; your .emacs file, for example:
117 ;; (require 'dropdown-list)
118 ;; (setq yas-prompt-functions '(yas-dropdown-prompt
120 ;; yas-completing-prompt))
122 ;; Also check out the customization group
124 ;; M-x customize-group RET yasnippet RET
126 ;; If you use the customization group to set variables
127 ;; `yas-snippet-dirs' or `yas-global-mode', make sure the path to
128 ;; "yasnippet.el" is present in the `load-path' *before* the
129 ;; `custom-set-variables' is executed in your .emacs file.
131 ;; For more information and detailed usage, refer to the project page:
132 ;; http://github.com/capitaomorte/yasnippet
141 (defvar yas--editing-template)
142 (defvar yas--guessed-modes)
143 (defvar yas--indent-original-column)
144 (defvar yas--scheduled-jit-loads)
146 (defvar yas-selected-text)
147 (defvar yas-verbosity))
150 ;;; User customizable variables
152 (defgroup yasnippet nil
153 "Yet Another Snippet extension"
156 (defvar yas--load-file-name load-file-name
157 "Store the filename that yasnippet.el was originally loaded from.")
159 (defcustom yas-snippet-dirs (remove nil
160 (list "~/.emacs.d/snippets"
161 (when yas--load-file-name
162 (concat (file-name-directory yas--load-file-name) "snippets"))))
163 "Directory or list of snippet dirs for each major mode.
165 The directory where user-created snippets are to be stored. Can
166 also be a list of directories. In that case, when used for
167 bulk (re)loading of snippets (at startup or via
168 `yas-reload-all'), directories appearing earlier in the list
169 shadow other dir's snippets. Also, the first directory is taken
170 as the default for storing the user's new snippets."
171 :type '(choice (string :tag "Single directory (string)")
172 (repeat :args (string) :tag "List of directories (strings)"))
175 :set #'(lambda (symbol new)
176 (let ((old (and (boundp symbol)
177 (symbol-value symbol))))
178 (set-default symbol new)
179 (unless (or (not (fboundp 'yas-reload-all))
183 (defun yas-snippet-dirs ()
184 "Returns `yas-snippet-dirs' (which see) as a list."
185 (if (listp yas-snippet-dirs) yas-snippet-dirs (list yas-snippet-dirs)))
187 (defvaralias 'yas/root-directory 'yas-snippet-dirs)
189 (defcustom yas-prompt-functions '(yas-x-prompt
191 yas-completing-prompt
194 "Functions to prompt for keys, templates, etc interactively.
196 These functions are called with the following arguments:
198 - PROMPT: A string to prompt the user
200 - CHOICES: a list of strings or objects.
202 - optional DISPLAY-FN : A function that, when applied to each of
203 the objects in CHOICES will return a string.
205 The return value of any function you put here should be one of
206 the objects in CHOICES, properly formatted with DISPLAY-FN (if
209 - To signal that your particular style of prompting is
210 unavailable at the moment, you can also have the function return
213 - To signal that the user quit the prompting process, you can
216 (signal 'quit \"user quit!\")."
217 :type '(repeat function)
220 (defcustom yas-indent-line 'auto
221 "Controls indenting applied to a recent snippet expansion.
223 The following values are possible:
225 - `fixed' Indent the snippet to the current column;
227 - `auto' Indent each line of the snippet with `indent-according-to-mode'
229 Every other value means don't apply any snippet-side indentation
230 after expansion (the manual per-line \"$>\" indentation still
232 :type '(choice (const :tag "Nothing" nothing)
233 (const :tag "Fixed" fixed)
234 (const :tag "Auto" auto))
237 (defcustom yas-also-auto-indent-first-line nil
238 "Non-nil means also auto indent first line according to mode.
240 Naturally this is only valid when `yas-indent-line' is `auto'"
244 (defcustom yas-snippet-revival t
245 "Non-nil means re-activate snippet fields after undo/redo."
249 (defcustom yas-triggers-in-field nil
250 "If non-nil, allow stacked expansions (snippets inside snippets).
252 Otherwise `yas-next-field-or-maybe-expand' just moves on to the
257 (defcustom yas-fallback-behavior 'call-other-command
258 "How to act when `yas-expand' does *not* expand a snippet.
260 - `call-other-command' means try to temporarily disable YASnippet
261 and call the next command bound to whatever key was used to
264 - nil or the symbol `return-nil' mean do nothing. (and
265 `yas-expand' returns nil)
267 - A Lisp form (apply COMMAND . ARGS) means interactively call
268 COMMAND, if ARGS is non-nil, call COMMAND non-interactively
269 with ARGS as arguments."
270 :type '(choice (const :tag "Call previous command" call-other-command)
271 (const :tag "Do nothing" return-nil))
274 (defcustom yas-choose-keys-first nil
275 "If non-nil, prompt for snippet key first, then for template.
277 Otherwise prompts for all possible snippet names.
279 This affects `yas-insert-snippet' and `yas-visit-snippet-file'."
283 (defcustom yas-choose-tables-first nil
284 "If non-nil, and multiple eligible snippet tables, prompts user for tables first.
286 Otherwise, user chooses between the merging together of all
289 This affects `yas-insert-snippet', `yas-visit-snippet-file'"
293 (defcustom yas-use-menu 'abbreviate
294 "Display a YASnippet menu in the menu bar.
296 When non-nil, submenus for each snippet table will be listed
297 under the menu \"Yasnippet\".
299 - If set to `abbreviate', only the current major-mode
300 menu and the modes set in `yas-extra-modes' are listed.
302 - If set to `full', every submenu is listed
304 - It set to nil, don't display a menu at all (this requires a
305 `yas-reload-all' call if the menu is already visible).
307 Any other non-nil value, every submenu is listed."
308 :type '(choice (const :tag "Full" full)
309 (const :tag "Abbreviate" abbreviate)
310 (const :tag "No menu" nil))
313 (defcustom yas-trigger-symbol (if (eq window-system 'mac)
314 (char-to-string ?\x21E5) ;; little ->| sign
316 "The text that will be used in menu to represent the trigger."
320 (defcustom yas-wrap-around-region nil
321 "If non-nil, snippet expansion wraps around selected region.
323 The wrapping occurs just before the snippet's exit marker. This
324 can be overridden on a per-snippet basis."
328 (defcustom yas-good-grace t
329 "If non-nil, don't raise errors in inline elisp evaluation.
331 An error string \"[yas] error\" is returned instead."
335 (defcustom yas-visit-from-menu nil
336 "If non-nil visit snippets's files from menu, instead of expanding them.
338 This can only work when snippets are loaded from files."
342 (defcustom yas-expand-only-for-last-commands nil
343 "List of `last-command' values to restrict tab-triggering to, or nil.
345 Leave this set at nil (the default) to be able to trigger an
346 expansion simply by placing the cursor after a valid tab trigger,
347 using whichever commands.
349 Optionally, set this to something like '(self-insert-command) if
350 you to wish restrict expansion to only happen when the last
351 letter of the snippet tab trigger was typed immediately before
352 the trigger key itself."
353 :type '(repeat function)
356 ;; Only two faces, and one of them shouldn't even be used...
358 (defface yas-field-highlight-face
359 '((t (:inherit 'region)))
360 "The face used to highlight the currently active field of a snippet"
363 (defface yas--field-debug-face
365 "The face used for debugging some overlays normally hidden"
369 (defvar yas-keymap (let ((map (make-sparse-keymap)))
370 (define-key map [(tab)] 'yas-next-field-or-maybe-expand)
371 (define-key map (kbd "TAB") 'yas-next-field-or-maybe-expand)
372 (define-key map [(shift tab)] 'yas-prev-field)
373 (define-key map [backtab] 'yas-prev-field)
374 (define-key map (kbd "C-g") 'yas-abort-snippet)
375 (define-key map (kbd "C-d") 'yas-skip-and-clear-or-delete-char)
377 "The active keymap while a snippet expansion is in progress.")
379 (defvar yas-key-syntaxes (list "w" "w_" "w_." "w_.()" "^ ")
380 "List of character syntaxes used to find a trigger key before point.
381 The list is tried in the order while scanning characters
382 backwards from point. For example, if the list is '(\"w\" \"w_\")
383 first look for trigger keys which are composed exclusively of
384 \"word\"-syntax characters, and then, if that fails, look for
385 keys which are either of \"word\" or \"symbol\"
386 syntax. Triggering after
390 will, according to the \"w\" element first try \"bar\". If that
391 isn't a trigger key, \"foo-bar\" is tried, respecting a second
394 (defvar yas-after-exit-snippet-hook
396 "Hooks to run after a snippet exited.
398 The hooks will be run in an environment where some variables bound to
401 `yas-snippet-beg' : The beginning of the region of the snippet.
403 `yas-snippet-end' : Similar to beg.
405 Attention: These hooks are not run when exiting nested/stacked snippet expansion!")
407 (defvar yas-before-expand-snippet-hook
409 "Hooks to run just before expanding a snippet.")
411 (defvar yas-buffer-local-condition
412 '(if (and (or (fourth (syntax-ppss))
413 (fifth (syntax-ppss)))
414 (eq (symbol-function this-command) 'yas-expand-from-trigger-key))
415 '(require-snippet-condition . force-in-comment)
417 "Snippet expanding condition.
419 This variable is a Lisp form which is evaluated every time a
420 snippet expansion is attempted:
422 * If it evaluates to nil, no snippets can be expanded.
424 * If it evaluates to the a cons (require-snippet-condition
427 * Snippets bearing no \"# condition:\" directive are not
430 * Snippets bearing conditions that evaluate to nil (or
431 produce an error) won't be considered.
433 * If the snippet has a condition that evaluates to non-nil
436 * If REQUIREMENT is t, the snippet is considered
438 * If REQUIREMENT is `eq' RESULT, the snippet is
441 * Otherwise, the snippet is not considered.
443 * If it evaluates to the symbol 'always, all snippets are
444 considered for expansion, regardless of any conditions.
446 * If it evaluates to t or some other non-nil value
448 * Snippet bearing no conditions, or conditions that
449 evaluate to non-nil, are considered for expansion.
451 * Otherwise, the snippet is not considered.
453 Here's an example preventing snippets from being expanded from
454 inside comments, in `python-mode' only, with the exception of
455 snippets returning the symbol 'force-in-comment in their
458 (add-hook 'python-mode-hook
460 (setq yas-buffer-local-condition
461 '(if (python-in-string/comment)
462 '(require-snippet-condition . force-in-comment)
465 The default value is similar, it filters out potential snippet
466 expansions inside comments and string literals, unless the
467 snippet itself contains a condition that returns the symbol
468 `force-in-comment'.")
471 ;;; Internal variables
473 (defvar yas--version "0.8.0 (beta)")
475 (defvar yas--menu-table (make-hash-table)
476 "A hash table of MAJOR-MODE symbols to menu keymaps.")
478 (defvar yas--known-modes
479 '(ruby-mode rst-mode markdown-mode)
480 "A list of mode which is well known but not part of Emacs.")
482 (defvar yas--escaped-characters
483 '(?\\ ?` ?\" ?' ?$ ?} ?{ ?\( ?\))
484 "List of characters which *might* need to be escaped.")
486 (defconst yas--field-regexp
487 "${\\([0-9]+:\\)?\\([^}]*\\)}"
488 "A regexp to *almost* recognize a field.")
490 (defconst yas--multi-dollar-lisp-expression-regexp
491 "$+[ \t\n]*\\(([^)]*)\\)"
492 "A regexp to *almost* recognize a \"$(...)\" expression.")
494 (defconst yas--backquote-lisp-expression-regexp
496 "A regexp to recognize a \"`lisp-expression`\" expression." )
498 (defconst yas--transform-mirror-regexp
499 "${\\(?:\\([0-9]+\\):\\)?$\\([ \t\n]*([^}]*\\)"
500 "A regexp to *almost* recognize a mirror with a transform.")
502 (defconst yas--simple-mirror-regexp
504 "A regexp to recognize a simple mirror.")
506 (defvar yas--snippet-id-seed 0
507 "Contains the next id for a snippet.")
509 (defun yas--snippet-next-id ()
510 (let ((id yas--snippet-id-seed))
511 (incf yas--snippet-id-seed)
517 ;; XXX: `last-buffer-undo-list' is somehow needed in Carbon Emacs for MacOSX
518 (defvar last-buffer-undo-list nil)
520 (defvar yas--minor-mode-menu nil
521 "Holds the YASnippet menu.")
523 (defun yas--init-minor-keymap ()
524 "Set up the `yas-minor-mode' keymap."
525 (let ((map (make-sparse-keymap)))
527 (easy-menu-define yas--minor-mode-menu
529 "Menu used when `yas-minor-mode' is active."
532 ["Expand trigger" yas-expand
533 :help "Possibly expand tab trigger before point"]
534 ["Insert at point..." yas-insert-snippet
535 :help "Prompt for an expandable snippet and expand it at point"]
536 ["New snippet..." yas-new-snippet
537 :help "Create a new snippet in an appropriate directory"]
538 ["Visit snippet file..." yas-visit-snippet-file
539 :help "Prompt for an expandable snippet and find its file"]
541 ("Snippet menu behaviour"
542 ["Visit snippets" (setq yas-visit-from-menu t)
543 :help "Visit snippets from the menu"
544 :active t :style radio :selected yas-visit-from-menu]
545 ["Expand snippets" (setq yas-visit-from-menu nil)
546 :help "Expand snippets from the menu"
547 :active t :style radio :selected (not yas-visit-from-menu)]
549 ["Show all known modes" (setq yas-use-menu 'full)
550 :help "Show one snippet submenu for each loaded table"
551 :active t :style radio :selected (eq yas-use-menu 'full)]
552 ["Abbreviate according to current mode" (setq yas-use-menu 'abbreviate)
553 :help "Show only snippet submenus for the current active modes"
554 :active t :style radio :selected (eq yas-use-menu 'abbreviate)])
556 ["Auto" (setq yas-indent-line 'auto)
557 :help "Indent each line of the snippet with `indent-according-to-mode'"
558 :active t :style radio :selected (eq yas-indent-line 'auto)]
559 ["Fixed" (setq yas-indent-line 'fixed)
560 :help "Indent the snippet to the current column"
561 :active t :style radio :selected (eq yas-indent-line 'fixed)]
562 ["None" (setq yas-indent-line 'none)
563 :help "Don't apply any particular snippet indentation after expansion"
564 :active t :style radio :selected (not (member yas-indent-line '(fixed auto)))]
566 ["Also auto indent first line" (setq yas-also-auto-indent-first-line
567 (not yas-also-auto-indent-first-line))
568 :help "When auto-indenting also, auto indent the first line menu"
569 :active (eq yas-indent-line 'auto)
570 :style toggle :selected yas-also-auto-indent-first-line]
573 ["System X-widget" (setq yas-prompt-functions
575 (remove 'yas-x-prompt
576 yas-prompt-functions)))
577 :help "Use your windowing system's (gtk, mac, windows, etc...) default menu"
578 :active t :style radio :selected (eq (car yas-prompt-functions)
580 ["Dropdown-list" (setq yas-prompt-functions
581 (cons 'yas-dropdown-prompt
582 (remove 'yas-dropdown-prompt
583 yas-prompt-functions)))
584 :help "Use a special dropdown list"
585 :active t :style radio :selected (eq (car yas-prompt-functions)
586 'yas-dropdown-prompt)]
587 ["Ido" (setq yas-prompt-functions
588 (cons 'yas-ido-prompt
589 (remove 'yas-ido-prompt
590 yas-prompt-functions)))
591 :help "Use an ido-style minibuffer prompt"
592 :active t :style radio :selected (eq (car yas-prompt-functions)
594 ["Completing read" (setq yas-prompt-functions
595 (cons 'yas-completing-prompt
596 (remove 'yas-completing-prompt
597 yas-prompt-functions)))
598 :help "Use a normal minibuffer prompt"
599 :active t :style radio :selected (eq (car yas-prompt-functions)
600 'yas-completing-prompt)]
603 ["Wrap region in exit marker"
604 (setq yas-wrap-around-region
605 (not yas-wrap-around-region))
606 :help "If non-nil automatically wrap the selected text in the $0 snippet exit"
607 :style toggle :selected yas-wrap-around-region]
608 ["Allow stacked expansions "
609 (setq yas-triggers-in-field
610 (not yas-triggers-in-field))
611 :help "If non-nil allow snippets to be triggered inside other snippet fields"
612 :style toggle :selected yas-triggers-in-field]
613 ["Revive snippets on undo "
614 (setq yas-snippet-revival
615 (not yas-snippet-revival))
616 :help "If non-nil allow snippets to become active again after undo"
617 :style toggle :selected yas-snippet-revival]
620 (not yas-good-grace))
621 :help "If non-nil don't raise errors in bad embedded elisp in snippets"
622 :style toggle :selected yas-good-grace]
625 ["Load snippets..." yas-load-directory
626 :help "Load snippets from a specific directory"]
627 ["Reload everything" yas-reload-all
628 :help "Cleanup stuff, reload snippets, rebuild menus"]
630 :help "Display some information about YASnippet"])))
632 ;; Now for the stuff that has direct keybindings
634 (define-key map [(tab)] 'yas-expand)
635 (define-key map (kbd "TAB") 'yas-expand)
636 (define-key map "\C-c&\C-s" 'yas-insert-snippet)
637 (define-key map "\C-c&\C-n" 'yas-new-snippet)
638 (define-key map "\C-c&\C-v" 'yas-visit-snippet-file)
641 (defvar yas-minor-mode-map (yas--init-minor-keymap)
642 "The keymap used when `yas-minor-mode' is active.")
644 (defvar yas--tables (make-hash-table)
645 "A hash table of mode symbols to `yas--table' objects.")
647 (defvar yas--parents (make-hash-table)
648 "A hash table of mode symbols do lists of direct parent mode symbols.
650 This list is populated when reading the \".yas-parents\" files
651 found when traversing snippet directories with
652 `yas-load-directory'.
654 There might be additional parenting information stored in the
655 `derived-mode-parent' property of some mode symbols, but that is
658 (defvar yas--direct-keymaps (list)
659 "Keymap alist supporting direct snippet keybindings.
661 This variable is placed in `emulation-mode-map-alists'.
663 Its elements looks like (TABLE-NAME . KEYMAP). They're
664 instantiated on `yas-reload-all' but KEYMAP is added to only when
665 loading snippets. `yas--direct-TABLE-NAME' is then a variable set
666 buffer-locally when entering `yas-minor-mode'. KEYMAP binds all
667 defined direct keybindings to the command
668 `yas-expand-from-keymap' which then which snippet to expand.")
670 (defun yas-direct-keymaps-reload ()
671 "Force reload the direct keybinding for active snippet tables."
673 (setq yas--direct-keymaps nil)
674 (maphash #'(lambda (name table)
675 (push (cons (intern (format "yas--direct-%s" name))
676 (yas--table-direct-keymap table))
677 yas--direct-keymaps))
680 (defun yas--modes-to-activate ()
681 "Compute list of mode symbols that are active for `yas-expand'
683 (let ((modes-to-activate (list major-mode))
685 (while (setq mode (get mode 'derived-mode-parent))
686 (push mode modes-to-activate))
687 (dolist (mode (yas-extra-modes))
688 (push mode modes-to-activate))
690 (append modes-to-activate
691 (mapcan #'(lambda (mode)
692 (yas--all-parents mode))
693 modes-to-activate)))))
695 (defvar yas-minor-mode-hook nil
696 "Hook run when `yas-minor-mode' is turned on.")
699 (define-minor-mode yas-minor-mode
700 "Toggle YASnippet mode.
702 When YASnippet mode is enabled, `yas-expand', normally bound to
703 the TAB key, expands snippets of code depending on the major
706 With no argument, this command toggles the mode.
707 positive prefix argument turns on the mode.
708 Negative prefix argument turns off the mode.
711 \\{yas-minor-mode-map}"
713 ;; The indicator for the mode line.
716 (cond (yas-minor-mode
717 ;; Install the direct keymaps in `emulation-mode-map-alists'
718 ;; (we use `add-hook' even though it's not technically a hook,
719 ;; but it works). Then define variables named after modes to
720 ;; index `yas--direct-keymaps'.
722 ;; Also install the post-command-hook.
724 (add-hook 'emulation-mode-map-alists 'yas--direct-keymaps)
725 (add-hook 'post-command-hook 'yas--post-command-handler nil t)
726 ;; Set the `yas--direct-%s' vars for direct keymap expansion
728 (dolist (mode (yas--modes-to-activate))
729 (let ((name (intern (format "yas--direct-%s" mode))))
730 (set-default name nil)
731 (set (make-local-variable name) t)))
734 (yas--load-pending-jits))
736 ;; Uninstall the direct keymaps and the post-command hook
738 (remove-hook 'post-command-hook 'yas--post-command-handler t)
739 (remove-hook 'emulation-mode-map-alists 'yas--direct-keymaps))))
741 (defvar yas-dont-activate '(minibufferp)
742 "If non-nil don't let `yas-minor-mode-on' activate for this buffer.
744 If a function, then its result is used.
746 If a list of functions, then all functions must return nil to
747 activate yas for this buffer.
749 `yas-minor-mode-on' is usually called by `yas-global-mode' so
750 this effectively lets you define exceptions to the \"global\"
751 behaviour. Can also be a function of zero arguments.")
752 (make-variable-buffer-local 'yas-dont-activate)
754 (defun yas-minor-mode-on ()
755 "Turn on YASnippet minor mode.
757 Honour `yas-dont-activate', which see."
759 ;; Check `yas-dont-activate'
760 (unless (cond ((functionp yas-dont-activate)
761 (funcall yas-dont-activate))
762 ((consp yas-dont-activate)
763 (some #'funcall yas-dont-activate))
768 (define-globalized-minor-mode yas-global-mode yas-minor-mode yas-minor-mode-on
772 (defun yas--global-mode-reload-with-jit-maybe ()
773 "Run `yas-reload-all' when `yas-global-mode' is on."
774 (when yas-global-mode (yas-reload-all)))
776 (add-hook 'yas-global-mode-hook 'yas--global-mode-reload-with-jit-maybe)
778 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
781 (defvar yas--font-lock-keywords
782 (append '(("^#.*$" . font-lock-comment-face))
783 lisp-font-lock-keywords
784 lisp-font-lock-keywords-1
785 lisp-font-lock-keywords-2
787 (0 font-lock-keyword-face)
788 (1 font-lock-string-face t))
790 (0 font-lock-keyword-face)
791 (1 font-lock-warning-face t))
792 ("${" font-lock-keyword-face)
793 ("$[0-9]+?" font-lock-preprocessor-face)
794 ("\\(\\$(\\)" 1 font-lock-preprocessor-face)
796 (0 font-lock-keyword-face)))))
798 (defun yas--init-major-keymap ()
799 "Setup YASnippet major-mode keymap."
800 (let ((map (make-sparse-keymap)))
801 (easy-menu-define nil
803 "Menu used when snippet-mode is active."
805 (mapcar #'(lambda (ent)
807 (define-key map (third ent) (second ent)))
808 (vector (first ent) (second ent) t))
810 (list "Load this snippet" 'yas-load-snippet-buffer "\C-c\C-c")
811 (list "Try out this snippet" 'yas-tryout-snippet "\C-c\C-t")))))
814 (defvar snippet-mode-map
815 (yas--init-major-keymap)
816 "The keymap used when `snippet-mode' is active.")
819 (define-derived-mode snippet-mode text-mode "Snippet"
820 "A mode for editing yasnippets"
821 (setq font-lock-defaults '(yas--font-lock-keywords))
822 (set (make-local-variable 'require-final-newline) nil)
823 (set (make-local-variable 'comment-start) "#")
824 (set (make-local-variable 'comment-start-skip) "#+[\t ]*"))
828 ;;; Internal structs for template management
830 (defstruct (yas--template (:constructor yas--make-blank-template))
831 "A template for a snippet."
841 group ;; as dictated by the #group: directive or .yas-make-groups
842 perm-group ;; as dictated by `yas-define-menu'
846 (defun yas--populate-template (template &rest args)
847 "Helper function to populate TEMPLATE with properties."
851 (position (intern (substring (symbol-name (car args)) 1))
852 (mapcar #'car (get 'yas--template 'cl-struct-slots)))
854 (setq args (cddr args)))
857 (defstruct (yas--table (:constructor yas--make-snippet-table (name)))
858 "A table to store snippets for a particular mode.
860 Has the following fields:
864 A symbol name normally corresponding to a major mode, but can
865 also be a pseudo major-mode to be referenced in
866 `yas-extra-modes', for example.
870 A hash table (KEY . NAMEHASH), known as the \"keyhash\". KEY is
871 a string or a vector, where the former is the snippet's trigger
872 and the latter means it's a direct keybinding. NAMEHASH is yet
873 another hash of (NAME . TEMPLATE) where NAME is the snippet's
874 name and TEMPLATE is a `yas--template' object.
876 `yas--table-direct-keymap'
878 A keymap for the snippets in this table that have direct
879 keybindings. This is kept in sync with the keyhash, i.e., all
880 the elements of the keyhash that are vectors appear here as
881 bindings to `yas-expand-from-keymap'.
883 `yas--table-uuidhash'
885 A hash table mapping snippets uuid's to the same `yas--template'
886 objects. A snippet uuid defaults to the snippet's name.
889 (hash (make-hash-table :test 'equal))
890 (uuidhash (make-hash-table :test 'equal))
892 (direct-keymap (make-sparse-keymap)))
894 (defun yas--get-template-by-uuid (mode uuid)
895 "Find the snippet template in MODE by its UUID."
896 (let* ((table (gethash mode yas--tables mode)))
898 (gethash uuid (yas--table-uuidhash table)))))
900 ;; Apropos storing/updating in TABLE, this works in two steps:
902 ;; 1. `yas--remove-template-by-uuid' removes any
903 ;; keyhash-namehash-template mappings from TABLE, grabbing the
904 ;; snippet by its uuid. Also removes mappings from TABLE's
905 ;; `yas--table-direct-keymap' (FIXME: and should probably take care
906 ;; of potentially stale menu bindings right?.)
908 ;; 2. `yas--add-template' adds this all over again.
910 ;; Create a new or add to an existing keyhash-namehash mapping.
912 ;; For reference on understanding this, consider three snippet
915 ;; A: # name: The Foo
917 ;; # binding: C-c M-l
919 ;; B: # name: Mrs Foo
922 ;; C: # name: The Bar
923 ;; # binding: C-c M-l
928 ;; keyhash namehashes(3) yas--template structs(4)
929 ;; -----------------------------------------------------
932 ;; "foo" ---> "The Foo" ---> [yas--template A] |
933 ;; "Mrs Foo" ---> [yas--template B] |
935 ;; [C-c M-l] ---> "The Foo" -------------------------/
936 ;; "The Bar" ---> [yas--template C]
938 ;; "baz" ---> "Baz" ---> [yas--template D]
940 ;; Additionally, since uuid defaults to the name, we have a
941 ;; `yas--table-uuidhash' for TABLE
943 ;; uuidhash yas--template structs
944 ;; -------------------------------
945 ;; "The Foo" ---> [yas--template A]
946 ;; "Mrs Foo" ---> [yas--template B]
947 ;; "The Bar" ---> [yas--template C]
948 ;; "Baz" ---> [yas--template D]
950 ;; FIXME: the more I look at this data-structure the more I think I'm
951 ;; stupid. There has to be an easier way (but beware lots of code
954 (defun yas--remove-template-by-uuid (table uuid)
955 "Remove from TABLE a template identified by UUID."
956 (let ((template (gethash uuid (yas--table-uuidhash table))))
958 (let* ((name (yas--template-name template))
960 ;; Remove the name from each of the targeted namehashes
962 (maphash #'(lambda (k v)
963 (let ((template (gethash name v)))
965 (eq uuid (yas--template-uuid template)))
967 (when (zerop (hash-table-count v))
968 (push k empty-keys)))))
969 (yas--table-hash table))
970 ;; Remove the namehash themselves if they've become empty
972 (dolist (key empty-keys)
974 (define-key (yas--table-direct-keymap table) key nil))
975 (remhash key (yas--table-hash table)))
977 ;; Finally, remove the uuid from the uuidhash
979 (remhash uuid (yas--table-uuidhash table))))))
981 (defun yas--add-template (table template)
982 "Store in TABLE the snippet template TEMPLATE.
984 KEY can be a string (trigger key) of a vector (direct
986 (let ((name (yas--template-name template))
987 (key (yas--template-key template))
988 (keybinding (yas--template-keybinding template))
989 (menu-binding-pair (yas--template-menu-binding-pair-get-create template)))
990 (dolist (k (remove nil (list key keybinding)))
994 (yas--table-hash table))
996 (make-hash-table :test 'equal)
997 (yas--table-hash table))))
999 (define-key (yas--table-direct-keymap table) k 'yas-expand-from-keymap)))
1001 ;; Update TABLE's `yas--table-uuidhash'
1002 (puthash (yas--template-uuid template)
1004 (yas--table-uuidhash table))))
1006 (defun yas--update-template (table template)
1007 "Add or update TEMPLATE in TABLE.
1009 Also takes care of adding and updating to the associated menu."
1010 ;; Remove from table by uuid
1012 (yas--remove-template-by-uuid table (yas--template-uuid template))
1013 ;; Add to table again
1015 (yas--add-template table template)
1016 ;; Take care of the menu
1019 (yas--update-template-menu table template)))
1021 (defun yas--update-template-menu (table template)
1022 "Update every menu-related for TEMPLATE."
1023 (let ((menu-binding-pair (yas--template-menu-binding-pair-get-create template))
1024 (key (yas--template-key template))
1025 (keybinding (yas--template-keybinding template)))
1026 ;; The snippet might have changed name or keys, so update
1027 ;; user-visible strings
1029 (unless (eq (cdr menu-binding-pair) :none)
1030 ;; the menu item name
1032 (setf (cadar menu-binding-pair) (yas--template-name template))
1033 ;; the :keys information (also visible to the user)
1034 (setf (getf (cdr (car menu-binding-pair)) :keys)
1035 (or (and keybinding (key-description keybinding))
1036 (and key (concat key yas-trigger-symbol))))))
1037 (unless (yas--template-menu-managed-by-yas-define-menu template)
1039 (yas--menu-keymap-get-create (yas--table-mode table)
1040 (mapcar #'yas--table-mode
1041 (yas--table-parents table))))
1042 (group (yas--template-group template)))
1043 ;; Remove from menu keymap
1045 (assert menu-keymap)
1046 (yas--delete-from-keymap menu-keymap (yas--template-uuid template))
1048 ;; Add necessary subgroups as necessary.
1050 (dolist (subgroup group)
1051 (let ((subgroup-keymap (lookup-key menu-keymap (vector (make-symbol subgroup)))))
1052 (unless (and subgroup-keymap
1053 (keymapp subgroup-keymap))
1054 (setq subgroup-keymap (make-sparse-keymap))
1055 (define-key menu-keymap (vector (make-symbol subgroup))
1056 `(menu-item ,subgroup ,subgroup-keymap)))
1057 (setq menu-keymap subgroup-keymap)))
1059 ;; Add this entry to the keymap
1061 (define-key menu-keymap
1062 (vector (make-symbol (yas--template-uuid template)))
1063 (car (yas--template-menu-binding-pair template))))))
1065 (defun yas--namehash-templates-alist (namehash)
1066 "Return NAMEHASH as an alist."
1068 (maphash #'(lambda (k v)
1069 (push (cons k v) alist))
1073 (defun yas--fetch (table key)
1074 "Fetch templates in TABLE by KEY.
1076 Return a list of cons (NAME . TEMPLATE) where NAME is a
1077 string and TEMPLATE is a `yas--template' structure."
1078 (let* ((keyhash (yas--table-hash table))
1079 (namehash (and keyhash (gethash key keyhash))))
1081 (yas--filter-templates-by-condition (yas--namehash-templates-alist namehash)))))
1084 ;;; Filtering/condition logic
1086 (defun yas--eval-condition (condition)
1093 (yas--message 1 "Error in condition evaluation: %s" (error-message-string err))
1097 (defun yas--filter-templates-by-condition (templates)
1098 "Filter the templates using the applicable condition.
1100 TEMPLATES is a list of cons (NAME . TEMPLATE) where NAME is a
1101 string and TEMPLATE is a `yas--template' structure.
1103 This function implements the rules described in
1104 `yas-buffer-local-condition'. See that variables documentation."
1105 (let ((requirement (yas--require-template-specific-condition-p)))
1106 (if (eq requirement 'always)
1108 (remove-if-not #'(lambda (pair)
1109 (yas--template-can-expand-p
1110 (yas--template-condition (cdr pair)) requirement))
1113 (defun yas--require-template-specific-condition-p ()
1114 "Decides if this buffer requests/requires snippet-specific
1115 conditions to filter out potential expansions."
1116 (if (eq 'always yas-buffer-local-condition)
1118 (let ((local-condition (or (and (consp yas-buffer-local-condition)
1119 (yas--eval-condition yas-buffer-local-condition))
1120 yas-buffer-local-condition)))
1121 (when local-condition
1122 (if (eq local-condition t)
1124 (and (consp local-condition)
1125 (eq 'require-snippet-condition (car local-condition))
1126 (symbolp (cdr local-condition))
1127 (cdr local-condition)))))))
1129 (defun yas--template-can-expand-p (condition requirement)
1130 "Evaluates CONDITION and REQUIREMENT and returns a boolean."
1131 (let* ((result (or (null condition)
1132 (yas--eval-condition condition))))
1133 (cond ((eq requirement t)
1136 (eq requirement result)))))
1138 (defun yas--all-parents (mode)
1139 "Returns a list of all parent modes of MODE."
1140 (let ((parents (gethash mode yas--parents)))
1142 (mapcan #'yas--all-parents parents))))
1144 (defun yas--table-templates (table)
1147 (maphash #'(lambda (key namehash)
1148 (maphash #'(lambda (name template)
1149 (push (cons name template) acc))
1151 (yas--table-hash table))
1152 (yas--filter-templates-by-condition acc))))
1154 (defun yas--current-key ()
1155 "Get the key under current position. A key is used to find
1156 the template of a snippet in the current snippet-table."
1157 (let ((start (point))
1159 (syntaxes yas-key-syntaxes)
1163 (while (and (not done) syntaxes)
1164 (setq syntax (car syntaxes))
1165 (setq syntaxes (cdr syntaxes))
1167 (skip-syntax-backward syntax)
1168 (setq start (point)))
1170 (mapcan #'(lambda (table)
1171 (yas--fetch table (buffer-substring-no-properties start end)))
1172 (yas--get-snippet-tables)))
1181 (defun yas--table-all-keys (table)
1182 "Get trigger keys of all active snippets in TABLE."
1184 (maphash #'(lambda (key namehash)
1185 (when (yas--filter-templates-by-condition (yas--namehash-templates-alist namehash))
1187 (yas--table-hash table))
1190 (defun yas--table-mode (table)
1191 (intern (yas--table-name table)))
1194 ;;; Internal functions:
1196 (defun yas--real-mode? (mode)
1197 "Try to find out if MODE is a real mode.
1199 The MODE bound to a function (like `c-mode') is considered real
1200 mode. Other well known mode like `ruby-mode' which is not part of
1201 Emacs might not bound to a function until it is loaded. So
1202 yasnippet keeps a list of modes like this to help the judgment."
1204 (find mode yas--known-modes)))
1206 (defun yas--eval-lisp (form)
1207 "Evaluate FORM and convert the result to string."
1208 (let ((retval (catch 'yas--exception
1214 (let ((result (eval form)))
1216 (format "%s" result))))))
1217 (error (if yas-good-grace
1218 (yas--format "elisp error! %s" (error-message-string err))
1219 (error (yas--format "elisp error: %s"
1220 (error-message-string err)))))))))
1221 (when (and (consp retval)
1222 (eq 'yas--exception (car retval)))
1223 (error (cdr retval)))
1226 (defun yas--eval-lisp-no-saves (form)
1229 (error (if yas-good-grace
1230 (yas--format "elisp error! %s" (error-message-string err))
1231 (error (yas--format "elisp error: %s"
1232 (error-message-string err)))))))
1234 (defun yas--read-lisp (string &optional nil-on-error)
1235 "Read STRING as a elisp expression and return it.
1237 In case STRING in an invalid expression and NIL-ON-ERROR is nil,
1238 return an expression that when evaluated will issue an error."
1241 (error (and (not nil-on-error)
1242 `(error (error-message-string ,err))))))
1244 (defun yas--read-keybinding (keybinding)
1245 "Read KEYBINDING as a snippet keybinding, return a vector."
1246 (when (and keybinding
1247 (not (string-match "keybinding" keybinding)))
1249 (let ((res (or (and (string-match "^\\[.*\\]$" keybinding)
1251 (read-kbd-macro keybinding 'need-vector))))
1254 (yas--message 3 "warning: keybinding \"%s\" invalid since %s."
1255 keybinding (error-message-string err))
1258 (defvar yas-extra-modes nil
1259 "If non-nil, also lookup snippets for this/these modes.
1261 Can be a symbol or a list of symbols.
1263 This variable probably makes more sense as buffer-local, so
1264 ensure your use `make-local-variable' when you set it.")
1265 (defun yas-extra-modes ()
1266 (if (listp yas-extra-modes) yas-extra-modes (list yas-extra-modes)))
1267 (defvaralias 'yas/mode-symbol 'yas-extra-modes)
1269 (defun yas--table-get-create (mode)
1270 "Get or create the snippet table corresponding to MODE."
1271 (let ((table (gethash mode
1274 (setq table (yas--make-snippet-table (symbol-name mode)))
1275 (puthash mode table yas--tables)
1276 (push (cons (intern (format "yas--direct-%s" mode))
1277 (yas--table-direct-keymap table))
1278 yas--direct-keymaps))
1281 (defun yas--get-snippet-tables ()
1282 "Get snippet tables for current buffer.
1284 Return a list of `yas--table' objects. The list of modes to
1285 consider is returned by `yas--modes-to-activate'"
1287 (mapcar #'(lambda (mode-name)
1288 (gethash mode-name yas--tables))
1289 (yas--modes-to-activate))))
1291 (defun yas--menu-keymap-get-create (mode &optional parents)
1292 "Get or create the menu keymap for MODE and its PARENTS.
1294 This may very well create a plethora of menu keymaps and arrange
1295 them all in `yas--menu-table'"
1296 (let* ((menu-keymap (or (gethash mode yas--menu-table)
1297 (puthash mode (make-sparse-keymap) yas--menu-table))))
1298 (mapc #'yas--menu-keymap-get-create parents)
1299 (define-key yas--minor-mode-menu (vector mode)
1300 `(menu-item ,(symbol-name mode) ,menu-keymap
1301 :visible (yas--show-menu-p ',mode)))
1304 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1305 ;;; Template-related and snippet loading functions
1307 (defun yas--parse-template (&optional file)
1308 "Parse the template in the current buffer.
1310 Optional FILE is the absolute file name of the file being
1313 Optional GROUP is the group where the template is to go,
1314 otherwise we attempt to calculate it from FILE.
1316 Return a snippet-definition, i.e. a list
1318 (KEY TEMPLATE NAME CONDITION GROUP VARS FILE KEYBINDING UUID)
1320 If the buffer contains a line of \"# --\" then the contents above
1321 this line are ignored. Directives can set most of these with the syntax:
1323 # directive-name : directive-value
1325 Here's a list of currently recognized directives:
1336 (goto-char (point-min))
1337 (let* ((type 'snippet)
1339 (file-name-nondirectory file)))
1345 (yas--calculate-group file)))
1349 (if (re-search-forward "^# --\n" nil t)
1350 (progn (setq template
1351 (buffer-substring-no-properties (point)
1353 (setq bound (point))
1354 (goto-char (point-min))
1355 (while (re-search-forward "^# *\\([^ ]+?\\) *: *\\(.*\\)$" bound t)
1356 (when (string= "uuid" (match-string-no-properties 1))
1357 (setq uuid (match-string-no-properties 2)))
1358 (when (string= "type" (match-string-no-properties 1))
1359 (setq type (if (string= "command" (match-string-no-properties 2))
1362 (when (string= "key" (match-string-no-properties 1))
1363 (setq key (match-string-no-properties 2)))
1364 (when (string= "name" (match-string-no-properties 1))
1365 (setq name (match-string-no-properties 2)))
1366 (when (string= "condition" (match-string-no-properties 1))
1367 (setq condition (yas--read-lisp (match-string-no-properties 2))))
1368 (when (string= "group" (match-string-no-properties 1))
1369 (setq group (match-string-no-properties 2)))
1370 (when (string= "expand-env" (match-string-no-properties 1))
1371 (setq expand-env (yas--read-lisp (match-string-no-properties 2)
1373 (when (string= "binding" (match-string-no-properties 1))
1374 (setq binding (match-string-no-properties 2)))))
1376 (buffer-substring-no-properties (point-min) (point-max))))
1377 (unless (or key binding)
1378 (setq key (and file (file-name-nondirectory file))))
1379 (when (eq type 'command)
1380 (setq template (yas--read-lisp (concat "(progn" template ")"))))
1382 (setq group (split-string group "\\.")))
1383 (list key template name condition group expand-env file binding uuid)))
1385 (defun yas--calculate-group (file)
1386 "Calculate the group for snippet file path FILE."
1387 (let* ((dominating-dir (locate-dominating-file file
1388 ".yas-make-groups"))
1389 (extra-path (and dominating-dir
1390 (replace-regexp-in-string (concat "^"
1391 (expand-file-name dominating-dir))
1393 (expand-file-name file))))
1394 (extra-dir (and extra-path
1395 (file-name-directory extra-path)))
1396 (group (and extra-dir
1397 (replace-regexp-in-string "/"
1399 (directory-file-name extra-dir)))))
1402 (defun yas--subdirs (directory &optional filep)
1403 "Return subdirs or files of DIRECTORY according to FILEP."
1404 (remove-if (lambda (file)
1405 (or (string-match "^\\."
1406 (file-name-nondirectory file))
1407 (string-match "^#.*#$"
1408 (file-name-nondirectory file))
1410 (file-name-nondirectory file))
1412 (file-directory-p file)
1413 (not (file-directory-p file)))))
1414 (directory-files directory t)))
1416 (defun yas--make-menu-binding (template)
1417 (let ((mode (yas--table-mode (yas--template-table template))))
1418 `(lambda () (interactive) (yas--expand-or-visit-from-menu ',mode ,(yas--template-uuid template)))))
1420 (defun yas--expand-or-visit-from-menu (mode uuid)
1421 (let* ((table (yas--table-get-create mode))
1422 (yas--current-template (and table
1423 (gethash uuid (yas--table-uuidhash table)))))
1424 (when yas--current-template
1425 (if yas-visit-from-menu
1426 (yas--visit-snippet-file-1 yas--current-template)
1427 (let ((where (if (region-active-p)
1428 (cons (region-beginning) (region-end))
1429 (cons (point) (point)))))
1430 (yas-expand-snippet (yas--template-content yas--current-template)
1433 (yas--template-expand-env yas--current-template)))))))
1435 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1436 ;; Popping up for keys and templates
1438 (defvar yas--x-pretty-prompt-templates nil
1439 "If non-nil, attempt to prompt for templates like TextMate.")
1442 (defun yas--prompt-for-template (templates &optional prompt)
1443 "Interactively choose a template from the list TEMPLATES.
1445 TEMPLATES is a list of `yas--template'.
1447 Optional PROMPT sets the prompt to use."
1450 (sort templates #'(lambda (t1 t2)
1451 (< (length (yas--template-name t1))
1452 (length (yas--template-name t2))))))
1453 (if yas--x-pretty-prompt-templates
1454 (yas--x-pretty-prompt-templates "Choose a snippet" templates)
1455 (some #'(lambda (fn)
1456 (funcall fn (or prompt "Choose a snippet: ")
1458 #'yas--template-name))
1459 yas-prompt-functions))))
1461 (defun yas--prompt-for-keys (keys &optional prompt)
1462 "Interactively choose a template key from the list KEYS.
1464 Optional PROMPT sets the prompt to use."
1466 (some #'(lambda (fn)
1467 (funcall fn (or prompt "Choose a snippet key: ") keys))
1468 yas-prompt-functions)))
1470 (defun yas--prompt-for-table (tables &optional prompt)
1471 "Interactively choose a table from the list TABLES.
1473 Optional PROMPT sets the prompt to use."
1475 (some #'(lambda (fn)
1476 (funcall fn (or prompt "Choose a snippet table: ")
1479 yas-prompt-functions)))
1481 (defun yas-x-prompt (prompt choices &optional display-fn)
1482 "Display choices in a x-window prompt."
1483 ;; FIXME: HACK: if we notice that one of the objects in choices is
1484 ;; actually a `yas--template', defer to `yas--x-prompt-pretty-templates'
1486 ;; This would be better implemented by passing CHOICES as a
1487 ;; structured tree rather than a list. Modifications would go as far
1488 ;; up as `yas--all-templates' I think.
1490 (when (and window-system choices)
1492 (let (menu d) ;; d for display
1494 (setq d (or (and display-fn (funcall display-fn c))
1497 (push (cons (concat " " d) c) menu))
1499 (push (car d) menu))))
1500 (setq menu (list prompt (push "title" menu)))
1501 (x-popup-menu (if (fboundp 'posn-at-point)
1502 (let ((x-y (posn-x-y (posn-at-point (point)))))
1503 (list (list (+ (car x-y) 10)
1511 (defun yas--x-pretty-prompt-templates (prompt templates)
1512 "Display TEMPLATES, grouping neatly by table name."
1513 (let ((organized (make-hash-table :test #'equal))
1517 (dolist (tl templates)
1518 (puthash (yas--template-table tl)
1520 (gethash (yas--template-table tl) organized))
1522 (setq more-than-one-table (> (hash-table-count organized) 1))
1523 (setq prefix (if more-than-one-table
1525 (if more-than-one-table
1526 (maphash #'(lambda (table templates)
1527 (push (yas--table-name table) menu)
1528 (dolist (tl templates)
1529 (push (cons (concat prefix (yas--template-name tl)) tl) menu))) organized)
1530 (setq menu (mapcar #'(lambda (tl) (cons (concat prefix (yas--template-name tl)) tl)) templates)))
1532 (setq menu (nreverse menu))
1533 (or (x-popup-menu (if (fboundp 'posn-at-point)
1534 (let ((x-y (posn-x-y (posn-at-point (point)))))
1535 (list (list (+ (car x-y) 10)
1539 (list prompt (push "title" menu)))
1542 (defun yas-ido-prompt (prompt choices &optional display-fn)
1543 (when (and (fboundp 'ido-completing-read)
1544 (or (>= emacs-major-version 24)
1546 (yas-completing-prompt prompt choices display-fn #'ido-completing-read)))
1548 (eval-when-compile (require 'dropdown-list nil t))
1549 (defun yas-dropdown-prompt (prompt choices &optional display-fn)
1550 (when (featurep 'dropdown-list)
1551 (let (formatted-choices
1555 (dolist (choice choices)
1556 (setq d (or (and display-fn (funcall display-fn choice))
1559 (push d formatted-choices)
1560 (push choice filtered-choices)))
1562 (setq n (and formatted-choices (dropdown-list formatted-choices)))
1564 (nth n filtered-choices)
1567 (defun yas-completing-prompt (prompt choices &optional display-fn completion-fn)
1568 (let (formatted-choices
1572 (completion-fn (or completion-fn
1573 #'completing-read)))
1574 (dolist (choice choices)
1575 (setq d (or (and display-fn (funcall display-fn choice))
1578 (push d formatted-choices)
1579 (push choice filtered-choices)))
1580 (setq chosen (and formatted-choices
1581 (funcall completion-fn prompt
1587 (let ((position (or (and chosen
1588 (position chosen formatted-choices :test #'string=))
1590 (nth position filtered-choices))))
1592 (defun yas-no-prompt (prompt choices &optional display-fn)
1595 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1596 ;; Loading snippets from files
1598 (defun yas--load-yas-setup-file (file)
1599 (load file 'noerror))
1601 (defun yas-load-directory (top-level-dir &optional use-jit)
1602 "Load snippets in directory hierarchy TOP-LEVEL-DIR.
1604 Below TOP-LEVEL-DIR each directory should be a mode name.
1606 Optional USE-JIT use jit-loading of snippets."
1607 (interactive "DSelect the root directory: ")
1608 (unless yas-snippet-dirs
1609 (setq yas-snippet-dirs top-level-dir))
1610 (dolist (dir (yas--subdirs top-level-dir))
1611 (let* ((major-mode-and-parents (yas--compute-major-mode-and-parents
1612 (concat dir "/dummy")))
1613 (mode-sym (car major-mode-and-parents))
1614 (parents (cdr major-mode-and-parents)))
1615 ;; Attention: The parents and the menus are already defined
1616 ;; here, even if the snippets are later jit-loaded.
1618 ;; * We need to know the parents at this point since entering a
1619 ;; given mode should jit load for its parents
1620 ;; immediately. This could be reviewed, the parents could be
1621 ;; discovered just-in-time-as well
1623 ;; * We need to create the menus here to support the `full'
1624 ;; option to `yas-use-menu' (all known snippet menus are shown to the user)
1626 (yas--define-parents mode-sym parents)
1627 (yas--menu-keymap-get-create mode-sym)
1628 (let ((form `(yas--load-directory-1 ,dir
1632 (yas--schedule-jit mode-sym form)
1634 (when (interactive-p)
1635 (yas--message 3 "Loaded snippets from %s." top-level-dir)))
1637 (defun yas--load-directory-1 (directory mode-sym parents &optional no-compiled-snippets)
1638 "Recursively load snippet templates from DIRECTORY."
1639 (unless (file-exists-p (concat directory "/" ".yas-skip"))
1640 (if (and (not no-compiled-snippets)
1641 (progn (yas--message 2 "Loading compiled snippets from %s" directory) t)
1642 (load (expand-file-name ".yas-compiled-snippets" directory) 'noerror (<= yas-verbosity 3)))
1643 (yas--message 2 "Loading snippet files from %s" directory)
1644 (yas--load-directory-2 directory mode-sym))))
1646 (defun yas--load-directory-2 (directory mode-sym)
1647 ;; Load .yas-setup.el files wherever we find them
1649 (yas--load-yas-setup-file (expand-file-name ".yas-setup" directory))
1650 (let* ((default-directory directory)
1652 ;; load the snippet files
1655 (dolist (file (yas--subdirs directory 'no-subdirs-just-files))
1656 (when (file-readable-p file)
1657 (insert-file-contents file nil nil nil t)
1658 (push (yas--parse-template file)
1661 (yas-define-snippets mode-sym
1663 ;; now recurse to a lower level
1665 (dolist (subdir (yas--subdirs directory))
1666 (yas--load-directory-2 subdir
1669 (defun yas--load-snippet-dirs (&optional nojit)
1670 "Reload the directories listed in `yas-snippet-dirs' or
1671 prompt the user to select one."
1673 (if yas-snippet-dirs
1674 (dolist (directory (reverse (yas-snippet-dirs)))
1675 (cond ((file-directory-p directory)
1676 (yas-load-directory directory (not nojit))
1678 (yas--message 3 "Loaded %s" directory)
1679 (yas--message 3 "Prepared just-in-time loading for %s" directory)))
1681 (push (yas--message 0 "Check your `yas-snippet-dirs': %s is not a directory" directory) errors))))
1682 (call-interactively 'yas-load-directory))
1685 (defun yas-reload-all (&optional interactive)
1686 "Reload all snippets and rebuild the YASnippet menu.
1688 When called interactively force immediate reload of all known
1689 snippets under `yas-snippet-dirs', otherwise use just-in-time
1694 (snippet-editing-buffers
1695 (remove-if-not #'(lambda (buffer)
1696 (with-current-buffer buffer yas--editing-template))
1698 ;; Warn if there are buffers visiting snippets, since reloading will break
1699 ;; any on-line editing of those buffers.
1701 (when snippet-editing-buffers
1703 (if (y-or-n-p "Some buffers editing live snippets, close them and proceed with reload? ")
1704 (mapc #'kill-buffer snippet-editing-buffers)
1705 (yas--message 1 "Aborted reload...")
1707 ;; in a non-interactive use, at least set
1708 ;; `yas--editing-template' to nil, make it guess it next time around
1709 (mapc #'(lambda (buffer) (setq yas--editing-template nil)) (buffer-list))))
1711 ;; Empty all snippet tables, parenting info and all menu tables
1713 (setq yas--tables (make-hash-table))
1714 (setq yas--parents (make-hash-table))
1715 (setq yas--menu-table (make-hash-table))
1717 ;; Cancel all pending 'yas--scheduled-jit-loads'
1719 (setq yas--scheduled-jit-loads (make-hash-table))
1721 ;; Init the `yas-minor-mode-map', taking care not to break the
1724 (setcdr yas-minor-mode-map (cdr (yas--init-minor-keymap)))
1726 ;; Reload the directories listed in `yas-snippet-dirs' or prompt
1727 ;; the user to select one.
1729 (setq errors (yas--load-snippet-dirs interactive))
1730 ;; Reload the direct keybindings
1732 (yas-direct-keymaps-reload)
1734 (yas--message 3 "Reloaded everything%s...%s."
1735 (if interactive "" " (snippets will load just-in-time)")
1736 (if errors " (some errors, check *Messages*)" "")))))
1738 (defun yas--load-pending-jits ()
1739 (when yas-minor-mode
1740 (dolist (mode (yas--modes-to-activate))
1741 (let ((forms (reverse (gethash mode yas--scheduled-jit-loads))))
1742 ;; must reverse to maintain coherence with `yas-snippet-dirs'
1743 (dolist (form forms)
1744 (yas--message 3 "Loading for `%s', just-in-time: %s!" mode form)
1746 (remhash mode yas--scheduled-jit-loads)))))
1748 ;; (when (<= emacs-major-version 22)
1749 ;; (add-hook 'after-change-major-mode-hook 'yas--load-pending-jits))
1751 (defun yas--quote-string (string)
1752 "Escape and quote STRING.
1753 foo\"bar\\! -> \"foo\\\"bar\\\\!\""
1755 (replace-regexp-in-string "[\\\"]"
1760 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1761 ;;; Snippet compilation function
1763 (defun yas--initialize ()
1764 "For backward compatibility, enable `yas-minor-mode' globally."
1765 (yas-global-mode 1))
1767 (defun yas-compile-directory (top-level-dir)
1768 "Create .yas-compiled-snippets.el files under subdirs of TOP-LEVEL-DIR.
1770 This works by stubbing a few functions, then calling
1771 `yas-load-directory'."
1772 (interactive "DTop level snippet directory?")
1773 (flet ((yas--load-yas-setup-file
1775 (let ((elfile (concat file ".el")))
1776 (when (file-exists-p elfile)
1777 (insert ";;; .yas-setup.el support file if any:\n;;;\n")
1778 (insert-file-contents elfile)
1779 (goto-char (point-max))
1781 (yas-define-snippets
1783 (insert ";;; Snippet definitions:\n;;;\n")
1784 (let ((literal-snippets (list))
1786 (dolist (snippet snippets)
1787 (let ((key (first snippet))
1788 (template-content (second snippet))
1789 (name (third snippet))
1790 (condition (fourth snippet))
1791 (group (fifth snippet))
1792 (expand-env (sixth snippet))
1793 (file nil) ;; (seventh snippet)) ;; omit on purpose
1794 (binding (eighth snippet))
1795 (uuid (ninth snippet)))
1806 (insert (pp-to-string `(yas-define-snippets ',mode ',literal-snippets)))
1808 (yas--load-directory-1
1809 (dir mode parents &rest ignore)
1810 (let ((output-file (concat (file-name-as-directory dir) ".yas-compiled-snippets.el")))
1811 (with-temp-file output-file
1812 (insert (format ";;; Compiled snippets and support files for `%s'\n" mode))
1813 (yas--load-directory-2 dir mode)
1814 (insert (format ";;; Do not edit! File generated at %s\n" (current-time-string)))))))
1815 (yas-load-directory top-level-dir nil)))
1817 (defun yas-recompile-all ()
1818 "Compile every dir in `yas-snippet-dirs'."
1820 (mapc #'yas-compile-directory (yas-snippet-dirs)))
1826 (defvar yas--scheduled-jit-loads (make-hash-table)
1827 "Alist of mode-symbols to forms to be evaled when `yas-minor-mode' kicks in.")
1829 (defun yas--schedule-jit (mode form)
1832 (gethash mode yas--scheduled-jit-loads))
1833 yas--scheduled-jit-loads))
1836 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1837 ;;; Some user level functions
1842 (message (concat "yasnippet (version "
1844 ") -- pluskid <pluskid@gmail.com>/joaotavora <joaotavora@gmail.com>")))
1846 (defun yas--define-parents (mode parents)
1847 "Add PARENTS to the list of MODE's parents."
1848 (puthash mode (remove-duplicates
1850 (gethash mode yas--parents)))
1853 (defun yas-define-snippets (mode snippets)
1854 "Define SNIPPETS for MODE.
1856 SNIPPETS is a list of snippet definitions, each taking the
1859 (KEY TEMPLATE NAME CONDITION GROUP EXPAND-ENV FILE KEYBINDING UUID)
1861 Within these, only KEY and TEMPLATE are actually mandatory.
1863 TEMPLATE might be a lisp form or a string, depending on whether
1864 this is a snippet or a snippet-command.
1866 CONDITION, EXPAND-ENV and KEYBINDING are lisp forms, they have
1867 been `yas--read-lisp'-ed and will eventually be
1868 `yas--eval-lisp'-ed.
1870 The remaining elements are strings.
1872 FILE is probably of very little use if you're programatically
1875 UUID is the snippets \"unique-id\". Loading a second snippet file
1876 with the same uuid replaced the previous snippet.
1878 You can use `yas--parse-template' to return such lists based on
1879 the current buffers contents."
1880 (let ((snippet-table (yas--table-get-create mode))
1882 (dolist (snippet snippets)
1883 (setq template (yas-define-snippets-1 snippet
1887 (defun yas-define-snippets-1 (snippet snippet-table)
1888 "Helper for `yas-define-snippets'."
1889 ;; X) Calculate some more defaults on the values returned by
1890 ;; `yas--parse-template'.
1892 (let* ((file (seventh snippet))
1894 (name (or (third snippet)
1896 (file-name-directory file))))
1897 (condition (fourth snippet))
1898 (group (fifth snippet))
1899 (keybinding (yas--read-keybinding (eighth snippet)))
1900 (uuid (or (ninth snippet)
1902 (template (or (gethash uuid (yas--table-uuidhash snippet-table))
1903 (yas--make-blank-template))))
1904 ;; X) populate the template object
1906 (yas--populate-template template
1907 :table snippet-table
1909 :content (second snippet)
1912 :condition condition
1913 :expand-env (sixth snippet)
1914 :file (seventh snippet)
1915 :keybinding keybinding
1917 ;; X) Update this template in the appropriate table. This step
1918 ;; also will take care of adding the key indicators in the
1919 ;; templates menu entry, if any
1921 (yas--update-template snippet-table template)
1922 ;; X) Return the template
1928 ;;; Apropos snippet menu:
1930 ;; The snippet menu keymaps are store by mode in hash table called
1931 ;; `yas--menu-table'. They are linked to the main menu in
1932 ;; `yas--menu-keymap-get-create' and are initially created empty,
1933 ;; reflecting the table hierarchy.
1935 ;; They can be populated in two mutually exclusive ways: (1) by
1936 ;; reading `yas--template-group', which in turn is populated by the "#
1937 ;; group:" directives of the snippets or the ".yas-make-groups" file
1938 ;; or (2) by using a separate `yas-define-menu' call, which declares a
1939 ;; menu structure based on snippets uuids.
1941 ;; Both situations are handled in `yas--update-template-menu', which
1942 ;; uses the predicate `yas--template-menu-managed-by-yas-define-menu'
1943 ;; that can tell between the two situations.
1947 ;; * if `yas-define-menu' is used it must run before
1948 ;; `yas-define-snippets' and the UUIDS must match, otherwise we get
1949 ;; duplicate entries. The `yas--template' objects are created in
1950 ;; `yas-define-menu', holding nothing but the menu entry,
1951 ;; represented by a pair of ((menu-item NAME :keys KEYS) TYPE) and
1952 ;; stored in `yas--template-menu-binding-pair'. The (menu-item ...)
1953 ;; part is then stored in the menu keymap itself which make the item
1954 ;; appear to the user. These limitations could probably be revised.
1956 ;; * The `yas--template-perm-group' slot is only used in
1957 ;; `yas-describe-tables'.
1959 (defun yas--template-menu-binding-pair-get-create (template &optional type)
1960 "Get TEMPLATE's menu binding or assign it a new one.
1962 TYPE may be `:stay', signaling this menu binding should be
1963 static in the menu."
1964 (or (yas--template-menu-binding-pair template)
1965 (let ((key (yas--template-key template))
1966 (keybinding (yas--template-keybinding template)))
1967 (setf (yas--template-menu-binding-pair template)
1968 (cons `(menu-item ,(or (yas--template-name template)
1969 (yas--template-uuid template))
1970 ,(yas--make-menu-binding template)
1973 (defun yas--template-menu-managed-by-yas-define-menu (template)
1974 "Non-nil if TEMPLATE's menu entry was included in a `yas-define-menu' call."
1975 (cdr (yas--template-menu-binding-pair template)))
1978 (defun yas--show-menu-p (mode)
1979 (cond ((eq yas-use-menu 'abbreviate)
1981 (mapcar #'(lambda (table)
1982 (yas--table-mode table))
1983 (yas--get-snippet-tables))))
1984 ((eq yas-use-menu 'full)
1986 ((eq yas-use-menu t)
1989 (defun yas--delete-from-keymap (keymap uuid)
1990 "Recursively delete items with UUID from KEYMAP and its submenus."
1992 ;; XXX: This used to skip any submenus named \"parent mode\"
1994 ;; First of all, recursively enter submenus, i.e. the tree is
1995 ;; searched depth first so that stale submenus can be found in the
1998 (mapc #'(lambda (item)
1999 (when (and (listp (cdr item))
2000 (keymapp (third (cdr item))))
2001 (yas--delete-from-keymap (third (cdr item)) uuid)))
2003 ;; Set the uuid entry to nil
2005 (define-key keymap (vector (make-symbol uuid)) nil)
2006 ;; Destructively modify keymap
2008 (setcdr keymap (delete-if #'(lambda (item)
2009 (or (null (cdr item))
2010 (and (keymapp (third (cdr item)))
2011 (null (cdr (third (cdr item)))))))
2014 (defun yas-define-menu (mode menu &optional omit-items)
2015 "Define a snippet menu for MODE according to MENU, omitting OMIT-ITEMS.
2017 MENU is a list, its elements can be:
2019 - (yas-item UUID) : Creates an entry the snippet identified with
2020 UUID. The menu entry for a snippet thus identified is
2021 permanent, i.e. it will never move (be reordered) in the menu.
2023 - (yas-separator) : Creates a separator
2025 - (yas-submenu NAME SUBMENU) : Creates a submenu with NAME,
2026 SUBMENU has the same form as MENU. NAME is also added to the
2027 list of groups of the snippets defined thereafter.
2029 OMIT-ITEMS is a list of snippet uuid's that will always be
2030 omitted from MODE's menu, even if they're manually loaded.
2032 This function does nothing if `yas-use-menu' is nil."
2034 (let* ((table (yas--table-get-create mode))
2035 (hash (yas--table-uuidhash table)))
2036 (yas--define-menu-1 table
2037 (yas--menu-keymap-get-create mode)
2040 (dolist (uuid omit-items)
2041 (let ((template (or (gethash uuid hash)
2042 (yas--populate-template (puthash uuid
2043 (yas--make-blank-template)
2047 (setf (yas--template-menu-binding-pair template) (cons nil :none)))))))
2049 (defun yas--define-menu-1 (table menu-keymap menu uuidhash &optional group-list)
2050 "Helper for `yas-define-menu'."
2051 (dolist (e (reverse menu))
2052 (cond ((eq (first e) 'yas-item)
2053 (let ((template (or (gethash (second e) uuidhash)
2054 (yas--populate-template (puthash (second e)
2055 (yas--make-blank-template)
2058 :perm-group group-list
2059 :uuid (second e)))))
2060 (define-key menu-keymap (vector (gensym))
2061 (car (yas--template-menu-binding-pair-get-create template :stay)))))
2062 ((eq (first e) 'yas-submenu)
2063 (let ((subkeymap (make-sparse-keymap)))
2064 (define-key menu-keymap (vector (gensym))
2065 `(menu-item ,(second e) ,subkeymap))
2066 (yas--define-menu-1 table
2070 (append group-list (list (second e))))))
2071 ((eq (first e) 'yas-separator)
2072 (define-key menu-keymap (vector (gensym))
2073 '(menu-item "----")))
2075 (yas--message 3 "Don't know anything about menu entry %s" (first e))))))
2077 (defun yas--define (mode key template &optional name condition group)
2078 "Define a snippet. Expanding KEY into TEMPLATE.
2080 NAME is a description to this template. Also update the menu if
2081 `yas-use-menu' is t. CONDITION is the condition attached to
2082 this snippet. If you attach a condition to a snippet, then it
2083 will only be expanded when the condition evaluated to non-nil."
2084 (yas-define-snippets mode
2085 (list (list key template name condition group))))
2087 (defun yas-hippie-try-expand (first-time?)
2088 "Integrate with hippie expand.
2090 Just put this function in `hippie-expand-try-functions-list'."
2091 (when yas-minor-mode
2092 (if (not first-time?)
2093 (let ((yas-fallback-behavior 'return-nil))
2099 ;;; Apropos condition-cache:
2104 (defvar yas--condition-cache-timestamp nil)
2105 (defmacro yas-define-condition-cache (func doc &rest body)
2106 "Define a function FUNC with doc DOC and body BODY, BODY is
2107 executed at most once every snippet expansion attempt, to check
2108 expansion conditions.
2110 It doesn't make any sense to call FUNC programatically."
2111 `(defun ,func () ,(if (and doc
2114 "\n\nFor use in snippets' conditions. Within each
2115 snippet-expansion routine like `yas-expand', computes actual
2116 value for the first time then always returns a cached value.")
2117 (setq body (cons doc body))
2119 (let ((timestamp-and-value (get ',func 'yas--condition-cache)))
2120 (if (equal (car timestamp-and-value) yas--condition-cache-timestamp)
2121 (cdr timestamp-and-value)
2122 (let ((new-value (progn
2125 (put ',func 'yas--condition-cache (cons yas--condition-cache-timestamp new-value))
2128 (defalias 'yas-expand 'yas-expand-from-trigger-key)
2129 (defun yas-expand-from-trigger-key (&optional field)
2130 "Expand a snippet before point.
2132 If no snippet expansion is possible, fall back to the behaviour
2133 defined in `yas-fallback-behavior'.
2135 Optional argument FIELD is for non-interactive use and is an
2136 object satisfying `yas--field-p' to restrict the expansion to."
2138 (setq yas--condition-cache-timestamp (current-time))
2139 (let (templates-and-pos)
2140 (unless (and yas-expand-only-for-last-commands
2141 (not (member last-command yas-expand-only-for-last-commands)))
2142 (setq templates-and-pos (if field
2144 (narrow-to-region (yas--field-start field)
2145 (yas--field-end field))
2147 (yas--current-key))))
2148 (if (and templates-and-pos
2149 (first templates-and-pos))
2150 (yas--expand-or-prompt-for-template (first templates-and-pos)
2151 (second templates-and-pos)
2152 (third templates-and-pos))
2153 (yas--fallback 'trigger-key))))
2155 (defun yas-expand-from-keymap ()
2156 "Directly expand some snippets, searching `yas--direct-keymaps'.
2158 If expansion fails, execute the previous binding for this key"
2160 (setq yas--condition-cache-timestamp (current-time))
2161 (let* ((yas--prefix current-prefix-arg)
2162 (vec (subseq (this-command-keys-vector) (if current-prefix-arg
2163 universal-argument-num-events
2165 (templates (mapcan #'(lambda (table)
2166 (yas--fetch table vec))
2167 (yas--get-snippet-tables))))
2169 (yas--expand-or-prompt-for-template templates)
2170 (let ((yas-fallback-behavior 'call-other-command))
2173 (defun yas--expand-or-prompt-for-template (templates &optional start end)
2174 "Expand one of TEMPLATES from START to END.
2176 Prompt the user if TEMPLATES has more than one element, else
2177 expand immediately. Common gateway for
2178 `yas-expand-from-trigger-key' and `yas-expand-from-keymap'."
2179 (let ((yas--current-template (or (and (rest templates) ;; more than one
2180 (yas--prompt-for-template (mapcar #'cdr templates)))
2182 (when yas--current-template
2183 (yas-expand-snippet (yas--template-content yas--current-template)
2186 (yas--template-expand-env yas--current-template)))))
2188 ;; Apropos the trigger key and the fallback binding:
2190 ;; When `yas-minor-mode-map' binds <tab>, that correctly overrides
2191 ;; org-mode's <tab>, for example and searching for fallbacks correctly
2192 ;; returns `org-cycle'. However, most other modes bind "TAB". TODO,
2193 ;; improve this explanation.
2195 (defun yas--fallback (&optional from-trigger-key-p)
2196 "Fallback after expansion has failed.
2198 Common gateway for `yas-expand-from-trigger-key' and
2199 `yas-expand-from-keymap'."
2200 (cond ((eq yas-fallback-behavior 'return-nil)
2203 ((eq yas-fallback-behavior 'call-other-command)
2204 (let* ((beyond-yasnippet (yas--keybinding-beyond-yasnippet)))
2205 (yas--message 4 "Falling back to %s" beyond-yasnippet)
2206 (assert (or (null beyond-yasnippet) (commandp beyond-yasnippet)))
2207 (setq this-original-command beyond-yasnippet)
2208 (call-interactively beyond-yasnippet)))
2209 ((and (listp yas-fallback-behavior)
2210 (cdr yas-fallback-behavior)
2211 (eq 'apply (car yas-fallback-behavior)))
2212 (if (cddr yas-fallback-behavior)
2213 (apply (cadr yas-fallback-behavior)
2214 (cddr yas-fallback-behavior))
2215 (when (commandp (cadr yas-fallback-behavior))
2216 (setq this-command (cadr yas-fallback-behavior))
2217 (call-interactively (cadr yas-fallback-behavior)))))
2219 ;; also return nil if all the other fallbacks have failed
2222 (defun yas--keybinding-beyond-yasnippet ()
2224 (let* ((yas-minor-mode nil)
2225 (yas--direct-keymaps nil)
2226 (keys (this-single-command-keys)))
2227 (or (key-binding keys t)
2228 (key-binding (yas--fallback-translate-input keys) t))))
2230 (defun yas--fallback-translate-input (keys)
2231 "Emulate `read-key-sequence', at least what I think it does.
2233 Keys should be an untranslated key vector. Returns a translated
2234 vector of keys. FIXME not thoroughly tested"
2237 (while (< i (length keys))
2239 (translated local-function-key-map))
2240 (while (and (< j (length keys))
2242 (keymapp translated))
2243 (setq translated (aget (remove 'keymap translated) (aref keys j))
2245 (setq retval (vconcat retval (cond ((symbolp translated)
2247 ((vectorp translated)
2250 (substring keys i j)))))
2255 ;;; Utils for snippet development:
2257 (defun yas--all-templates (tables)
2258 "Get `yas--template' objects in TABLES, applicable for buffer and point.
2260 Honours `yas-choose-tables-first', `yas-choose-keys-first' and
2261 `yas-buffer-local-condition'"
2262 (when yas-choose-tables-first
2263 (setq tables (list (yas--prompt-for-table tables))))
2265 (if yas-choose-keys-first
2266 (let ((key (yas--prompt-for-keys
2267 (mapcan #'yas--table-all-keys tables))))
2269 (mapcan #'(lambda (table)
2270 (yas--fetch table key))
2272 (remove-duplicates (mapcan #'yas--table-templates tables)
2275 (defun yas-insert-snippet (&optional no-condition)
2276 "Choose a snippet to expand, pop-up a list of choices according
2277 to `yas--prompt-function'.
2279 With prefix argument NO-CONDITION, bypass filtering of snippets
2282 (setq yas--condition-cache-timestamp (current-time))
2283 (let* ((yas-buffer-local-condition (or (and no-condition
2285 yas-buffer-local-condition))
2286 (templates (yas--all-templates (yas--get-snippet-tables)))
2287 (yas--current-template (and templates
2288 (or (and (rest templates) ;; more than one template for same key
2289 (yas--prompt-for-template templates))
2291 (where (if (region-active-p)
2292 (cons (region-beginning) (region-end))
2293 (cons (point) (point)))))
2294 (if yas--current-template
2295 (yas-expand-snippet (yas--template-content yas--current-template)
2298 (yas--template-expand-env yas--current-template))
2299 (yas--message 3 "No snippets can be inserted here!"))))
2301 (defun yas-visit-snippet-file ()
2302 "Choose a snippet to edit, selection like `yas-insert-snippet'.
2304 Only success if selected snippet was loaded from a file. Put the
2305 visited file in `snippet-mode'."
2307 (let* ((yas-buffer-local-condition 'always)
2308 (templates (yas--all-templates (yas--get-snippet-tables)))
2309 (yas-prompt-functions '(yas-ido-prompt yas-completing-prompt))
2310 (template (and templates
2311 (or (yas--prompt-for-template templates
2312 "Choose a snippet template to edit: ")
2316 (yas--visit-snippet-file-1 template)
2317 (message "No snippets tables active!"))))
2319 (defun yas--visit-snippet-file-1 (template)
2320 "Helper for `yas-visit-snippet-file'."
2321 (let ((file (yas--template-file template)))
2322 (cond ((and file (file-readable-p file))
2323 (find-file-other-window file)
2325 (set (make-local-variable 'yas--editing-template) template))
2327 (message "Original file %s no longer exists!" file))
2329 (switch-to-buffer (format "*%s*"(yas--template-name template)))
2330 (let ((type 'snippet))
2331 (when (listp (yas--template-content template))
2332 (insert (format "# type: command\n"))
2333 (setq type 'command))
2334 (insert (format "# key: %s\n" (yas--template-key template)))
2335 (insert (format "# name: %s\n" (yas--template-name template)))
2336 (when (yas--template-keybinding template)
2337 (insert (format "# binding: %s\n" (yas--template-keybinding template))))
2338 (when (yas--template-expand-env template)
2339 (insert (format "# expand-env: %s\n" (yas--template-expand-env template))))
2340 (when (yas--template-condition template)
2341 (insert (format "# condition: %s\n" (yas--template-condition template))))
2343 (insert (if (eq type 'command)
2344 (pp-to-string (yas--template-content template))
2345 (yas--template-content template))))
2347 (set (make-local-variable 'yas--editing-template) template)))))
2349 (defun yas--guess-snippet-directories-1 (table)
2350 "Guesses possible snippet subdirectories for TABLE."
2351 (cons (yas--table-name table)
2352 (mapcan #'(lambda (parent)
2353 (yas--guess-snippet-directories-1
2355 (yas--table-parents table))))
2357 (defun yas--guess-snippet-directories (&optional table)
2358 "Try to guess suitable directories based on the current active
2359 tables (or optional TABLE).
2361 Returns a list of elements (TABLE . DIRS) where TABLE is a
2362 `yas--table' object and DIRS is a list of all possible directories
2363 where snippets of table might exist."
2364 (let ((main-dir (replace-regexp-in-string
2366 (or (first (or (yas-snippet-dirs)
2367 (setq yas-snippet-dirs '("~/.emacs.d/snippets")))))))
2368 (tables (or (and table
2370 (yas--get-snippet-tables))))
2371 ;; HACK! the snippet table created here is actually registered!
2373 (unless (or table (gethash major-mode yas--tables))
2374 (push (yas--table-get-create major-mode)
2377 (mapcar #'(lambda (table)
2379 (mapcar #'(lambda (subdir)
2380 (concat main-dir "/" subdir))
2381 (yas--guess-snippet-directories-1 table))))
2384 (defun yas--make-directory-maybe (table-and-dirs &optional main-table-string)
2385 "Returns a dir inside TABLE-AND-DIRS, prompts for creation if none exists."
2386 (or (some #'(lambda (dir) (when (file-directory-p dir) dir)) (cdr table-and-dirs))
2387 (let ((candidate (first (cdr table-and-dirs))))
2388 (unless (file-writable-p (file-name-directory candidate))
2389 (error (yas--format "%s is not writable." candidate)))
2390 (if (y-or-n-p (format "Guessed directory (%s) for%s%s table \"%s\" does not exist! Create? "
2392 (if (gethash (yas--table-mode (car table-and-dirs))
2396 (or main-table-string
2398 (yas--table-name (car table-and-dirs))))
2400 (make-directory candidate 'also-make-parents)
2401 ;; create the .yas-parents file here...
2404 (defun yas-new-snippet (&optional no-template)
2405 "Pops a new buffer for writing a snippet.
2407 Expands a snippet-writing snippet, unless the optional prefix arg
2408 NO-TEMPLATE is non-nil."
2410 (let ((guessed-directories (yas--guess-snippet-directories)))
2412 (switch-to-buffer "*new snippet*")
2414 (kill-all-local-variables)
2417 (set (make-local-variable 'yas--guessed-modes) (mapcar #'(lambda (d)
2418 (yas--table-mode (car d)))
2419 guessed-directories))
2420 (unless no-template (yas-expand-snippet "\
2421 # -*- mode: snippet -*-
2423 # key: ${2:${1:$(replace-regexp-in-string \"\\\\\\\\(\\\\\\\\w+\\\\\\\\).*\" \"\\\\\\\\1\" yas-text)}}${3:
2424 # binding: ${4:direct-keybinding}}${5:
2425 # expand-env: ((${6:some-var} ${7:some-value}))}${8:
2430 (defun yas--compute-major-mode-and-parents (file)
2431 "Given FILE, find the nearest snippet directory for a given mode.
2433 Returns a list (MODE-SYM PARENTS), the mode's symbol and a list
2434 representing one or more of the mode's parents.
2436 Note that MODE-SYM need not be the symbol of a real major mode,
2437 neither do the elements of PARENTS."
2438 (let* ((file-dir (and file
2439 (directory-file-name (or (some #'(lambda (special)
2440 (locate-dominating-file file special))
2444 (directory-file-name (file-name-directory file))))))
2445 (parents-file-name (concat file-dir "/.yas-parents"))
2446 (major-mode-name (and file-dir
2447 (file-name-nondirectory file-dir)))
2448 (major-mode-sym (or (and major-mode-name
2449 (intern major-mode-name))))
2450 (parents (when (file-readable-p parents-file-name)
2454 (insert-file-contents parents-file-name)
2455 (buffer-substring-no-properties (point-min)
2457 (when major-mode-sym
2458 (cons major-mode-sym parents))))
2460 (defvar yas--editing-template nil
2461 "Supporting variable for `yas-load-snippet-buffer' and `yas--visit-snippet'.")
2463 (defvar yas--current-template nil
2464 "Holds the current template being expanded into a snippet.")
2466 (defvar yas--guessed-modes nil
2467 "List of guessed modes supporting `yas-load-snippet-buffer'.")
2469 (defun yas--read-table ()
2470 "Ask user for a snippet table, help with some guessing."
2471 (let ((prompt (if (and (featurep 'ido)
2473 'ido-completing-read 'completing-read)))
2474 (unless yas--guessed-modes
2475 (set (make-local-variable 'yas--guessed-modes)
2476 (or (yas--compute-major-mode-and-parents buffer-file-name))))
2478 (funcall prompt (format "Choose or enter a table (yas guesses %s): "
2479 (if yas--guessed-modes
2480 (first yas--guessed-modes)
2482 (mapcar #'symbol-name yas--guessed-modes)
2487 (if (first yas--guessed-modes)
2488 (symbol-name (first yas--guessed-modes)))))))
2490 (defun yas-load-snippet-buffer (table &optional interactive)
2491 "Parse and load current buffer's snippet definition into TABLE.
2493 TABLE is a symbol naming a passed to `yas--table-get-create'.
2495 When called interactively, prompt for the table name and
2496 whether (and where) to save the snippet, then quit the window."
2497 (interactive (list (yas--read-table) t))
2499 ;; We have `yas--editing-template', this buffer's content comes from a
2500 ;; template which is already loaded and neatly positioned,...
2502 (yas--editing-template
2503 (yas-define-snippets-1 (yas--parse-template (yas--template-file yas--editing-template))
2504 (yas--template-table yas--editing-template)))
2505 ;; Try to use `yas--guessed-modes'. If we don't have that use the
2506 ;; value from `yas--compute-major-mode-and-parents'
2509 (unless yas--guessed-modes
2510 (set (make-local-variable 'yas--guessed-modes) (or (yas--compute-major-mode-and-parents buffer-file-name))))
2511 (let* ((table (yas--table-get-create table)))
2512 (set (make-local-variable 'yas--editing-template)
2513 (yas-define-snippets-1 (yas--parse-template buffer-file-name)
2516 (when (and interactive
2518 ;; Only offer to save this if it looks like a library or new
2519 ;; snippet (loaded from elisp, from a dir in `yas-snippet-dirs'
2520 ;; which is not the first, or from an unwritable file)
2522 (not (yas--template-file yas--editing-template))
2523 (not (file-writable-p (yas--template-file yas--editing-template)))
2524 (and (listp yas-snippet-dirs)
2525 (second yas-snippet-dirs)
2526 (not (string-match (expand-file-name (first yas-snippet-dirs))
2527 (yas--template-file yas--editing-template)))))
2528 (y-or-n-p (yas--format "Looks like a library or new snippet. Save to new file? ")))
2529 (let* ((option (first (yas--guess-snippet-directories (yas--template-table yas--editing-template))))
2531 (yas--make-directory-maybe option))))
2533 (let ((default-file-name (or (and (yas--template-file yas--editing-template)
2534 (file-name-nondirectory (yas--template-file yas--editing-template)))
2535 (yas--template-name yas--editing-template))))
2536 (write-file (concat chosen "/"
2537 (read-from-minibuffer (format "File name to create in %s? " chosen)
2538 default-file-name)))
2539 (setf (yas--template-file yas--editing-template) buffer-file-name)))))
2541 (yas--message 3 "Snippet \"%s\" loaded for %s."
2542 (yas--template-name yas--editing-template)
2543 (yas--table-name (yas--template-table yas--editing-template)))
2544 (quit-window interactive)))
2546 (defun yas-tryout-snippet (&optional debug)
2547 "Test current buffer's snippet template in other buffer."
2549 (let* ((major-mode-and-parent (yas--compute-major-mode-and-parents buffer-file-name))
2550 (parsed (yas--parse-template))
2551 (test-mode (or (and (car major-mode-and-parent)
2552 (fboundp (car major-mode-and-parent))
2553 (car major-mode-and-parent))
2554 (first yas--guessed-modes)
2555 (intern (read-from-minibuffer (yas--format "Please input a mode: ")))))
2556 (yas--current-template
2559 (yas--populate-template (yas--make-blank-template)
2560 :table nil ;; no tables for ephemeral snippets
2562 :content (second parsed)
2563 :name (third parsed)
2564 :expand-env (sixth parsed)))))
2565 (cond (yas--current-template
2566 (let ((buffer-name (format "*testing snippet: %s*" (yas--template-name yas--current-template))))
2567 (kill-buffer (get-buffer-create buffer-name))
2568 (switch-to-buffer (get-buffer-create buffer-name))
2569 (setq buffer-undo-list nil)
2570 (condition-case nil (funcall test-mode) (error nil))
2572 (setq buffer-read-only nil)
2573 (yas-expand-snippet (yas--template-content yas--current-template)
2576 (yas--template-expand-env yas--current-template))
2578 (require 'yasnippet-debug nil t))
2579 (add-hook 'post-command-hook 'yas-debug-snippet-vars nil t))))
2581 (yas--message 3 "Cannot test snippet for unknown major mode")))))
2583 (defun yas-active-keys ()
2584 "Return all active trigger keys for current buffer and point."
2585 (remove-duplicates (mapcan #'yas--table-all-keys (yas--get-snippet-tables))
2588 (defun yas--template-fine-group (template)
2589 (car (last (or (yas--template-group template)
2590 (yas--template-perm-group template)))))
2592 (defun yas-describe-tables (&optional choose)
2593 "Display snippets for each table."
2595 (let* ((by-name-hash (and choose
2596 (y-or-n-p "Show by namehash? ")))
2597 (buffer (get-buffer-create "*YASnippet tables*"))
2598 (active-tables (yas--get-snippet-tables))
2599 (remain-tables (let ((all))
2600 (maphash #'(lambda (k v)
2601 (unless (find v active-tables)
2605 (table-lists (list active-tables remain-tables))
2606 (original-buffer (current-buffer))
2608 (yas--condition-cache-timestamp (current-time)))
2609 (with-current-buffer buffer
2610 (setq buffer-read-only nil)
2612 (cond ((not by-name-hash)
2613 (insert "YASnippet tables: \n")
2614 (while (and table-lists
2616 (dolist (table (car table-lists))
2617 (yas--describe-pretty-table table original-buffer))
2618 (setq table-lists (cdr table-lists))
2620 (yas--create-snippet-xrefs)
2621 (display-buffer buffer)
2622 (setq continue (and choose (y-or-n-p "Show also non-active tables? ")))))
2623 (yas--create-snippet-xrefs)
2627 (insert "\n\nYASnippet tables by NAMEHASH: \n")
2628 (dolist (table (append active-tables remain-tables))
2629 (insert (format "\nSnippet table `%s':\n\n" (yas--table-name table)))
2631 (maphash #'(lambda (k v)
2633 (yas--table-hash table))
2635 (insert (format " key %s maps snippets: %s\n" key
2637 (maphash #'(lambda (k v)
2639 (gethash key (yas--table-hash table)))
2642 (setq buffer-read-only t))
2643 (display-buffer buffer)))
2645 (defun yas--describe-pretty-table (table &optional original-buffer)
2646 (insert (format "\nSnippet table `%s'"
2647 (yas--table-name table)))
2648 (if (yas--table-parents table)
2649 (insert (format " parents: %s\n"
2650 (mapcar #'yas--table-name
2651 (yas--table-parents table))))
2653 (insert (make-string 100 ?-) "\n")
2654 (insert "group state name key binding\n")
2655 (let ((groups-hash (make-hash-table :test #'equal)))
2656 (maphash #'(lambda (k v)
2657 (let ((group (or (yas--template-fine-group v)
2659 (when (yas--template-name v)
2661 (cons v (gethash group groups-hash))
2663 (yas--table-uuidhash table))
2665 #'(lambda (group templates)
2666 (setq group (truncate-string-to-width group 25 0 ? "..."))
2667 (insert (make-string 100 ?-) "\n")
2668 (dolist (p templates)
2669 (let ((name (truncate-string-to-width (propertize (format "\\\\snippet `%s'" (yas--template-name p))
2673 (setq group (make-string (length group) ? ))))
2674 (condition-string (let ((condition (yas--template-condition p)))
2677 (with-current-buffer original-buffer
2678 (if (yas--eval-condition condition)
2683 (insert condition-string " ")
2685 (if (string-match "\\.\\.\\.$" name)
2689 (insert (truncate-string-to-width (or (yas--template-key p) "")
2691 (insert (truncate-string-to-width (key-description (yas--template-keybinding p))
2698 ;;; User convenience functions, for using in snippet definitions
2700 (defvar yas-modified-p nil
2701 "Non-nil if field has been modified by user or transformation.")
2703 (defvar yas-moving-away-p nil
2704 "Non-nil if user is about to exit field.")
2706 (defvar yas-text nil
2707 "Contains current field text.")
2709 (defun yas-substr (str pattern &optional subexp)
2710 "Search PATTERN in STR and return SUBEXPth match.
2712 If found, the content of subexp group SUBEXP (default 0) is
2713 returned, or else the original STR will be returned."
2714 (let ((grp (or subexp 0)))
2716 (if (string-match pattern str)
2717 (match-string-no-properties grp str)
2720 (defun yas-choose-value (&rest possibilities)
2721 "Prompt for a string in POSSIBILITIES and return it.
2723 The last element of POSSIBILITIES may be a list of strings."
2724 (unless (or yas-moving-away-p
2726 (setq possibilities (nreverse possibilities))
2727 (setq possibilities (if (listp (car possibilities))
2728 (append (reverse (car possibilities)) (rest possibilities))
2730 (some #'(lambda (fn)
2731 (funcall fn "Choose: " possibilities))
2732 yas-prompt-functions)))
2734 (defun yas-key-to-value (alist)
2735 (unless (or yas-moving-away-p
2737 (let ((key (read-key-sequence "")))
2739 (or (cdr (find key alist :key #'car :test #'string=))
2742 (defun yas-throw (text)
2743 "Throw a yas--exception with TEXT as the reason."
2744 (throw 'yas--exception (cons 'yas--exception text)))
2746 (defun yas-verify-value (possibilities)
2747 "Verify that the current field value is in POSSIBILITIES.
2749 Otherwise throw exception."
2750 (when (and yas-moving-away-p (notany #'(lambda (pos) (string= pos yas-text)) possibilities))
2751 (yas-throw (yas--format "Field only allows %s" possibilities))))
2753 (defun yas-field-value (number)
2754 "Get the string for field with NUMBER.
2756 Use this in primary and mirror transformations to tget."
2757 (let* ((snippet (car (yas--snippets-at-point)))
2759 (yas--snippet-find-field snippet number))))
2761 (yas--field-text-for-display field))))
2764 "Return `yas-text' if that exists and is non-empty, else nil."
2766 (not (string= "" yas-text)))
2769 (defun yas-selected-text ()
2770 "Return `yas-selected-text' if that exists and is non-empty, else nil."
2771 (if (and yas-selected-text
2772 (not (string= "" yas-selected-text)))
2775 (defun yas--get-field-once (number &optional transform-fn)
2776 (unless yas-modified-p
2778 (funcall transform-fn (yas-field-value number))
2779 (yas-field-value number))))
2781 (defun yas-default-from-field (number)
2782 (unless yas-modified-p
2783 (yas-field-value number)))
2785 (defun yas-inside-string ()
2786 "Return non-nil if the point is inside a string according to font-lock."
2787 (equal 'font-lock-string-face (get-char-property (1- (point)) 'face)))
2789 (defun yas-unimplemented (&optional missing-feature)
2790 (if yas--current-template
2791 (if (y-or-n-p (format "This snippet is unimplemented (missing %s) Visit the snippet definition? "
2794 (yas--visit-snippet-file-1 yas--current-template))
2795 (message "No implementation. Missing %s" (or missing-feature "something"))))
2798 ;;; Snippet expansion and field management
2800 (defvar yas--active-field-overlay nil
2801 "Overlays the currently active field.")
2803 (defvar yas--field-protection-overlays nil
2804 "Two overlays protect the current active field.")
2806 (defconst yas--prefix nil
2807 "A prefix argument for expansion direct from keybindings.")
2809 (defvar yas-selected-text nil
2810 "The selected region deleted on the last snippet expansion.")
2812 (defvar yas--start-column nil
2813 "The column where the snippet expansion started.")
2815 (make-variable-buffer-local 'yas--active-field-overlay)
2816 (make-variable-buffer-local 'yas--field-protection-overlays)
2817 (put 'yas--active-field-overlay 'permanent-local t)
2818 (put 'yas--field-protection-overlays 'permanent-local t)
2820 (defstruct (yas--snippet (:constructor yas--make-snippet ()))
2826 (id (yas--snippet-next-id) :read-only t)
2827 (control-overlay nil)
2829 ;; stacked expansion: the `previous-active-field' slot saves the
2830 ;; active field where the child expansion took place
2831 previous-active-field
2834 (defstruct (yas--field (:constructor yas--make-field (number start end parent-field)))
2844 (defstruct (yas--mirror (:constructor yas--make-mirror (start end transform)))
2851 (defstruct (yas--exit (:constructor yas--make-exit (marker)))
2855 (defun yas--apply-transform (field-or-mirror field &optional empty-on-nil-p)
2856 "Calculate transformed string for FIELD-OR-MIRROR from FIELD.
2858 If there is no transform for ht field, return nil.
2860 If there is a transform but it returns nil, return the empty
2861 string iff EMPTY-ON-NIL-P is true."
2862 (let* ((yas-text (yas--field-text-for-display field))
2864 (yas-modified-p (yas--field-modified-p field))
2865 (yas-moving-away-p nil)
2866 (transform (if (yas--mirror-p field-or-mirror)
2867 (yas--mirror-transform field-or-mirror)
2868 (yas--field-transform field-or-mirror)))
2869 (start-point (if (yas--mirror-p field-or-mirror)
2870 (yas--mirror-start field-or-mirror)
2871 (yas--field-start field-or-mirror)))
2872 (transformed (and transform
2874 (goto-char start-point)
2875 (let ((ret (yas--eval-lisp transform)))
2876 (or ret (and empty-on-nil-p "")))))))
2879 (defsubst yas--replace-all (from to &optional text)
2880 "Replace all occurrences from FROM to TO.
2882 With optional string TEXT do it in that string."
2884 (replace-regexp-in-string (regexp-quote from) to text t t)
2885 (goto-char (point-min))
2886 (while (search-forward from nil t)
2887 (replace-match to t t text))))
2889 (defun yas--snippet-find-field (snippet number)
2890 (find-if #'(lambda (field)
2891 (eq number (yas--field-number field)))
2892 (yas--snippet-fields snippet)))
2894 (defun yas--snippet-sort-fields (snippet)
2895 "Sort the fields of SNIPPET in navigation order."
2896 (setf (yas--snippet-fields snippet)
2897 (sort (yas--snippet-fields snippet)
2898 #'yas--snippet-field-compare)))
2900 (defun yas--snippet-field-compare (field1 field2)
2901 "Compare FIELD1 and FIELD2.
2903 The field with a number is sorted first. If they both have a
2904 number, compare through the number. If neither have, compare
2905 through the field's start point"
2906 (let ((n1 (yas--field-number field1))
2907 (n2 (yas--field-number field2)))
2910 (or (zerop n2) (and (not (zerop n1))
2915 (< (yas--field-start field1)
2916 (yas--field-start field2))))))
2918 (defun yas--field-probably-deleted-p (snippet field)
2919 "Guess if SNIPPET's FIELD should be skipped."
2921 ;; field must be zero length
2923 (zerop (- (yas--field-start field) (yas--field-end field)))
2926 ;; 1) is a nested field and it's been modified
2928 (and (yas--field-parent-field field)
2929 (yas--field-modified-p field))
2930 ;; 2) ends just before the snippet end
2932 (and (eq field (car (last (yas--snippet-fields snippet))))
2933 (= (yas--field-start field) (overlay-end (yas--snippet-control-overlay snippet)))))
2934 ;; the field numbered 0, just before the exit marker, should
2937 (not (zerop (yas--field-number field)))))
2939 (defun yas--snippets-at-point (&optional all-snippets)
2940 "Return a sorted list of snippets at point.
2942 The most recently-inserted snippets are returned first."
2944 (remove nil (remove-duplicates (mapcar #'(lambda (ov)
2945 (overlay-get ov 'yas--snippet))
2947 (overlays-in (point-min) (point-max))
2948 (nconc (overlays-at (point)) (overlays-at (1- (point))))))))
2950 (<= (yas--snippet-id s2) (yas--snippet-id s1)))))
2952 (defun yas-next-field-or-maybe-expand ()
2953 "Try to expand a snippet at a key before point.
2955 Otherwise delegate to `yas-next-field'."
2957 (if yas-triggers-in-field
2958 (let ((yas-fallback-behavior 'return-nil)
2959 (active-field (overlay-get yas--active-field-overlay 'yas--field)))
2961 (unless (yas-expand-from-trigger-key active-field)
2965 (defun yas-next-field (&optional arg)
2966 "Navigate to the ARGth next field.
2968 If there's none, exit the snippet."
2972 (snippet (first (yas--snippets-at-point)))
2973 (active-field (overlay-get yas--active-field-overlay 'yas--field))
2974 (live-fields (remove-if #'(lambda (field)
2975 (and (not (eq field active-field))
2976 (yas--field-probably-deleted-p snippet field)))
2977 (yas--snippet-fields snippet)))
2978 (active-field-pos (position active-field live-fields))
2979 (target-pos (and active-field-pos (+ arg active-field-pos)))
2980 (target-field (and target-pos (nth target-pos live-fields))))
2981 ;; First check if we're moving out of a field with a transform
2983 (when (and active-field
2984 (yas--field-transform active-field))
2985 (let* ((yas-moving-away-p t)
2986 (yas-text (yas--field-text-for-display active-field))
2988 (yas-modified-p (yas--field-modified-p active-field)))
2989 ;; primary field transform: exit call to field-transform
2990 (yas--eval-lisp (yas--field-transform active-field))))
2991 ;; Now actually move...
2992 (cond ((and target-pos (>= target-pos (length live-fields)))
2993 (yas-exit-snippet snippet))
2995 (yas--move-to-field snippet target-field))
2999 (defun yas--place-overlays (snippet field)
3000 "Correctly place overlays for SNIPPET's FIELD."
3001 (yas--make-move-field-protection-overlays snippet field)
3002 (yas--make-move-active-field-overlay snippet field))
3004 (defun yas--move-to-field (snippet field)
3005 "Update SNIPPET to move to field FIELD.
3007 Also create some protection overlays"
3008 (goto-char (yas--field-start field))
3009 (yas--place-overlays snippet field)
3010 (overlay-put yas--active-field-overlay 'yas--field field)
3011 (let ((number (yas--field-number field)))
3012 ;; check for the special ${0: ...} field
3013 (if (and number (zerop number))
3015 (set-mark (yas--field-end field))
3016 (setf (yas--snippet-force-exit snippet)
3017 (or (yas--field-transform field)
3019 ;; make this field active
3020 (setf (yas--snippet-active-field snippet) field)
3021 ;; primary field transform: first call to snippet transform
3022 (unless (yas--field-modified-p field)
3023 (if (yas--field-update-display field snippet)
3024 (yas--update-mirrors snippet)
3025 (setf (yas--field-modified-p field) nil))))))
3027 (defun yas-prev-field ()
3028 "Navigate to prev field. If there's none, exit the snippet."
3030 (yas-next-field -1))
3032 (defun yas-abort-snippet (&optional snippet)
3034 (let ((snippet (or snippet
3035 (car (yas--snippets-at-point)))))
3037 (setf (yas--snippet-force-exit snippet) t))))
3039 (defun yas-exit-snippet (snippet)
3040 "Goto exit-marker of SNIPPET."
3041 (interactive (list (first (yas--snippets-at-point))))
3043 (setf (yas--snippet-force-exit snippet) t)
3044 (goto-char (if (yas--snippet-exit snippet)
3045 (yas--exit-marker (yas--snippet-exit snippet))
3046 (overlay-end (yas--snippet-control-overlay snippet))))))
3048 (defun yas-exit-all-snippets ()
3049 "Exit all snippets."
3051 (mapc #'(lambda (snippet)
3052 (yas-exit-snippet snippet)
3053 (yas--check-commit-snippet))
3054 (yas--snippets-at-point 'all-snippets)))
3057 ;;; Some low level snippet-routines:
3059 (defmacro yas--inhibit-overlay-hooks (&rest body)
3060 "Run BODY with `yas--inhibit-overlay-hooks' set to t."
3061 (declare (indent 0))
3062 `(let ((yas--inhibit-overlay-hooks t))
3065 (defvar yas-snippet-beg nil "Beginning position of the last snippet committed.")
3066 (defvar yas-snippet-end nil "End position of the last snippet committed.")
3068 (defun yas--commit-snippet (snippet)
3069 "Commit SNIPPET, but leave point as it is.
3071 This renders the snippet as ordinary text."
3073 (let ((control-overlay (yas--snippet-control-overlay snippet)))
3075 ;; Save the end of the moribund snippet in case we need to revive it
3076 ;; its original expansion.
3078 (when (and control-overlay
3079 (overlay-buffer control-overlay))
3080 (setq yas-snippet-beg (overlay-start control-overlay))
3081 (setq yas-snippet-end (overlay-end control-overlay))
3082 (delete-overlay control-overlay))
3084 (yas--inhibit-overlay-hooks
3085 (when yas--active-field-overlay
3086 (delete-overlay yas--active-field-overlay))
3087 (when yas--field-protection-overlays
3088 (mapc #'delete-overlay yas--field-protection-overlays)))
3090 ;; stacked expansion: if the original expansion took place from a
3091 ;; field, make sure we advance it here at least to
3092 ;; `yas-snippet-end'...
3094 (let ((previous-field (yas--snippet-previous-active-field snippet)))
3095 (when (and yas-snippet-end previous-field)
3096 (yas--advance-end-maybe previous-field yas-snippet-end)))
3098 ;; Convert all markers to points,
3100 (yas--markers-to-points snippet)
3102 ;; Take care of snippet revival
3104 (if yas-snippet-revival
3105 (push `(apply yas--snippet-revive ,yas-snippet-beg ,yas-snippet-end ,snippet)
3107 ;; Dismember the snippet... this is useful if we get called
3108 ;; again from `yas--take-care-of-redo'....
3109 (setf (yas--snippet-fields snippet) nil)))
3111 (yas--message 3 "Snippet %s exited." (yas--snippet-id snippet)))
3113 (defun yas--safely-run-hooks (hook-var)
3114 (condition-case error
3115 (run-hooks hook-var)
3117 (yas--message 3 "%s error: %s" hook-var (error-message-string error)))))
3120 (defun yas--check-commit-snippet ()
3121 "Checks if point exited the currently active field of the snippet.
3123 If so cleans up the whole snippet up."
3124 (let* ((snippets (yas--snippets-at-point 'all-snippets))
3125 (snippets-left snippets)
3126 (snippet-exit-transform))
3127 (dolist (snippet snippets)
3128 (let ((active-field (yas--snippet-active-field snippet)))
3129 (setq snippet-exit-transform (yas--snippet-force-exit snippet))
3130 (cond ((or snippet-exit-transform
3131 (not (and active-field (yas--field-contains-point-p active-field))))
3132 (setq snippets-left (delete snippet snippets-left))
3133 (setf (yas--snippet-force-exit snippet) nil)
3134 (yas--commit-snippet snippet))
3136 (or (not yas--active-field-overlay)
3137 (not (overlay-buffer yas--active-field-overlay))))
3139 ;; stacked expansion: this case is mainly for recent
3140 ;; snippet exits that place us back int the field of
3144 (yas--move-to-field snippet active-field)
3145 (yas--update-mirrors snippet)))
3148 (unless (or (null snippets) snippets-left)
3149 (if snippet-exit-transform
3150 (yas--eval-lisp-no-saves snippet-exit-transform))
3151 (yas--safely-run-hooks 'yas-after-exit-snippet-hook))))
3153 ;; Apropos markers-to-points:
3155 ;; This was found useful for performance reasons, so that an
3156 ;; excessive number of live markers aren't kept around in the
3157 ;; `buffer-undo-list'. However, in `markers-to-points', the
3158 ;; set-to-nil markers can't simply be discarded and replaced with
3159 ;; fresh ones in `points-to-markers'. The original marker that was
3160 ;; just set to nil has to be reused.
3162 ;; This shouldn't bring horrible problems with undo/redo, but it
3165 (defun yas--markers-to-points (snippet)
3166 "Convert all markers in SNIPPET to a cons (POINT . MARKER)
3167 where POINT is the original position of the marker and MARKER is
3168 the original marker object with the position set to nil."
3169 (dolist (field (yas--snippet-fields snippet))
3170 (let ((start (marker-position (yas--field-start field)))
3171 (end (marker-position (yas--field-end field))))
3172 (set-marker (yas--field-start field) nil)
3173 (set-marker (yas--field-end field) nil)
3174 (setf (yas--field-start field) (cons start (yas--field-start field)))
3175 (setf (yas--field-end field) (cons end (yas--field-end field))))
3176 (dolist (mirror (yas--field-mirrors field))
3177 (let ((start (marker-position (yas--mirror-start mirror)))
3178 (end (marker-position (yas--mirror-end mirror))))
3179 (set-marker (yas--mirror-start mirror) nil)
3180 (set-marker (yas--mirror-end mirror) nil)
3181 (setf (yas--mirror-start mirror) (cons start (yas--mirror-start mirror)))
3182 (setf (yas--mirror-end mirror) (cons end (yas--mirror-end mirror))))))
3183 (let ((snippet-exit (yas--snippet-exit snippet)))
3185 (let ((exit (marker-position (yas--exit-marker snippet-exit))))
3186 (set-marker (yas--exit-marker snippet-exit) nil)
3187 (setf (yas--exit-marker snippet-exit) (cons exit (yas--exit-marker snippet-exit)))))))
3189 (defun yas--points-to-markers (snippet)
3190 "Convert all cons (POINT . MARKER) in SNIPPET to markers.
3192 This is done by setting MARKER to POINT with `set-marker'."
3193 (dolist (field (yas--snippet-fields snippet))
3194 (setf (yas--field-start field) (set-marker (cdr (yas--field-start field))
3195 (car (yas--field-start field))))
3196 (setf (yas--field-end field) (set-marker (cdr (yas--field-end field))
3197 (car (yas--field-end field))))
3198 (dolist (mirror (yas--field-mirrors field))
3199 (setf (yas--mirror-start mirror) (set-marker (cdr (yas--mirror-start mirror))
3200 (car (yas--mirror-start mirror))))
3201 (setf (yas--mirror-end mirror) (set-marker (cdr (yas--mirror-end mirror))
3202 (car (yas--mirror-end mirror))))))
3203 (let ((snippet-exit (yas--snippet-exit snippet)))
3205 (setf (yas--exit-marker snippet-exit) (set-marker (cdr (yas--exit-marker snippet-exit))
3206 (car (yas--exit-marker snippet-exit)))))))
3208 (defun yas--field-contains-point-p (field &optional point)
3209 (let ((point (or point
3211 (and (>= point (yas--field-start field))
3212 (<= point (yas--field-end field)))))
3214 (defun yas--field-text-for-display (field)
3215 "Return the propertized display text for field FIELD."
3216 (buffer-substring (yas--field-start field) (yas--field-end field)))
3218 (defun yas--undo-in-progress ()
3219 "True if some kind of undo is in progress."
3220 (or undo-in-progress
3221 (eq this-command 'undo)
3222 (eq this-command 'redo)))
3224 (defun yas--make-control-overlay (snippet start end)
3225 "Creates the control overlay that surrounds the snippet and
3227 (let ((overlay (make-overlay start
3232 (overlay-put overlay 'keymap yas-keymap)
3233 (overlay-put overlay 'priority 100)
3234 (overlay-put overlay 'yas--snippet snippet)
3237 (defun yas-skip-and-clear-or-delete-char (&optional field)
3238 "Clears unmodified field if at field start, skips to next tab.
3240 Otherwise deletes a character normally by calling `delete-char'."
3242 (let ((field (or field
3243 (and yas--active-field-overlay
3244 (overlay-buffer yas--active-field-overlay)
3245 (overlay-get yas--active-field-overlay 'yas--field)))))
3247 (not (yas--field-modified-p field))
3248 (eq (point) (marker-position (yas--field-start field))))
3249 (yas--skip-and-clear field)
3252 (call-interactively 'delete-char)))))
3254 (defun yas--skip-and-clear (field)
3255 "Deletes the region of FIELD and sets it's modified state to t."
3256 ;; Just before skipping-and-clearing the field, mark its children
3257 ;; fields as modified, too. If the children have mirrors-in-fields
3258 ;; this prevents them from updating erroneously (we're skipping and
3261 (yas--mark-this-and-children-modified field)
3262 (delete-region (yas--field-start field) (yas--field-end field)))
3264 (defun yas--mark-this-and-children-modified (field)
3265 (setf (yas--field-modified-p field) t)
3266 (let ((fom (yas--field-next field)))
3268 (yas--fom-parent-field fom))
3269 (when (and (eq (yas--fom-parent-field fom) field)
3271 (yas--mark-this-and-children-modified fom))
3272 (setq fom (yas--fom-next fom)))))
3274 (defun yas--make-move-active-field-overlay (snippet field)
3275 "Place the active field overlay in SNIPPET's FIELD.
3277 Move the overlay, or create it if it does not exit."
3278 (if (and yas--active-field-overlay
3279 (overlay-buffer yas--active-field-overlay))
3280 (move-overlay yas--active-field-overlay
3281 (yas--field-start field)
3282 (yas--field-end field))
3283 (setq yas--active-field-overlay
3284 (make-overlay (yas--field-start field)
3285 (yas--field-end field)
3287 (overlay-put yas--active-field-overlay 'priority 100)
3288 (overlay-put yas--active-field-overlay 'face 'yas-field-highlight-face)
3289 (overlay-put yas--active-field-overlay 'yas--snippet snippet)
3290 (overlay-put yas--active-field-overlay 'modification-hooks '(yas--on-field-overlay-modification))
3291 (overlay-put yas--active-field-overlay 'insert-in-front-hooks
3292 '(yas--on-field-overlay-modification))
3293 (overlay-put yas--active-field-overlay 'insert-behind-hooks
3294 '(yas--on-field-overlay-modification))))
3296 (defvar yas--inhibit-overlay-hooks nil
3297 "Bind this temporarily to non-nil to prevent running `yas--on-*-modification'.")
3299 (defun yas--on-field-overlay-modification (overlay after? beg end &optional length)
3300 "Clears the field and updates mirrors, conditionally.
3302 Only clears the field if it hasn't been modified and it point it
3303 at field start. This hook doesn't do anything if an undo is in
3305 (unless (or yas--inhibit-overlay-hooks
3306 (yas--undo-in-progress))
3307 (let* ((field (overlay-get overlay 'yas--field))
3308 (number (and field (yas--field-number field)))
3309 (snippet (overlay-get yas--active-field-overlay 'yas--snippet)))
3311 (yas--advance-end-maybe field (overlay-end overlay))
3313 (yas--field-update-display field snippet))
3314 (yas--update-mirrors snippet))
3316 (when (and (not after?)
3317 (not (yas--field-modified-p field))
3318 (eq (point) (if (markerp (yas--field-start field))
3319 (marker-position (yas--field-start field))
3320 (yas--field-start field))))
3321 (yas--skip-and-clear field))
3322 (setf (yas--field-modified-p field) t))))))
3324 ;;; Apropos protection overlays:
3326 ;; These exist for nasty users who will try to delete parts of the
3327 ;; snippet outside the active field. Actual protection happens in
3328 ;; `yas--on-protection-overlay-modification'.
3330 ;; Currently this signals an error which inhibits the command. For
3331 ;; commands that move point (like `kill-line'), point is restored in
3332 ;; the `yas--post-command-handler' using a global
3333 ;; `yas--protection-violation' variable.
3335 ;; Alternatively, I've experimented with an implementation that
3336 ;; commits the snippet before actually calling `this-command'
3337 ;; interactively, and then signals an error, which is ignored. but
3338 ;; blocks all other million modification hooks. This presented some
3339 ;; problems with stacked expansion.
3341 (defun yas--make-move-field-protection-overlays (snippet field)
3342 "Place protection overlays surrounding SNIPPET's FIELD.
3344 Move the overlays, or create them if they do not exit."
3345 (let ((start (yas--field-start field))
3346 (end (yas--field-end field)))
3347 ;; First check if the (1+ end) is contained in the buffer,
3348 ;; otherwise we'll have to do a bit of cheating and silently
3349 ;; insert a newline. the `(1+ (buffer-size))' should prevent this
3350 ;; when using stacked expansion
3352 (when (< (buffer-size) end)
3354 (yas--inhibit-overlay-hooks
3355 (goto-char (point-max))
3357 ;; go on to normal overlay creation/moving
3359 (cond ((and yas--field-protection-overlays
3360 (every #'overlay-buffer yas--field-protection-overlays))
3361 (move-overlay (first yas--field-protection-overlays) (1- start) start)
3362 (move-overlay (second yas--field-protection-overlays) end (1+ end)))
3364 (setq yas--field-protection-overlays
3365 (list (make-overlay (1- start) start nil t nil)
3366 (make-overlay end (1+ end) nil t nil)))
3367 (dolist (ov yas--field-protection-overlays)
3368 (overlay-put ov 'face 'yas--field-debug-face)
3369 (overlay-put ov 'yas--snippet snippet)
3370 ;; (overlay-put ov 'evaporate t)
3371 (overlay-put ov 'modification-hooks '(yas--on-protection-overlay-modification)))))))
3373 (defvar yas--protection-violation nil
3374 "When non-nil, signals attempts to erroneously exit or modify the snippet.
3376 Functions in the `post-command-hook', for example
3377 `yas--post-command-handler' can check it and reset its value to
3378 nil. The variables value is the point where the violation
3381 (defun yas--on-protection-overlay-modification (overlay after? beg end &optional length)
3382 "Signals a snippet violation, then issues error.
3384 The error should be ignored in `debug-ignored-errors'"
3385 (unless yas--inhibit-overlay-hooks
3386 (cond ((not (or after?
3387 (yas--undo-in-progress)))
3388 (setq yas--protection-violation (point))
3389 (error "Exit the snippet first!")))))
3391 (add-to-list 'debug-ignored-errors "^Exit the snippet first!$")
3394 ;; Snippet expansion and "stacked" expansion:
3396 ;; Stacked expansion is when you try to expand a snippet when already
3397 ;; inside a snippet expansion.
3399 ;; The parent snippet does not run its fields modification hooks
3400 ;; (`yas--on-field-overlay-modification' and
3401 ;; `yas--on-protection-overlay-modification') while the child snippet
3402 ;; is active. This means, among other things, that the mirrors of the
3403 ;; parent snippet are not updated, this only happening when one exits
3404 ;; the child snippet.
3406 ;; Unfortunately, this also puts some ugly (and not fully-tested)
3407 ;; bits of code in `yas-expand-snippet' and
3408 ;; `yas--commit-snippet'. I've tried to mark them with "stacked
3411 ;; This was thought to be safer in an undo/redo perspective, but
3412 ;; maybe the correct implementation is to make the globals
3413 ;; `yas--active-field-overlay' and `yas--field-protection-overlays' be
3414 ;; snippet-local and be active even while the child snippet is
3415 ;; running. This would mean a lot of overlay modification hooks
3416 ;; running, but if managed correctly (including overlay priorities)
3417 ;; they should account for all situations...
3419 (defun yas-expand-snippet (content &optional start end expand-env)
3420 "Expand snippet CONTENT at current point.
3422 Text between START and END will be deleted before inserting
3423 template. EXPAND-ENV is are let-style variable to value bindings
3424 considered when expanding the snippet."
3425 (run-hooks 'yas-before-expand-snippet-hook)
3428 (let* ((yas-selected-text (or yas-selected-text
3429 (and (region-active-p)
3430 (buffer-substring-no-properties (region-beginning)
3433 (and (region-active-p)
3437 (and (region-active-p)
3440 (to-delete (and start
3442 (buffer-substring-no-properties start end)))
3445 (setq yas--indent-original-column (current-column))
3446 ;; Delete the region to delete, this *does* get undo-recorded.
3448 (when (and to-delete
3450 (delete-region start end))
3452 (cond ((listp content)
3453 ;; x) This is a snippet-command
3455 (yas--eval-lisp-no-saves content))
3457 ;; x) This is a snippet-snippet :-)
3459 ;; Narrow the region down to the content, shoosh the
3460 ;; `buffer-undo-list', and create the snippet, the new
3461 ;; snippet updates its mirrors once, so we are left with
3462 ;; some plain text. The undo action for deleting this
3463 ;; plain text will get recorded at the end.
3465 ;; stacked expansion: also shoosh the overlay modification hooks
3467 (narrow-to-region start start)
3468 (let ((buffer-undo-list t))
3469 ;; snippet creation might evaluate users elisp, which
3470 ;; might generate errors, so we have to be ready to catch
3471 ;; them mostly to make the undo information
3473 (setq yas--start-column (save-restriction (widen) (current-column)))
3474 (yas--inhibit-overlay-hooks
3477 (eval `(let* ,expand-env
3479 (yas--snippet-create (point-min) (point-max))))
3481 (yas--snippet-create (point-min) (point-max)))))))
3483 ;; stacked-expansion: This checks for stacked expansion, save the
3484 ;; `yas--previous-active-field' and advance its boundary.
3486 (let ((existing-field (and yas--active-field-overlay
3487 (overlay-buffer yas--active-field-overlay)
3488 (overlay-get yas--active-field-overlay 'yas--field))))
3489 (when existing-field
3490 (setf (yas--snippet-previous-active-field snippet) existing-field)
3491 (yas--advance-end-maybe existing-field (overlay-end yas--active-field-overlay))))
3493 ;; Exit the snippet immediately if no fields
3495 (unless (yas--snippet-fields snippet)
3496 (yas-exit-snippet snippet))
3498 ;; Push two undo actions: the deletion of the inserted contents of
3499 ;; the new snippet (without the "key") followed by an apply of
3500 ;; `yas--take-care-of-redo' on the newly inserted snippet boundaries
3502 ;; A small exception, if `yas-also-auto-indent-first-line'
3503 ;; is t and `yas--indent' decides to indent the line to a
3504 ;; point before the actual expansion point, undo would be
3505 ;; messed up. We call the early point "newstart"". case,
3506 ;; and attempt to fix undo.
3508 (let ((newstart (overlay-start (yas--snippet-control-overlay snippet)))
3509 (end (overlay-end (yas--snippet-control-overlay snippet))))
3510 (when (< newstart start)
3511 (push (cons (make-string (- start newstart) ? ) newstart) buffer-undo-list))
3512 (push (cons newstart end) buffer-undo-list)
3513 (push `(apply yas--take-care-of-redo ,start ,end ,snippet)
3515 ;; Now, schedule a move to the first field
3517 (let ((first-field (car (yas--snippet-fields snippet))))
3519 (sit-for 0) ;; fix issue 125
3520 (yas--move-to-field snippet first-field)))
3521 (yas--message 3 "snippet expanded.")
3524 (defun yas--take-care-of-redo (beg end snippet)
3525 "Commits SNIPPET, which in turn pushes an undo action for reviving it.
3527 Meant to exit in the `buffer-undo-list'."
3528 ;; slightly optimize: this action is only needed for snippets with
3529 ;; at least one field
3530 (when (yas--snippet-fields snippet)
3531 (yas--commit-snippet snippet)))
3533 (defun yas--snippet-revive (beg end snippet)
3534 "Revives SNIPPET and creates a control overlay from BEG to END.
3536 BEG and END are, we hope, the original snippets boundaries. All
3537 the markers/points exiting existing inside SNIPPET should point
3538 to their correct locations *at the time the snippet is revived*.
3540 After revival, push the `yas--take-care-of-redo' in the
3542 ;; Reconvert all the points to markers
3544 (yas--points-to-markers snippet)
3545 ;; When at least one editable field existed in the zombie snippet,
3546 ;; try to revive the whole thing...
3548 (let ((target-field (or (yas--snippet-active-field snippet)
3549 (car (yas--snippet-fields snippet)))))
3551 (setf (yas--snippet-control-overlay snippet) (yas--make-control-overlay snippet beg end))
3552 (overlay-put (yas--snippet-control-overlay snippet) 'yas--snippet snippet)
3554 (yas--move-to-field snippet target-field)
3556 (push `(apply yas--take-care-of-redo ,beg ,end ,snippet)
3557 buffer-undo-list))))
3559 (defun yas--snippet-create (begin end)
3560 "Creates a snippet from an template inserted between BEGIN and END.
3562 Returns the newly created snippet."
3563 (let ((snippet (yas--make-snippet)))
3565 (yas--snippet-parse-create snippet)
3567 ;; Sort and link each field
3568 (yas--snippet-sort-fields snippet)
3570 ;; Create keymap overlay for snippet
3571 (setf (yas--snippet-control-overlay snippet)
3572 (yas--make-control-overlay snippet (point-min) (point-max)))
3575 (goto-char (point-max))
3580 ;;; Apropos adjacencies and "fom's":
3582 ;; Once the $-constructs bits like "$n" and "${:n" are deleted in the
3583 ;; recently expanded snippet, we might actually have many fields,
3584 ;; mirrors (and the snippet exit) in the very same position in the
3585 ;; buffer. Therefore we need to single-link the
3586 ;; fields-or-mirrors-or-exit (which I have abbreviated to "fom")
3587 ;; according to their original positions in the buffer.
3589 ;; Then we have operation `yas--advance-end-maybe' and
3590 ;; `yas--advance-start-maybe', which conditionally push the starts and
3591 ;; ends of these foms down the chain.
3593 ;; This allows for like the printf with the magic ",":
3595 ;; printf ("${1:%s}\\n"${1:$(if (string-match "%" text) "," "\);")} \
3596 ;; $2${1:$(if (string-match "%" text) "\);" "")}$0
3598 (defun yas--fom-start (fom)
3599 (cond ((yas--field-p fom)
3600 (yas--field-start fom))
3601 ((yas--mirror-p fom)
3602 (yas--mirror-start fom))
3604 (yas--exit-marker fom))))
3606 (defun yas--fom-end (fom)
3607 (cond ((yas--field-p fom)
3608 (yas--field-end fom))
3609 ((yas--mirror-p fom)
3610 (yas--mirror-end fom))
3612 (yas--exit-marker fom))))
3614 (defun yas--fom-next (fom)
3615 (cond ((yas--field-p fom)
3616 (yas--field-next fom))
3617 ((yas--mirror-p fom)
3618 (yas--mirror-next fom))
3620 (yas--exit-next fom))))
3622 (defun yas--fom-parent-field (fom)
3623 (cond ((yas--field-p fom)
3624 (yas--field-parent-field fom))
3625 ((yas--mirror-p fom)
3626 (yas--mirror-parent-field fom))
3630 (defun yas--calculate-adjacencies (snippet)
3631 "Calculate adjacencies for fields or mirrors of SNIPPET.
3633 This is according to their relative positions in the buffer, and
3634 has to be called before the $-constructs are deleted."
3635 (flet ((yas--fom-set-next-fom (fom nextfom)
3636 (cond ((yas--field-p fom)
3637 (setf (yas--field-next fom) nextfom))
3638 ((yas--mirror-p fom)
3639 (setf (yas--mirror-next fom) nextfom))
3641 (setf (yas--exit-next fom) nextfom))))
3642 (yas--compare-fom-begs (fom1 fom2)
3643 (if (= (yas--fom-start fom2) (yas--fom-start fom1))
3644 (yas--mirror-p fom2)
3645 (>= (yas--fom-start fom2) (yas--fom-start fom1))))
3646 (yas--link-foms (fom1 fom2)
3647 (yas--fom-set-next-fom fom1 fom2)))
3648 ;; make some yas--field, yas--mirror and yas--exit soup
3650 (when (yas--snippet-exit snippet)
3651 (push (yas--snippet-exit snippet) soup))
3652 (dolist (field (yas--snippet-fields snippet))
3654 (dolist (mirror (yas--field-mirrors field))
3655 (push mirror soup)))
3658 #'yas--compare-fom-begs))
3660 (reduce #'yas--link-foms soup)))))
3662 (defun yas--calculate-mirrors-in-fields (snippet mirror)
3663 "Attempt to assign a parent field of SNIPPET to the mirror MIRROR.
3665 Use the tightest containing field if more than one field contains
3666 the mirror. Intended to be called *before* the dollar-regions are
3668 (let ((min (point-min))
3670 (dolist (field (yas--snippet-fields snippet))
3671 (when (and (<= (yas--field-start field) (yas--mirror-start mirror))
3672 (<= (yas--mirror-end mirror) (yas--field-end field))
3673 (< min (yas--field-start field))
3674 (< (yas--field-end field) max))
3675 (setq min (yas--field-start field)
3676 max (yas--field-end field))
3677 (setf (yas--mirror-parent-field mirror) field)))))
3679 (defun yas--advance-end-maybe (fom newend)
3680 "Maybe advance FOM's end to NEWEND if it needs it.
3684 * call `yas--advance-start-maybe' on FOM's next fom.
3686 * in case FOM is field call `yas--advance-end-maybe' on its parent
3689 Also, if FOM is an exit-marker, always call
3690 `yas--advance-start-maybe' on its next fom. This is because
3691 exit-marker have identical start and end markers."
3692 (cond ((and fom (< (yas--fom-end fom) newend))
3693 (set-marker (yas--fom-end fom) newend)
3694 (yas--advance-start-maybe (yas--fom-next fom) newend)
3695 (yas--advance-end-of-parents-maybe (yas--fom-parent-field fom) newend))
3697 (yas--advance-start-maybe (yas--fom-next fom) newend))))
3699 (defun yas--advance-start-maybe (fom newstart)
3700 "Maybe advance FOM's start to NEWSTART if it needs it.
3702 If it does, also call `yas--advance-end-maybe' on FOM."
3703 (when (and fom (< (yas--fom-start fom) newstart))
3704 (set-marker (yas--fom-start fom) newstart)
3705 (yas--advance-end-maybe fom newstart)))
3707 (defun yas--advance-end-of-parents-maybe (field newend)
3708 "Like `yas--advance-end-maybe' but for parent fields.
3710 Only works for fields and doesn't care about the start of the
3711 next FOM. Works its way up recursively for parents of parents."
3713 (< (yas--field-end field) newend))
3714 (set-marker (yas--field-end field) newend)
3715 (yas--advance-end-of-parents-maybe (yas--field-parent-field field) newend)))
3717 (defvar yas--dollar-regions nil
3718 "When expanding the snippet the \"parse-create\" functions add
3719 cons cells to this var.")
3721 (defvar yas--backquote-markers-and-strings nil
3722 "List of (MARKER . STRING) marking where the values from
3723 backquoted lisp expressions should be inserted at the end of
3726 (defun yas--snippet-parse-create (snippet)
3727 "Parse a recently inserted snippet template, creating all
3728 necessary fields, mirrors and exit points.
3730 Meant to be called in a narrowed buffer, does various passes"
3731 (let ((parse-start (point)))
3732 ;; Reset the yas--dollar-regions
3734 (setq yas--dollar-regions nil)
3735 ;; protect just the backquotes
3737 (yas--protect-escapes nil '(?`))
3738 ;; replace all backquoted expressions
3740 (goto-char parse-start)
3741 (yas--save-backquotes)
3742 ;; protect escaped characters
3744 (yas--protect-escapes)
3745 ;; parse fields with {}
3747 (goto-char parse-start)
3748 (yas--field-parse-create snippet)
3749 ;; parse simple mirrors and fields
3751 (goto-char parse-start)
3752 (yas--simple-mirror-parse-create snippet)
3753 ;; parse mirror transforms
3755 (goto-char parse-start)
3756 (yas--transform-mirror-parse-create snippet)
3757 ;; calculate adjacencies of fields and mirrors
3759 (yas--calculate-adjacencies snippet)
3760 ;; Delete $-constructs
3762 (yas--delete-regions yas--dollar-regions)
3763 ;; restore backquoted expression values
3765 (yas--restore-backquotes)
3768 (goto-char parse-start)
3769 (yas--restore-escapes)
3770 ;; update mirrors for the first time
3772 (yas--update-mirrors snippet)
3773 ;; indent the best we can
3775 (goto-char parse-start)
3776 (yas--indent snippet)))
3778 (defun yas--indent-according-to-mode (snippet-markers)
3779 "Indent current line according to mode, preserving SNIPPET-MARKERS."
3780 ;;; Apropos indenting problems....
3782 ;; `indent-according-to-mode' uses whatever `indent-line-function'
3783 ;; is available. Some implementations of these functions delete text
3784 ;; before they insert. If there happens to be a marker just after
3785 ;; the text being deleted, the insertion actually happens after the
3786 ;; marker, which misplaces it.
3788 ;; This would also happen if we had used overlays with the
3789 ;; `front-advance' property set to nil.
3791 ;; This is why I have these `trouble-markers', they are the ones at
3792 ;; they are the ones at the first non-whitespace char at the line
3793 ;; (i.e. at `yas--real-line-beginning'. After indentation takes place
3794 ;; we should be at the correct to restore them to. All other
3795 ;; non-trouble-markers have been *pushed* and don't need special
3798 (goto-char (yas--real-line-beginning))
3799 (let ((trouble-markers (remove-if-not #'(lambda (marker)
3805 (indent-according-to-mode)
3806 (error (yas--message 3 "Warning: `yas--indent-according-to-mode' having problems running %s" indent-line-function)
3808 (mapc #'(lambda (marker)
3809 (set-marker marker (point)))
3812 (defvar yas--indent-original-column nil)
3813 (defun yas--indent (snippet)
3814 (let ((snippet-markers (yas--collect-snippet-markers snippet)))
3815 ;; Look for those $>
3817 (while (re-search-forward "$>" nil t)
3818 (delete-region (match-beginning 0) (match-end 0))
3819 (when (not (eq yas-indent-line 'auto))
3820 (yas--indent-according-to-mode snippet-markers))))
3821 ;; Now do stuff for 'fixed and 'auto
3823 (cond ((eq yas-indent-line 'fixed)
3824 (while (and (zerop (forward-line))
3825 (zerop (current-column)))
3826 (indent-to-column yas--indent-original-column)))
3827 ((eq yas-indent-line 'auto)
3828 (let ((end (set-marker (make-marker) (point-max)))
3829 (indent-first-line-p yas-also-auto-indent-first-line))
3830 (while (and (zerop (if indent-first-line-p
3833 (setq indent-first-line-p nil))
3837 (yas--indent-according-to-mode snippet-markers))))
3841 (defun yas--collect-snippet-markers (snippet)
3842 "Make a list of all the markers used by SNIPPET."
3844 (dolist (field (yas--snippet-fields snippet))
3845 (push (yas--field-start field) markers)
3846 (push (yas--field-end field) markers)
3847 (dolist (mirror (yas--field-mirrors field))
3848 (push (yas--mirror-start mirror) markers)
3849 (push (yas--mirror-end mirror) markers)))
3850 (let ((snippet-exit (yas--snippet-exit snippet)))
3851 (when (and snippet-exit
3852 (marker-buffer (yas--exit-marker snippet-exit)))
3853 (push (yas--exit-marker snippet-exit) markers)))
3856 (defun yas--real-line-beginning ()
3857 (let ((c (char-after (line-beginning-position)))
3858 (n (line-beginning-position)))
3859 (while (or (eql c ?\ )
3862 (setq c (char-after n)))
3865 (defun yas--escape-string (escaped)
3866 (concat "YASESCAPE" (format "%d" escaped) "PROTECTGUARD"))
3868 (defun yas--protect-escapes (&optional text escaped)
3869 "Protect all escaped characters with their numeric ASCII value.
3871 With optional string TEXT do it in string instead of buffer."
3872 (let ((changed-text text)
3873 (text-provided-p text))
3874 (mapc #'(lambda (escaped)
3876 (yas--replace-all (concat "\\" (char-to-string escaped))
3877 (yas--escape-string escaped)
3878 (when text-provided-p changed-text))))
3879 (or escaped yas--escaped-characters))
3882 (defun yas--restore-escapes (&optional text escaped)
3883 "Restore all escaped characters from their numeric ASCII value.
3885 With optional string TEXT do it in string instead of the buffer."
3886 (let ((changed-text text)
3887 (text-provided-p text))
3888 (mapc #'(lambda (escaped)
3890 (yas--replace-all (yas--escape-string escaped)
3891 (char-to-string escaped)
3892 (when text-provided-p changed-text))))
3893 (or escaped yas--escaped-characters))
3896 (defun yas--save-backquotes ()
3897 "Save all the \"`(lisp-expression)`\"-style expressions
3898 with their evaluated value into `yas--backquote-markers-and-strings'."
3899 (while (re-search-forward yas--backquote-lisp-expression-regexp nil t)
3900 (let ((current-string (match-string-no-properties 1)) transformed)
3901 (delete-region (match-beginning 0) (match-end 0))
3902 (setq transformed (yas--eval-lisp (yas--read-lisp (yas--restore-escapes current-string '(?`)))))
3903 (goto-char (match-beginning 0))
3905 (let ((marker (make-marker)))
3906 (insert "Y") ;; quite horrendous, I love it :)
3907 (set-marker marker (point))
3909 (push (cons marker transformed) yas--backquote-markers-and-strings))))))
3911 (defun yas--restore-backquotes ()
3912 "Replace markers in `yas--backquote-markers-and-strings' with their values."
3913 (while yas--backquote-markers-and-strings
3914 (let* ((marker-and-string (pop yas--backquote-markers-and-strings))
3915 (marker (car marker-and-string))
3916 (string (cdr marker-and-string)))
3922 (set-marker marker nil)))))
3924 (defun yas--scan-sexps (from count)
3926 (with-syntax-table (standard-syntax-table)
3927 (scan-sexps from count))
3931 (defun yas--make-marker (pos)
3932 "Create a marker at POS with nil `marker-insertion-type'."
3933 (let ((marker (set-marker (make-marker) pos)))
3934 (set-marker-insertion-type marker nil)
3937 (defun yas--field-parse-create (snippet &optional parent-field)
3938 "Parse most field expressions in SNIPPET, except for the simple one \"$n\".
3940 The following count as a field:
3942 * \"${n: text}\", for a numbered field with default text, as long as N is not 0;
3944 * \"${n: text$(expression)}, the same with a lisp expression;
3945 this is caught with the curiously named `yas--multi-dollar-lisp-expression-regexp'
3947 * the same as above but unnumbered, (no N:) and number is calculated automatically.
3949 When multiple expressions are found, only the last one counts."
3952 (while (re-search-forward yas--field-regexp nil t)
3953 (let* ((real-match-end-0 (yas--scan-sexps (1+ (match-beginning 0)) 1))
3954 (number (and (match-string-no-properties 1)
3955 (string-to-number (match-string-no-properties 1))))
3956 (brand-new-field (and real-match-end-0
3957 ;; break if on "$(" immediately
3958 ;; after the ":", this will be
3959 ;; caught as a mirror with
3961 (not (save-match-data
3962 (eq (string-match "$[ \t\n]*("
3963 (match-string-no-properties 2)) 0)))
3964 ;; allow ${0: some exit text}
3965 ;; (not (and number (zerop number)))
3966 (yas--make-field number
3967 (yas--make-marker (match-beginning 2))
3968 (yas--make-marker (1- real-match-end-0))
3970 (when brand-new-field
3971 (goto-char real-match-end-0)
3972 (push (cons (1- real-match-end-0) real-match-end-0)
3973 yas--dollar-regions)
3974 (push (cons (match-beginning 0) (match-beginning 2))
3975 yas--dollar-regions)
3976 (push brand-new-field (yas--snippet-fields snippet))
3979 (narrow-to-region (yas--field-start brand-new-field) (yas--field-end brand-new-field))
3980 (goto-char (point-min))
3981 (yas--field-parse-create snippet brand-new-field)))))))
3982 ;; if we entered from a parent field, now search for the
3983 ;; `yas--multi-dollar-lisp-expression-regexp'. This is used for
3984 ;; primary field transformations
3988 (while (re-search-forward yas--multi-dollar-lisp-expression-regexp nil t)
3989 (let* ((real-match-end-1 (yas--scan-sexps (match-beginning 1) 1)))
3990 ;; commit the primary field transformation if:
3992 ;; 1. we don't find it in yas--dollar-regions (a subnested
3993 ;; field) might have already caught it.
3995 ;; 2. we really make sure we have either two '$' or some
3996 ;; text and a '$' after the colon ':'. This is a FIXME: work
3997 ;; my regular expressions and end these ugly hacks.
3999 (when (and real-match-end-1
4000 (not (member (cons (match-beginning 0)
4002 yas--dollar-regions))
4004 (char-before (1- (match-beginning 1))))))
4005 (let ((lisp-expression-string (buffer-substring-no-properties (match-beginning 1)
4007 (setf (yas--field-transform parent-field)
4008 (yas--read-lisp (yas--restore-escapes lisp-expression-string))))
4009 (push (cons (match-beginning 0) real-match-end-1)
4010 yas--dollar-regions)))))))
4012 (defun yas--transform-mirror-parse-create (snippet)
4013 "Parse the \"${n:$(lisp-expression)}\" mirror transformations in SNIPPET."
4014 (while (re-search-forward yas--transform-mirror-regexp nil t)
4015 (let* ((real-match-end-0 (yas--scan-sexps (1+ (match-beginning 0)) 1))
4016 (number (string-to-number (match-string-no-properties 1)))
4018 (not (zerop number))
4019 (yas--snippet-find-field snippet number)))
4021 (and real-match-end-0
4023 (yas--make-mirror (yas--make-marker (match-beginning 0))
4024 (yas--make-marker (match-beginning 0))
4026 (yas--restore-escapes
4027 (buffer-substring-no-properties (match-beginning 2)
4028 (1- real-match-end-0))))))))
4029 (when brand-new-mirror
4030 (push brand-new-mirror
4031 (yas--field-mirrors field))
4032 (yas--calculate-mirrors-in-fields snippet brand-new-mirror)
4033 (push (cons (match-beginning 0) real-match-end-0) yas--dollar-regions)))))
4035 (defun yas--simple-mirror-parse-create (snippet)
4036 "Parse the simple \"$n\" fields/mirrors/exitmarkers in SNIPPET."
4037 (while (re-search-forward yas--simple-mirror-regexp nil t)
4038 (let ((number (string-to-number (match-string-no-properties 1))))
4039 (cond ((zerop number)
4041 (setf (yas--snippet-exit snippet)
4042 (yas--make-exit (yas--make-marker (match-end 0))))
4044 (goto-char (match-beginning 0))
4045 (when yas-wrap-around-region
4046 (cond (yas-selected-text
4047 (insert yas-selected-text))
4048 ((and (eq yas-wrap-around-region 'cua)
4051 (insert (prog1 (get-register ?0)
4052 (set-register ?0 nil))))))
4053 (push (cons (point) (yas--exit-marker (yas--snippet-exit snippet)))
4054 yas--dollar-regions)))
4056 (let ((field (yas--snippet-find-field snippet number)))
4058 (let ((brand-new-mirror (yas--make-mirror
4059 (yas--make-marker (match-beginning 0))
4060 (yas--make-marker (match-beginning 0))
4062 (push brand-new-mirror
4063 (yas--field-mirrors field))
4064 (yas--calculate-mirrors-in-fields snippet brand-new-mirror))
4065 (push (yas--make-field number
4066 (yas--make-marker (match-beginning 0))
4067 (yas--make-marker (match-beginning 0))
4069 (yas--snippet-fields snippet))))
4070 (push (cons (match-beginning 0) (match-end 0))
4071 yas--dollar-regions))))))
4073 (defun yas--delete-regions (regions)
4074 "Sort disjuct REGIONS by start point, then delete from the back."
4075 (mapc #'(lambda (reg)
4076 (delete-region (car reg) (cdr reg)))
4079 (>= (car r1) (car r2))))))
4081 (defun yas--update-mirrors (snippet)
4082 "Updates all the mirrors of SNIPPET."
4084 (dolist (field-and-mirror (sort
4085 ;; make a list of ((F1 . M1) (F1 . M2) (F2 . M3) (F2 . M4) ...)
4086 ;; where F is the field that M is mirroring
4088 (mapcan #'(lambda (field)
4089 (mapcar #'(lambda (mirror)
4090 (cons field mirror))
4091 (yas--field-mirrors field)))
4092 (yas--snippet-fields snippet))
4093 ;; then sort this list so that entries with mirrors with parent
4094 ;; fields appear before. This was important for fixing #290, and
4095 ;; luckily also handles the case where a mirror in a field causes
4096 ;; another mirror to need reupdating
4098 #'(lambda (field-and-mirror1 field-and-mirror2)
4099 (yas--mirror-parent-field (cdr field-and-mirror1)))))
4100 (let* ((field (car field-and-mirror))
4101 (mirror (cdr field-and-mirror))
4102 (parent-field (yas--mirror-parent-field mirror)))
4103 ;; before updating a mirror with a parent-field, maybe advance
4107 (yas--advance-start-maybe mirror (yas--fom-start parent-field)))
4108 ;; update this mirror
4110 (yas--mirror-update-display mirror field)
4111 ;; `yas--place-overlays' is needed if the active field and
4112 ;; protected overlays have been changed because of insertions
4113 ;; in `yas--mirror-update-display'
4115 (when (eq field (yas--snippet-active-field snippet))
4116 (yas--place-overlays snippet field))))))
4118 (defun yas--mirror-update-display (mirror field)
4119 "Update MIRROR according to FIELD (and mirror transform)."
4121 (let* ((mirror-parent-field (yas--mirror-parent-field mirror))
4122 (reflection (and (not (and mirror-parent-field
4123 (yas--field-modified-p mirror-parent-field)))
4124 (or (yas--apply-transform mirror field 'empty-on-nil)
4125 (yas--field-text-for-display field)))))
4126 (when (and reflection
4127 (not (string= reflection (buffer-substring-no-properties (yas--mirror-start mirror)
4128 (yas--mirror-end mirror)))))
4129 (goto-char (yas--mirror-start mirror))
4130 (yas--inhibit-overlay-hooks
4131 (insert reflection))
4132 (if (> (yas--mirror-end mirror) (point))
4133 (delete-region (point) (yas--mirror-end mirror))
4134 (set-marker (yas--mirror-end mirror) (point))
4135 (yas--advance-start-maybe (yas--mirror-next mirror) (point))
4136 ;; super-special advance
4137 (yas--advance-end-of-parents-maybe mirror-parent-field (point))))))
4139 (defun yas--field-update-display (field snippet)
4140 "Much like `yas--mirror-update-display', but for fields."
4141 (when (yas--field-transform field)
4142 (let ((transformed (and (not (eq (yas--field-number field) 0))
4143 (yas--apply-transform field field)))
4145 (when (and transformed
4146 (not (string= transformed (buffer-substring-no-properties (yas--field-start field)
4147 (yas--field-end field)))))
4148 (setf (yas--field-modified-p field) t)
4149 (goto-char (yas--field-start field))
4150 (yas--inhibit-overlay-hooks
4151 (insert transformed)
4152 (if (> (yas--field-end field) (point))
4153 (delete-region (point) (yas--field-end field))
4154 (set-marker (yas--field-end field) (point))
4155 (yas--advance-start-maybe (yas--field-next field) (point)))
4159 ;;; Post-command hook:
4161 (defun yas--post-command-handler ()
4162 "Handles various yasnippet conditions after each command."
4163 (cond (yas--protection-violation
4164 (goto-char yas--protection-violation)
4165 (setq yas--protection-violation nil))
4166 ((eq 'undo this-command)
4168 ;; After undo revival the correct field is sometimes not
4169 ;; restored correctly, this condition handles that
4171 (let* ((snippet (car (yas--snippets-at-point)))
4172 (target-field (and snippet
4173 (find-if-not #'(lambda (field)
4174 (yas--field-probably-deleted-p snippet field))
4176 (cons (yas--snippet-active-field snippet)
4177 (yas--snippet-fields snippet)))))))
4179 (yas--move-to-field snippet target-field))))
4180 ((not (yas--undo-in-progress))
4181 ;; When not in an undo, check if we must commit the snippet
4182 ;; (user exited it).
4183 (yas--check-commit-snippet))))
4187 ;; The docstrings for some functions are generated dynamically
4188 ;; depending on the context.
4190 (put 'yas-expand 'function-documentation
4191 '(yas--expand-from-trigger-key-doc))
4192 (defun yas--expand-from-trigger-key-doc ()
4193 "A doc synthesizer for `yas--expand-from-trigger-key-doc'."
4194 (let ((fallback-description
4195 (cond ((eq yas-fallback-behavior 'call-other-command)
4196 (let* ((fallback (yas--keybinding-beyond-yasnippet)))
4198 (format " call command `%s'." (pp-to-string fallback)))
4199 " do nothing (`yas-expand' doesn't shadow\nanything)")))
4200 ((eq yas-fallback-behavior 'return-nil)
4203 ", defer to `yas-fallback-behaviour' (which see)"))))
4204 (concat "Expand a snippet before point. If no snippet
4205 expansion is possible,"
4206 fallback-description
4207 "\n\nOptional argument FIELD is for non-interactive use and is an
4208 object satisfying `yas--field-p' to restrict the expansion to.")))
4210 (put 'yas-expand-from-keymap 'function-documentation '(yas--expand-from-keymap-doc))
4211 (defun yas--expand-from-keymap-doc ()
4212 "A doc synthesizer for `yas--expand-from-keymap-doc'."
4213 (add-hook 'temp-buffer-show-hook 'yas--snippet-description-finish-runonce)
4214 (concat "Expand/run snippets from keymaps, possibly falling back to original binding.\n"
4215 (when (eq this-command 'describe-key)
4216 (let* ((vec (this-single-command-keys))
4217 (templates (mapcan #'(lambda (table)
4218 (yas--fetch table vec))
4219 (yas--get-snippet-tables)))
4220 (yas--direct-keymaps nil)
4221 (fallback (key-binding vec)))
4222 (concat "In this case, "
4224 (concat "these snippets are bound to this key:\n"
4225 (yas--template-pretty-list templates)
4226 "\n\nIf none of these expands, "))
4228 (format "fallback `%s' will be called." (pp-to-string fallback)))
4229 "no fallback keybinding is called."))))))
4231 (defun yas--template-pretty-list (templates)
4233 (yas-buffer-local-condition 'always))
4234 (dolist (plate templates)
4235 (setq acc (concat acc "\n*) "
4236 (propertize (concat "\\\\snippet `" (car plate) "'")
4237 'yasnippet (cdr plate)))))
4240 (define-button-type 'help-snippet-def
4241 :supertype 'help-xref
4242 'help-function (lambda (template) (yas--visit-snippet-file-1 template))
4243 'help-echo (purecopy "mouse-2, RET: find snippets's definition"))
4245 (defun yas--snippet-description-finish-runonce ()
4246 "Final adjustments for the help buffer when snippets are concerned."
4247 (yas--create-snippet-xrefs)
4248 (remove-hook 'temp-buffer-show-hook 'yas--snippet-description-finish-runonce))
4250 (defun yas--create-snippet-xrefs ()
4252 (goto-char (point-min))
4253 (while (search-forward-regexp "\\\\\\\\snippet[ \s\t]+`\\([^']+\\)'" nil t)
4254 (let ((template (get-text-property (match-beginning 1)
4257 (help-xref-button 1 'help-snippet-def template)
4258 (kill-region (match-end 1) (match-end 0))
4259 (kill-region (match-beginning 0) (match-beginning 1)))))))
4261 (defun yas--expand-uuid (mode-symbol uuid &optional start end expand-env)
4262 "Expand a snippet registered in MODE-SYMBOL's table with UUID.
4264 Remaining args as in `yas-expand-snippet'."
4265 (let* ((table (gethash mode-symbol yas--tables))
4266 (yas--current-template (and table
4267 (gethash uuid (yas--table-uuidhash table)))))
4268 (when yas--current-template
4269 (yas-expand-snippet (yas--template-content yas--current-template)))))
4273 (defvar yas-verbosity 4
4274 "Log level for `yas--message' 4 means trace most anything, 0 means nothing.")
4276 (defun yas--message (level message &rest args)
4277 "When LEVEL is above `yas-verbosity-level', log MESSAGE and ARGS."
4278 (when (> yas-verbosity level)
4279 (message (apply #'yas--format message args))))
4281 (defun yas--format (format-control &rest format-args)
4282 (apply #'format (concat "[yas] " format-control) format-args))
4289 ;; `locate-dominating-file'
4290 ;; `region-active-p'
4292 ;; added for compatibility in emacsen < 23
4293 (unless (>= emacs-major-version 23)
4294 (unless (fboundp 'region-active-p)
4295 (defun region-active-p () (and transient-mark-mode mark-active)))
4297 (unless (fboundp 'locate-dominating-file)
4298 (defvar locate-dominating-stop-dir-regexp
4299 "\\`\\(?:[\\/][\\/][^\\/]+[\\/]\\|/\\(?:net\\|afs\\|\\.\\.\\.\\)/\\)\\'"
4300 "Regexp of directory names which stop the search in `locate-dominating-file'.
4301 Any directory whose name matches this regexp will be treated like
4302 a kind of root directory by `locate-dominating-file' which will stop its search
4303 when it bumps into it.
4304 The default regexp prevents fruitless and time-consuming attempts to find
4305 special files in directories in which filenames are interpreted as hostnames,
4306 or mount points potentially requiring authentication as a different user.")
4308 (defun locate-dominating-file (file name)
4309 "Look up the directory hierarchy from FILE for a file named NAME.
4310 Stop at the first parent directory containing a file NAME,
4311 and return the directory. Return nil if not found."
4312 ;; We used to use the above locate-dominating-files code, but the
4313 ;; directory-files call is very costly, so we're much better off doing
4314 ;; multiple calls using the code in here.
4316 ;; Represent /home/luser/foo as ~/foo so that we don't try to look for
4317 ;; `name' in /home or in /.
4318 (setq file (abbreviate-file-name file))
4321 ;; `user' is not initialized outside the loop because
4322 ;; `file' may not exist, so we may have to walk up part of the
4323 ;; hierarchy before we find the "initial UUID".
4326 (while (not (or root
4328 ;; FIXME: Disabled this heuristic because it is sometimes
4330 ;; As a heuristic, we stop looking up the hierarchy of
4331 ;; directories as soon as we find a directory belonging
4332 ;; to another user. This should save us from looking in
4333 ;; things like /net and /afs. This assumes that all the
4334 ;; files inside a project belong to the same user.
4335 ;; (let ((prev-user user))
4336 ;; (setq user (nth 2 (file-attributes file)))
4337 ;; (and prev-user (not (equal user prev-user))))
4338 (string-match locate-dominating-stop-dir-regexp file)))
4339 (setq try (file-exists-p (expand-file-name name file)))
4340 (cond (try (setq root file))
4341 ((equal file (setq prev-file file
4342 file (file-name-directory
4343 (directory-file-name file))))
4347 ;; `c-neutralize-syntax-in-CPP` sometimes fires "End of Buffer" error
4348 ;; (when it execute forward-char) and interrupt the after change
4349 ;; hook. Thus prevent the insert-behind hook of yasnippet to be
4350 ;; invoked. Here's a way to reproduce it:
4352 ;; # open a *new* Emacs.
4353 ;; # load yasnippet.
4354 ;; # open a *new* .cpp file.
4355 ;; # input "inc" and press TAB to expand the snippet.
4356 ;; # select the `#include <...>` snippet.
4357 ;; # type inside `<>`
4359 (defadvice c-neutralize-syntax-in-CPP
4360 (around yas--mp/c-neutralize-syntax-in-CPP activate)
4361 "Adviced `c-neutralize-syntax-in-CPP' to properly
4362 handle the end-of-buffer error fired in it by calling
4363 `forward-char' at the end of buffer."
4366 (error (message (error-message-string err)))))
4368 ;; disable c-electric-* serial command in YAS fields
4369 (add-hook 'c-mode-common-hook
4371 (dolist (k '(":" ">" ";" "<" "{" "}"))
4372 (define-key (symbol-value (make-local-variable 'yas-keymap))
4373 k 'self-insert-command))))
4375 ;;; Backward compatibility to yasnippet <= 0.7
4376 (defvar yas--exported-syms '(;; `defcustom's
4379 yas-prompt-functions
4381 yas-also-auto-indent-first-line
4383 yas-triggers-in-field
4384 yas-fallback-behavior
4385 yas-choose-keys-first
4386 yas-choose-tables-first
4389 yas-wrap-around-region
4392 yas-expand-only-for-last-commands
4393 yas-field-highlight-face
4395 ;; these vars can be customized as well
4401 yas-after-exit-snippet-hook
4402 yas-before-expand-snippet-hook
4403 yas-buffer-local-condition
4406 ;; prompting functions
4411 yas-completing-prompt
4414 ;; interactive functions
4419 yas-direct-keymaps-reload
4423 yas-compile-directory
4426 yas-expand-from-trigger-key
4427 yas-expand-from-keymap
4429 yas-visit-snippet-file
4431 yas-load-snippet-buffer
4434 yas-next-field-or-maybe-expand
4439 yas-exit-all-snippets
4440 yas-skip-and-clear-or-delete-char
4442 ;; symbols that I "exported" for use
4443 ;; in snippets and hookage
4461 yas-default-from-field
4464 yas-define-condition-cache
4465 yas-hippie-try-expand
4468 ;; debug definitions
4469 ;; yas-debug-snippet-vars
4470 ;; yas-exterminate-package
4473 ;; testing definitions
4474 ;; yas-should-expand
4475 ;; yas-should-not-expand
4477 ;; yas-make-file-or-dirs
4479 ;; yas-saving-variables
4480 ;; yas-call-with-snippet-dirs
4481 ;; yas-with-snippet-dirs
4483 "Exported yasnippet symbols.
4485 i.e. ones that I will try to keep in future yasnippet versions
4486 and ones that other elisp libraries can more or less safely rely
4489 (defvar yas--dont-backport '(yas-active-keys)
4490 "Exported symbols that don't map back to \"yas/*\" variants.")
4492 (dolist (sym (set-difference yas--exported-syms yas--dont-backport))
4493 (let ((backported (intern (replace-regexp-in-string "^yas-" "yas/" (symbol-name sym)))))
4495 (make-obsolete-variable backported sym "yasnippet 0.8")
4496 (defvaralias backported sym))
4498 (make-obsolete backported sym "yasnippet 0.8")
4499 (defalias backported sym))))
4502 (provide 'yasnippet)
4504 ;;; yasnippet.el ends here
4507 ;; byte-compile-warnings: (not cl-functions)