1 ;;; yasnippet.el --- Yet another snippet extension for Emacs.
3 ;; Copyright (C) 2008-2016 Free Software Foundation, Inc.
4 ;; Authors: pluskid <pluskid@gmail.com>,
5 ;; João Távora <joaotavora@gmail.com>,
6 ;; Noam Postavsky <npostavs@gmail.com>
7 ;; Maintainer: Noam Postavsky <npostavs@gmail.com>
9 ;; X-URL: http://github.com/capitaomorte/yasnippet
10 ;; Keywords: convenience, emulation
11 ;; URL: http://github.com/capitaomorte/yasnippet
12 ;; Package-Requires: ((cl-lib "0.5"))
13 ;; EmacsWiki: YaSnippetMode
15 ;; This program is free software: you can redistribute it and/or modify
16 ;; it under the terms of the GNU General Public License as published by
17 ;; the Free Software Foundation, either version 3 of the License, or
18 ;; (at your option) any later version.
20 ;; This program is distributed in the hope that it will be useful,
21 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
22 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 ;; GNU General Public License for more details.
25 ;; You should have received a copy of the GNU General Public License
26 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
30 ;; Basic steps to setup:
32 ;; (add-to-list 'load-path
33 ;; "~/path-to-yasnippet")
34 ;; (require 'yasnippet)
35 ;; (yas-global-mode 1)
38 ;; Interesting variables are:
42 ;; The directory where user-created snippets are to be
43 ;; stored. Can also be a list of directories. In that case,
44 ;; when used for bulk (re)loading of snippets (at startup or
45 ;; via `yas-reload-all'), directories appearing earlier in
46 ;; the list override other dir's snippets. Also, the first
47 ;; directory is taken as the default for storing the user's
50 ;; The deprecated `yas/root-directory' aliases this variable
51 ;; for backward-compatibility.
54 ;; Major commands are:
58 ;; Try to expand snippets before point. In `yas-minor-mode',
59 ;; this is normally bound to TAB, but you can customize it in
60 ;; `yas-minor-mode-map'.
62 ;; M-x yas-load-directory
64 ;; Prompts you for a directory hierarchy of snippets to load.
66 ;; M-x yas-activate-extra-mode
68 ;; Prompts you for an extra mode to add snippets for in the
71 ;; M-x yas-insert-snippet
73 ;; Prompts you for possible snippet expansion if that is
74 ;; possible according to buffer-local and snippet-local
75 ;; expansion conditions. With prefix argument, ignore these
78 ;; M-x yas-visit-snippet-file
80 ;; Prompts you for possible snippet expansions like
81 ;; `yas-insert-snippet', but instead of expanding it, takes
82 ;; you directly to the snippet definition's file, if it
85 ;; M-x yas-new-snippet
87 ;; Lets you create a new snippet file in the correct
88 ;; subdirectory of `yas-snippet-dirs', according to the
91 ;; M-x yas-load-snippet-buffer
93 ;; When editing a snippet, this loads the snippet. This is
94 ;; bound to "C-c C-c" while in the `snippet-mode' editing
97 ;; M-x yas-tryout-snippet
99 ;; When editing a snippet, this opens a new empty buffer,
100 ;; sets it to the appropriate major mode and inserts the
101 ;; snippet there, so you can see what it looks like. This is
102 ;; bound to "C-c C-t" while in `snippet-mode'.
104 ;; M-x yas-describe-tables
106 ;; Lists known snippets in a separate buffer. User is
107 ;; prompted as to whether only the currently active tables
108 ;; are to be displayed, or all the tables for all major
111 ;; If you have `dropdown-list' installed, you can optionally use it
112 ;; as the preferred "prompting method", putting in your .emacs file,
115 ;; (require 'dropdown-list)
116 ;; (setq yas-prompt-functions '(yas-dropdown-prompt
118 ;; yas-completing-prompt))
120 ;; Also check out the customization group
122 ;; M-x customize-group RET yasnippet RET
124 ;; If you use the customization group to set variables
125 ;; `yas-snippet-dirs' or `yas-global-mode', make sure the path to
126 ;; "yasnippet.el" is present in the `load-path' *before* the
127 ;; `custom-set-variables' is executed in your .emacs file.
129 ;; For more information and detailed usage, refer to the project page:
130 ;; http://github.com/capitaomorte/yasnippet
139 (defvar yas--editing-template)
140 (defvar yas--guessed-modes)
141 (defvar yas--indent-original-column)
142 (defvar yas--scheduled-jit-loads)
144 (defvar yas-selected-text)
145 (defvar yas-verbosity)
146 (defvar yas--current-template)
149 ;;; User customizable variables
151 (defgroup yasnippet nil
152 "Yet Another Snippet extension"
156 (defvar yas-installed-snippets-dir nil)
157 (setq yas-installed-snippets-dir
159 (expand-file-name "snippets" (file-name-directory load-file-name))))
161 (defconst yas--default-user-snippets-dir
162 (expand-file-name "snippets" user-emacs-directory))
164 (defcustom yas-snippet-dirs (remove nil
165 (list yas--default-user-snippets-dir
166 'yas-installed-snippets-dir))
167 "List of top-level snippet directories.
169 Each element, a string or a symbol whose value is a string,
170 designates a top-level directory where per-mode snippet
171 directories can be found.
173 Elements appearing earlier in the list override later elements'
176 The first directory is taken as the default for storing snippet's
177 created with `yas-new-snippet'. "
178 :type '(choice (directory :tag "Single directory")
179 (repeat :tag "List of directories"
180 (choice (directory) (variable))))
183 :set #'(lambda (symbol new)
184 (let ((old (and (boundp symbol)
185 (symbol-value symbol))))
186 (set-default symbol new)
187 (unless (or (not (fboundp 'yas-reload-all))
191 (defun yas-snippet-dirs ()
192 "Return variable `yas-snippet-dirs' as list of strings."
193 (cl-loop for e in (if (listp yas-snippet-dirs)
195 (list yas-snippet-dirs))
197 (cond ((stringp e) e)
200 (stringp (symbol-value e)))
203 (error "[yas] invalid element %s in `yas-snippet-dirs'" e)))))
205 (defcustom yas-new-snippet-default "\
206 # -*- mode: snippet -*-
208 # key: ${2:${1:$(yas--key-from-desc yas-text)}}
211 "Default snippet to use when creating a new snippet.
212 If nil, don't use any snippet."
216 (defcustom yas-prompt-functions '(yas-dropdown-prompt
217 yas-completing-prompt
220 "Functions to prompt for keys, templates, etc interactively.
222 These functions are called with the following arguments:
224 - PROMPT: A string to prompt the user
226 - CHOICES: a list of strings or objects.
228 - optional DISPLAY-FN : A function that, when applied to each of
229 the objects in CHOICES will return a string.
231 The return value of any function you put here should be one of
232 the objects in CHOICES, properly formatted with DISPLAY-FN (if
235 - To signal that your particular style of prompting is
236 unavailable at the moment, you can also have the function return
239 - To signal that the user quit the prompting process, you can
242 (signal 'quit \"user quit!\")."
243 :type '(repeat function)
246 (defcustom yas-indent-line 'auto
247 "Controls indenting applied to a recent snippet expansion.
249 The following values are possible:
251 - `fixed' Indent the snippet to the current column;
253 - `auto' Indent each line of the snippet with `indent-according-to-mode'
255 Every other value means don't apply any snippet-side indentation
256 after expansion (the manual per-line \"$>\" indentation still
258 :type '(choice (const :tag "Nothing" nothing)
259 (const :tag "Fixed" fixed)
260 (const :tag "Auto" auto))
263 (defcustom yas-also-auto-indent-first-line nil
264 "Non-nil means also auto indent first line according to mode.
266 Naturally this is only valid when `yas-indent-line' is `auto'"
270 (defcustom yas-snippet-revival t
271 "Non-nil means re-activate snippet fields after undo/redo."
275 (defcustom yas-triggers-in-field nil
276 "If non-nil, allow stacked expansions (snippets inside snippets).
278 Otherwise `yas-next-field-or-maybe-expand' just moves on to the
283 (defcustom yas-fallback-behavior 'call-other-command
284 "How to act when `yas-expand' does *not* expand a snippet.
286 - `call-other-command' means try to temporarily disable YASnippet
287 and call the next command bound to whatever key was used to
290 - nil or the symbol `return-nil' mean do nothing. (and
291 `yas-expand' returns nil)
293 - A Lisp form (apply COMMAND . ARGS) means interactively call
294 COMMAND. If ARGS is non-nil, call COMMAND non-interactively
295 with ARGS as arguments."
296 :type '(choice (const :tag "Call previous command" call-other-command)
297 (const :tag "Do nothing" return-nil))
300 (defcustom yas-choose-keys-first nil
301 "If non-nil, prompt for snippet key first, then for template.
303 Otherwise prompts for all possible snippet names.
305 This affects `yas-insert-snippet' and `yas-visit-snippet-file'."
309 (defcustom yas-choose-tables-first nil
310 "If non-nil, and multiple eligible snippet tables, prompts user for tables first.
312 Otherwise, user chooses between the merging together of all
315 This affects `yas-insert-snippet', `yas-visit-snippet-file'"
319 (defcustom yas-use-menu 'abbreviate
320 "Display a YASnippet menu in the menu bar.
322 When non-nil, submenus for each snippet table will be listed
323 under the menu \"Yasnippet\".
325 - If set to `abbreviate', only the current major-mode
326 menu and the modes set in `yas--extra-modes' are listed.
328 - If set to `full', every submenu is listed
330 - If set to `nil', hide the menu.
332 Any other non-nil value, every submenu is listed."
333 :type '(choice (const :tag "Full" full)
334 (const :tag "Abbreviate" abbreviate)
335 (const :tag "No menu" nil))
338 (defcustom yas-trigger-symbol (or (and (eq window-system 'mac)
340 (char-to-string ?\x21E5))) ;; little ->| sign
342 "The text that will be used in menu to represent the trigger."
346 (defcustom yas-wrap-around-region nil
347 "What to insert for snippet's $0 field.
349 If set to a character, insert contents of corresponding register.
350 If non-nil insert region contents. This can be overridden on a
351 per-snippet basis. A value of `cua' is considered equivalent to
352 `?0' for backwards compatibility."
353 :type '(choice (character :tag "Insert from register")
354 (const t :tag "Insert region contents")
355 (const nil :tag "Don't insert anything")
356 (const cua)) ; backwards compat
359 (defcustom yas-good-grace t
360 "If non-nil, don't raise errors in inline elisp evaluation.
362 An error string \"[yas] error\" is returned instead."
366 (defcustom yas-visit-from-menu nil
367 "If non-nil visit snippets's files from menu, instead of expanding them.
369 This can only work when snippets are loaded from files."
373 (defcustom yas-expand-only-for-last-commands nil
374 "List of `last-command' values to restrict tab-triggering to, or nil.
376 Leave this set at nil (the default) to be able to trigger an
377 expansion simply by placing the cursor after a valid tab trigger,
378 using whichever commands.
380 Optionally, set this to something like '(self-insert-command) if
381 you to wish restrict expansion to only happen when the last
382 letter of the snippet tab trigger was typed immediately before
383 the trigger key itself."
384 :type '(repeat function)
387 (defcustom yas-alias-to-yas/prefix-p t
388 "If non-nil make aliases for the old style yas/ prefixed symbols.
389 It must be set to nil before loading yasnippet to take effect."
393 ;; Only two faces, and one of them shouldn't even be used...
395 (defface yas-field-highlight-face
396 '((t (:inherit 'region)))
397 "The face used to highlight the currently active field of a snippet"
400 (defface yas--field-debug-face
402 "The face used for debugging some overlays normally hidden"
406 ;;; User-visible variables
408 (defvar yas-keymap (let ((map (make-sparse-keymap)))
409 (define-key map [(tab)] 'yas-next-field-or-maybe-expand)
410 (define-key map (kbd "TAB") 'yas-next-field-or-maybe-expand)
411 (define-key map [(shift tab)] 'yas-prev-field)
412 (define-key map [backtab] 'yas-prev-field)
413 (define-key map (kbd "C-g") 'yas-abort-snippet)
414 (define-key map (kbd "C-d") 'yas-skip-and-clear-or-delete-char)
416 "The active keymap while a snippet expansion is in progress.")
418 (defvar yas-key-syntaxes (list "w" "w_" "w_." "w_.()"
419 #'yas-try-key-from-whitespace)
420 "Syntaxes and functions to help look for trigger keys before point.
422 Each element in this list specifies how to skip buffer positions
423 backwards and look for the start of a trigger key.
425 Each element can be either a string or a function receiving the
426 original point as an argument. A string element is simply passed
427 to `skip-syntax-backward' whereas a function element is called
428 with no arguments and should also place point before the original
431 The string between the resulting buffer position and the original
432 point is matched against the trigger keys in the active snippet
435 If no expandable snippets are found, the next element is the list
436 is tried, unless a function element returned the symbol `again',
437 in which case it is called again from the previous position and
438 may once more reposition point.
440 For example, if `yas-key-syntaxes'' value is '(\"w\" \"w_\"),
441 trigger keys composed exclusively of \"word\"-syntax characters
442 are looked for first. Failing that, longer keys composed of
443 \"word\" or \"symbol\" syntax are looked for. Therefore,
448 will, according to the \"w\" element first try \"barbaz\". If
449 that isn't a trigger key, \"foo-barbaz\" is tried, respecting the
450 second \"w_\" element. Notice that even if \"baz\" is a trigger
451 key for an active snippet, it won't be expanded, unless a
452 function is added to `yas-key-syntaxes' that eventually places
453 point between \"bar\" and \"baz\".
455 See also Info node `(elisp) Syntax Descriptors'.")
457 (defvar yas-after-exit-snippet-hook
459 "Hooks to run after a snippet exited.
461 The hooks will be run in an environment where some variables bound to
464 `yas-snippet-beg' : The beginning of the region of the snippet.
466 `yas-snippet-end' : Similar to beg.
468 Attention: These hooks are not run when exiting nested/stacked snippet expansion!")
470 (defvar yas-before-expand-snippet-hook
472 "Hooks to run just before expanding a snippet.")
474 (defvar yas-buffer-local-condition
475 '(if (and (let ((ppss (syntax-ppss)))
476 (or (nth 3 ppss) (nth 4 ppss)))
477 (memq this-command '(yas-expand yas-expand-from-trigger-key
478 yas-expand-from-keymap)))
479 '(require-snippet-condition . force-in-comment)
481 "Snippet expanding condition.
483 This variable is a Lisp form which is evaluated every time a
484 snippet expansion is attempted:
486 * If it evaluates to nil, no snippets can be expanded.
488 * If it evaluates to the a cons (require-snippet-condition
491 * Snippets bearing no \"# condition:\" directive are not
494 * Snippets bearing conditions that evaluate to nil (or
495 produce an error) won't be considered.
497 * If the snippet has a condition that evaluates to non-nil
500 * If REQUIREMENT is t, the snippet is considered
502 * If REQUIREMENT is `eq' RESULT, the snippet is
505 * Otherwise, the snippet is not considered.
507 * If it evaluates to the symbol 'always, all snippets are
508 considered for expansion, regardless of any conditions.
510 * If it evaluates to t or some other non-nil value
512 * Snippet bearing no conditions, or conditions that
513 evaluate to non-nil, are considered for expansion.
515 * Otherwise, the snippet is not considered.
517 Here's an example preventing snippets from being expanded from
518 inside comments, in `python-mode' only, with the exception of
519 snippets returning the symbol 'force-in-comment in their
522 (add-hook 'python-mode-hook
524 (setq yas-buffer-local-condition
525 '(if (python-in-string/comment)
526 '(require-snippet-condition . force-in-comment)
529 The default value is similar, it filters out potential snippet
530 expansions inside comments and string literals, unless the
531 snippet itself contains a condition that returns the symbol
532 `force-in-comment'.")
535 ;;; Internal variables
537 (defvar yas--version "0.9.1")
539 (defvar yas--menu-table (make-hash-table)
540 "A hash table of MAJOR-MODE symbols to menu keymaps.")
542 (defvar yas--escaped-characters
543 '(?\\ ?` ?\" ?' ?$ ?} ?{ ?\( ?\))
544 "List of characters which *might* need to be escaped.")
546 (defconst yas--field-regexp
547 "${\\([0-9]+:\\)?\\([^}]*\\)}"
548 "A regexp to *almost* recognize a field.")
550 (defconst yas--multi-dollar-lisp-expression-regexp
551 "$+[ \t\n]*\\(([^)]*)\\)"
552 "A regexp to *almost* recognize a \"$(...)\" expression.")
554 (defconst yas--backquote-lisp-expression-regexp
556 "A regexp to recognize a \"`lisp-expression`\" expression." )
558 (defconst yas--transform-mirror-regexp
559 "${\\(?:\\([0-9]+\\):\\)?$\\([ \t\n]*([^}]*\\)"
560 "A regexp to *almost* recognize a mirror with a transform.")
562 (defconst yas--simple-mirror-regexp
564 "A regexp to recognize a simple mirror.")
566 (defvar yas--snippet-id-seed 0
567 "Contains the next id for a snippet.")
569 (defun yas--snippet-next-id ()
570 (let ((id yas--snippet-id-seed))
571 (cl-incf yas--snippet-id-seed)
577 ;; XXX: `last-buffer-undo-list' is somehow needed in Carbon Emacs for MacOSX
578 (defvar last-buffer-undo-list nil)
580 (defvar yas--minor-mode-menu nil
581 "Holds the YASnippet menu.")
583 (defvar yas-minor-mode-map
584 (let ((map (make-sparse-keymap)))
585 (define-key map [(tab)] 'yas-expand)
586 (define-key map (kbd "TAB") 'yas-expand)
587 (define-key map "\C-c&\C-s" 'yas-insert-snippet)
588 (define-key map "\C-c&\C-n" 'yas-new-snippet)
589 (define-key map "\C-c&\C-v" 'yas-visit-snippet-file)
591 "The keymap used when `yas-minor-mode' is active.")
593 (easy-menu-define yas--minor-mode-menu
595 "Menu used when `yas-minor-mode' is active."
596 '("YASnippet" :visible yas-use-menu
598 ["Expand trigger" yas-expand
599 :help "Possibly expand tab trigger before point"]
600 ["Insert at point..." yas-insert-snippet
601 :help "Prompt for an expandable snippet and expand it at point"]
602 ["New snippet..." yas-new-snippet
603 :help "Create a new snippet in an appropriate directory"]
604 ["Visit snippet file..." yas-visit-snippet-file
605 :help "Prompt for an expandable snippet and find its file"]
607 ("Snippet menu behaviour"
608 ["Visit snippets" (setq yas-visit-from-menu t)
609 :help "Visit snippets from the menu"
610 :active t :style radio :selected yas-visit-from-menu]
611 ["Expand snippets" (setq yas-visit-from-menu nil)
612 :help "Expand snippets from the menu"
613 :active t :style radio :selected (not yas-visit-from-menu)]
615 ["Show all known modes" (setq yas-use-menu 'full)
616 :help "Show one snippet submenu for each loaded table"
617 :active t :style radio :selected (eq yas-use-menu 'full)]
618 ["Abbreviate according to current mode" (setq yas-use-menu 'abbreviate)
619 :help "Show only snippet submenus for the current active modes"
620 :active t :style radio :selected (eq yas-use-menu 'abbreviate)])
622 ["Auto" (setq yas-indent-line 'auto)
623 :help "Indent each line of the snippet with `indent-according-to-mode'"
624 :active t :style radio :selected (eq yas-indent-line 'auto)]
625 ["Fixed" (setq yas-indent-line 'fixed)
626 :help "Indent the snippet to the current column"
627 :active t :style radio :selected (eq yas-indent-line 'fixed)]
628 ["None" (setq yas-indent-line 'none)
629 :help "Don't apply any particular snippet indentation after expansion"
630 :active t :style radio :selected (not (member yas-indent-line '(fixed auto)))]
632 ["Also auto indent first line" (setq yas-also-auto-indent-first-line
633 (not yas-also-auto-indent-first-line))
634 :help "When auto-indenting also, auto indent the first line menu"
635 :active (eq yas-indent-line 'auto)
636 :style toggle :selected yas-also-auto-indent-first-line]
639 ["System X-widget" (setq yas-prompt-functions
641 (remove 'yas-x-prompt
642 yas-prompt-functions)))
643 :help "Use your windowing system's (gtk, mac, windows, etc...) default menu"
644 :active t :style radio :selected (eq (car yas-prompt-functions)
646 ["Dropdown-list" (setq yas-prompt-functions
647 (cons 'yas-dropdown-prompt
648 (remove 'yas-dropdown-prompt
649 yas-prompt-functions)))
650 :help "Use a special dropdown list"
651 :active t :style radio :selected (eq (car yas-prompt-functions)
652 'yas-dropdown-prompt)]
653 ["Ido" (setq yas-prompt-functions
654 (cons 'yas-ido-prompt
655 (remove 'yas-ido-prompt
656 yas-prompt-functions)))
657 :help "Use an ido-style minibuffer prompt"
658 :active t :style radio :selected (eq (car yas-prompt-functions)
660 ["Completing read" (setq yas-prompt-functions
661 (cons 'yas-completing-prompt
662 (remove 'yas-completing-prompt
663 yas-prompt-functions)))
664 :help "Use a normal minibuffer prompt"
665 :active t :style radio :selected (eq (car yas-prompt-functions)
666 'yas-completing-prompt)]
669 ["Wrap region in exit marker"
670 (setq yas-wrap-around-region
671 (not yas-wrap-around-region))
672 :help "If non-nil automatically wrap the selected text in the $0 snippet exit"
673 :style toggle :selected yas-wrap-around-region]
674 ["Allow stacked expansions "
675 (setq yas-triggers-in-field
676 (not yas-triggers-in-field))
677 :help "If non-nil allow snippets to be triggered inside other snippet fields"
678 :style toggle :selected yas-triggers-in-field]
679 ["Revive snippets on undo "
680 (setq yas-snippet-revival
681 (not yas-snippet-revival))
682 :help "If non-nil allow snippets to become active again after undo"
683 :style toggle :selected yas-snippet-revival]
686 (not yas-good-grace))
687 :help "If non-nil don't raise errors in bad embedded elisp in snippets"
688 :style toggle :selected yas-good-grace]
691 ["Load snippets..." yas-load-directory
692 :help "Load snippets from a specific directory"]
693 ["Reload everything" yas-reload-all
694 :help "Cleanup stuff, reload snippets, rebuild menus"]
696 :help "Display some information about YASnippet"]))
698 (defvar yas--extra-modes nil
699 "An internal list of modes for which to also lookup snippets.
701 This variable probably makes more sense as buffer-local, so
702 ensure your use `make-local-variable' when you set it.")
703 (define-obsolete-variable-alias 'yas-extra-modes 'yas--extra-modes "0.9.1")
705 (defvar yas--tables (make-hash-table)
706 "A hash table of mode symbols to `yas--table' objects.")
708 (defvar yas--parents (make-hash-table)
709 "A hash table of mode symbols do lists of direct parent mode symbols.
711 This list is populated when reading the \".yas-parents\" files
712 found when traversing snippet directories with
713 `yas-load-directory'.
715 There might be additional parenting information stored in the
716 `derived-mode-parent' property of some mode symbols, but that is
719 (defvar yas--direct-keymaps (list)
720 "Keymap alist supporting direct snippet keybindings.
722 This variable is placed in `emulation-mode-map-alists'.
724 Its elements looks like (TABLE-NAME . KEYMAP). They're
725 instantiated on `yas-reload-all' but KEYMAP is added to only when
726 loading snippets. `yas--direct-TABLE-NAME' is then a variable set
727 buffer-locally when entering `yas-minor-mode'. KEYMAP binds all
728 defined direct keybindings to the command
729 `yas-expand-from-keymap' which then which snippet to expand.")
731 (defun yas-direct-keymaps-reload ()
732 "Force reload the direct keybinding for active snippet tables."
734 (setq yas--direct-keymaps nil)
735 (maphash #'(lambda (name table)
736 (push (cons (intern (format "yas--direct-%s" name))
737 (yas--table-direct-keymap table))
738 yas--direct-keymaps))
741 (defun yas--modes-to-activate (&optional mode)
742 "Compute list of mode symbols that are active for `yas-expand' and friends."
743 (defvar yas--dfs) ;We rely on dynbind. We could use `letrec' instead!
744 (let* ((explored (if mode (list mode) ; Building up list in reverse.
745 (cons major-mode (reverse yas--extra-modes))))
748 (cl-loop for neighbour
749 in (cl-list* (get mode 'derived-mode-parent)
750 ;; NOTE: `fboundp' check is redundant
752 (and (fboundp mode) (symbol-function mode))
753 (gethash mode yas--parents))
755 (not (memq neighbour explored))
757 do (push neighbour explored)
758 (funcall yas--dfs neighbour)))))
759 (mapc yas--dfs explored)
760 (nreverse explored)))
762 (defvar yas-minor-mode-hook nil
763 "Hook run when `yas-minor-mode' is turned on.")
766 (define-minor-mode yas-minor-mode
767 "Toggle YASnippet mode.
769 When YASnippet mode is enabled, `yas-expand', normally bound to
770 the TAB key, expands snippets of code depending on the major
773 With no argument, this command toggles the mode.
774 positive prefix argument turns on the mode.
775 Negative prefix argument turns off the mode.
778 \\{yas-minor-mode-map}"
780 ;; The indicator for the mode line.
783 (cond ((and yas-minor-mode (featurep 'yasnippet))
784 ;; Install the direct keymaps in `emulation-mode-map-alists'
785 ;; (we use `add-hook' even though it's not technically a hook,
786 ;; but it works). Then define variables named after modes to
787 ;; index `yas--direct-keymaps'.
789 ;; Also install the post-command-hook.
791 (cl-pushnew 'yas--direct-keymaps emulation-mode-map-alists)
792 (add-hook 'post-command-hook #'yas--post-command-handler nil t)
793 ;; Set the `yas--direct-%s' vars for direct keymap expansion
795 (dolist (mode (yas--modes-to-activate))
796 (let ((name (intern (format "yas--direct-%s" mode))))
797 (set-default name nil)
798 (set (make-local-variable name) t)))
801 (yas--load-pending-jits))
803 ;; Uninstall the direct keymaps and the post-command hook
805 (remove-hook 'post-command-hook #'yas--post-command-handler t)
806 (setq emulation-mode-map-alists
807 (remove 'yas--direct-keymaps emulation-mode-map-alists)))))
809 (defun yas-activate-extra-mode (mode)
810 "Activates the snippets for the given `mode' in the buffer.
812 The function can be called in the hook of a minor mode to
813 activate snippets associated with that mode."
817 (maphash (lambda (k _)
818 (setq modes (cons (list k) modes)))
820 (setq symbol (completing-read
821 "Activate mode: " modes nil t))
823 (when (not (string= "" symbol))
826 (add-to-list (make-local-variable 'yas--extra-modes) mode)
827 (yas--load-pending-jits)))
829 (defun yas-deactivate-extra-mode (mode)
830 "Deactivates the snippets for the given `mode' in the buffer."
834 "Deactivate mode: " (mapcar #'list yas--extra-modes) nil t))))
835 (set (make-local-variable 'yas--extra-modes)
839 (define-obsolete-variable-alias 'yas-dont-activate
840 'yas-dont-activate-functions "0.9.2")
841 (defvar yas-dont-activate-functions (list #'minibufferp)
842 "Special hook to control which buffers `yas-global-mode' affects.
843 Functions are called with no argument, and should return non-nil to prevent
844 `yas-global-mode' from enabling yasnippet in this buffer.
846 In Emacsen < 24, this variable is buffer-local. Because
847 `yas-minor-mode-on' is called by `yas-global-mode' after
848 executing the buffer's major mode hook, setting this variable
849 there is an effective way to define exceptions to the \"global\"
850 activation behaviour.
852 In Emacsen >= 24, only the global value is used. To define
853 per-mode exceptions to the \"global\" activation behaviour, call
854 `yas-minor-mode' with a negative argument directily in the major
856 (unless (> emacs-major-version 23)
858 (make-variable-buffer-local 'yas-dont-activate)))
861 (defun yas-minor-mode-on ()
862 "Turn on YASnippet minor mode.
864 Honour `yas-dont-activate-functions', which see."
867 ;; The old behavior used for Emacs<24 was to set
868 ;; `yas-dont-activate-functions' to t buffer-locally.
869 (not (or (listp yas-dont-activate-functions)
870 (functionp yas-dont-activate-functions)))
871 (run-hook-with-args-until-success 'yas-dont-activate-functions))
875 (define-globalized-minor-mode yas-global-mode yas-minor-mode yas-minor-mode-on
879 (defun yas--global-mode-reload-with-jit-maybe ()
880 "Run `yas-reload-all' when `yas-global-mode' is on."
881 (when yas-global-mode (yas-reload-all)))
883 (add-hook 'yas-global-mode-hook #'yas--global-mode-reload-with-jit-maybe)
888 (defvar yas--font-lock-keywords
889 (append '(("^#.*$" . font-lock-comment-face))
891 (let ((prog-mode-hook nil)
892 (emacs-lisp-mode-hook nil))
893 (ignore-errors (emacs-lisp-mode)))
894 (font-lock-set-defaults)
895 (if (eq t (car-safe font-lock-keywords))
896 ;; They're "compiled", so extract the source.
897 (cadr font-lock-keywords)
900 (0 font-lock-keyword-face)
901 (1 font-lock-string-face t))
903 (0 font-lock-keyword-face)
904 (1 font-lock-warning-face t))
905 ("\\(\\$(\\)" 1 font-lock-preprocessor-face)
907 (0 font-lock-keyword-face)))))
909 (defvar snippet-mode-map
910 (let ((map (make-sparse-keymap)))
911 (easy-menu-define nil
913 "Menu used when snippet-mode is active."
915 (mapcar #'(lambda (ent)
917 (define-key map (third ent) (second ent)))
918 (vector (first ent) (second ent) t))
919 '(("Load this snippet" yas-load-snippet-buffer "\C-c\C-l")
920 ("Load and quit window" yas-load-snippet-buffer-and-close "\C-c\C-c")
921 ("Try out this snippet" yas-tryout-snippet "\C-c\C-t")))))
923 "The keymap used when `snippet-mode' is active.")
927 (define-derived-mode snippet-mode text-mode "Snippet"
928 "A mode for editing yasnippets"
929 (setq font-lock-defaults '(yas--font-lock-keywords))
930 (set (make-local-variable 'require-final-newline) nil)
931 (set (make-local-variable 'comment-start) "#")
932 (set (make-local-variable 'comment-start-skip) "#+[\t ]*"))
936 ;;; Internal structs for template management
938 (cl-defstruct (yas--template
939 (:constructor yas--make-template)
940 ;; Handles `yas-define-snippets' format, plus the
941 ;; initial TABLE argument.
943 yas--define-snippets-2
946 &optional xname condition group
947 expand-env load-file xkeybinding xuuid save-file
950 ;; A little redundant: we always get a name
951 ;; from `yas--parse-template' except when
952 ;; there isn't a file.
953 (and load-file (file-name-nondirectory load-file))
954 (and save-file (file-name-nondirectory save-file))
956 (keybinding (yas--read-keybinding xkeybinding))
957 (uuid (or xuuid name))
958 (old (gethash uuid (yas--table-uuidhash table)))
960 (and old (yas--template-menu-binding-pair old)))
962 (and old (yas--template-perm-group old))))))
963 "A template for a snippet."
974 group ;; as dictated by the #group: directive or .yas-make-groups
975 perm-group ;; as dictated by `yas-define-menu'
979 (defstruct (yas--table (:constructor yas--make-snippet-table (name)))
980 "A table to store snippets for a particular mode.
982 Has the following fields:
986 A symbol name normally corresponding to a major mode, but can
987 also be a pseudo major-mode to be used in
988 `yas-activate-extra-mode', for example.
992 A hash table (KEY . NAMEHASH), known as the \"keyhash\". KEY is
993 a string or a vector, where the former is the snippet's trigger
994 and the latter means it's a direct keybinding. NAMEHASH is yet
995 another hash of (NAME . TEMPLATE) where NAME is the snippet's
996 name and TEMPLATE is a `yas--template' object.
998 `yas--table-direct-keymap'
1000 A keymap for the snippets in this table that have direct
1001 keybindings. This is kept in sync with the keyhash, i.e., all
1002 the elements of the keyhash that are vectors appear here as
1003 bindings to `yas-expand-from-keymap'.
1005 `yas--table-uuidhash'
1007 A hash table mapping snippets uuid's to the same `yas--template'
1008 objects. A snippet uuid defaults to the snippet's name."
1010 (hash (make-hash-table :test 'equal))
1011 (uuidhash (make-hash-table :test 'equal))
1013 (direct-keymap (make-sparse-keymap)))
1015 (defun yas--get-template-by-uuid (mode uuid)
1016 "Find the snippet template in MODE by its UUID."
1017 (let* ((table (gethash mode yas--tables mode)))
1019 (gethash uuid (yas--table-uuidhash table)))))
1021 ;; Apropos storing/updating in TABLE, this works in two steps:
1023 ;; 1. `yas--remove-template-by-uuid' removes any
1024 ;; keyhash-namehash-template mappings from TABLE, grabbing the
1025 ;; snippet by its uuid. Also removes mappings from TABLE's
1026 ;; `yas--table-direct-keymap' (FIXME: and should probably take care
1027 ;; of potentially stale menu bindings right?.)
1029 ;; 2. `yas--add-template' adds this all over again.
1031 ;; Create a new or add to an existing keyhash-namehash mapping.
1033 ;; For reference on understanding this, consider three snippet
1036 ;; A: # name: The Foo
1038 ;; # binding: C-c M-l
1040 ;; B: # name: Mrs Foo
1043 ;; C: # name: The Bar
1044 ;; # binding: C-c M-l
1049 ;; keyhash namehashes(3) yas--template structs(4)
1050 ;; -----------------------------------------------------
1053 ;; "foo" ---> "The Foo" ---> [yas--template A] |
1054 ;; "Mrs Foo" ---> [yas--template B] |
1056 ;; [C-c M-l] ---> "The Foo" -------------------------/
1057 ;; "The Bar" ---> [yas--template C]
1059 ;; "baz" ---> "Baz" ---> [yas--template D]
1061 ;; Additionally, since uuid defaults to the name, we have a
1062 ;; `yas--table-uuidhash' for TABLE
1064 ;; uuidhash yas--template structs
1065 ;; -------------------------------
1066 ;; "The Foo" ---> [yas--template A]
1067 ;; "Mrs Foo" ---> [yas--template B]
1068 ;; "The Bar" ---> [yas--template C]
1069 ;; "Baz" ---> [yas--template D]
1071 ;; FIXME: the more I look at this data-structure the more I think I'm
1072 ;; stupid. There has to be an easier way (but beware lots of code
1073 ;; depends on this).
1075 (defun yas--remove-template-by-uuid (table uuid)
1076 "Remove from TABLE a template identified by UUID."
1077 (let ((template (gethash uuid (yas--table-uuidhash table))))
1079 (let* ((name (yas--template-name template))
1081 ;; Remove the name from each of the targeted namehashes
1083 (maphash #'(lambda (k v)
1084 (let ((template (gethash name v)))
1086 (eq uuid (yas--template-uuid template)))
1088 (when (zerop (hash-table-count v))
1089 (push k empty-keys)))))
1090 (yas--table-hash table))
1091 ;; Remove the namehash themselves if they've become empty
1093 (dolist (key empty-keys)
1095 (define-key (yas--table-direct-keymap table) key nil))
1096 (remhash key (yas--table-hash table)))
1098 ;; Finally, remove the uuid from the uuidhash
1100 (remhash uuid (yas--table-uuidhash table))))))
1102 (defun yas--add-template (table template)
1103 "Store in TABLE the snippet template TEMPLATE.
1105 KEY can be a string (trigger key) of a vector (direct
1107 (let ((name (yas--template-name template))
1108 (key (yas--template-key template))
1109 (keybinding (yas--template-keybinding template))
1110 (_menu-binding-pair (yas--template-menu-binding-pair-get-create template)))
1111 (dolist (k (remove nil (list key keybinding)))
1115 (yas--table-hash table))
1117 (make-hash-table :test 'equal)
1118 (yas--table-hash table))))
1120 (define-key (yas--table-direct-keymap table) k 'yas-expand-from-keymap)))
1122 ;; Update TABLE's `yas--table-uuidhash'
1123 (puthash (yas--template-uuid template)
1125 (yas--table-uuidhash table))))
1127 (defun yas--update-template (table template)
1128 "Add or update TEMPLATE in TABLE.
1130 Also takes care of adding and updating to the associated menu.
1132 ;; Remove from table by uuid
1134 (yas--remove-template-by-uuid table (yas--template-uuid template))
1135 ;; Add to table again
1137 (yas--add-template table template)
1138 ;; Take care of the menu
1140 (yas--update-template-menu table template)
1143 (defun yas--update-template-menu (table template)
1144 "Update every menu-related for TEMPLATE."
1145 (let ((menu-binding-pair (yas--template-menu-binding-pair-get-create template))
1146 (key (yas--template-key template))
1147 (keybinding (yas--template-keybinding template)))
1148 ;; The snippet might have changed name or keys, so update
1149 ;; user-visible strings
1151 (unless (eq (cdr menu-binding-pair) :none)
1152 ;; the menu item name
1154 (setf (cadar menu-binding-pair) (yas--template-name template))
1155 ;; the :keys information (also visible to the user)
1156 (setf (getf (cdr (car menu-binding-pair)) :keys)
1157 (or (and keybinding (key-description keybinding))
1158 (and key (concat key yas-trigger-symbol))))))
1159 (unless (yas--template-menu-managed-by-yas-define-menu template)
1161 (yas--menu-keymap-get-create (yas--table-mode table)
1162 (mapcar #'yas--table-mode
1163 (yas--table-parents table))))
1164 (group (yas--template-group template)))
1165 ;; Remove from menu keymap
1167 (assert menu-keymap)
1168 (yas--delete-from-keymap menu-keymap (yas--template-uuid template))
1170 ;; Add necessary subgroups as necessary.
1172 (dolist (subgroup group)
1173 (let ((subgroup-keymap (lookup-key menu-keymap (vector (make-symbol subgroup)))))
1174 (unless (and subgroup-keymap
1175 (keymapp subgroup-keymap))
1176 (setq subgroup-keymap (make-sparse-keymap))
1177 (define-key menu-keymap (vector (make-symbol subgroup))
1178 `(menu-item ,subgroup ,subgroup-keymap)))
1179 (setq menu-keymap subgroup-keymap)))
1181 ;; Add this entry to the keymap
1183 (define-key menu-keymap
1184 (vector (make-symbol (yas--template-uuid template)))
1185 (car (yas--template-menu-binding-pair template))))))
1187 (defun yas--namehash-templates-alist (namehash)
1188 "Return NAMEHASH as an alist."
1190 (maphash #'(lambda (k v)
1191 (push (cons k v) alist))
1195 (defun yas--fetch (table key)
1196 "Fetch templates in TABLE by KEY.
1198 Return a list of cons (NAME . TEMPLATE) where NAME is a
1199 string and TEMPLATE is a `yas--template' structure."
1200 (let* ((keyhash (yas--table-hash table))
1201 (namehash (and keyhash (gethash key keyhash))))
1203 (yas--filter-templates-by-condition (yas--namehash-templates-alist namehash)))))
1206 ;;; Filtering/condition logic
1208 (defun yas--eval-condition (condition)
1215 (yas--message 1 "Error in condition evaluation: %s" (error-message-string err))
1219 (defun yas--filter-templates-by-condition (templates)
1220 "Filter the templates using the applicable condition.
1222 TEMPLATES is a list of cons (NAME . TEMPLATE) where NAME is a
1223 string and TEMPLATE is a `yas--template' structure.
1225 This function implements the rules described in
1226 `yas-buffer-local-condition'. See that variables documentation."
1227 (let ((requirement (yas--require-template-specific-condition-p)))
1228 (if (eq requirement 'always)
1230 (remove-if-not #'(lambda (pair)
1231 (yas--template-can-expand-p
1232 (yas--template-condition (cdr pair)) requirement))
1235 (defun yas--require-template-specific-condition-p ()
1236 "Decide if this buffer requests/requires snippet-specific
1237 conditions to filter out potential expansions."
1238 (if (eq 'always yas-buffer-local-condition)
1240 (let ((local-condition (or (and (consp yas-buffer-local-condition)
1241 (yas--eval-condition yas-buffer-local-condition))
1242 yas-buffer-local-condition)))
1243 (when local-condition
1244 (if (eq local-condition t)
1246 (and (consp local-condition)
1247 (eq 'require-snippet-condition (car local-condition))
1248 (symbolp (cdr local-condition))
1249 (cdr local-condition)))))))
1251 (defun yas--template-can-expand-p (condition requirement)
1252 "Evaluate CONDITION and REQUIREMENT and return a boolean."
1253 (let* ((result (or (null condition)
1254 (yas--eval-condition condition))))
1255 (cond ((eq requirement t)
1258 (eq requirement result)))))
1260 (defun yas--table-templates (table)
1263 (maphash #'(lambda (_key namehash)
1264 (maphash #'(lambda (name template)
1265 (push (cons name template) acc))
1267 (yas--table-hash table))
1268 (yas--filter-templates-by-condition acc))))
1270 (defun yas--templates-for-key-at-point ()
1271 "Find `yas--template' objects for any trigger keys preceding point.
1272 Returns (TEMPLATES START END). This function respects
1273 `yas-key-syntaxes', which see."
1275 (let ((original (point))
1276 (methods yas-key-syntaxes)
1281 (unless (eq method (car methods))
1282 ;; TRICKY: `eq'-ness test means we can only be here if
1283 ;; `method' is a function that returned `again', and hence
1284 ;; don't revert back to original position as per
1285 ;; `yas-key-syntaxes'.
1286 (goto-char original))
1287 (setq method (car methods))
1288 (cond ((stringp method)
1289 (skip-syntax-backward method)
1290 (setq methods (cdr methods)))
1292 (unless (eq (funcall method original)
1294 (setq methods (cdr methods))))
1296 (setq methods (cdr methods))
1297 (yas--warning "Invalid element `%s' in `yas-key-syntaxes'" method)))
1298 (let ((possible-key (buffer-substring-no-properties (point) original)))
1300 (goto-char original)
1302 (mapcan #'(lambda (table)
1303 (yas--fetch table possible-key))
1304 (yas--get-snippet-tables))))))
1306 (list templates (point) original)))))
1308 (defun yas--table-all-keys (table)
1309 "Get trigger keys of all active snippets in TABLE."
1311 (maphash #'(lambda (key namehash)
1312 (when (yas--filter-templates-by-condition (yas--namehash-templates-alist namehash))
1314 (yas--table-hash table))
1317 (defun yas--table-mode (table)
1318 (intern (yas--table-name table)))
1321 ;;; Internal functions and macros:
1323 (defun yas--handle-error (err)
1324 "Handle error depending on value of `yas-good-grace'."
1325 (let ((msg (yas--format "elisp error: %s" (error-message-string err))))
1326 (if yas-good-grace msg
1329 (defun yas--eval-lisp (form)
1330 "Evaluate FORM and convert the result to string."
1331 (let ((retval (catch 'yas--exception
1337 (let ((result (eval form)))
1339 (format "%s" result))))))
1340 (error (yas--handle-error err))))))
1341 (when (and (consp retval)
1342 (eq 'yas--exception (car retval)))
1343 (error (cdr retval)))
1346 (defun yas--eval-lisp-no-saves (form)
1349 (error (message "%s" (yas--handle-error err)))))
1351 (defun yas--read-lisp (string &optional nil-on-error)
1352 "Read STRING as a elisp expression and return it.
1354 In case STRING in an invalid expression and NIL-ON-ERROR is nil,
1355 return an expression that when evaluated will issue an error."
1358 (error (and (not nil-on-error)
1359 `(error (error-message-string ,err))))))
1361 (defun yas--read-keybinding (keybinding)
1362 "Read KEYBINDING as a snippet keybinding, return a vector."
1363 (when (and keybinding
1364 (not (string-match "keybinding" keybinding)))
1366 (let ((res (or (and (string-match "^\\[.*\\]$" keybinding)
1368 (read-kbd-macro keybinding 'need-vector))))
1371 (yas--message 2 "warning: keybinding \"%s\" invalid since %s."
1372 keybinding (error-message-string err))
1375 (defun yas--table-get-create (mode)
1376 "Get or create the snippet table corresponding to MODE."
1377 (let ((table (gethash mode
1380 (setq table (yas--make-snippet-table (symbol-name mode)))
1381 (puthash mode table yas--tables)
1382 (push (cons (intern (format "yas--direct-%s" mode))
1383 (yas--table-direct-keymap table))
1384 yas--direct-keymaps))
1387 (defun yas--get-snippet-tables (&optional mode)
1388 "Get snippet tables for MODE.
1390 MODE defaults to the current buffer's `major-mode'.
1392 Return a list of `yas--table' objects. The list of modes to
1393 consider is returned by `yas--modes-to-activate'"
1395 (mapcar #'(lambda (name)
1396 (gethash name yas--tables))
1397 (yas--modes-to-activate mode))))
1399 (defun yas--menu-keymap-get-create (mode &optional parents)
1400 "Get or create the menu keymap for MODE and its PARENTS.
1402 This may very well create a plethora of menu keymaps and arrange
1403 them all in `yas--menu-table'"
1404 (let* ((menu-keymap (or (gethash mode yas--menu-table)
1405 (puthash mode (make-sparse-keymap) yas--menu-table))))
1406 (mapc #'yas--menu-keymap-get-create parents)
1407 (define-key yas--minor-mode-menu (vector mode)
1408 `(menu-item ,(symbol-name mode) ,menu-keymap
1409 :visible (yas--show-menu-p ',mode)))
1413 ;;; Template-related and snippet loading functions
1415 (defun yas--parse-template (&optional file)
1416 "Parse the template in the current buffer.
1418 Optional FILE is the absolute file name of the file being
1421 Optional GROUP is the group where the template is to go,
1422 otherwise we attempt to calculate it from FILE.
1424 Return a snippet-definition, i.e. a list
1426 (KEY TEMPLATE NAME CONDITION GROUP VARS LOAD-FILE KEYBINDING UUID)
1428 If the buffer contains a line of \"# --\" then the contents above
1429 this line are ignored. Directives can set most of these with the syntax:
1431 # directive-name : directive-value
1433 Here's a list of currently recognized directives:
1444 (goto-char (point-min))
1445 (let* ((type 'snippet)
1447 (file-name-nondirectory file)))
1453 (yas--calculate-group file)))
1457 (if (re-search-forward "^# --\n" nil t)
1458 (progn (setq template
1459 (buffer-substring-no-properties (point)
1461 (setq bound (point))
1462 (goto-char (point-min))
1463 (while (re-search-forward "^# *\\([^ ]+?\\) *: *\\(.*?\\)[[:space:]]*$" bound t)
1464 (when (string= "uuid" (match-string-no-properties 1))
1465 (setq uuid (match-string-no-properties 2)))
1466 (when (string= "type" (match-string-no-properties 1))
1467 (setq type (if (string= "command" (match-string-no-properties 2))
1470 (when (string= "key" (match-string-no-properties 1))
1471 (setq key (match-string-no-properties 2)))
1472 (when (string= "name" (match-string-no-properties 1))
1473 (setq name (match-string-no-properties 2)))
1474 (when (string= "condition" (match-string-no-properties 1))
1475 (setq condition (yas--read-lisp (match-string-no-properties 2))))
1476 (when (string= "group" (match-string-no-properties 1))
1477 (setq group (match-string-no-properties 2)))
1478 (when (string= "expand-env" (match-string-no-properties 1))
1479 (setq expand-env (yas--read-lisp (match-string-no-properties 2)
1481 (when (string= "binding" (match-string-no-properties 1))
1482 (setq binding (match-string-no-properties 2)))))
1484 (buffer-substring-no-properties (point-min) (point-max))))
1485 (unless (or key binding)
1486 (setq key (and file (file-name-nondirectory file))))
1487 (when (eq type 'command)
1488 (setq template (yas--read-lisp (concat "(progn" template ")"))))
1490 (setq group (split-string group "\\.")))
1491 (list key template name condition group expand-env file binding uuid)))
1493 (defun yas--calculate-group (file)
1494 "Calculate the group for snippet file path FILE."
1495 (let* ((dominating-dir (locate-dominating-file file
1496 ".yas-make-groups"))
1497 (extra-path (and dominating-dir
1498 (file-relative-name file dominating-dir)))
1499 (extra-dir (and extra-path
1500 (file-name-directory extra-path)))
1501 (group (and extra-dir
1502 (replace-regexp-in-string "/"
1504 (directory-file-name extra-dir)))))
1507 (defun yas--subdirs (directory &optional filep)
1508 "Return subdirs or files of DIRECTORY according to FILEP."
1509 (cl-remove-if (lambda (file)
1510 (or (string-match "\\`\\."
1511 (file-name-nondirectory file))
1512 (string-match "\\`#.*#\\'"
1513 (file-name-nondirectory file))
1514 (string-match "~\\'"
1515 (file-name-nondirectory file))
1517 (file-directory-p file)
1518 (not (file-directory-p file)))))
1519 (directory-files directory t)))
1521 (defun yas--make-menu-binding (template)
1522 (let ((mode (yas--table-mode (yas--template-table template))))
1523 `(lambda () (interactive) (yas--expand-or-visit-from-menu ',mode ,(yas--template-uuid template)))))
1525 (defun yas--expand-or-visit-from-menu (mode uuid)
1526 (let* ((table (yas--table-get-create mode))
1527 (yas--current-template (and table
1528 (gethash uuid (yas--table-uuidhash table)))))
1529 (when yas--current-template
1530 (if yas-visit-from-menu
1531 (yas--visit-snippet-file-1 yas--current-template)
1532 (let ((where (if (region-active-p)
1533 (cons (region-beginning) (region-end))
1534 (cons (point) (point)))))
1535 (yas-expand-snippet (yas--template-content yas--current-template)
1538 (yas--template-expand-env yas--current-template)))))))
1540 (defun yas--key-from-desc (text)
1541 "Return a yasnippet key from a description string TEXT."
1542 (replace-regexp-in-string "\\(\\w+\\).*" "\\1" text))
1545 ;;; Popping up for keys and templates
1547 (defun yas--prompt-for-template (templates &optional prompt)
1548 "Interactively choose a template from the list TEMPLATES.
1550 TEMPLATES is a list of `yas--template'.
1552 Optional PROMPT sets the prompt to use."
1555 (sort templates #'(lambda (t1 t2)
1556 (< (length (yas--template-name t1))
1557 (length (yas--template-name t2))))))
1558 (some #'(lambda (fn)
1559 (funcall fn (or prompt "Choose a snippet: ")
1561 #'yas--template-name))
1562 yas-prompt-functions)))
1564 (defun yas--prompt-for-keys (keys &optional prompt)
1565 "Interactively choose a template key from the list KEYS.
1567 Optional PROMPT sets the prompt to use."
1569 (some #'(lambda (fn)
1570 (funcall fn (or prompt "Choose a snippet key: ") keys))
1571 yas-prompt-functions)))
1573 (defun yas--prompt-for-table (tables &optional prompt)
1574 "Interactively choose a table from the list TABLES.
1576 Optional PROMPT sets the prompt to use."
1578 (some #'(lambda (fn)
1579 (funcall fn (or prompt "Choose a snippet table: ")
1582 yas-prompt-functions)))
1584 (defun yas-x-prompt (prompt choices &optional display-fn)
1585 "Display choices in a x-window prompt."
1586 (when (and window-system choices)
1587 ;; Let window position be recalculated to ensure that
1588 ;; `posn-at-point' returns non-nil.
1592 (if (fboundp 'posn-at-point)
1593 (let ((x-y (posn-x-y (posn-at-point (point)))))
1594 (list (list (+ (car x-y) 10)
1599 ,@(mapcar* (lambda (c d) `(,(concat " " d) . ,c))
1601 (if display-fn (mapcar display-fn choices) choices)))))
1604 (defun yas-maybe-ido-prompt (prompt choices &optional display-fn)
1605 (when (bound-and-true-p ido-mode)
1606 (yas-ido-prompt prompt choices display-fn)))
1608 (defun yas-ido-prompt (prompt choices &optional display-fn)
1610 (yas-completing-prompt prompt choices display-fn #'ido-completing-read))
1612 (defun yas-dropdown-prompt (_prompt choices &optional display-fn)
1613 (when (fboundp 'dropdown-list)
1614 (let* ((formatted-choices
1615 (if display-fn (mapcar display-fn choices) choices))
1616 (n (dropdown-list formatted-choices)))
1617 (if n (nth n choices)
1620 (defun yas-completing-prompt (prompt choices &optional display-fn completion-fn)
1621 (let* ((formatted-choices
1622 (if display-fn (mapcar display-fn choices) choices))
1623 (chosen (funcall (or completion-fn #'completing-read)
1624 prompt formatted-choices
1625 nil 'require-match nil nil)))
1626 (if (eq choices formatted-choices)
1628 (nth (or (position chosen formatted-choices :test #'string=) 0)
1631 (defun yas-no-prompt (_prompt choices &optional _display-fn)
1635 ;;; Defining snippets
1636 ;; This consists of creating and registering `yas--template' objects in the
1640 (defvar yas--creating-compiled-snippets nil)
1642 (defun yas--define-snippets-1 (snippet snippet-table)
1643 "Helper for `yas-define-snippets'."
1644 ;; Update the appropriate table. Also takes care of adding the
1645 ;; key indicators in the templates menu entry, if any.
1646 (yas--update-template
1647 snippet-table (apply #'yas--define-snippets-2 snippet-table snippet)))
1649 (defun yas-define-snippets (mode snippets)
1650 "Define SNIPPETS for MODE.
1652 SNIPPETS is a list of snippet definitions, each taking the
1655 (KEY TEMPLATE NAME CONDITION GROUP EXPAND-ENV LOAD-FILE KEYBINDING UUID SAVE-FILE)
1657 Within these, only KEY and TEMPLATE are actually mandatory.
1659 TEMPLATE might be a Lisp form or a string, depending on whether
1660 this is a snippet or a snippet-command.
1662 CONDITION, EXPAND-ENV and KEYBINDING are Lisp forms, they have
1663 been `yas--read-lisp'-ed and will eventually be
1664 `yas--eval-lisp'-ed.
1666 The remaining elements are strings.
1668 FILE is probably of very little use if you're programatically
1671 UUID is the snippet's \"unique-id\". Loading a second snippet
1672 file with the same uuid would replace the previous snippet.
1674 You can use `yas--parse-template' to return such lists based on
1675 the current buffers contents."
1676 (if yas--creating-compiled-snippets
1677 (let ((print-length nil))
1678 (insert ";;; Snippet definitions:\n;;;\n")
1679 (dolist (snippet snippets)
1680 ;; Fill in missing elements with nil.
1681 (setq snippet (append snippet (make-list (- 10 (length snippet)) nil)))
1682 ;; Move LOAD-FILE to SAVE-FILE because we will load from the
1683 ;; compiled file, not LOAD-FILE.
1684 (let ((load-file (nth 6 snippet)))
1685 (setcar (nthcdr 6 snippet) nil)
1686 (setcar (nthcdr 9 snippet) load-file)))
1687 (insert (pp-to-string
1688 `(yas-define-snippets ',mode ',snippets)))
1691 (let ((snippet-table (yas--table-get-create mode))
1693 (dolist (snippet snippets)
1694 (setq template (yas--define-snippets-1 snippet
1699 ;;; Loading snippets from files
1701 (defun yas--template-get-file (template)
1702 "Return TEMPLATE's LOAD-FILE or SAVE-FILE."
1703 (or (yas--template-load-file template)
1704 (let ((file (yas--template-save-file template)))
1706 (yas--message 3 "%s has no load file, using save file, %s, instead."
1707 (yas--template-name template) file))
1710 (defun yas--load-yas-setup-file (file)
1711 (if (not yas--creating-compiled-snippets)
1713 (load file 'noerror (<= yas-verbosity 4))
1714 (let ((elfile (concat file ".el")))
1715 (when (file-exists-p elfile)
1716 (insert ";;; contents of the .yas-setup.el support file:\n;;;\n")
1717 (insert-file-contents elfile)
1718 (goto-char (point-max))))))
1720 (defun yas--define-parents (mode parents)
1721 "Add PARENTS to the list of MODE's parents."
1722 (puthash mode (remove-duplicates
1724 (gethash mode yas--parents)))
1727 (defun yas-load-directory (top-level-dir &optional use-jit interactive)
1728 "Load snippets in directory hierarchy TOP-LEVEL-DIR.
1730 Below TOP-LEVEL-DIR each directory should be a mode name.
1732 With prefix argument USE-JIT do jit-loading of snippets."
1734 (list (read-directory-name "Select the root directory: " nil nil t)
1735 current-prefix-arg t))
1736 (unless yas-snippet-dirs
1737 (setq yas-snippet-dirs top-level-dir))
1738 (let ((impatient-buffers))
1739 (dolist (dir (yas--subdirs top-level-dir))
1740 (let* ((major-mode-and-parents (yas--compute-major-mode-and-parents
1741 (concat dir "/dummy")))
1742 (mode-sym (car major-mode-and-parents))
1743 (parents (cdr major-mode-and-parents)))
1744 ;; Attention: The parents and the menus are already defined
1745 ;; here, even if the snippets are later jit-loaded.
1747 ;; * We need to know the parents at this point since entering a
1748 ;; given mode should jit load for its parents
1749 ;; immediately. This could be reviewed, the parents could be
1750 ;; discovered just-in-time-as well
1752 ;; * We need to create the menus here to support the `full'
1753 ;; option to `yas-use-menu' (all known snippet menus are shown to the user)
1755 (yas--define-parents mode-sym parents)
1756 (yas--menu-keymap-get-create mode-sym)
1757 (let ((fun `(lambda () ;; FIXME: Simulating lexical-binding.
1758 (yas--load-directory-1 ',dir ',mode-sym))))
1760 (yas--schedule-jit mode-sym fun)
1762 ;; Look for buffers that are already in `mode-sym', and so
1763 ;; need the new snippets immediately...
1766 (cl-loop for buffer in (buffer-list)
1767 do (with-current-buffer buffer
1768 (when (eq major-mode mode-sym)
1769 (yas--message 4 "Discovered there was already %s in %s" buffer mode-sym)
1770 (push buffer impatient-buffers)))))))
1771 ;; ...after TOP-LEVEL-DIR has been completely loaded, call
1772 ;; `yas--load-pending-jits' in these impatient buffers.
1774 (cl-loop for buffer in impatient-buffers
1775 do (with-current-buffer buffer (yas--load-pending-jits))))
1777 (yas--message 3 "Loaded snippets from %s." top-level-dir)))
1779 (defun yas--load-directory-1 (directory mode-sym)
1780 "Recursively load snippet templates from DIRECTORY."
1781 (if yas--creating-compiled-snippets
1782 (let ((output-file (expand-file-name ".yas-compiled-snippets.el"
1784 (with-temp-file output-file
1785 (insert (format ";;; Compiled snippets and support files for `%s'\n"
1787 (yas--load-directory-2 directory mode-sym)
1788 (insert (format ";;; Do not edit! File generated at %s\n"
1789 (current-time-string)))))
1791 (unless (file-exists-p (expand-file-name ".yas-skip" directory))
1792 (unless (and (load (expand-file-name ".yas-compiled-snippets" directory) 'noerror (<= yas-verbosity 3))
1793 (progn (yas--message 4 "Loaded compiled snippets from %s" directory) t))
1794 (yas--message 4 "Loading snippet files from %s" directory)
1795 (yas--load-directory-2 directory mode-sym)))))
1797 (defun yas--load-directory-2 (directory mode-sym)
1798 ;; Load .yas-setup.el files wherever we find them
1800 (yas--load-yas-setup-file (expand-file-name ".yas-setup" directory))
1801 (let* ((default-directory directory)
1803 ;; load the snippet files
1806 (dolist (file (yas--subdirs directory 'no-subdirs-just-files))
1807 (when (file-readable-p file)
1808 (insert-file-contents file nil nil nil t)
1809 (push (yas--parse-template file)
1812 (yas-define-snippets mode-sym
1814 ;; now recurse to a lower level
1816 (dolist (subdir (yas--subdirs directory))
1817 (yas--load-directory-2 subdir
1820 (defun yas--load-snippet-dirs (&optional nojit)
1821 "Reload the directories listed in `yas-snippet-dirs' or
1822 prompt the user to select one."
1824 (if (null yas-snippet-dirs)
1825 (call-interactively 'yas-load-directory)
1826 (when (member yas--default-user-snippets-dir yas-snippet-dirs)
1827 (make-directory yas--default-user-snippets-dir t))
1828 (dolist (directory (reverse (yas-snippet-dirs)))
1829 (cond ((file-directory-p directory)
1830 (yas-load-directory directory (not nojit))
1832 (yas--message 4 "Loaded %s" directory)
1833 (yas--message 4 "Prepared just-in-time loading for %s" directory)))
1835 (push (yas--message 0 "Check your `yas-snippet-dirs': %s is not a directory" directory) errors)))))
1838 (defun yas-reload-all (&optional no-jit interactive)
1839 "Reload all snippets and rebuild the YASnippet menu.
1841 When NO-JIT is non-nil force immediate reload of all known
1842 snippets under `yas-snippet-dirs', otherwise use just-in-time
1845 When called interactively, use just-in-time loading when given a
1847 (interactive (list (not current-prefix-arg) t))
1850 (snippet-editing-buffers
1851 (remove-if-not #'(lambda (buffer)
1852 (with-current-buffer buffer yas--editing-template))
1854 ;; Warn if there are buffers visiting snippets, since reloading will break
1855 ;; any on-line editing of those buffers.
1857 (when snippet-editing-buffers
1859 (if (y-or-n-p "Some buffers editing live snippets, close them and proceed with reload? ")
1860 (mapc #'kill-buffer snippet-editing-buffers)
1861 (yas--message 1 "Aborted reload...")
1863 ;; in a non-interactive use, at least set
1864 ;; `yas--editing-template' to nil, make it guess it next time around
1865 (mapc #'(lambda (buffer)
1866 (with-current-buffer buffer
1867 (kill-local-variable 'yas--editing-template)))
1870 ;; Empty all snippet tables and parenting info
1872 (setq yas--tables (make-hash-table))
1873 (setq yas--parents (make-hash-table))
1875 ;; Before killing `yas--menu-table' use its keys to cleanup the
1876 ;; mode menu parts of `yas--minor-mode-menu' (thus also cleaning
1877 ;; up `yas-minor-mode-map', which points to it)
1879 (maphash #'(lambda (menu-symbol _keymap)
1880 (define-key yas--minor-mode-menu (vector menu-symbol) nil))
1882 ;; Now empty `yas--menu-table' as well
1883 (setq yas--menu-table (make-hash-table))
1885 ;; Cancel all pending 'yas--scheduled-jit-loads'
1887 (setq yas--scheduled-jit-loads (make-hash-table))
1889 ;; Reload the directories listed in `yas-snippet-dirs' or prompt
1890 ;; the user to select one.
1892 (setq errors (yas--load-snippet-dirs no-jit))
1893 ;; Reload the direct keybindings
1895 (yas-direct-keymaps-reload)
1897 (run-hooks 'yas-after-reload-hook)
1898 (yas--message (if errors 2 3) "Reloaded everything%s...%s."
1899 (if no-jit "" " (snippets will load just-in-time)")
1900 (if errors " (some errors, check *Messages*)" "")))))
1902 (defvar yas-after-reload-hook nil
1903 "Hooks run after `yas-reload-all'.")
1905 (defun yas--load-pending-jits ()
1906 (dolist (mode (yas--modes-to-activate))
1907 (let ((funs (reverse (gethash mode yas--scheduled-jit-loads))))
1908 ;; must reverse to maintain coherence with `yas-snippet-dirs'
1910 (yas--message 4 "Loading for `%s', just-in-time: %s!" mode fun)
1912 (remhash mode yas--scheduled-jit-loads))))
1914 ;; (when (<= emacs-major-version 22)
1915 ;; (add-hook 'after-change-major-mode-hook 'yas--load-pending-jits))
1917 (defun yas--quote-string (string)
1918 "Escape and quote STRING.
1919 foo\"bar\\! -> \"foo\\\"bar\\\\!\""
1921 (replace-regexp-in-string "[\\\"]"
1927 ;;; Snippet compilation function
1929 (defun yas-compile-directory (top-level-dir)
1930 "Create .yas-compiled-snippets.el files under subdirs of TOP-LEVEL-DIR.
1932 This works by stubbing a few functions, then calling
1933 `yas-load-directory'."
1934 (interactive "DTop level snippet directory?")
1935 (let ((yas--creating-compiled-snippets t))
1936 (yas-load-directory top-level-dir nil)))
1938 (defun yas-recompile-all ()
1939 "Compile every dir in `yas-snippet-dirs'."
1941 (mapc #'yas-compile-directory (yas-snippet-dirs)))
1947 (defvar yas--scheduled-jit-loads (make-hash-table)
1948 "Alist of mode-symbols to forms to be evaled when `yas-minor-mode' kicks in.")
1950 (defun yas--schedule-jit (mode fun)
1951 (push fun (gethash mode yas--scheduled-jit-loads)))
1955 ;;; Some user level functions
1959 (message (concat "yasnippet (version "
1961 ") -- pluskid/joaotavora/npostavs")))
1964 ;;; Apropos snippet menu:
1966 ;; The snippet menu keymaps are stored by mode in hash table called
1967 ;; `yas--menu-table'. They are linked to the main menu in
1968 ;; `yas--menu-keymap-get-create' and are initially created empty,
1969 ;; reflecting the table hierarchy.
1971 ;; They can be populated in two mutually exclusive ways: (1) by
1972 ;; reading `yas--template-group', which in turn is populated by the "#
1973 ;; group:" directives of the snippets or the ".yas-make-groups" file
1974 ;; or (2) by using a separate `yas-define-menu' call, which declares a
1975 ;; menu structure based on snippets uuids.
1977 ;; Both situations are handled in `yas--update-template-menu', which
1978 ;; uses the predicate `yas--template-menu-managed-by-yas-define-menu'
1979 ;; that can tell between the two situations.
1983 ;; * if `yas-define-menu' is used it must run before
1984 ;; `yas-define-snippets' and the UUIDS must match, otherwise we get
1985 ;; duplicate entries. The `yas--template' objects are created in
1986 ;; `yas-define-menu', holding nothing but the menu entry,
1987 ;; represented by a pair of ((menu-item NAME :keys KEYS) TYPE) and
1988 ;; stored in `yas--template-menu-binding-pair'. The (menu-item ...)
1989 ;; part is then stored in the menu keymap itself which make the item
1990 ;; appear to the user. These limitations could probably be revised.
1992 ;; * The `yas--template-perm-group' slot is only used in
1993 ;; `yas-describe-tables'.
1995 (defun yas--template-menu-binding-pair-get-create (template &optional type)
1996 "Get TEMPLATE's menu binding or assign it a new one.
1998 TYPE may be `:stay', signaling this menu binding should be
1999 static in the menu."
2000 (or (yas--template-menu-binding-pair template)
2001 (let (;; (key (yas--template-key template))
2002 ;; (keybinding (yas--template-keybinding template))
2004 (setf (yas--template-menu-binding-pair template)
2005 (cons `(menu-item ,(or (yas--template-name template)
2006 (yas--template-uuid template))
2007 ,(yas--make-menu-binding template)
2010 (defun yas--template-menu-managed-by-yas-define-menu (template)
2011 "Non-nil if TEMPLATE's menu entry was included in a `yas-define-menu' call."
2012 (cdr (yas--template-menu-binding-pair template)))
2015 (defun yas--show-menu-p (mode)
2016 (cond ((eq yas-use-menu 'abbreviate)
2018 (mapcar #'(lambda (table)
2019 (yas--table-mode table))
2020 (yas--get-snippet-tables))))
2023 (defun yas--delete-from-keymap (keymap uuid)
2024 "Recursively delete items with UUID from KEYMAP and its submenus."
2026 ;; XXX: This used to skip any submenus named \"parent mode\"
2028 ;; First of all, recursively enter submenus, i.e. the tree is
2029 ;; searched depth first so that stale submenus can be found in the
2032 (mapc #'(lambda (item)
2033 (when (and (listp (cdr item))
2034 (keymapp (third (cdr item))))
2035 (yas--delete-from-keymap (third (cdr item)) uuid)))
2037 ;; Set the uuid entry to nil
2039 (define-key keymap (vector (make-symbol uuid)) nil)
2040 ;; Destructively modify keymap
2042 (setcdr keymap (delete-if #'(lambda (item)
2043 (or (null (cdr item))
2044 (and (keymapp (third (cdr item)))
2045 (null (cdr (third (cdr item)))))))
2048 (defun yas-define-menu (mode menu &optional omit-items)
2049 "Define a snippet menu for MODE according to MENU, omitting OMIT-ITEMS.
2051 MENU is a list, its elements can be:
2053 - (yas-item UUID) : Creates an entry the snippet identified with
2054 UUID. The menu entry for a snippet thus identified is
2055 permanent, i.e. it will never move (be reordered) in the menu.
2057 - (yas-separator) : Creates a separator
2059 - (yas-submenu NAME SUBMENU) : Creates a submenu with NAME,
2060 SUBMENU has the same form as MENU. NAME is also added to the
2061 list of groups of the snippets defined thereafter.
2063 OMIT-ITEMS is a list of snippet uuid's that will always be
2064 omitted from MODE's menu, even if they're manually loaded."
2065 (let* ((table (yas--table-get-create mode))
2066 (hash (yas--table-uuidhash table)))
2067 (yas--define-menu-1 table
2068 (yas--menu-keymap-get-create mode)
2071 (dolist (uuid omit-items)
2072 (let ((template (or (gethash uuid hash)
2074 (yas--make-template :table table
2077 (setf (yas--template-menu-binding-pair template) (cons nil :none))))))
2079 (defun yas--define-menu-1 (table menu-keymap menu uuidhash &optional group-list)
2080 "Helper for `yas-define-menu'."
2081 (dolist (e (reverse menu))
2082 (cond ((eq (first e) 'yas-item)
2083 (let ((template (or (gethash (second e) uuidhash)
2087 :perm-group group-list
2090 (define-key menu-keymap (vector (gensym))
2091 (car (yas--template-menu-binding-pair-get-create template :stay)))))
2092 ((eq (first e) 'yas-submenu)
2093 (let ((subkeymap (make-sparse-keymap)))
2094 (define-key menu-keymap (vector (gensym))
2095 `(menu-item ,(second e) ,subkeymap))
2096 (yas--define-menu-1 table
2100 (append group-list (list (second e))))))
2101 ((eq (first e) 'yas-separator)
2102 (define-key menu-keymap (vector (gensym))
2103 '(menu-item "----")))
2105 (yas--message 1 "Don't know anything about menu entry %s" (first e))))))
2107 (defun yas--define (mode key template &optional name condition group)
2108 "Define a snippet. Expanding KEY into TEMPLATE.
2110 NAME is a description to this template. Also update the menu if
2111 `yas-use-menu' is t. CONDITION is the condition attached to
2112 this snippet. If you attach a condition to a snippet, then it
2113 will only be expanded when the condition evaluated to non-nil."
2114 (yas-define-snippets mode
2115 (list (list key template name condition group))))
2117 (defun yas-hippie-try-expand (first-time?)
2118 "Integrate with hippie expand.
2120 Just put this function in `hippie-expand-try-functions-list'."
2121 (when yas-minor-mode
2122 (if (not first-time?)
2123 (let ((yas-fallback-behavior 'return-nil))
2129 ;;; Apropos condition-cache:
2134 (defvar yas--condition-cache-timestamp nil)
2135 (defmacro yas-define-condition-cache (func doc &rest body)
2136 "Define a function FUNC with doc DOC and body BODY.
2137 BODY is executed at most once every snippet expansion attempt, to check
2138 expansion conditions.
2140 It doesn't make any sense to call FUNC programatically."
2141 `(defun ,func () ,(if (and doc
2144 "\n\nFor use in snippets' conditions. Within each
2145 snippet-expansion routine like `yas-expand', computes actual
2146 value for the first time then always returns a cached value.")
2147 (setq body (cons doc body))
2149 (let ((timestamp-and-value (get ',func 'yas--condition-cache)))
2150 (if (equal (car timestamp-and-value) yas--condition-cache-timestamp)
2151 (cdr timestamp-and-value)
2152 (let ((new-value (progn
2155 (put ',func 'yas--condition-cache (cons yas--condition-cache-timestamp new-value))
2158 (defalias 'yas-expand 'yas-expand-from-trigger-key)
2159 (defun yas-expand-from-trigger-key (&optional field)
2160 "Expand a snippet before point.
2162 If no snippet expansion is possible, fall back to the behaviour
2163 defined in `yas-fallback-behavior'.
2165 Optional argument FIELD is for non-interactive use and is an
2166 object satisfying `yas--field-p' to restrict the expansion to."
2168 (setq yas--condition-cache-timestamp (current-time))
2169 (let (templates-and-pos)
2170 (unless (and yas-expand-only-for-last-commands
2171 (not (member last-command yas-expand-only-for-last-commands)))
2172 (setq templates-and-pos (if field
2174 (narrow-to-region (yas--field-start field)
2175 (yas--field-end field))
2176 (yas--templates-for-key-at-point))
2177 (yas--templates-for-key-at-point))))
2178 (if templates-and-pos
2179 (yas--expand-or-prompt-for-template
2180 (nth 0 templates-and-pos)
2181 ;; Delete snippet key and active region when expanding.
2182 (min (if (use-region-p) (region-beginning) most-positive-fixnum)
2183 (nth 1 templates-and-pos))
2184 (max (if (use-region-p) (region-end) most-negative-fixnum)
2185 (nth 2 templates-and-pos)))
2188 (defun yas-expand-from-keymap ()
2189 "Directly expand some snippets, searching `yas--direct-keymaps'.
2191 If expansion fails, execute the previous binding for this key"
2193 (setq yas--condition-cache-timestamp (current-time))
2194 (let* ((vec (subseq (this-command-keys-vector) (if current-prefix-arg
2195 (length (this-command-keys))
2197 (templates (mapcan #'(lambda (table)
2198 (yas--fetch table vec))
2199 (yas--get-snippet-tables))))
2201 (yas--expand-or-prompt-for-template templates)
2202 (let ((yas-fallback-behavior 'call-other-command))
2205 (defun yas--expand-or-prompt-for-template (templates &optional start end)
2206 "Expand one of TEMPLATES from START to END.
2208 Prompt the user if TEMPLATES has more than one element, else
2209 expand immediately. Common gateway for
2210 `yas-expand-from-trigger-key' and `yas-expand-from-keymap'."
2211 (let ((yas--current-template (or (and (rest templates) ;; more than one
2212 (yas--prompt-for-template (mapcar #'cdr templates)))
2214 (when yas--current-template
2215 (yas-expand-snippet (yas--template-content yas--current-template)
2218 (yas--template-expand-env yas--current-template)))))
2220 ;; Apropos the trigger key and the fallback binding:
2222 ;; When `yas-minor-mode-map' binds <tab>, that correctly overrides
2223 ;; org-mode's <tab>, for example and searching for fallbacks correctly
2224 ;; returns `org-cycle'. However, most other modes bind "TAB". TODO,
2225 ;; improve this explanation.
2227 (defun yas--fallback ()
2228 "Fallback after expansion has failed.
2230 Common gateway for `yas-expand-from-trigger-key' and
2231 `yas-expand-from-keymap'."
2232 (cond ((eq yas-fallback-behavior 'return-nil)
2235 ((eq yas-fallback-behavior 'yas--fallback)
2236 (error (concat "yasnippet fallback loop!\n"
2237 "This can happen when you bind `yas-expand' "
2238 "outside of the `yas-minor-mode-map'.")))
2239 ((eq yas-fallback-behavior 'call-other-command)
2240 (let* ((yas-fallback-behavior 'yas--fallback)
2241 ;; Also bind `yas-minor-mode' to prevent fallback
2242 ;; loops when other extensions use mechanisms similar
2243 ;; to `yas--keybinding-beyond-yasnippet'. (github #525
2246 (yas-minor-mode nil)
2247 (beyond-yasnippet (yas--keybinding-beyond-yasnippet)))
2248 (yas--message 4 "Falling back to %s" beyond-yasnippet)
2249 (assert (or (null beyond-yasnippet) (commandp beyond-yasnippet)))
2250 (setq this-command beyond-yasnippet)
2251 (when beyond-yasnippet
2252 (call-interactively beyond-yasnippet))))
2253 ((and (listp yas-fallback-behavior)
2254 (cdr yas-fallback-behavior)
2255 (eq 'apply (car yas-fallback-behavior)))
2256 (let ((command-or-fn (cadr yas-fallback-behavior))
2257 (args (cddr yas-fallback-behavior))
2258 (yas-fallback-behavior 'yas--fallback)
2259 (yas-minor-mode nil))
2261 (apply command-or-fn args)
2262 (when (commandp command-or-fn)
2263 (setq this-command command-or-fn)
2264 (call-interactively command-or-fn)))))
2266 ;; also return nil if all the other fallbacks have failed
2269 (defun yas--keybinding-beyond-yasnippet ()
2270 "Get current keys's binding as if YASsnippet didn't exist."
2271 (let* ((yas-minor-mode nil)
2272 (yas--direct-keymaps nil)
2273 (keys (this-single-command-keys)))
2274 (or (key-binding keys t)
2275 (key-binding (yas--fallback-translate-input keys) t))))
2277 (defun yas--fallback-translate-input (keys)
2278 "Emulate `read-key-sequence', at least what I think it does.
2280 Keys should be an untranslated key vector. Returns a translated
2281 vector of keys. FIXME not thoroughly tested."
2284 (while (< i (length keys))
2286 (translated local-function-key-map))
2287 (while (and (< j (length keys))
2289 (keymapp translated))
2290 (setq translated (cdr (assoc (aref keys j) (remove 'keymap translated)))
2292 (setq retval (vconcat retval (cond ((symbolp translated)
2294 ((vectorp translated)
2297 (substring keys i j)))))
2302 ;;; Utils for snippet development:
2304 (defun yas--all-templates (tables)
2305 "Get `yas--template' objects in TABLES, applicable for buffer and point.
2307 Honours `yas-choose-tables-first', `yas-choose-keys-first' and
2308 `yas-buffer-local-condition'"
2309 (when yas-choose-tables-first
2310 (setq tables (list (yas--prompt-for-table tables))))
2312 (if yas-choose-keys-first
2313 (let ((key (yas--prompt-for-keys
2314 (mapcan #'yas--table-all-keys tables))))
2316 (mapcan #'(lambda (table)
2317 (yas--fetch table key))
2319 (remove-duplicates (mapcan #'yas--table-templates tables)
2322 (defun yas--lookup-snippet-1 (name mode)
2323 "Get the snippet called NAME in MODE's tables."
2324 (let ((yas-choose-tables-first nil) ; avoid prompts
2325 (yas-choose-keys-first nil))
2326 (cl-find name (yas--all-templates
2327 (yas--get-snippet-tables mode))
2328 :key #'yas--template-name :test #'string=)))
2330 (defun yas-lookup-snippet (name &optional mode noerror)
2331 "Get the snippet content for the snippet NAME in MODE's tables.
2333 MODE defaults to the current buffer's `major-mode'. If NOERROR
2334 is non-nil, then don't signal an error if there isn't any snippet
2337 Honours `yas-buffer-local-condition'."
2338 (let ((snippet (yas--lookup-snippet-1 name mode)))
2340 (snippet (yas--template-content snippet))
2342 (t (error "No snippet named: %s" name)))))
2344 (defun yas-insert-snippet (&optional no-condition)
2345 "Choose a snippet to expand, pop-up a list of choices according
2346 to `yas-prompt-functions'.
2348 With prefix argument NO-CONDITION, bypass filtering of snippets
2351 (setq yas--condition-cache-timestamp (current-time))
2352 (let* ((yas-buffer-local-condition (or (and no-condition
2354 yas-buffer-local-condition))
2355 (templates (yas--all-templates (yas--get-snippet-tables)))
2356 (yas--current-template (and templates
2357 (or (and (rest templates) ;; more than one template for same key
2358 (yas--prompt-for-template templates))
2360 (where (if (region-active-p)
2361 (cons (region-beginning) (region-end))
2362 (cons (point) (point)))))
2363 (if yas--current-template
2364 (yas-expand-snippet (yas--template-content yas--current-template)
2367 (yas--template-expand-env yas--current-template))
2368 (yas--message 1 "No snippets can be inserted here!"))))
2370 (defun yas-visit-snippet-file ()
2371 "Choose a snippet to edit, selection like `yas-insert-snippet'.
2373 Only success if selected snippet was loaded from a file. Put the
2374 visited file in `snippet-mode'."
2376 (let* ((yas-buffer-local-condition 'always)
2377 (templates (yas--all-templates (yas--get-snippet-tables)))
2378 (template (and templates
2379 (or (yas--prompt-for-template templates
2380 "Choose a snippet template to edit: ")
2384 (yas--visit-snippet-file-1 template)
2385 (message "No snippets tables active!"))))
2387 (defun yas--visit-snippet-file-1 (template)
2388 "Helper for `yas-visit-snippet-file'."
2389 (let ((file (yas--template-get-file template)))
2390 (cond ((and file (file-readable-p file))
2391 (find-file-other-window file)
2393 (set (make-local-variable 'yas--editing-template) template))
2395 (message "Original file %s no longer exists!" file))
2397 (switch-to-buffer (format "*%s*"(yas--template-name template)))
2398 (let ((type 'snippet))
2399 (when (listp (yas--template-content template))
2400 (insert (format "# type: command\n"))
2401 (setq type 'command))
2402 (insert (format "# key: %s\n" (yas--template-key template)))
2403 (insert (format "# name: %s\n" (yas--template-name template)))
2404 (when (yas--template-keybinding template)
2405 (insert (format "# binding: %s\n" (yas--template-keybinding template))))
2406 (when (yas--template-expand-env template)
2407 (insert (format "# expand-env: %s\n" (yas--template-expand-env template))))
2408 (when (yas--template-condition template)
2409 (insert (format "# condition: %s\n" (yas--template-condition template))))
2411 (insert (if (eq type 'command)
2412 (pp-to-string (yas--template-content template))
2413 (yas--template-content template))))
2415 (set (make-local-variable 'yas--editing-template) template)))))
2417 (defun yas--guess-snippet-directories-1 (table)
2418 "Guess possible snippet subdirectories for TABLE."
2419 (cons (yas--table-name table)
2420 (mapcan #'(lambda (parent)
2421 (yas--guess-snippet-directories-1
2423 (yas--table-parents table))))
2425 (defun yas--guess-snippet-directories (&optional table)
2426 "Try to guess suitable directories based on the current active
2427 tables (or optional TABLE).
2429 Returns a list of elements (TABLE . DIRS) where TABLE is a
2430 `yas--table' object and DIRS is a list of all possible directories
2431 where snippets of table might exist."
2432 (let ((main-dir (car (or (yas-snippet-dirs)
2433 (setq yas-snippet-dirs
2434 (list yas--default-user-snippets-dir)))))
2435 (tables (if table (list table)
2436 (yas--get-snippet-tables))))
2437 ;; HACK! the snippet table created here is actually registered!
2439 (unless (or table (gethash major-mode yas--tables))
2440 (push (yas--table-get-create major-mode)
2443 (mapcar #'(lambda (table)
2445 (mapcar #'(lambda (subdir)
2446 (expand-file-name subdir main-dir))
2447 (yas--guess-snippet-directories-1 table))))
2450 (defun yas--make-directory-maybe (table-and-dirs &optional main-table-string)
2451 "Return a dir inside TABLE-AND-DIRS, prompts for creation if none exists."
2452 (or (some #'(lambda (dir) (when (file-directory-p dir) dir)) (cdr table-and-dirs))
2453 (let ((candidate (first (cdr table-and-dirs))))
2454 (unless (file-writable-p (file-name-directory candidate))
2455 (error (yas--format "%s is not writable." candidate)))
2456 (if (y-or-n-p (format "Guessed directory (%s) for%s%s table \"%s\" does not exist! Create? "
2458 (if (gethash (yas--table-mode (car table-and-dirs))
2462 (or main-table-string
2464 (yas--table-name (car table-and-dirs))))
2466 (make-directory candidate 'also-make-parents)
2467 ;; create the .yas-parents file here...
2470 (defun yas-new-snippet (&optional no-template)
2471 "Pops a new buffer for writing a snippet.
2473 Expands a snippet-writing snippet, unless the optional prefix arg
2474 NO-TEMPLATE is non-nil."
2476 (let ((guessed-directories (yas--guess-snippet-directories)))
2478 (switch-to-buffer "*new snippet*")
2480 (kill-all-local-variables)
2483 (set (make-local-variable 'yas--guessed-modes) (mapcar #'(lambda (d)
2484 (yas--table-mode (car d)))
2485 guessed-directories))
2486 (if (and (not no-template) yas-new-snippet-default)
2487 (yas-expand-snippet yas-new-snippet-default))))
2489 (defun yas--compute-major-mode-and-parents (file)
2490 "Given FILE, find the nearest snippet directory for a given mode.
2492 Returns a list (MODE-SYM PARENTS), the mode's symbol and a list
2493 representing one or more of the mode's parents.
2495 Note that MODE-SYM need not be the symbol of a real major mode,
2496 neither do the elements of PARENTS."
2497 (let* ((file-dir (and file
2498 (directory-file-name (or (some #'(lambda (special)
2499 (locate-dominating-file file special))
2503 (directory-file-name (file-name-directory file))))))
2504 (parents-file-name (concat file-dir "/.yas-parents"))
2505 (major-mode-name (and file-dir
2506 (file-name-nondirectory file-dir)))
2507 (major-mode-sym (or (and major-mode-name
2508 (intern major-mode-name))))
2509 (parents (when (file-readable-p parents-file-name)
2513 (insert-file-contents parents-file-name)
2514 (buffer-substring-no-properties (point-min)
2516 (when major-mode-sym
2517 (cons major-mode-sym (remove major-mode-sym parents)))))
2519 (defvar yas--editing-template nil
2520 "Supporting variable for `yas-load-snippet-buffer' and `yas--visit-snippet'.")
2522 (defvar yas--current-template nil
2523 "Holds the current template being expanded into a snippet.")
2525 (defvar yas--guessed-modes nil
2526 "List of guessed modes supporting `yas-load-snippet-buffer'.")
2528 (defun yas--read-table ()
2529 "Ask user for a snippet table, help with some guessing."
2530 (let ((prompt (if (and (featurep 'ido)
2532 'ido-completing-read 'completing-read)))
2533 (unless yas--guessed-modes
2534 (set (make-local-variable 'yas--guessed-modes)
2535 (or (yas--compute-major-mode-and-parents buffer-file-name))))
2537 (funcall prompt (format "Choose or enter a table (yas guesses %s): "
2538 (if yas--guessed-modes
2539 (first yas--guessed-modes)
2541 (mapcar #'symbol-name yas--guessed-modes)
2546 (if (first yas--guessed-modes)
2547 (symbol-name (first yas--guessed-modes)))))))
2549 (defun yas-load-snippet-buffer (table &optional interactive)
2550 "Parse and load current buffer's snippet definition into TABLE.
2551 TABLE is a symbol name passed to `yas--table-get-create'. When
2552 called interactively, prompt for the table name."
2553 (interactive (list (yas--read-table) t))
2555 ;; We have `yas--editing-template', this buffer's content comes from a
2556 ;; template which is already loaded and neatly positioned,...
2558 (yas--editing-template
2559 (yas--define-snippets-1 (yas--parse-template (yas--template-load-file yas--editing-template))
2560 (yas--template-table yas--editing-template)))
2561 ;; Try to use `yas--guessed-modes'. If we don't have that use the
2562 ;; value from `yas--compute-major-mode-and-parents'
2565 (unless yas--guessed-modes
2566 (set (make-local-variable 'yas--guessed-modes) (or (yas--compute-major-mode-and-parents buffer-file-name))))
2567 (let* ((table (yas--table-get-create table)))
2568 (set (make-local-variable 'yas--editing-template)
2569 (yas--define-snippets-1 (yas--parse-template buffer-file-name)
2572 (yas--message 3 "Snippet \"%s\" loaded for %s."
2573 (yas--template-name yas--editing-template)
2574 (yas--table-name (yas--template-table yas--editing-template)))))
2576 (defun yas-load-snippet-buffer-and-close (table &optional kill)
2577 "Load and save the snippet, then `quit-window' if saved.
2578 Loading is performed by `yas-load-snippet-buffer'. If the
2579 snippet is new, ask the user whether (and where) to save it. If
2580 the snippet already has a file, just save it.
2582 The prefix argument KILL is passed to `quit-window'.
2584 Don't use this from a Lisp program, call `yas-load-snippet-buffer'
2585 and `kill-buffer' instead."
2586 (interactive (list (yas--read-table) current-prefix-arg))
2587 (yas-load-snippet-buffer table t)
2588 (let ((file (yas--template-get-file yas--editing-template)))
2590 ;; Only offer to save this if it looks like a library or new
2591 ;; snippet (loaded from elisp, from a dir in `yas-snippet-dirs'
2592 ;; which is not the first, or from an unwritable file)
2595 (not (file-writable-p file))
2596 (and (cdr-safe yas-snippet-dirs)
2597 (not (string-prefix-p (expand-file-name (car yas-snippet-dirs)) file))))
2598 (y-or-n-p (yas--format "Looks like a library or new snippet. Save to new file? ")))
2599 (let* ((option (first (yas--guess-snippet-directories (yas--template-table yas--editing-template))))
2601 (yas--make-directory-maybe option))))
2603 (let ((default-file-name (or (and file (file-name-nondirectory file))
2604 (yas--template-name yas--editing-template))))
2605 (write-file (expand-file-name
2606 (read-file-name (format "File name to create in %s? " chosen)
2607 chosen default-file-name)
2609 (setf (yas--template-load-file yas--editing-template) buffer-file-name))))))
2610 (when buffer-file-name
2612 (quit-window kill)))
2614 (defun yas-tryout-snippet (&optional debug)
2615 "Test current buffer's snippet template in other buffer."
2617 (let* ((major-mode-and-parent (yas--compute-major-mode-and-parents buffer-file-name))
2618 (parsed (yas--parse-template))
2619 (test-mode (or (and (car major-mode-and-parent)
2620 (fboundp (car major-mode-and-parent))
2621 (car major-mode-and-parent))
2622 (first yas--guessed-modes)
2623 (intern (read-from-minibuffer (yas--format "Please input a mode: ")))))
2624 (yas--current-template
2627 (yas--make-template :table nil ;; no tables for ephemeral snippets
2629 :content (nth 1 parsed)
2630 :name (nth 2 parsed)
2631 :expand-env (nth 5 parsed)))))
2632 (cond (yas--current-template
2633 (let ((buffer-name (format "*testing snippet: %s*" (yas--template-name yas--current-template))))
2634 (kill-buffer (get-buffer-create buffer-name))
2635 (switch-to-buffer (get-buffer-create buffer-name))
2636 (setq buffer-undo-list nil)
2637 (condition-case nil (funcall test-mode) (error nil))
2639 (setq buffer-read-only nil)
2640 (yas-expand-snippet (yas--template-content yas--current-template)
2643 (yas--template-expand-env yas--current-template))
2645 (require 'yasnippet-debug nil t))
2646 (add-hook 'post-command-hook 'yas-debug-snippet-vars nil t))))
2648 (yas--message 1 "Cannot test snippet for unknown major mode")))))
2650 (defun yas-active-keys ()
2651 "Return all active trigger keys for current buffer and point."
2653 (remove-if-not #'stringp (mapcan #'yas--table-all-keys (yas--get-snippet-tables)))
2656 (defun yas--template-fine-group (template)
2657 (car (last (or (yas--template-group template)
2658 (yas--template-perm-group template)))))
2660 (defun yas-describe-tables (&optional choose)
2661 "Display snippets for each table."
2663 (let* ((by-name-hash (and choose
2664 (y-or-n-p "Show by namehash? ")))
2665 (buffer (get-buffer-create "*YASnippet tables*"))
2666 (active-tables (yas--get-snippet-tables))
2667 (remain-tables (let ((all))
2668 (maphash #'(lambda (_k v)
2669 (unless (find v active-tables)
2673 (table-lists (list active-tables remain-tables))
2674 (original-buffer (current-buffer))
2676 (yas--condition-cache-timestamp (current-time)))
2677 (with-current-buffer buffer
2678 (setq buffer-read-only nil)
2680 (cond ((not by-name-hash)
2681 (insert "YASnippet tables:\n")
2682 (while (and table-lists
2684 (dolist (table (car table-lists))
2685 (yas--describe-pretty-table table original-buffer))
2686 (setq table-lists (cdr table-lists))
2688 (yas--create-snippet-xrefs)
2689 (display-buffer buffer)
2690 (setq continue (and choose (y-or-n-p "Show also non-active tables? ")))))
2691 (yas--create-snippet-xrefs)
2695 (insert "\n\nYASnippet tables by NAMEHASH: \n")
2696 (dolist (table (append active-tables remain-tables))
2697 (insert (format "\nSnippet table `%s':\n\n" (yas--table-name table)))
2699 (maphash #'(lambda (k _v)
2701 (yas--table-hash table))
2703 (insert (format " key %s maps snippets: %s\n" key
2705 (maphash #'(lambda (k _v)
2707 (gethash key (yas--table-hash table)))
2710 (setq buffer-read-only t))
2711 (display-buffer buffer)))
2713 (defun yas--describe-pretty-table (table &optional original-buffer)
2714 (insert (format "\nSnippet table `%s'"
2715 (yas--table-name table)))
2716 (if (yas--table-parents table)
2717 (insert (format " parents: %s\n"
2718 (mapcar #'yas--table-name
2719 (yas--table-parents table))))
2721 (insert (make-string 100 ?-) "\n")
2722 (insert "group state name key binding\n")
2723 (let ((groups-hash (make-hash-table :test #'equal)))
2724 (maphash #'(lambda (_k v)
2725 (let ((group (or (yas--template-fine-group v)
2727 (when (yas--template-name v)
2729 (cons v (gethash group groups-hash))
2731 (yas--table-uuidhash table))
2733 #'(lambda (group templates)
2734 (setq group (truncate-string-to-width group 25 0 ? "..."))
2735 (insert (make-string 100 ?-) "\n")
2736 (dolist (p templates)
2737 (let* ((name (truncate-string-to-width (propertize (format "\\\\snippet `%s'" (yas--template-name p))
2741 (setq group (make-string (length group) ? ))))
2742 (condition-string (let ((condition (yas--template-condition p)))
2745 (with-current-buffer original-buffer
2746 (if (yas--eval-condition condition)
2750 (key-description-string (key-description (yas--template-keybinding p)))
2751 (template-key-padding (if (string= key-description-string "") nil ? )))
2753 condition-string " "
2754 name (if (string-match "\\.\\.\\.$" name)
2757 (truncate-string-to-width (or (yas--template-key p) "")
2758 15 0 template-key-padding "...")
2759 (or template-key-padding "")
2760 (truncate-string-to-width key-description-string
2767 ;;; User convenience functions, for using in `yas-key-syntaxes'
2769 (defun yas-try-key-from-whitespace (_start-point)
2770 "As `yas-key-syntaxes' element, look for whitespace delimited key.
2772 A newline will be considered whitespace even if the mode syntax
2773 marks it as something else (typically comment ender)."
2774 (skip-chars-backward "^[:space:]\n"))
2776 (defun yas-shortest-key-until-whitespace (_start-point)
2777 "Like `yas-longest-key-from-whitespace' but take the shortest key."
2778 (when (/= (skip-chars-backward "^[:space:]\n" (1- (point))) 0)
2781 (defun yas-longest-key-from-whitespace (start-point)
2782 "As `yas-key-syntaxes' element, look for longest key between point and whitespace.
2784 A newline will be considered whitespace even if the mode syntax
2785 marks it as something else (typically comment ender)."
2786 (if (= (point) start-point)
2787 (yas-try-key-from-whitespace start-point)
2789 (unless (<= start-point (1+ (point)))
2794 ;;; User convenience functions, for using in snippet definitions
2796 (defvar yas-modified-p nil
2797 "Non-nil if field has been modified by user or transformation.")
2799 (defvar yas-moving-away-p nil
2800 "Non-nil if user is about to exit field.")
2802 (defvar yas-text nil
2803 "Contains current field text.")
2805 (defun yas-substr (str pattern &optional subexp)
2806 "Search PATTERN in STR and return SUBEXPth match.
2808 If found, the content of subexp group SUBEXP (default 0) is
2809 returned, or else the original STR will be returned."
2810 (let ((grp (or subexp 0)))
2812 (if (string-match pattern str)
2813 (match-string-no-properties grp str)
2816 (defun yas-choose-value (&rest possibilities)
2817 "Prompt for a string in POSSIBILITIES and return it.
2819 The last element of POSSIBILITIES may be a list of strings."
2820 (unless (or yas-moving-away-p
2822 (let* ((last-link (last possibilities))
2823 (last-elem (car last-link)))
2824 (when (listp last-elem)
2825 (setcar last-link (car last-elem))
2826 (setcdr last-link (cdr last-elem))))
2827 (some #'(lambda (fn)
2828 (funcall fn "Choose: " possibilities))
2829 yas-prompt-functions)))
2831 (defun yas-key-to-value (alist)
2832 (unless (or yas-moving-away-p
2834 (let ((key (read-key-sequence "")))
2836 (or (cdr (find key alist :key #'car :test #'string=))
2839 (defun yas-throw (text)
2840 "Throw a yas--exception with TEXT as the reason."
2841 (throw 'yas--exception (cons 'yas--exception text)))
2843 (defun yas-verify-value (possibilities)
2844 "Verify that the current field value is in POSSIBILITIES.
2846 Otherwise throw exception."
2847 (when (and yas-moving-away-p (notany #'(lambda (pos) (string= pos yas-text)) possibilities))
2848 (yas-throw (yas--format "Field only allows %s" possibilities))))
2850 (defun yas-field-value (number)
2851 "Get the string for field with NUMBER.
2853 Use this in primary and mirror transformations to tget."
2854 (let* ((snippet (car (yas--snippets-at-point)))
2856 (yas--snippet-find-field snippet number))))
2858 (yas--field-text-for-display field))))
2861 "Return `yas-text' if that exists and is non-empty, else nil."
2863 (not (string= "" yas-text)))
2866 (defun yas-selected-text ()
2867 "Return `yas-selected-text' if that exists and is non-empty, else nil."
2868 (if (and yas-selected-text
2869 (not (string= "" yas-selected-text)))
2872 (defun yas--get-field-once (number &optional transform-fn)
2873 (unless yas-modified-p
2875 (funcall transform-fn (yas-field-value number))
2876 (yas-field-value number))))
2878 (defun yas-default-from-field (number)
2879 (unless yas-modified-p
2880 (yas-field-value number)))
2882 (defun yas-inside-string ()
2883 "Return non-nil if the point is inside a string according to font-lock."
2884 (equal 'font-lock-string-face (get-char-property (1- (point)) 'face)))
2886 (defun yas-unimplemented (&optional missing-feature)
2887 (if yas--current-template
2888 (if (y-or-n-p (format "This snippet is unimplemented (missing %s) Visit the snippet definition? "
2891 (yas--visit-snippet-file-1 yas--current-template))
2892 (message "No implementation. Missing %s" (or missing-feature "something"))))
2895 ;;; Snippet expansion and field management
2897 (defvar yas--active-field-overlay nil
2898 "Overlays the currently active field.")
2900 (defvar yas--field-protection-overlays nil
2901 "Two overlays protect the current active field.")
2903 (defvar yas-selected-text nil
2904 "The selected region deleted on the last snippet expansion.")
2906 (defvar yas--start-column nil
2907 "The column where the snippet expansion started.")
2909 (make-variable-buffer-local 'yas--active-field-overlay)
2910 (make-variable-buffer-local 'yas--field-protection-overlays)
2911 (put 'yas--active-field-overlay 'permanent-local t)
2912 (put 'yas--field-protection-overlays 'permanent-local t)
2914 (defstruct (yas--snippet (:constructor yas--make-snippet ()))
2920 (id (yas--snippet-next-id) :read-only t)
2921 (control-overlay nil)
2923 ;; stacked expansion: the `previous-active-field' slot saves the
2924 ;; active field where the child expansion took place
2925 previous-active-field
2928 (defstruct (yas--field (:constructor yas--make-field (number start end parent-field)))
2931 NUMBER is the field number.
2932 START and END are mostly buffer markers, but see \"apropos markers-to-points\".
2933 PARENT-FIELD is a `yas--field' this field is nested under, or nil.
2934 MIRRORS is a list of `yas--mirror's
2935 TRANSFORM is a lisp form.
2936 MODIFIED-P is a boolean set to true once user inputs text.
2937 NEXT is another `yas--field' or `yas--mirror' or `yas--exit'.
2948 (defstruct (yas--mirror (:constructor yas--make-mirror (start end transform)))
2951 START and END are mostly buffer markers, but see \"apropos markers-to-points\".
2952 TRANSFORM is a lisp form.
2953 PARENT-FIELD is a `yas--field' this mirror is nested under, or nil.
2954 NEXT is another `yas--field' or `yas--mirror' or `yas--exit'
2955 DEPTH is a count of how many nested mirrors can affect this mirror"
2962 (defstruct (yas--exit (:constructor yas--make-exit (marker)))
2966 (defun yas--apply-transform (field-or-mirror field &optional empty-on-nil-p)
2967 "Calculate transformed string for FIELD-OR-MIRROR from FIELD.
2969 If there is no transform for ht field, return nil.
2971 If there is a transform but it returns nil, return the empty
2972 string iff EMPTY-ON-NIL-P is true."
2973 (let* ((yas-text (yas--field-text-for-display field))
2974 (yas-modified-p (yas--field-modified-p field))
2975 (transform (if (yas--mirror-p field-or-mirror)
2976 (yas--mirror-transform field-or-mirror)
2977 (yas--field-transform field-or-mirror)))
2978 (start-point (if (yas--mirror-p field-or-mirror)
2979 (yas--mirror-start field-or-mirror)
2980 (yas--field-start field-or-mirror)))
2981 (transformed (and transform
2983 (goto-char start-point)
2984 (let ((ret (yas--eval-lisp transform)))
2985 (or ret (and empty-on-nil-p "")))))))
2988 (defsubst yas--replace-all (from to &optional text)
2989 "Replace all occurrences from FROM to TO.
2991 With optional string TEXT do it in that string."
2993 (replace-regexp-in-string (regexp-quote from) to text t t)
2994 (goto-char (point-min))
2995 (while (search-forward from nil t)
2996 (replace-match to t t text))))
2998 (defun yas--snippet-find-field (snippet number)
2999 (find-if #'(lambda (field)
3000 (eq number (yas--field-number field)))
3001 (yas--snippet-fields snippet)))
3003 (defun yas--snippet-sort-fields (snippet)
3004 "Sort the fields of SNIPPET in navigation order."
3005 (setf (yas--snippet-fields snippet)
3006 (sort (yas--snippet-fields snippet)
3007 #'yas--snippet-field-compare)))
3009 (defun yas--snippet-field-compare (field1 field2)
3010 "Compare FIELD1 and FIELD2.
3012 The field with a number is sorted first. If they both have a
3013 number, compare through the number. If neither have, compare
3014 through the field's start point"
3015 (let ((n1 (yas--field-number field1))
3016 (n2 (yas--field-number field2)))
3019 (or (zerop n2) (and (not (zerop n1))
3024 (< (yas--field-start field1)
3025 (yas--field-start field2))))))
3027 (defun yas--field-probably-deleted-p (snippet field)
3028 "Guess if SNIPPET's FIELD should be skipped."
3030 ;; field must be zero length
3032 (zerop (- (yas--field-start field) (yas--field-end field)))
3033 ;; field must have been modified
3035 (yas--field-modified-p field)
3038 ;; 1) it's a nested field
3040 (yas--field-parent-field field)
3041 ;; 2) ends just before the snippet end
3043 (and (eq field (car (last (yas--snippet-fields snippet))))
3044 (= (yas--field-start field) (overlay-end (yas--snippet-control-overlay snippet)))))
3045 ;; the field numbered 0, just before the exit marker, should
3048 (not (and (yas--field-number field)
3049 (zerop (yas--field-number field))))))
3051 (defun yas--snippets-at-point (&optional all-snippets)
3052 "Return a sorted list of snippets at point.
3054 The most recently-inserted snippets are returned first."
3056 (delq nil (delete-dups
3057 (mapcar (lambda (ov) (overlay-get ov 'yas--snippet))
3058 (if all-snippets (overlays-in (point-min) (point-max))
3059 (nconc (overlays-at (point))
3060 (overlays-at (1- (point))))))))
3062 (<= (yas--snippet-id s2) (yas--snippet-id s1)))))
3064 (defun yas-next-field-or-maybe-expand ()
3065 "Try to expand a snippet at a key before point.
3067 Otherwise delegate to `yas-next-field'."
3069 (if yas-triggers-in-field
3070 (let ((yas-fallback-behavior 'return-nil)
3071 (active-field (overlay-get yas--active-field-overlay 'yas--field)))
3073 (unless (yas-expand-from-trigger-key active-field)
3077 (defun yas-next-field-will-exit-p (&optional arg)
3078 "Return non-nil if (yas-next-field ARG) would exit the current snippet."
3079 (let ((snippet (car (yas--snippets-at-point)))
3080 (active (overlay-get yas--active-field-overlay 'yas--field)))
3082 (not (yas--find-next-field arg snippet active)))))
3084 (defun yas--find-next-field (n snippet active)
3085 "Return the Nth field after the ACTIVE one in SNIPPET."
3086 (let ((live-fields (cl-remove-if
3088 (and (not (eq field active))
3089 (yas--field-probably-deleted-p snippet field)))
3090 (yas--snippet-fields snippet))))
3091 (if (>= n 0) (nth n (memq active live-fields))
3092 (car (last (memq active (reverse live-fields)) (- n))))))
3094 (defun yas-next-field (&optional arg)
3095 "Navigate to the ARGth next field.
3097 If there's none, exit the snippet."
3099 (unless arg (setq arg 1))
3100 (let* ((snippet (car (yas--snippets-at-point)))
3101 (active-field (overlay-get yas--active-field-overlay 'yas--field))
3102 (target-field (yas--find-next-field arg snippet active-field)))
3103 ;; Apply transform to active field.
3105 (let ((yas-moving-away-p t))
3106 (when (yas--field-update-display active-field)
3107 (yas--update-mirrors snippet))))
3108 ;; Now actually move...
3110 (yas--move-to-field snippet target-field)
3111 (yas-exit-snippet snippet))))
3113 (defun yas--place-overlays (snippet field)
3114 "Correctly place overlays for SNIPPET's FIELD."
3115 (yas--make-move-field-protection-overlays snippet field)
3116 (yas--make-move-active-field-overlay snippet field))
3118 (defun yas--move-to-field (snippet field)
3119 "Update SNIPPET to move to field FIELD.
3121 Also create some protection overlays"
3122 (goto-char (yas--field-start field))
3123 (yas--place-overlays snippet field)
3124 (overlay-put yas--active-field-overlay 'yas--field field)
3125 (let ((number (yas--field-number field)))
3126 ;; check for the special ${0: ...} field
3127 (if (and number (zerop number))
3129 (set-mark (yas--field-end field))
3130 (setf (yas--snippet-force-exit snippet)
3131 (or (yas--field-transform field)
3133 ;; make this field active
3134 (setf (yas--snippet-active-field snippet) field)
3135 ;; primary field transform: first call to snippet transform
3136 (unless (yas--field-modified-p field)
3137 (if (yas--field-update-display field)
3138 (yas--update-mirrors snippet)
3139 (setf (yas--field-modified-p field) nil))))))
3141 (defun yas-prev-field ()
3142 "Navigate to prev field. If there's none, exit the snippet."
3144 (yas-next-field -1))
3146 (defun yas-abort-snippet (&optional snippet)
3148 (let ((snippet (or snippet
3149 (car (yas--snippets-at-point)))))
3151 (setf (yas--snippet-force-exit snippet) t))))
3153 (defun yas-exit-snippet (snippet)
3154 "Goto exit-marker of SNIPPET."
3155 (interactive (list (first (yas--snippets-at-point))))
3157 (setf (yas--snippet-force-exit snippet) t)
3158 (goto-char (if (yas--snippet-exit snippet)
3159 (yas--exit-marker (yas--snippet-exit snippet))
3160 (overlay-end (yas--snippet-control-overlay snippet))))))
3162 (defun yas-exit-all-snippets ()
3163 "Exit all snippets."
3165 (mapc #'(lambda (snippet)
3166 (yas-exit-snippet snippet)
3167 (yas--check-commit-snippet))
3168 (yas--snippets-at-point 'all-snippets)))
3171 ;;; Some low level snippet-routines:
3173 (defvar yas--inhibit-overlay-hooks nil
3174 "Bind this temporarily to non-nil to prevent running `yas--on-*-modification'.")
3176 (defvar yas-snippet-beg nil "Beginning position of the last snippet committed.")
3177 (defvar yas-snippet-end nil "End position of the last snippet committed.")
3179 (defun yas--commit-snippet (snippet)
3180 "Commit SNIPPET, but leave point as it is.
3182 This renders the snippet as ordinary text."
3184 (let ((control-overlay (yas--snippet-control-overlay snippet)))
3186 ;; Save the end of the moribund snippet in case we need to revive it
3187 ;; its original expansion.
3189 (when (and control-overlay
3190 (overlay-buffer control-overlay))
3191 (setq yas-snippet-beg (overlay-start control-overlay))
3192 (setq yas-snippet-end (overlay-end control-overlay))
3193 (delete-overlay control-overlay))
3195 (let ((yas--inhibit-overlay-hooks t))
3196 (when yas--active-field-overlay
3197 (delete-overlay yas--active-field-overlay))
3198 (when yas--field-protection-overlays
3199 (mapc #'delete-overlay yas--field-protection-overlays)))
3201 ;; stacked expansion: if the original expansion took place from a
3202 ;; field, make sure we advance it here at least to
3203 ;; `yas-snippet-end'...
3205 (let ((previous-field (yas--snippet-previous-active-field snippet)))
3206 (when (and yas-snippet-end previous-field)
3207 (yas--advance-end-maybe previous-field yas-snippet-end)))
3209 ;; Convert all markers to points,
3211 (yas--markers-to-points snippet)
3213 ;; Take care of snippet revival
3215 (if yas-snippet-revival
3216 (push `(apply yas--snippet-revive ,yas-snippet-beg ,yas-snippet-end ,snippet)
3218 ;; Dismember the snippet... this is useful if we get called
3219 ;; again from `yas--take-care-of-redo'....
3220 (setf (yas--snippet-fields snippet) nil)))
3222 (yas--message 3 "Snippet %s exited." (yas--snippet-id snippet)))
3224 (defun yas--safely-run-hooks (hook-var)
3225 (condition-case error
3226 (run-hooks hook-var)
3228 (yas--message 2 "%s error: %s" hook-var (error-message-string error)))))
3231 (defun yas--check-commit-snippet ()
3232 "Check if point exited the currently active field of the snippet.
3234 If so cleans up the whole snippet up."
3235 (let* ((snippets (yas--snippets-at-point 'all-snippets))
3236 (snippets-left snippets)
3237 (snippet-exit-transform))
3238 (dolist (snippet snippets)
3239 (let ((active-field (yas--snippet-active-field snippet)))
3240 (setq snippet-exit-transform (yas--snippet-force-exit snippet))
3241 (cond ((or snippet-exit-transform
3242 (not (and active-field (yas--field-contains-point-p active-field))))
3243 (setq snippets-left (delete snippet snippets-left))
3244 (setf (yas--snippet-force-exit snippet) nil)
3245 (yas--commit-snippet snippet))
3247 (or (not yas--active-field-overlay)
3248 (not (overlay-buffer yas--active-field-overlay))))
3250 ;; stacked expansion: this case is mainly for recent
3251 ;; snippet exits that place us back int the field of
3255 (yas--move-to-field snippet active-field)
3256 (yas--update-mirrors snippet)))
3259 (unless (or (null snippets) snippets-left)
3260 (if snippet-exit-transform
3261 (yas--eval-lisp-no-saves snippet-exit-transform))
3262 (yas--safely-run-hooks 'yas-after-exit-snippet-hook))))
3264 ;; Apropos markers-to-points:
3266 ;; This was found useful for performance reasons, so that an
3267 ;; excessive number of live markers aren't kept around in the
3268 ;; `buffer-undo-list'. However, in `markers-to-points', the
3269 ;; set-to-nil markers can't simply be discarded and replaced with
3270 ;; fresh ones in `points-to-markers'. The original marker that was
3271 ;; just set to nil has to be reused.
3273 ;; This shouldn't bring horrible problems with undo/redo, but it
3276 (defun yas--markers-to-points (snippet)
3277 "Convert all markers in SNIPPET to a cons (POINT . MARKER)
3278 where POINT is the original position of the marker and MARKER is
3279 the original marker object with the position set to nil."
3280 (dolist (field (yas--snippet-fields snippet))
3281 (let ((start (marker-position (yas--field-start field)))
3282 (end (marker-position (yas--field-end field))))
3283 (set-marker (yas--field-start field) nil)
3284 (set-marker (yas--field-end field) nil)
3285 (setf (yas--field-start field) (cons start (yas--field-start field)))
3286 (setf (yas--field-end field) (cons end (yas--field-end field))))
3287 (dolist (mirror (yas--field-mirrors field))
3288 (let ((start (marker-position (yas--mirror-start mirror)))
3289 (end (marker-position (yas--mirror-end mirror))))
3290 (set-marker (yas--mirror-start mirror) nil)
3291 (set-marker (yas--mirror-end mirror) nil)
3292 (setf (yas--mirror-start mirror) (cons start (yas--mirror-start mirror)))
3293 (setf (yas--mirror-end mirror) (cons end (yas--mirror-end mirror))))))
3294 (let ((snippet-exit (yas--snippet-exit snippet)))
3296 (let ((exit (marker-position (yas--exit-marker snippet-exit))))
3297 (set-marker (yas--exit-marker snippet-exit) nil)
3298 (setf (yas--exit-marker snippet-exit) (cons exit (yas--exit-marker snippet-exit)))))))
3300 (defun yas--points-to-markers (snippet)
3301 "Convert all cons (POINT . MARKER) in SNIPPET to markers.
3303 This is done by setting MARKER to POINT with `set-marker'."
3304 (dolist (field (yas--snippet-fields snippet))
3305 (setf (yas--field-start field) (set-marker (cdr (yas--field-start field))
3306 (car (yas--field-start field))))
3307 (setf (yas--field-end field) (set-marker (cdr (yas--field-end field))
3308 (car (yas--field-end field))))
3309 (dolist (mirror (yas--field-mirrors field))
3310 (setf (yas--mirror-start mirror) (set-marker (cdr (yas--mirror-start mirror))
3311 (car (yas--mirror-start mirror))))
3312 (setf (yas--mirror-end mirror) (set-marker (cdr (yas--mirror-end mirror))
3313 (car (yas--mirror-end mirror))))))
3314 (let ((snippet-exit (yas--snippet-exit snippet)))
3316 (setf (yas--exit-marker snippet-exit) (set-marker (cdr (yas--exit-marker snippet-exit))
3317 (car (yas--exit-marker snippet-exit)))))))
3319 (defun yas--field-contains-point-p (field &optional point)
3320 (let ((point (or point
3322 (and (>= point (yas--field-start field))
3323 (<= point (yas--field-end field)))))
3325 (defun yas--field-text-for-display (field)
3326 "Return the propertized display text for field FIELD."
3327 (buffer-substring (yas--field-start field) (yas--field-end field)))
3329 (defun yas--undo-in-progress ()
3330 "True if some kind of undo is in progress."
3331 (or undo-in-progress
3332 (eq this-command 'undo)
3333 (eq this-command 'redo)))
3335 (defun yas--make-control-overlay (snippet start end)
3336 "Create the control overlay that surrounds the snippet and
3338 (let ((overlay (make-overlay start
3343 (overlay-put overlay 'keymap yas-keymap)
3344 (overlay-put overlay 'priority 100)
3345 (overlay-put overlay 'yas--snippet snippet)
3348 (defun yas-skip-and-clear-or-delete-char (&optional field)
3349 "Clears unmodified field if at field start, skips to next tab.
3351 Otherwise deletes a character normally by calling `delete-char'."
3353 (let ((field (or field
3354 (and yas--active-field-overlay
3355 (overlay-buffer yas--active-field-overlay)
3356 (overlay-get yas--active-field-overlay 'yas--field)))))
3358 (not (yas--field-modified-p field))
3359 (eq (point) (marker-position (yas--field-start field))))
3360 (yas--skip-and-clear field)
3363 (call-interactively 'delete-char)))))
3365 (defun yas--skip-and-clear (field &optional from)
3366 "Deletes the region of FIELD and sets it's modified state to t.
3367 If given, FROM indicates position to start at instead of FIELD's beginning."
3368 ;; Just before skipping-and-clearing the field, mark its children
3369 ;; fields as modified, too. If the children have mirrors-in-fields
3370 ;; this prevents them from updating erroneously (we're skipping and
3373 (yas--mark-this-and-children-modified field)
3374 (unless (= (yas--field-start field) (yas--field-end field))
3375 (delete-region (or from (yas--field-start field)) (yas--field-end field))))
3377 (defun yas--mark-this-and-children-modified (field)
3378 (setf (yas--field-modified-p field) t)
3379 (let ((fom (yas--field-next field)))
3381 (yas--fom-parent-field fom))
3382 (when (and (eq (yas--fom-parent-field fom) field)
3384 (yas--mark-this-and-children-modified fom))
3385 (setq fom (yas--fom-next fom)))))
3387 (defun yas--make-move-active-field-overlay (snippet field)
3388 "Place the active field overlay in SNIPPET's FIELD.
3390 Move the overlay, or create it if it does not exit."
3391 (if (and yas--active-field-overlay
3392 (overlay-buffer yas--active-field-overlay))
3393 (move-overlay yas--active-field-overlay
3394 (yas--field-start field)
3395 (yas--field-end field))
3396 (setq yas--active-field-overlay
3397 (make-overlay (yas--field-start field)
3398 (yas--field-end field)
3400 (overlay-put yas--active-field-overlay 'priority 100)
3401 (overlay-put yas--active-field-overlay 'face 'yas-field-highlight-face)
3402 (overlay-put yas--active-field-overlay 'yas--snippet snippet)
3403 (overlay-put yas--active-field-overlay 'modification-hooks '(yas--on-field-overlay-modification))
3404 (overlay-put yas--active-field-overlay 'insert-in-front-hooks
3405 '(yas--on-field-overlay-modification))
3406 (overlay-put yas--active-field-overlay 'insert-behind-hooks
3407 '(yas--on-field-overlay-modification))))
3409 (defun yas--skip-and-clear-field-p (field beg _end length)
3410 "Tell if newly modified FIELD should be cleared and skipped.
3411 BEG, END and LENGTH like overlay modification hooks."
3412 (and (= length 0) ; A 0 pre-change length indicates insertion.
3413 (= beg (yas--field-start field)) ; Insertion at field start?
3414 (not (yas--field-modified-p field))))
3416 (defun yas--on-field-overlay-modification (overlay after? beg end &optional length)
3417 "Clears the field and updates mirrors, conditionally.
3419 Only clears the field if it hasn't been modified and point is at
3420 field start. This hook does nothing if an undo is in progress."
3421 (unless (or (not after?)
3422 yas--inhibit-overlay-hooks
3423 (not (overlayp yas--active-field-overlay)) ; Avoid Emacs bug #21824.
3424 (yas--undo-in-progress))
3425 (let* ((inhibit-modification-hooks t)
3426 (field (overlay-get overlay 'yas--field))
3427 (snippet (overlay-get yas--active-field-overlay 'yas--snippet)))
3428 (when (yas--skip-and-clear-field-p field beg end length)
3429 ;; We delete text starting from the END of insertion.
3430 (yas--skip-and-clear field end))
3431 (setf (yas--field-modified-p field) t)
3432 (yas--advance-end-maybe field (overlay-end overlay))
3434 (yas--field-update-display field))
3435 (yas--update-mirrors snippet))))
3437 ;;; Apropos protection overlays:
3439 ;; These exist for nasty users who will try to delete parts of the
3440 ;; snippet outside the active field. Actual protection happens in
3441 ;; `yas--on-protection-overlay-modification'.
3443 ;; As of github #537 this no longer inhibits the command by issuing an
3444 ;; error: all the snippets at point, including nested snippets, are
3445 ;; automatically commited and the current command can proceed.
3447 (defun yas--make-move-field-protection-overlays (snippet field)
3448 "Place protection overlays surrounding SNIPPET's FIELD.
3450 Move the overlays, or create them if they do not exit."
3451 (let ((start (yas--field-start field))
3452 (end (yas--field-end field)))
3453 ;; First check if the (1+ end) is contained in the buffer,
3454 ;; otherwise we'll have to do a bit of cheating and silently
3455 ;; insert a newline. the `(1+ (buffer-size))' should prevent this
3456 ;; when using stacked expansion
3458 (when (< (buffer-size) end)
3460 (let ((yas--inhibit-overlay-hooks t))
3461 (goto-char (point-max))
3463 ;; go on to normal overlay creation/moving
3465 (cond ((and yas--field-protection-overlays
3466 (every #'overlay-buffer yas--field-protection-overlays))
3467 (move-overlay (first yas--field-protection-overlays) (1- start) start)
3468 (move-overlay (second yas--field-protection-overlays) end (1+ end)))
3470 (setq yas--field-protection-overlays
3471 (list (make-overlay (1- start) start nil t nil)
3472 (make-overlay end (1+ end) nil t nil)))
3473 (dolist (ov yas--field-protection-overlays)
3474 (overlay-put ov 'face 'yas--field-debug-face)
3475 (overlay-put ov 'yas--snippet snippet)
3476 ;; (overlay-put ov 'evaporate t)
3477 (overlay-put ov 'modification-hooks '(yas--on-protection-overlay-modification)))))))
3479 (defun yas--on-protection-overlay-modification (_overlay after? beg end &optional length)
3480 "Commit the snippet if the protection overlay is being killed."
3481 (unless (or yas--inhibit-overlay-hooks
3483 (= length (- end beg)) ; deletion or insertion
3484 (yas--undo-in-progress))
3485 (let ((snippets (yas--snippets-at-point)))
3486 (yas--message 2 "Committing snippets. Action would destroy a protection overlay.")
3487 (cl-loop for snippet in snippets
3488 do (yas--commit-snippet snippet)))))
3490 (add-to-list 'debug-ignored-errors "^Exit the snippet first!$")
3493 ;;; Snippet expansion and "stacked" expansion:
3495 ;; Stacked expansion is when you try to expand a snippet when already
3496 ;; inside a snippet expansion.
3498 ;; The parent snippet does not run its fields modification hooks
3499 ;; (`yas--on-field-overlay-modification' and
3500 ;; `yas--on-protection-overlay-modification') while the child snippet
3501 ;; is active. This means, among other things, that the mirrors of the
3502 ;; parent snippet are not updated, this only happening when one exits
3503 ;; the child snippet.
3505 ;; Unfortunately, this also puts some ugly (and not fully-tested)
3506 ;; bits of code in `yas-expand-snippet' and
3507 ;; `yas--commit-snippet'. I've tried to mark them with "stacked
3510 ;; This was thought to be safer in an undo/redo perspective, but
3511 ;; maybe the correct implementation is to make the globals
3512 ;; `yas--active-field-overlay' and `yas--field-protection-overlays' be
3513 ;; snippet-local and be active even while the child snippet is
3514 ;; running. This would mean a lot of overlay modification hooks
3515 ;; running, but if managed correctly (including overlay priorities)
3516 ;; they should account for all situations...
3518 (defun yas-expand-snippet (content &optional start end expand-env)
3519 "Expand snippet CONTENT at current point.
3521 Text between START and END will be deleted before inserting
3522 template. EXPAND-ENV is a list of (SYM VALUE) let-style dynamic bindings
3523 considered when expanding the snippet."
3524 (cl-assert (and yas-minor-mode
3525 (memq 'yas--post-command-handler post-command-hook))
3527 "[yas] `yas-expand-snippet' needs properly setup `yas-minor-mode'")
3528 (run-hooks 'yas-before-expand-snippet-hook)
3531 (let* ((yas-selected-text (or yas-selected-text
3532 (and (region-active-p)
3533 (buffer-substring-no-properties (region-beginning)
3536 (and (region-active-p)
3540 (and (region-active-p)
3543 (to-delete (and start
3545 (buffer-substring-no-properties start end)))
3548 (setq yas--indent-original-column (current-column))
3549 ;; Delete the region to delete, this *does* get undo-recorded.
3551 (when (and to-delete
3553 (delete-region start end))
3555 (cond ((listp content)
3556 ;; x) This is a snippet-command
3558 (yas--eval-lisp-no-saves content))
3560 ;; x) This is a snippet-snippet :-)
3562 ;; Narrow the region down to the content, shoosh the
3563 ;; `buffer-undo-list', and create the snippet, the new
3564 ;; snippet updates its mirrors once, so we are left with
3565 ;; some plain text. The undo action for deleting this
3566 ;; plain text will get recorded at the end.
3568 ;; stacked expansion: also shoosh the overlay modification hooks
3569 (let ((buffer-undo-list t))
3570 ;; snippet creation might evaluate users elisp, which
3571 ;; might generate errors, so we have to be ready to catch
3572 ;; them mostly to make the undo information
3574 (setq yas--start-column (current-column))
3575 (let ((yas--inhibit-overlay-hooks t)
3576 ;; Avoid major-mode's syntax propertizing function,
3577 ;; since we mess with the syntax-table and also
3578 ;; insert things that are not valid in the
3579 ;; major-mode language syntax anyway.
3580 (syntax-propertize-function nil))
3583 (eval `(let* ,expand-env
3585 (yas--snippet-create start (point))))
3587 (yas--snippet-create start (point)))))
3588 ;; Invalidate any syntax-propertizing done while `syntax-propertize-function' was nil
3589 (syntax-ppss-flush-cache start))
3591 ;; stacked-expansion: This checks for stacked expansion, save the
3592 ;; `yas--previous-active-field' and advance its boundary.
3594 (let ((existing-field (and yas--active-field-overlay
3595 (overlay-buffer yas--active-field-overlay)
3596 (overlay-get yas--active-field-overlay 'yas--field))))
3597 (when existing-field
3598 (setf (yas--snippet-previous-active-field snippet) existing-field)
3599 (yas--advance-end-maybe existing-field (overlay-end yas--active-field-overlay))))
3601 ;; Exit the snippet immediately if no fields
3603 (unless (yas--snippet-fields snippet)
3604 (yas-exit-snippet snippet))
3606 ;; Push two undo actions: the deletion of the inserted contents of
3607 ;; the new snippet (without the "key") followed by an apply of
3608 ;; `yas--take-care-of-redo' on the newly inserted snippet boundaries
3610 ;; A small exception, if `yas-also-auto-indent-first-line'
3611 ;; is t and `yas--indent' decides to indent the line to a
3612 ;; point before the actual expansion point, undo would be
3613 ;; messed up. We call the early point "newstart"". case,
3614 ;; and attempt to fix undo.
3616 (let ((newstart (overlay-start (yas--snippet-control-overlay snippet)))
3617 (end (overlay-end (yas--snippet-control-overlay snippet))))
3618 (when (< newstart start)
3619 (push (cons (make-string (- start newstart) ? ) newstart) buffer-undo-list))
3620 (push (cons newstart end) buffer-undo-list)
3621 (push `(apply yas--take-care-of-redo ,start ,end ,snippet)
3623 ;; Now, schedule a move to the first field
3625 (let ((first-field (car (yas--snippet-fields snippet))))
3627 (sit-for 0) ;; fix issue 125
3628 (yas--move-to-field snippet first-field)))
3629 (yas--message 4 "snippet expanded.")
3632 (defun yas--take-care-of-redo (_beg _end snippet)
3633 "Commits SNIPPET, which in turn pushes an undo action for reviving it.
3635 Meant to exit in the `buffer-undo-list'."
3636 ;; slightly optimize: this action is only needed for snippets with
3637 ;; at least one field
3638 (when (yas--snippet-fields snippet)
3639 (yas--commit-snippet snippet)))
3641 (defun yas--snippet-revive (beg end snippet)
3642 "Revives SNIPPET and creates a control overlay from BEG to END.
3644 BEG and END are, we hope, the original snippets boundaries.
3645 All the markers/points exiting existing inside SNIPPET should point
3646 to their correct locations *at the time the snippet is revived*.
3648 After revival, push the `yas--take-care-of-redo' in the
3650 ;; Reconvert all the points to markers
3652 (yas--points-to-markers snippet)
3653 ;; When at least one editable field existed in the zombie snippet,
3654 ;; try to revive the whole thing...
3656 (let ((target-field (or (yas--snippet-active-field snippet)
3657 (car (yas--snippet-fields snippet)))))
3659 (setf (yas--snippet-control-overlay snippet) (yas--make-control-overlay snippet beg end))
3660 (overlay-put (yas--snippet-control-overlay snippet) 'yas--snippet snippet)
3662 (yas--move-to-field snippet target-field)
3664 (push `(apply yas--take-care-of-redo ,beg ,end ,snippet)
3665 buffer-undo-list))))
3667 (defun yas--snippet-create (begin end)
3668 "Create a snippet from a template inserted at BEGIN to END.
3670 Returns the newly created snippet."
3672 (narrow-to-region begin end)
3673 (let ((snippet (yas--make-snippet)))
3675 (yas--snippet-parse-create snippet)
3677 ;; Sort and link each field
3678 (yas--snippet-sort-fields snippet)
3680 ;; Create keymap overlay for snippet
3681 (setf (yas--snippet-control-overlay snippet)
3682 (yas--make-control-overlay snippet (point-min) (point-max)))
3685 (goto-char (point-max))
3690 ;;; Apropos adjacencies and "fom's":
3692 ;; Once the $-constructs bits like "$n" and "${:n" are deleted in the
3693 ;; recently expanded snippet, we might actually have many fields,
3694 ;; mirrors (and the snippet exit) in the very same position in the
3695 ;; buffer. Therefore we need to single-link the
3696 ;; fields-or-mirrors-or-exit (which I have abbreviated to "fom")
3697 ;; according to their original positions in the buffer.
3699 ;; Then we have operation `yas--advance-end-maybe' and
3700 ;; `yas--advance-start-maybe', which conditionally push the starts and
3701 ;; ends of these foms down the chain.
3703 ;; This allows for like the printf with the magic ",":
3705 ;; printf ("${1:%s}\\n"${1:$(if (string-match "%" text) "," "\);")} \
3706 ;; $2${1:$(if (string-match "%" text) "\);" "")}$0
3708 (defun yas--fom-start (fom)
3709 (cond ((yas--field-p fom)
3710 (yas--field-start fom))
3711 ((yas--mirror-p fom)
3712 (yas--mirror-start fom))
3714 (yas--exit-marker fom))))
3716 (defun yas--fom-end (fom)
3717 (cond ((yas--field-p fom)
3718 (yas--field-end fom))
3719 ((yas--mirror-p fom)
3720 (yas--mirror-end fom))
3722 (yas--exit-marker fom))))
3724 (defun yas--fom-next (fom)
3725 (cond ((yas--field-p fom)
3726 (yas--field-next fom))
3727 ((yas--mirror-p fom)
3728 (yas--mirror-next fom))
3730 (yas--exit-next fom))))
3732 (defun yas--fom-parent-field (fom)
3733 (cond ((yas--field-p fom)
3734 (yas--field-parent-field fom))
3735 ((yas--mirror-p fom)
3736 (yas--mirror-parent-field fom))
3740 (defun yas--calculate-adjacencies (snippet)
3741 "Calculate adjacencies for fields or mirrors of SNIPPET.
3743 This is according to their relative positions in the buffer, and
3744 has to be called before the $-constructs are deleted."
3745 (let* ((fom-set-next-fom
3746 (lambda (fom nextfom)
3747 (cond ((yas--field-p fom)
3748 (setf (yas--field-next fom) nextfom))
3749 ((yas--mirror-p fom)
3750 (setf (yas--mirror-next fom) nextfom))
3752 (setf (yas--exit-next fom) nextfom)))))
3755 (if (= (yas--fom-start fom2) (yas--fom-start fom1))
3756 (yas--mirror-p fom2)
3757 (>= (yas--fom-start fom2) (yas--fom-start fom1)))))
3758 (link-foms fom-set-next-fom))
3759 ;; make some yas--field, yas--mirror and yas--exit soup
3761 (when (yas--snippet-exit snippet)
3762 (push (yas--snippet-exit snippet) soup))
3763 (dolist (field (yas--snippet-fields snippet))
3765 (dolist (mirror (yas--field-mirrors field))
3766 (push mirror soup)))
3768 (sort soup compare-fom-begs))
3770 (reduce link-foms soup)))))
3772 (defun yas--calculate-mirrors-in-fields (snippet mirror)
3773 "Attempt to assign a parent field of SNIPPET to the mirror MIRROR.
3775 Use the tightest containing field if more than one field contains
3776 the mirror. Intended to be called *before* the dollar-regions are
3778 (let ((min (point-min))
3780 (dolist (field (yas--snippet-fields snippet))
3781 (when (and (<= (yas--field-start field) (yas--mirror-start mirror))
3782 (<= (yas--mirror-end mirror) (yas--field-end field))
3783 (< min (yas--field-start field))
3784 (< (yas--field-end field) max))
3785 (setq min (yas--field-start field)
3786 max (yas--field-end field))
3787 (setf (yas--mirror-parent-field mirror) field)))))
3789 (defun yas--advance-end-maybe (fom newend)
3790 "Maybe advance FOM's end to NEWEND if it needs it.
3794 * call `yas--advance-start-maybe' on FOM's next fom.
3796 * in case FOM is field call `yas--advance-end-maybe' on its parent
3799 Also, if FOM is an exit-marker, always call
3800 `yas--advance-start-maybe' on its next fom. This is because
3801 exit-marker have identical start and end markers."
3802 (cond ((and fom (< (yas--fom-end fom) newend))
3803 (set-marker (yas--fom-end fom) newend)
3804 (yas--advance-start-maybe (yas--fom-next fom) newend)
3805 (yas--advance-end-of-parents-maybe (yas--fom-parent-field fom) newend))
3807 (yas--advance-start-maybe (yas--fom-next fom) newend))))
3809 (defun yas--advance-start-maybe (fom newstart)
3810 "Maybe advance FOM's start to NEWSTART if it needs it.
3812 If it does, also call `yas--advance-end-maybe' on FOM."
3813 (when (and fom (< (yas--fom-start fom) newstart))
3814 (set-marker (yas--fom-start fom) newstart)
3815 (yas--advance-end-maybe fom newstart)))
3817 (defun yas--advance-end-of-parents-maybe (field newend)
3818 "Like `yas--advance-end-maybe' but for parent fields.
3820 Only works for fields and doesn't care about the start of the
3821 next FOM. Works its way up recursively for parents of parents."
3823 (< (yas--field-end field) newend))
3824 (set-marker (yas--field-end field) newend)
3825 (yas--advance-end-of-parents-maybe (yas--field-parent-field field) newend)))
3827 (defvar yas--dollar-regions nil
3828 "When expanding the snippet the \"parse-create\" functions add
3829 cons cells to this var.")
3831 (defvar yas--backquote-markers-and-strings nil
3832 "List of (MARKER . STRING) marking where the values from
3833 backquoted Lisp expressions should be inserted at the end of
3836 (defvar yas--indent-markers nil
3837 "List of markers for manual indentation.")
3839 (defun yas--snippet-parse-create (snippet)
3840 "Parse a recently inserted snippet template, creating all
3841 necessary fields, mirrors and exit points.
3843 Meant to be called in a narrowed buffer, does various passes"
3844 (let ((parse-start (point)))
3845 ;; Reset the yas--dollar-regions
3847 (setq yas--dollar-regions nil)
3848 ;; protect just the backquotes
3850 (yas--protect-escapes nil '(?`))
3851 ;; replace all backquoted expressions
3853 (goto-char parse-start)
3854 (yas--save-backquotes)
3855 ;; protect escaped characters
3857 (yas--protect-escapes)
3858 ;; Parse indent markers: `$>'.
3859 (goto-char parse-start)
3860 (yas--indent-parse-create snippet)
3861 ;; parse fields with {}
3863 (goto-char parse-start)
3864 (yas--field-parse-create snippet)
3865 ;; parse simple mirrors and fields
3867 (goto-char parse-start)
3868 (yas--simple-mirror-parse-create snippet)
3869 ;; parse mirror transforms
3871 (goto-char parse-start)
3872 (yas--transform-mirror-parse-create snippet)
3873 ;; calculate adjacencies of fields and mirrors
3875 (yas--calculate-adjacencies snippet)
3876 ;; Delete $-constructs
3880 (yas--delete-regions yas--dollar-regions))
3881 ;; Make sure to do this insertion *after* deleting the dollar
3882 ;; regions, otherwise we invalidate the calculated positions of
3883 ;; all the fields following $0.
3884 (let ((exit (yas--snippet-exit snippet)))
3885 (goto-char (if exit (yas--exit-marker exit) (point-max))))
3886 (when (eq yas-wrap-around-region 'cua)
3887 (setq yas-wrap-around-region ?0))
3888 (cond ((and yas-wrap-around-region yas-selected-text)
3889 (insert yas-selected-text))
3890 ((and (characterp yas-wrap-around-region)
3891 (get-register yas-wrap-around-region))
3892 (insert (prog1 (get-register yas-wrap-around-region)
3893 (set-register yas-wrap-around-region nil)))))
3894 ;; restore backquoted expression values
3896 (yas--restore-backquotes)
3899 (goto-char parse-start)
3900 (yas--restore-escapes)
3901 ;; update mirrors for the first time
3903 (yas--update-mirrors snippet)
3904 ;; indent the best we can
3906 (goto-char parse-start)
3907 (yas--indent snippet)))
3909 (defun yas--indent-region (from to snippet)
3910 "Indent the lines between FROM and TO with `indent-according-to-mode'.
3911 The SNIPPET's markers are preserved."
3912 ;;; Apropos indenting problems....
3914 ;; `indent-according-to-mode' uses whatever `indent-line-function'
3915 ;; is available. Some implementations of these functions delete text
3916 ;; before they insert. If there happens to be a marker just after
3917 ;; the text being deleted, the insertion actually happens after the
3918 ;; marker, which misplaces it.
3920 ;; This would also happen if we had used overlays with the
3921 ;; `front-advance' property set to nil.
3923 ;; This is why I have these `trouble-markers', they are the ones at
3924 ;; the first non-whitespace char at the line. After indentation
3925 ;; takes place we should be at the correct to restore them. All
3926 ;; other non-trouble-markers should have been *pushed* and don't
3927 ;; need special attention.
3928 (let* ((snippet-markers (yas--collect-snippet-markers snippet))
3929 (to (set-marker (make-marker) to)))
3934 ;; Indent each non-empty line.
3935 (cl-loop if (/= (line-beginning-position) (line-end-position)) do
3936 (back-to-indentation)
3937 (let ((trouble-markers ; The markers at (point).
3938 (cl-remove (point) snippet-markers :test #'/=)))
3940 (indent-according-to-mode)
3941 (dolist (marker trouble-markers)
3942 (set-marker marker (point)))))
3943 while (and (zerop (forward-line 1))
3944 (< (point) to)))))))
3946 (defvar yas--indent-original-column nil)
3947 (defun yas--indent (snippet)
3948 ;; Indent lines that had indent markers (`$>') on them.
3950 (dolist (marker yas--indent-markers)
3951 (unless (eq yas-indent-line 'auto)
3953 (yas--indent-region (line-beginning-position)
3956 ;; Finished with this marker.
3957 (set-marker marker nil))
3958 (setq yas--indent-markers nil))
3959 ;; Now do stuff for `fixed' and `auto'.
3961 (cond ((eq yas-indent-line 'fixed)
3962 (while (and (zerop (forward-line))
3963 (zerop (current-column)))
3964 (indent-to-column yas--indent-original-column)))
3965 ((eq yas-indent-line 'auto)
3966 (let ((end (set-marker (make-marker) (point-max))))
3967 (unless yas-also-auto-indent-first-line
3969 (yas--indent-region (line-beginning-position)
3973 (defun yas--collect-snippet-markers (snippet)
3974 "Make a list of all the markers used by SNIPPET."
3976 (dolist (field (yas--snippet-fields snippet))
3977 (push (yas--field-start field) markers)
3978 (push (yas--field-end field) markers)
3979 (dolist (mirror (yas--field-mirrors field))
3980 (push (yas--mirror-start mirror) markers)
3981 (push (yas--mirror-end mirror) markers)))
3982 (let ((snippet-exit (yas--snippet-exit snippet)))
3983 (when (and snippet-exit
3984 (marker-buffer (yas--exit-marker snippet-exit)))
3985 (push (yas--exit-marker snippet-exit) markers)))
3988 (defun yas--escape-string (escaped)
3989 (concat "YASESCAPE" (format "%d" escaped) "PROTECTGUARD"))
3991 (defun yas--protect-escapes (&optional text escaped)
3992 "Protect all escaped characters with their numeric ASCII value.
3994 With optional string TEXT do it in string instead of buffer."
3995 (let ((changed-text text)
3996 (text-provided-p text))
3997 (mapc #'(lambda (escaped)
3999 (yas--replace-all (concat "\\" (char-to-string escaped))
4000 (yas--escape-string escaped)
4001 (when text-provided-p changed-text))))
4002 (or escaped yas--escaped-characters))
4005 (defun yas--restore-escapes (&optional text escaped)
4006 "Restore all escaped characters from their numeric ASCII value.
4008 With optional string TEXT do it in string instead of the buffer."
4009 (let ((changed-text text)
4010 (text-provided-p text))
4011 (mapc #'(lambda (escaped)
4013 (yas--replace-all (yas--escape-string escaped)
4014 (char-to-string escaped)
4015 (when text-provided-p changed-text))))
4016 (or escaped yas--escaped-characters))
4019 (defun yas--save-backquotes ()
4020 "Save all the \"`(lisp-expression)`\"-style expressions
4021 with their evaluated value into `yas--backquote-markers-and-strings'."
4022 (while (re-search-forward yas--backquote-lisp-expression-regexp nil t)
4023 (let ((current-string (match-string-no-properties 1)) transformed)
4024 (save-restriction (widen)
4025 (delete-region (match-beginning 0) (match-end 0)))
4026 (setq transformed (yas--eval-lisp (yas--read-lisp (yas--restore-escapes current-string '(?`)))))
4027 (goto-char (match-beginning 0))
4029 (let ((marker (make-marker)))
4032 (insert "Y") ;; quite horrendous, I love it :)
4033 (set-marker marker (point))
4035 (push (cons marker transformed) yas--backquote-markers-and-strings))))))
4037 (defun yas--restore-backquotes ()
4038 "Replace markers in `yas--backquote-markers-and-strings' with their values."
4039 (while yas--backquote-markers-and-strings
4040 (let* ((marker-and-string (pop yas--backquote-markers-and-strings))
4041 (marker (car marker-and-string))
4042 (string (cdr marker-and-string)))
4050 (set-marker marker nil)))))
4052 (defun yas--scan-sexps (from count)
4054 (save-match-data ; `scan-sexps' may modify match data.
4055 (with-syntax-table (standard-syntax-table)
4056 (scan-sexps from count)))))
4058 (defun yas--make-marker (pos)
4059 "Create a marker at POS with nil `marker-insertion-type'."
4060 (let ((marker (set-marker (make-marker) pos)))
4061 (set-marker-insertion-type marker nil)
4064 (defun yas--indent-parse-create (snippet)
4065 "Parse the \"$>\" indentation markers in SNIPPET."
4066 (setq yas--indent-markers ())
4067 (while (search-forward "$>" nil t)
4068 (delete-region (match-beginning 0) (match-end 0))
4069 ;; Mark the beginning of the line.
4070 (push (yas--make-marker (line-beginning-position))
4071 yas--indent-markers))
4072 (setq yas--indent-markers (nreverse yas--indent-markers)))
4074 (defun yas--field-parse-create (snippet &optional parent-field)
4075 "Parse most field expressions in SNIPPET, except for the simple one \"$n\".
4077 The following count as a field:
4079 * \"${n: text}\", for a numbered field with default text, as long as N is not 0;
4081 * \"${n: text$(expression)}, the same with a Lisp expression;
4082 this is caught with the curiously named `yas--multi-dollar-lisp-expression-regexp'
4084 * the same as above but unnumbered, (no N:) and number is calculated automatically.
4086 When multiple expressions are found, only the last one counts."
4089 (while (re-search-forward yas--field-regexp nil t)
4090 (let* ((real-match-end-0 (yas--scan-sexps (1+ (match-beginning 0)) 1))
4091 (number (and (match-string-no-properties 1)
4092 (string-to-number (match-string-no-properties 1))))
4093 (brand-new-field (and real-match-end-0
4094 ;; break if on "$(" immediately
4095 ;; after the ":", this will be
4096 ;; caught as a mirror with
4098 (not (string-match-p "\\`\\$[ \t\n]*("
4099 (match-string-no-properties 2)))
4100 ;; allow ${0: some exit text}
4101 ;; (not (and number (zerop number)))
4102 (yas--make-field number
4103 (yas--make-marker (match-beginning 2))
4104 (yas--make-marker (1- real-match-end-0))
4106 (when brand-new-field
4107 (goto-char real-match-end-0)
4108 (push (cons (1- real-match-end-0) real-match-end-0)
4109 yas--dollar-regions)
4110 (push (cons (match-beginning 0) (match-beginning 2))
4111 yas--dollar-regions)
4112 (push brand-new-field (yas--snippet-fields snippet))
4115 (narrow-to-region (yas--field-start brand-new-field) (yas--field-end brand-new-field))
4116 (goto-char (point-min))
4117 (yas--field-parse-create snippet brand-new-field)))))))
4118 ;; if we entered from a parent field, now search for the
4119 ;; `yas--multi-dollar-lisp-expression-regexp'. This is used for
4120 ;; primary field transformations
4124 (while (re-search-forward yas--multi-dollar-lisp-expression-regexp nil t)
4125 (let* ((real-match-end-1 (yas--scan-sexps (match-beginning 1) 1)))
4126 ;; commit the primary field transformation if:
4128 ;; 1. we don't find it in yas--dollar-regions (a subnested
4129 ;; field) might have already caught it.
4131 ;; 2. we really make sure we have either two '$' or some
4132 ;; text and a '$' after the colon ':'. This is a FIXME: work
4133 ;; my regular expressions and end these ugly hacks.
4135 (when (and real-match-end-1
4136 (not (member (cons (match-beginning 0)
4138 yas--dollar-regions))
4140 (char-before (1- (match-beginning 1))))))
4141 (let ((lisp-expression-string (buffer-substring-no-properties (match-beginning 1)
4143 (setf (yas--field-transform parent-field)
4144 (yas--read-lisp (yas--restore-escapes lisp-expression-string))))
4145 (push (cons (match-beginning 0) real-match-end-1)
4146 yas--dollar-regions)))))))
4148 (defun yas--transform-mirror-parse-create (snippet)
4149 "Parse the \"${n:$(lisp-expression)}\" mirror transformations in SNIPPET."
4150 (while (re-search-forward yas--transform-mirror-regexp nil t)
4151 (let* ((real-match-end-0 (yas--scan-sexps (1+ (match-beginning 0)) 1))
4152 (number (string-to-number (match-string-no-properties 1)))
4154 (not (zerop number))
4155 (yas--snippet-find-field snippet number)))
4157 (and real-match-end-0
4159 (yas--make-mirror (yas--make-marker (match-beginning 0))
4160 (yas--make-marker (match-beginning 0))
4162 (yas--restore-escapes
4163 (buffer-substring-no-properties (match-beginning 2)
4164 (1- real-match-end-0))))))))
4165 (when brand-new-mirror
4166 (push brand-new-mirror
4167 (yas--field-mirrors field))
4168 (yas--calculate-mirrors-in-fields snippet brand-new-mirror)
4169 (push (cons (match-beginning 0) real-match-end-0) yas--dollar-regions)))))
4171 (defun yas--simple-mirror-parse-create (snippet)
4172 "Parse the simple \"$n\" fields/mirrors/exitmarkers in SNIPPET."
4173 (while (re-search-forward yas--simple-mirror-regexp nil t)
4174 (let ((number (string-to-number (match-string-no-properties 1))))
4175 (cond ((zerop number)
4176 (setf (yas--snippet-exit snippet)
4177 (yas--make-exit (yas--make-marker (match-end 0))))
4178 (push (cons (match-beginning 0) (yas--exit-marker (yas--snippet-exit snippet)))
4179 yas--dollar-regions))
4181 (let ((field (yas--snippet-find-field snippet number)))
4183 (let ((brand-new-mirror (yas--make-mirror
4184 (yas--make-marker (match-beginning 0))
4185 (yas--make-marker (match-beginning 0))
4187 (push brand-new-mirror
4188 (yas--field-mirrors field))
4189 (yas--calculate-mirrors-in-fields snippet brand-new-mirror))
4190 (push (yas--make-field number
4191 (yas--make-marker (match-beginning 0))
4192 (yas--make-marker (match-beginning 0))
4194 (yas--snippet-fields snippet))))
4195 (push (cons (match-beginning 0) (match-end 0))
4196 yas--dollar-regions))))))
4198 (defun yas--delete-regions (regions)
4199 "Sort disjuct REGIONS by start point, then delete from the back."
4200 (mapc #'(lambda (reg)
4201 (delete-region (car reg) (cdr reg)))
4204 (>= (car r1) (car r2))))))
4206 (defun yas--calculate-mirror-depth (mirror &optional traversed)
4207 (let* ((parent (yas--mirror-parent-field mirror))
4208 (parents-mirrors (and parent
4209 (yas--field-mirrors parent))))
4210 (or (yas--mirror-depth mirror)
4211 (setf (yas--mirror-depth mirror)
4212 (cond ((memq mirror traversed)
4214 ((and parent parents-mirrors)
4216 (mapcar #'(lambda (m)
4217 (yas--calculate-mirror-depth m
4226 (defun yas--update-mirrors (snippet)
4227 "Update all the mirrors of SNIPPET."
4231 (dolist (field-and-mirror
4233 ;; make a list of ((F1 . M1) (F1 . M2) (F2 . M3) (F2 . M4) ...)
4234 ;; where F is the field that M is mirroring
4236 (cl-mapcan #'(lambda (field)
4237 (mapcar #'(lambda (mirror)
4238 (cons field mirror))
4239 (yas--field-mirrors field)))
4240 (yas--snippet-fields snippet))
4241 ;; then sort this list so that entries with mirrors with parent
4242 ;; fields appear before. This was important for fixing #290, and
4243 ;; luckily also handles the case where a mirror in a field causes
4244 ;; another mirror to need reupdating
4246 #'(lambda (field-and-mirror1 field-and-mirror2)
4247 (> (yas--calculate-mirror-depth (cdr field-and-mirror1))
4248 (yas--calculate-mirror-depth (cdr field-and-mirror2))))))
4249 (let* ((field (car field-and-mirror))
4250 (mirror (cdr field-and-mirror))
4251 (parent-field (yas--mirror-parent-field mirror)))
4252 ;; before updating a mirror with a parent-field, maybe advance
4256 (yas--advance-start-maybe mirror (yas--fom-start parent-field)))
4257 ;; update this mirror
4259 (yas--mirror-update-display mirror field snippet)
4260 ;; `yas--place-overlays' is needed since the active field and
4261 ;; protected overlays might have been changed because of insertions
4262 ;; in `yas--mirror-update-display'.
4263 (let ((active-field (yas--snippet-active-field snippet)))
4264 (when active-field (yas--place-overlays snippet active-field))))))))
4266 (defun yas--mirror-update-display (mirror field snippet)
4267 "Update MIRROR according to FIELD (and mirror transform)."
4269 (let* ((mirror-parent-field (yas--mirror-parent-field mirror))
4270 (reflection (and (not (and mirror-parent-field
4271 (yas--field-modified-p mirror-parent-field)))
4272 (or (yas--apply-transform mirror field 'empty-on-nil)
4273 (yas--field-text-for-display field)))))
4274 (when (and reflection
4275 (not (string= reflection (buffer-substring-no-properties (yas--mirror-start mirror)
4276 (yas--mirror-end mirror)))))
4277 (goto-char (yas--mirror-start mirror))
4278 (let ((yas--inhibit-overlay-hooks t))
4279 (insert reflection))
4280 (if (> (yas--mirror-end mirror) (point))
4281 (delete-region (point) (yas--mirror-end mirror))
4282 (set-marker (yas--mirror-end mirror) (point))
4283 (yas--advance-start-maybe (yas--mirror-next mirror) (point))
4284 ;; super-special advance
4285 (yas--advance-end-of-parents-maybe mirror-parent-field (point)))
4286 (let ((yas--inhibit-overlay-hooks t))
4287 (yas--indent-region (yas--mirror-start mirror)
4288 (yas--mirror-end mirror)
4291 (defun yas--field-update-display (field)
4292 "Much like `yas--mirror-update-display', but for fields."
4293 (when (yas--field-transform field)
4294 (let ((transformed (and (not (eq (yas--field-number field) 0))
4295 (yas--apply-transform field field))))
4296 (when (and transformed
4297 (not (string= transformed (buffer-substring-no-properties (yas--field-start field)
4298 (yas--field-end field)))))
4299 (setf (yas--field-modified-p field) t)
4300 (goto-char (yas--field-start field))
4301 (let ((yas--inhibit-overlay-hooks t))
4302 (insert transformed)
4303 (if (> (yas--field-end field) (point))
4304 (delete-region (point) (yas--field-end field))
4305 (set-marker (yas--field-end field) (point))
4306 (yas--advance-start-maybe (yas--field-next field) (point)))
4310 ;;; Post-command hook:
4312 (defun yas--post-command-handler ()
4313 "Handles various yasnippet conditions after each command."
4314 (cond ((eq 'undo this-command)
4316 ;; After undo revival the correct field is sometimes not
4317 ;; restored correctly, this condition handles that
4319 (let* ((snippet (car (yas--snippets-at-point)))
4320 (target-field (and snippet
4321 (find-if-not #'(lambda (field)
4322 (yas--field-probably-deleted-p snippet field))
4324 (cons (yas--snippet-active-field snippet)
4325 (yas--snippet-fields snippet)))))))
4327 (yas--move-to-field snippet target-field))))
4328 ((not (yas--undo-in-progress))
4329 ;; When not in an undo, check if we must commit the snippet
4330 ;; (user exited it).
4331 (yas--check-commit-snippet))))
4335 ;; The docstrings for some functions are generated dynamically
4336 ;; depending on the context.
4338 (put 'yas-expand 'function-documentation
4339 '(yas--expand-from-trigger-key-doc t))
4340 (defun yas--expand-from-trigger-key-doc (context)
4341 "A doc synthesizer for `yas--expand-from-trigger-key-doc'."
4342 (let* ((yas-fallback-behavior (and context yas-fallback-behavior))
4343 (fallback-description
4344 (cond ((eq yas-fallback-behavior 'call-other-command)
4345 (let* ((fallback (yas--keybinding-beyond-yasnippet)))
4347 (format "call command `%s'."
4348 (pp-to-string fallback)))
4349 "do nothing (`yas-expand' doesn't override\nanything).")))
4350 ((eq yas-fallback-behavior 'return-nil)
4352 (t "defer to `yas-fallback-behavior' (which see)."))))
4353 (concat "Expand a snippet before point. If no snippet
4354 expansion is possible, "
4355 fallback-description
4356 "\n\nOptional argument FIELD is for non-interactive use and is an
4357 object satisfying `yas--field-p' to restrict the expansion to.")))
4359 (put 'yas-expand-from-keymap 'function-documentation
4360 '(yas--expand-from-keymap-doc t))
4361 (defun yas--expand-from-keymap-doc (context)
4362 "A doc synthesizer for `yas--expand-from-keymap-doc'."
4363 (add-hook 'temp-buffer-show-hook #'yas--snippet-description-finish-runonce)
4364 (concat "Expand/run snippets from keymaps, possibly falling back to original binding.\n"
4365 (when (and context (eq this-command 'describe-key))
4366 (let* ((vec (this-single-command-keys))
4367 (templates (mapcan #'(lambda (table)
4368 (yas--fetch table vec))
4369 (yas--get-snippet-tables)))
4370 (yas--direct-keymaps nil)
4371 (fallback (key-binding vec)))
4372 (concat "In this case, "
4374 (concat "these snippets are bound to this key:\n"
4375 (yas--template-pretty-list templates)
4376 "\n\nIf none of these expands, "))
4378 (format "fallback `%s' will be called." (pp-to-string fallback)))
4379 "no fallback keybinding is called."))))))
4381 (defun yas--template-pretty-list (templates)
4383 (yas-buffer-local-condition 'always))
4384 (dolist (plate templates)
4385 (setq acc (concat acc "\n*) "
4386 (propertize (concat "\\\\snippet `" (car plate) "'")
4387 'yasnippet (cdr plate)))))
4390 (define-button-type 'help-snippet-def
4391 :supertype 'help-xref
4392 'help-function (lambda (template) (yas--visit-snippet-file-1 template))
4393 'help-echo (purecopy "mouse-2, RET: find snippets's definition"))
4395 (defun yas--snippet-description-finish-runonce ()
4396 "Final adjustments for the help buffer when snippets are concerned."
4397 (yas--create-snippet-xrefs)
4398 (remove-hook 'temp-buffer-show-hook
4399 #'yas--snippet-description-finish-runonce))
4401 (defun yas--create-snippet-xrefs ()
4403 (goto-char (point-min))
4404 (while (search-forward-regexp "\\\\\\\\snippet[ \s\t]+`\\([^']+\\)'" nil t)
4405 (let ((template (get-text-property (match-beginning 1)
4408 (help-xref-button 1 'help-snippet-def template)
4409 (delete-region (match-end 1) (match-end 0))
4410 (delete-region (match-beginning 0) (match-beginning 1)))))))
4414 (defvar yas-verbosity 3
4415 "Log level for `yas--message' 4 means trace most anything, 0 means nothing.")
4417 (defun yas--message (level message &rest args)
4418 "When LEVEL is above `yas-verbosity-level', log MESSAGE and ARGS."
4419 (when (> yas-verbosity level)
4420 (message "%s" (apply #'yas--format message args))))
4422 (defun yas--warning (format-control &rest format-args)
4423 (let ((msg (apply #'format format-control format-args)))
4424 (display-warning 'yasnippet msg :warning)
4425 (yas--message 1 msg)))
4427 (defun yas--format (format-control &rest format-args)
4428 (apply #'format (concat "[yas] " format-control) format-args))
4435 ;; `locate-dominating-file'
4436 ;; `region-active-p'
4438 ;; added for compatibility in emacsen < 23
4439 (unless (>= emacs-major-version 23)
4440 (unless (fboundp 'region-active-p)
4441 (defun region-active-p () (and transient-mark-mode mark-active)))
4443 (unless (fboundp 'locate-dominating-file)
4444 (defvar locate-dominating-stop-dir-regexp
4445 "\\`\\(?:[\\/][\\/][^\\/]+[\\/]\\|/\\(?:net\\|afs\\|\\.\\.\\.\\)/\\)\\'"
4446 "Regexp of directory names which stop the search in `locate-dominating-file'.
4447 Any directory whose name matches this regexp will be treated like
4448 a kind of root directory by `locate-dominating-file' which will stop its search
4449 when it bumps into it.
4450 The default regexp prevents fruitless and time-consuming attempts to find
4451 special files in directories in which filenames are interpreted as hostnames,
4452 or mount points potentially requiring authentication as a different user.")
4454 (defun locate-dominating-file (file name)
4455 "Look up the directory hierarchy from FILE for a file named NAME.
4456 Stop at the first parent directory containing a file NAME,
4457 and return the directory. Return nil if not found."
4458 ;; We used to use the above locate-dominating-files code, but the
4459 ;; directory-files call is very costly, so we're much better off doing
4460 ;; multiple calls using the code in here.
4462 ;; Represent /home/luser/foo as ~/foo so that we don't try to look for
4463 ;; `name' in /home or in /.
4464 (setq file (abbreviate-file-name file))
4467 (while (not (or root
4469 ;; FIXME: Disabled this heuristic because it is sometimes
4471 ;; As a heuristic, we stop looking up the hierarchy of
4472 ;; directories as soon as we find a directory belonging
4473 ;; to another user. This should save us from looking in
4474 ;; things like /net and /afs. This assumes that all the
4475 ;; files inside a project belong to the same user.
4476 ;; (let ((prev-user user))
4477 ;; (setq user (nth 2 (file-attributes file)))
4478 ;; (and prev-user (not (equal user prev-user))))
4479 (string-match locate-dominating-stop-dir-regexp file)))
4480 (setq try (file-exists-p (expand-file-name name file)))
4481 (cond (try (setq root file))
4482 ((equal file (setq file (file-name-directory
4483 (directory-file-name file))))
4488 ;;; Backward compatibility to yasnippet <= 0.7
4490 (defun yas-initialize ()
4491 "For backward compatibility, enable `yas-minor-mode' globally."
4492 (declare (obsolete "Use (yas-global-mode 1) instead." "0.8"))
4493 (yas-global-mode 1))
4495 (defvar yas--backported-syms '(;; `defcustom's
4498 yas-prompt-functions
4500 yas-also-auto-indent-first-line
4502 yas-triggers-in-field
4503 yas-fallback-behavior
4504 yas-choose-keys-first
4505 yas-choose-tables-first
4508 yas-wrap-around-region
4511 yas-expand-only-for-last-commands
4512 yas-field-highlight-face
4514 ;; these vars can be customized as well
4520 yas-after-exit-snippet-hook
4521 yas-before-expand-snippet-hook
4522 yas-buffer-local-condition
4525 ;; prompting functions
4530 yas-completing-prompt
4533 ;; interactive functions
4538 yas-direct-keymaps-reload
4542 yas-compile-directory
4545 yas-expand-from-trigger-key
4546 yas-expand-from-keymap
4548 yas-visit-snippet-file
4550 yas-load-snippet-buffer
4553 yas-next-field-or-maybe-expand
4558 yas-exit-all-snippets
4559 yas-skip-and-clear-or-delete-char
4562 ;; symbols that I "exported" for use
4563 ;; in snippets and hookage
4580 yas-default-from-field
4583 yas-define-condition-cache
4584 yas-hippie-try-expand
4586 ;; debug definitions
4587 ;; yas-debug-snippet-vars
4588 ;; yas-exterminate-package
4591 ;; testing definitions
4592 ;; yas-should-expand
4593 ;; yas-should-not-expand
4595 ;; yas-make-file-or-dirs
4597 ;; yas-saving-variables
4598 ;; yas-call-with-snippet-dirs
4599 ;; yas-with-snippet-dirs
4601 "Backported yasnippet symbols.
4603 They are mapped to \"yas/*\" variants.")
4605 (when yas-alias-to-yas/prefix-p
4606 (dolist (sym yas--backported-syms)
4607 (let ((backported (intern (replace-regexp-in-string "\\`yas-" "yas/" (symbol-name sym)))))
4609 (make-obsolete-variable backported sym "yasnippet 0.8")
4610 (defvaralias backported sym))
4612 (make-obsolete backported sym "yasnippet 0.8")
4613 (defalias backported sym))))
4614 (make-obsolete 'yas/root-directory 'yas-snippet-dirs "yasnippet 0.8")
4615 (defvaralias 'yas/root-directory 'yas-snippet-dirs))
4617 (defvar yas--exported-syms
4619 (mapatoms (lambda (atom)
4620 (if (and (or (and (boundp atom)
4621 (not (get atom 'byte-obsolete-variable)))
4623 (not (get atom 'byte-obsolete-info))))
4624 (string-match-p "\\`yas-[^-]" (symbol-name atom)))
4625 (push atom exported))))
4627 "Exported yasnippet symbols.
4629 i.e. the ones with \"yas-\" single dash prefix. I will try to
4630 keep them in future yasnippet versions and other elisp libraries
4631 can more or less safely rely upon them.")
4634 (provide 'yasnippet)
4637 ;; indent-tabs-mode: nil
4638 ;; byte-compile-warnings: (not cl-functions)
4640 ;;; yasnippet.el ends here