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 (defvaralias 'yas/root-directory 'yas-snippet-dirs)
207 (defcustom yas-new-snippet-default "\
208 # -*- mode: snippet -*-
210 # key: ${2:${1:$(yas--key-from-desc yas-text)}}
213 "Default snippet to use when creating a new snippet.
214 If nil, don't use any snippet."
218 (defcustom yas-prompt-functions '(yas-dropdown-prompt
219 yas-completing-prompt
222 "Functions to prompt for keys, templates, etc interactively.
224 These functions are called with the following arguments:
226 - PROMPT: A string to prompt the user
228 - CHOICES: a list of strings or objects.
230 - optional DISPLAY-FN : A function that, when applied to each of
231 the objects in CHOICES will return a string.
233 The return value of any function you put here should be one of
234 the objects in CHOICES, properly formatted with DISPLAY-FN (if
237 - To signal that your particular style of prompting is
238 unavailable at the moment, you can also have the function return
241 - To signal that the user quit the prompting process, you can
244 (signal 'quit \"user quit!\")."
245 :type '(repeat function)
248 (defcustom yas-indent-line 'auto
249 "Controls indenting applied to a recent snippet expansion.
251 The following values are possible:
253 - `fixed' Indent the snippet to the current column;
255 - `auto' Indent each line of the snippet with `indent-according-to-mode'
257 Every other value means don't apply any snippet-side indentation
258 after expansion (the manual per-line \"$>\" indentation still
260 :type '(choice (const :tag "Nothing" nothing)
261 (const :tag "Fixed" fixed)
262 (const :tag "Auto" auto))
265 (defcustom yas-also-auto-indent-first-line nil
266 "Non-nil means also auto indent first line according to mode.
268 Naturally this is only valid when `yas-indent-line' is `auto'"
272 (defcustom yas-snippet-revival t
273 "Non-nil means re-activate snippet fields after undo/redo."
277 (defcustom yas-triggers-in-field nil
278 "If non-nil, allow stacked expansions (snippets inside snippets).
280 Otherwise `yas-next-field-or-maybe-expand' just moves on to the
285 (defcustom yas-fallback-behavior 'call-other-command
286 "How to act when `yas-expand' does *not* expand a snippet.
288 - `call-other-command' means try to temporarily disable YASnippet
289 and call the next command bound to whatever key was used to
292 - nil or the symbol `return-nil' mean do nothing. (and
293 `yas-expand' returns nil)
295 - A Lisp form (apply COMMAND . ARGS) means interactively call
296 COMMAND. If ARGS is non-nil, call COMMAND non-interactively
297 with ARGS as arguments."
298 :type '(choice (const :tag "Call previous command" call-other-command)
299 (const :tag "Do nothing" return-nil))
302 (defcustom yas-choose-keys-first nil
303 "If non-nil, prompt for snippet key first, then for template.
305 Otherwise prompts for all possible snippet names.
307 This affects `yas-insert-snippet' and `yas-visit-snippet-file'."
311 (defcustom yas-choose-tables-first nil
312 "If non-nil, and multiple eligible snippet tables, prompts user for tables first.
314 Otherwise, user chooses between the merging together of all
317 This affects `yas-insert-snippet', `yas-visit-snippet-file'"
321 (defcustom yas-use-menu 'abbreviate
322 "Display a YASnippet menu in the menu bar.
324 When non-nil, submenus for each snippet table will be listed
325 under the menu \"Yasnippet\".
327 - If set to `abbreviate', only the current major-mode
328 menu and the modes set in `yas--extra-modes' are listed.
330 - If set to `full', every submenu is listed
332 - If set to `nil', hide the menu.
334 Any other non-nil value, every submenu is listed."
335 :type '(choice (const :tag "Full" full)
336 (const :tag "Abbreviate" abbreviate)
337 (const :tag "No menu" nil))
340 (defcustom yas-trigger-symbol (or (and (eq window-system 'mac)
342 (char-to-string ?\x21E5))) ;; little ->| sign
344 "The text that will be used in menu to represent the trigger."
348 (defcustom yas-wrap-around-region nil
349 "What to insert for snippet's $0 field.
351 If set to a character, insert contents of corresponding register.
352 If non-nil insert region contents. This can be overridden on a
353 per-snippet basis. A value of `cua' is considered equivalent to
354 `?0' for backwards compatibility."
355 :type '(choice (character :tag "Insert from register")
356 (const t :tag "Insert region contents")
357 (const nil :tag "Don't insert anything")
358 (const cua)) ; backwards compat
361 (defcustom yas-good-grace t
362 "If non-nil, don't raise errors in inline elisp evaluation.
364 An error string \"[yas] error\" is returned instead."
368 (defcustom yas-visit-from-menu nil
369 "If non-nil visit snippets's files from menu, instead of expanding them.
371 This can only work when snippets are loaded from files."
375 (defcustom yas-expand-only-for-last-commands nil
376 "List of `last-command' values to restrict tab-triggering to, or nil.
378 Leave this set at nil (the default) to be able to trigger an
379 expansion simply by placing the cursor after a valid tab trigger,
380 using whichever commands.
382 Optionally, set this to something like '(self-insert-command) if
383 you to wish restrict expansion to only happen when the last
384 letter of the snippet tab trigger was typed immediately before
385 the trigger key itself."
386 :type '(repeat function)
389 ;; Only two faces, and one of them shouldn't even be used...
391 (defface yas-field-highlight-face
392 '((t (:inherit 'region)))
393 "The face used to highlight the currently active field of a snippet"
396 (defface yas--field-debug-face
398 "The face used for debugging some overlays normally hidden"
402 ;;; User-visible variables
404 (defvar yas-keymap (let ((map (make-sparse-keymap)))
405 (define-key map [(tab)] 'yas-next-field-or-maybe-expand)
406 (define-key map (kbd "TAB") 'yas-next-field-or-maybe-expand)
407 (define-key map [(shift tab)] 'yas-prev-field)
408 (define-key map [backtab] 'yas-prev-field)
409 (define-key map (kbd "C-g") 'yas-abort-snippet)
410 (define-key map (kbd "C-d") 'yas-skip-and-clear-or-delete-char)
412 "The active keymap while a snippet expansion is in progress.")
414 (defvar yas-key-syntaxes (list "w" "w_" "w_." "w_.()"
415 #'yas-try-key-from-whitespace)
416 "Syntaxes and functions to help look for trigger keys before point.
418 Each element in this list specifies how to skip buffer positions
419 backwards and look for the start of a trigger key.
421 Each element can be either a string or a function receiving the
422 original point as an argument. A string element is simply passed
423 to `skip-syntax-backward' whereas a function element is called
424 with no arguments and should also place point before the original
427 The string between the resulting buffer position and the original
428 point is matched against the trigger keys in the active snippet
431 If no expandable snippets are found, the next element is the list
432 is tried, unless a function element returned the symbol `again',
433 in which case it is called again from the previous position and
434 may once more reposition point.
436 For example, if `yas-key-syntaxes'' value is '(\"w\" \"w_\"),
437 trigger keys composed exclusively of \"word\"-syntax characters
438 are looked for first. Failing that, longer keys composed of
439 \"word\" or \"symbol\" syntax are looked for. Therefore,
444 will, according to the \"w\" element first try \"barbaz\". If
445 that isn't a trigger key, \"foo-barbaz\" is tried, respecting the
446 second \"w_\" element. Notice that even if \"baz\" is a trigger
447 key for an active snippet, it won't be expanded, unless a
448 function is added to `yas-key-syntaxes' that eventually places
449 point between \"bar\" and \"baz\".
451 See also Info node `(elisp) Syntax Descriptors'.")
453 (defvar yas-after-exit-snippet-hook
455 "Hooks to run after a snippet exited.
457 The hooks will be run in an environment where some variables bound to
460 `yas-snippet-beg' : The beginning of the region of the snippet.
462 `yas-snippet-end' : Similar to beg.
464 Attention: These hooks are not run when exiting nested/stacked snippet expansion!")
466 (defvar yas-before-expand-snippet-hook
468 "Hooks to run just before expanding a snippet.")
470 (defvar yas-buffer-local-condition
471 '(if (and (let ((ppss (syntax-ppss)))
472 (or (nth 3 ppss) (nth 4 ppss)))
473 (memq this-command '(yas-expand yas-expand-from-trigger-key
474 yas-expand-from-keymap)))
475 '(require-snippet-condition . force-in-comment)
477 "Snippet expanding condition.
479 This variable is a Lisp form which is evaluated every time a
480 snippet expansion is attempted:
482 * If it evaluates to nil, no snippets can be expanded.
484 * If it evaluates to the a cons (require-snippet-condition
487 * Snippets bearing no \"# condition:\" directive are not
490 * Snippets bearing conditions that evaluate to nil (or
491 produce an error) won't be considered.
493 * If the snippet has a condition that evaluates to non-nil
496 * If REQUIREMENT is t, the snippet is considered
498 * If REQUIREMENT is `eq' RESULT, the snippet is
501 * Otherwise, the snippet is not considered.
503 * If it evaluates to the symbol 'always, all snippets are
504 considered for expansion, regardless of any conditions.
506 * If it evaluates to t or some other non-nil value
508 * Snippet bearing no conditions, or conditions that
509 evaluate to non-nil, are considered for expansion.
511 * Otherwise, the snippet is not considered.
513 Here's an example preventing snippets from being expanded from
514 inside comments, in `python-mode' only, with the exception of
515 snippets returning the symbol 'force-in-comment in their
518 (add-hook 'python-mode-hook
520 (setq yas-buffer-local-condition
521 '(if (python-in-string/comment)
522 '(require-snippet-condition . force-in-comment)
525 The default value is similar, it filters out potential snippet
526 expansions inside comments and string literals, unless the
527 snippet itself contains a condition that returns the symbol
528 `force-in-comment'.")
531 ;;; Internal variables
533 (defvar yas--version "0.9.1")
535 (defvar yas--menu-table (make-hash-table)
536 "A hash table of MAJOR-MODE symbols to menu keymaps.")
538 (defvar yas--escaped-characters
539 '(?\\ ?` ?\" ?' ?$ ?} ?{ ?\( ?\))
540 "List of characters which *might* need to be escaped.")
542 (defconst yas--field-regexp
543 "${\\([0-9]+:\\)?\\([^}]*\\)}"
544 "A regexp to *almost* recognize a field.")
546 (defconst yas--multi-dollar-lisp-expression-regexp
547 "$+[ \t\n]*\\(([^)]*)\\)"
548 "A regexp to *almost* recognize a \"$(...)\" expression.")
550 (defconst yas--backquote-lisp-expression-regexp
552 "A regexp to recognize a \"`lisp-expression`\" expression." )
554 (defconst yas--transform-mirror-regexp
555 "${\\(?:\\([0-9]+\\):\\)?$\\([ \t\n]*([^}]*\\)"
556 "A regexp to *almost* recognize a mirror with a transform.")
558 (defconst yas--simple-mirror-regexp
560 "A regexp to recognize a simple mirror.")
562 (defvar yas--snippet-id-seed 0
563 "Contains the next id for a snippet.")
565 (defun yas--snippet-next-id ()
566 (let ((id yas--snippet-id-seed))
567 (cl-incf yas--snippet-id-seed)
573 ;; XXX: `last-buffer-undo-list' is somehow needed in Carbon Emacs for MacOSX
574 (defvar last-buffer-undo-list nil)
576 (defvar yas--minor-mode-menu nil
577 "Holds the YASnippet menu.")
579 (defvar yas-minor-mode-map
580 (let ((map (make-sparse-keymap)))
581 (define-key map [(tab)] 'yas-expand)
582 (define-key map (kbd "TAB") 'yas-expand)
583 (define-key map "\C-c&\C-s" 'yas-insert-snippet)
584 (define-key map "\C-c&\C-n" 'yas-new-snippet)
585 (define-key map "\C-c&\C-v" 'yas-visit-snippet-file)
587 "The keymap used when `yas-minor-mode' is active.")
589 (easy-menu-define yas--minor-mode-menu
591 "Menu used when `yas-minor-mode' is active."
592 '("YASnippet" :visible yas-use-menu
594 ["Expand trigger" yas-expand
595 :help "Possibly expand tab trigger before point"]
596 ["Insert at point..." yas-insert-snippet
597 :help "Prompt for an expandable snippet and expand it at point"]
598 ["New snippet..." yas-new-snippet
599 :help "Create a new snippet in an appropriate directory"]
600 ["Visit snippet file..." yas-visit-snippet-file
601 :help "Prompt for an expandable snippet and find its file"]
603 ("Snippet menu behaviour"
604 ["Visit snippets" (setq yas-visit-from-menu t)
605 :help "Visit snippets from the menu"
606 :active t :style radio :selected yas-visit-from-menu]
607 ["Expand snippets" (setq yas-visit-from-menu nil)
608 :help "Expand snippets from the menu"
609 :active t :style radio :selected (not yas-visit-from-menu)]
611 ["Show all known modes" (setq yas-use-menu 'full)
612 :help "Show one snippet submenu for each loaded table"
613 :active t :style radio :selected (eq yas-use-menu 'full)]
614 ["Abbreviate according to current mode" (setq yas-use-menu 'abbreviate)
615 :help "Show only snippet submenus for the current active modes"
616 :active t :style radio :selected (eq yas-use-menu 'abbreviate)])
618 ["Auto" (setq yas-indent-line 'auto)
619 :help "Indent each line of the snippet with `indent-according-to-mode'"
620 :active t :style radio :selected (eq yas-indent-line 'auto)]
621 ["Fixed" (setq yas-indent-line 'fixed)
622 :help "Indent the snippet to the current column"
623 :active t :style radio :selected (eq yas-indent-line 'fixed)]
624 ["None" (setq yas-indent-line 'none)
625 :help "Don't apply any particular snippet indentation after expansion"
626 :active t :style radio :selected (not (member yas-indent-line '(fixed auto)))]
628 ["Also auto indent first line" (setq yas-also-auto-indent-first-line
629 (not yas-also-auto-indent-first-line))
630 :help "When auto-indenting also, auto indent the first line menu"
631 :active (eq yas-indent-line 'auto)
632 :style toggle :selected yas-also-auto-indent-first-line]
635 ["System X-widget" (setq yas-prompt-functions
637 (remove 'yas-x-prompt
638 yas-prompt-functions)))
639 :help "Use your windowing system's (gtk, mac, windows, etc...) default menu"
640 :active t :style radio :selected (eq (car yas-prompt-functions)
642 ["Dropdown-list" (setq yas-prompt-functions
643 (cons 'yas-dropdown-prompt
644 (remove 'yas-dropdown-prompt
645 yas-prompt-functions)))
646 :help "Use a special dropdown list"
647 :active t :style radio :selected (eq (car yas-prompt-functions)
648 'yas-dropdown-prompt)]
649 ["Ido" (setq yas-prompt-functions
650 (cons 'yas-ido-prompt
651 (remove 'yas-ido-prompt
652 yas-prompt-functions)))
653 :help "Use an ido-style minibuffer prompt"
654 :active t :style radio :selected (eq (car yas-prompt-functions)
656 ["Completing read" (setq yas-prompt-functions
657 (cons 'yas-completing-prompt
658 (remove 'yas-completing-prompt
659 yas-prompt-functions)))
660 :help "Use a normal minibuffer prompt"
661 :active t :style radio :selected (eq (car yas-prompt-functions)
662 'yas-completing-prompt)]
665 ["Wrap region in exit marker"
666 (setq yas-wrap-around-region
667 (not yas-wrap-around-region))
668 :help "If non-nil automatically wrap the selected text in the $0 snippet exit"
669 :style toggle :selected yas-wrap-around-region]
670 ["Allow stacked expansions "
671 (setq yas-triggers-in-field
672 (not yas-triggers-in-field))
673 :help "If non-nil allow snippets to be triggered inside other snippet fields"
674 :style toggle :selected yas-triggers-in-field]
675 ["Revive snippets on undo "
676 (setq yas-snippet-revival
677 (not yas-snippet-revival))
678 :help "If non-nil allow snippets to become active again after undo"
679 :style toggle :selected yas-snippet-revival]
682 (not yas-good-grace))
683 :help "If non-nil don't raise errors in bad embedded elisp in snippets"
684 :style toggle :selected yas-good-grace]
687 ["Load snippets..." yas-load-directory
688 :help "Load snippets from a specific directory"]
689 ["Reload everything" yas-reload-all
690 :help "Cleanup stuff, reload snippets, rebuild menus"]
692 :help "Display some information about YASnippet"]))
694 (defvar yas--extra-modes nil
695 "An internal list of modes for which to also lookup snippets.
697 This variable probably makes more sense as buffer-local, so
698 ensure your use `make-local-variable' when you set it.")
699 (define-obsolete-variable-alias 'yas-extra-modes 'yas--extra-modes "0.9.1")
701 (defvar yas--tables (make-hash-table)
702 "A hash table of mode symbols to `yas--table' objects.")
704 (defvar yas--parents (make-hash-table)
705 "A hash table of mode symbols do lists of direct parent mode symbols.
707 This list is populated when reading the \".yas-parents\" files
708 found when traversing snippet directories with
709 `yas-load-directory'.
711 There might be additional parenting information stored in the
712 `derived-mode-parent' property of some mode symbols, but that is
715 (defvar yas--direct-keymaps (list)
716 "Keymap alist supporting direct snippet keybindings.
718 This variable is placed in `emulation-mode-map-alists'.
720 Its elements looks like (TABLE-NAME . KEYMAP). They're
721 instantiated on `yas-reload-all' but KEYMAP is added to only when
722 loading snippets. `yas--direct-TABLE-NAME' is then a variable set
723 buffer-locally when entering `yas-minor-mode'. KEYMAP binds all
724 defined direct keybindings to the command
725 `yas-expand-from-keymap' which then which snippet to expand.")
727 (defun yas-direct-keymaps-reload ()
728 "Force reload the direct keybinding for active snippet tables."
730 (setq yas--direct-keymaps nil)
731 (maphash #'(lambda (name table)
732 (push (cons (intern (format "yas--direct-%s" name))
733 (yas--table-direct-keymap table))
734 yas--direct-keymaps))
737 (defun yas--modes-to-activate (&optional mode)
738 "Compute list of mode symbols that are active for `yas-expand' and friends."
739 (defvar yas--dfs) ;We rely on dynbind. We could use `letrec' instead!
740 (let* ((explored (if mode (list mode) ; Building up list in reverse.
741 (cons major-mode (reverse yas--extra-modes))))
744 (cl-loop for neighbour
745 in (cl-list* (get mode 'derived-mode-parent)
746 ;; NOTE: `fboundp' check is redundant
748 (and (fboundp mode) (symbol-function mode))
749 (gethash mode yas--parents))
751 (not (memq neighbour explored))
753 do (push neighbour explored)
754 (funcall yas--dfs neighbour)))))
755 (mapc yas--dfs explored)
756 (nreverse explored)))
758 (defvar yas-minor-mode-hook nil
759 "Hook run when `yas-minor-mode' is turned on.")
762 (define-minor-mode yas-minor-mode
763 "Toggle YASnippet mode.
765 When YASnippet mode is enabled, `yas-expand', normally bound to
766 the TAB key, expands snippets of code depending on the major
769 With no argument, this command toggles the mode.
770 positive prefix argument turns on the mode.
771 Negative prefix argument turns off the mode.
774 \\{yas-minor-mode-map}"
776 ;; The indicator for the mode line.
779 (cond (yas-minor-mode
780 ;; Install the direct keymaps in `emulation-mode-map-alists'
781 ;; (we use `add-hook' even though it's not technically a hook,
782 ;; but it works). Then define variables named after modes to
783 ;; index `yas--direct-keymaps'.
785 ;; Also install the post-command-hook.
787 (cl-pushnew 'yas--direct-keymaps emulation-mode-map-alists)
788 (add-hook 'post-command-hook #'yas--post-command-handler nil t)
789 ;; Set the `yas--direct-%s' vars for direct keymap expansion
791 (dolist (mode (yas--modes-to-activate))
792 (let ((name (intern (format "yas--direct-%s" mode))))
793 (set-default name nil)
794 (set (make-local-variable name) t)))
797 (yas--load-pending-jits))
799 ;; Uninstall the direct keymaps and the post-command hook
801 (remove-hook 'post-command-hook #'yas--post-command-handler t)
802 (setq emulation-mode-map-alists
803 (remove 'yas--direct-keymaps emulation-mode-map-alists)))))
805 (defun yas-activate-extra-mode (mode)
806 "Activates the snippets for the given `mode' in the buffer.
808 The function can be called in the hook of a minor mode to
809 activate snippets associated with that mode."
813 (maphash (lambda (k _)
814 (setq modes (cons (list k) modes)))
816 (setq symbol (completing-read
817 "Activate mode: " modes nil t))
819 (when (not (string= "" symbol))
822 (add-to-list (make-local-variable 'yas--extra-modes) mode)
823 (yas--load-pending-jits)))
825 (defun yas-deactivate-extra-mode (mode)
826 "Deactivates the snippets for the given `mode' in the buffer."
830 "Deactivate mode: " (mapcar #'list yas--extra-modes) nil t))))
831 (set (make-local-variable 'yas--extra-modes)
835 (define-obsolete-variable-alias 'yas-dont-activate
836 'yas-dont-activate-functions "0.9.2")
837 (defvar yas-dont-activate-functions (list #'minibufferp)
838 "Special hook to control which buffers `yas-global-mode' affects.
839 Functions are called with no argument, and should return non-nil to prevent
840 `yas-global-mode' from enabling yasnippet in this buffer.
842 In Emacsen < 24, this variable is buffer-local. Because
843 `yas-minor-mode-on' is called by `yas-global-mode' after
844 executing the buffer's major mode hook, setting this variable
845 there is an effective way to define exceptions to the \"global\"
846 activation behaviour.
848 In Emacsen >= 24, only the global value is used. To define
849 per-mode exceptions to the \"global\" activation behaviour, call
850 `yas-minor-mode' with a negative argument directily in the major
852 (unless (> emacs-major-version 23)
854 (make-variable-buffer-local 'yas-dont-activate)))
857 (defun yas-minor-mode-on ()
858 "Turn on YASnippet minor mode.
860 Honour `yas-dont-activate-functions', which see."
863 ;; The old behavior used for Emacs<24 was to set
864 ;; `yas-dont-activate-functions' to t buffer-locally.
865 (not (or (listp yas-dont-activate-functions)
866 (functionp yas-dont-activate-functions)))
867 (run-hook-with-args-until-success 'yas-dont-activate-functions))
871 (define-globalized-minor-mode yas-global-mode yas-minor-mode yas-minor-mode-on
875 (defun yas--global-mode-reload-with-jit-maybe ()
876 "Run `yas-reload-all' when `yas-global-mode' is on."
877 (when yas-global-mode (yas-reload-all)))
879 (add-hook 'yas-global-mode-hook #'yas--global-mode-reload-with-jit-maybe)
884 (defvar yas--font-lock-keywords
885 (append '(("^#.*$" . font-lock-comment-face))
887 (ignore-errors (emacs-lisp-mode))
888 (font-lock-set-defaults)
889 (if (eq t (car-safe font-lock-keywords))
890 ;; They're "compiled", so extract the source.
891 (cadr font-lock-keywords)
894 (0 font-lock-keyword-face)
895 (1 font-lock-string-face t))
897 (0 font-lock-keyword-face)
898 (1 font-lock-warning-face t))
899 ("\\(\\$(\\)" 1 font-lock-preprocessor-face)
901 (0 font-lock-keyword-face)))))
903 (defvar snippet-mode-map
904 (let ((map (make-sparse-keymap)))
905 (easy-menu-define nil
907 "Menu used when snippet-mode is active."
909 (mapcar #'(lambda (ent)
911 (define-key map (third ent) (second ent)))
912 (vector (first ent) (second ent) t))
913 '(("Load this snippet" yas-load-snippet-buffer "\C-c\C-l")
914 ("Load and quit window" yas-load-snippet-buffer-and-close "\C-c\C-c")
915 ("Try out this snippet" yas-tryout-snippet "\C-c\C-t")))))
917 "The keymap used when `snippet-mode' is active.")
921 (define-derived-mode snippet-mode text-mode "Snippet"
922 "A mode for editing yasnippets"
923 (setq font-lock-defaults '(yas--font-lock-keywords))
924 (set (make-local-variable 'require-final-newline) nil)
925 (set (make-local-variable 'comment-start) "#")
926 (set (make-local-variable 'comment-start-skip) "#+[\t ]*"))
930 ;;; Internal structs for template management
932 (cl-defstruct (yas--template
933 (:constructor yas--make-template)
934 ;; Handles `yas-define-snippets' format, plus the
935 ;; initial TABLE argument.
937 yas--define-snippets-2
940 &optional xname condition group
941 expand-env load-file xkeybinding xuuid save-file
944 ;; A little redundant: we always get a name
945 ;; from `yas--parse-template' except when
946 ;; there isn't a file.
947 (and load-file (file-name-nondirectory load-file))
948 (and save-file (file-name-nondirectory save-file))
950 (keybinding (yas--read-keybinding xkeybinding))
951 (uuid (or xuuid name))
952 (old (gethash uuid (yas--table-uuidhash table)))
954 (and old (yas--template-menu-binding-pair old)))
956 (and old (yas--template-perm-group old))))))
957 "A template for a snippet."
968 group ;; as dictated by the #group: directive or .yas-make-groups
969 perm-group ;; as dictated by `yas-define-menu'
973 (defstruct (yas--table (:constructor yas--make-snippet-table (name)))
974 "A table to store snippets for a particular mode.
976 Has the following fields:
980 A symbol name normally corresponding to a major mode, but can
981 also be a pseudo major-mode to be used in
982 `yas-activate-extra-mode', for example.
986 A hash table (KEY . NAMEHASH), known as the \"keyhash\". KEY is
987 a string or a vector, where the former is the snippet's trigger
988 and the latter means it's a direct keybinding. NAMEHASH is yet
989 another hash of (NAME . TEMPLATE) where NAME is the snippet's
990 name and TEMPLATE is a `yas--template' object.
992 `yas--table-direct-keymap'
994 A keymap for the snippets in this table that have direct
995 keybindings. This is kept in sync with the keyhash, i.e., all
996 the elements of the keyhash that are vectors appear here as
997 bindings to `yas-expand-from-keymap'.
999 `yas--table-uuidhash'
1001 A hash table mapping snippets uuid's to the same `yas--template'
1002 objects. A snippet uuid defaults to the snippet's name."
1004 (hash (make-hash-table :test 'equal))
1005 (uuidhash (make-hash-table :test 'equal))
1007 (direct-keymap (make-sparse-keymap)))
1009 (defun yas--get-template-by-uuid (mode uuid)
1010 "Find the snippet template in MODE by its UUID."
1011 (let* ((table (gethash mode yas--tables mode)))
1013 (gethash uuid (yas--table-uuidhash table)))))
1015 ;; Apropos storing/updating in TABLE, this works in two steps:
1017 ;; 1. `yas--remove-template-by-uuid' removes any
1018 ;; keyhash-namehash-template mappings from TABLE, grabbing the
1019 ;; snippet by its uuid. Also removes mappings from TABLE's
1020 ;; `yas--table-direct-keymap' (FIXME: and should probably take care
1021 ;; of potentially stale menu bindings right?.)
1023 ;; 2. `yas--add-template' adds this all over again.
1025 ;; Create a new or add to an existing keyhash-namehash mapping.
1027 ;; For reference on understanding this, consider three snippet
1030 ;; A: # name: The Foo
1032 ;; # binding: C-c M-l
1034 ;; B: # name: Mrs Foo
1037 ;; C: # name: The Bar
1038 ;; # binding: C-c M-l
1043 ;; keyhash namehashes(3) yas--template structs(4)
1044 ;; -----------------------------------------------------
1047 ;; "foo" ---> "The Foo" ---> [yas--template A] |
1048 ;; "Mrs Foo" ---> [yas--template B] |
1050 ;; [C-c M-l] ---> "The Foo" -------------------------/
1051 ;; "The Bar" ---> [yas--template C]
1053 ;; "baz" ---> "Baz" ---> [yas--template D]
1055 ;; Additionally, since uuid defaults to the name, we have a
1056 ;; `yas--table-uuidhash' for TABLE
1058 ;; uuidhash yas--template structs
1059 ;; -------------------------------
1060 ;; "The Foo" ---> [yas--template A]
1061 ;; "Mrs Foo" ---> [yas--template B]
1062 ;; "The Bar" ---> [yas--template C]
1063 ;; "Baz" ---> [yas--template D]
1065 ;; FIXME: the more I look at this data-structure the more I think I'm
1066 ;; stupid. There has to be an easier way (but beware lots of code
1067 ;; depends on this).
1069 (defun yas--remove-template-by-uuid (table uuid)
1070 "Remove from TABLE a template identified by UUID."
1071 (let ((template (gethash uuid (yas--table-uuidhash table))))
1073 (let* ((name (yas--template-name template))
1075 ;; Remove the name from each of the targeted namehashes
1077 (maphash #'(lambda (k v)
1078 (let ((template (gethash name v)))
1080 (eq uuid (yas--template-uuid template)))
1082 (when (zerop (hash-table-count v))
1083 (push k empty-keys)))))
1084 (yas--table-hash table))
1085 ;; Remove the namehash themselves if they've become empty
1087 (dolist (key empty-keys)
1089 (define-key (yas--table-direct-keymap table) key nil))
1090 (remhash key (yas--table-hash table)))
1092 ;; Finally, remove the uuid from the uuidhash
1094 (remhash uuid (yas--table-uuidhash table))))))
1096 (defun yas--add-template (table template)
1097 "Store in TABLE the snippet template TEMPLATE.
1099 KEY can be a string (trigger key) of a vector (direct
1101 (let ((name (yas--template-name template))
1102 (key (yas--template-key template))
1103 (keybinding (yas--template-keybinding template))
1104 (_menu-binding-pair (yas--template-menu-binding-pair-get-create template)))
1105 (dolist (k (remove nil (list key keybinding)))
1109 (yas--table-hash table))
1111 (make-hash-table :test 'equal)
1112 (yas--table-hash table))))
1114 (define-key (yas--table-direct-keymap table) k 'yas-expand-from-keymap)))
1116 ;; Update TABLE's `yas--table-uuidhash'
1117 (puthash (yas--template-uuid template)
1119 (yas--table-uuidhash table))))
1121 (defun yas--update-template (table template)
1122 "Add or update TEMPLATE in TABLE.
1124 Also takes care of adding and updating to the associated menu.
1126 ;; Remove from table by uuid
1128 (yas--remove-template-by-uuid table (yas--template-uuid template))
1129 ;; Add to table again
1131 (yas--add-template table template)
1132 ;; Take care of the menu
1134 (yas--update-template-menu table template)
1137 (defun yas--update-template-menu (table template)
1138 "Update every menu-related for TEMPLATE."
1139 (let ((menu-binding-pair (yas--template-menu-binding-pair-get-create template))
1140 (key (yas--template-key template))
1141 (keybinding (yas--template-keybinding template)))
1142 ;; The snippet might have changed name or keys, so update
1143 ;; user-visible strings
1145 (unless (eq (cdr menu-binding-pair) :none)
1146 ;; the menu item name
1148 (setf (cadar menu-binding-pair) (yas--template-name template))
1149 ;; the :keys information (also visible to the user)
1150 (setf (getf (cdr (car menu-binding-pair)) :keys)
1151 (or (and keybinding (key-description keybinding))
1152 (and key (concat key yas-trigger-symbol))))))
1153 (unless (yas--template-menu-managed-by-yas-define-menu template)
1155 (yas--menu-keymap-get-create (yas--table-mode table)
1156 (mapcar #'yas--table-mode
1157 (yas--table-parents table))))
1158 (group (yas--template-group template)))
1159 ;; Remove from menu keymap
1161 (assert menu-keymap)
1162 (yas--delete-from-keymap menu-keymap (yas--template-uuid template))
1164 ;; Add necessary subgroups as necessary.
1166 (dolist (subgroup group)
1167 (let ((subgroup-keymap (lookup-key menu-keymap (vector (make-symbol subgroup)))))
1168 (unless (and subgroup-keymap
1169 (keymapp subgroup-keymap))
1170 (setq subgroup-keymap (make-sparse-keymap))
1171 (define-key menu-keymap (vector (make-symbol subgroup))
1172 `(menu-item ,subgroup ,subgroup-keymap)))
1173 (setq menu-keymap subgroup-keymap)))
1175 ;; Add this entry to the keymap
1177 (define-key menu-keymap
1178 (vector (make-symbol (yas--template-uuid template)))
1179 (car (yas--template-menu-binding-pair template))))))
1181 (defun yas--namehash-templates-alist (namehash)
1182 "Return NAMEHASH as an alist."
1184 (maphash #'(lambda (k v)
1185 (push (cons k v) alist))
1189 (defun yas--fetch (table key)
1190 "Fetch templates in TABLE by KEY.
1192 Return a list of cons (NAME . TEMPLATE) where NAME is a
1193 string and TEMPLATE is a `yas--template' structure."
1194 (let* ((keyhash (yas--table-hash table))
1195 (namehash (and keyhash (gethash key keyhash))))
1197 (yas--filter-templates-by-condition (yas--namehash-templates-alist namehash)))))
1200 ;;; Filtering/condition logic
1202 (defun yas--eval-condition (condition)
1209 (yas--message 1 "Error in condition evaluation: %s" (error-message-string err))
1213 (defun yas--filter-templates-by-condition (templates)
1214 "Filter the templates using the applicable condition.
1216 TEMPLATES is a list of cons (NAME . TEMPLATE) where NAME is a
1217 string and TEMPLATE is a `yas--template' structure.
1219 This function implements the rules described in
1220 `yas-buffer-local-condition'. See that variables documentation."
1221 (let ((requirement (yas--require-template-specific-condition-p)))
1222 (if (eq requirement 'always)
1224 (remove-if-not #'(lambda (pair)
1225 (yas--template-can-expand-p
1226 (yas--template-condition (cdr pair)) requirement))
1229 (defun yas--require-template-specific-condition-p ()
1230 "Decide if this buffer requests/requires snippet-specific
1231 conditions to filter out potential expansions."
1232 (if (eq 'always yas-buffer-local-condition)
1234 (let ((local-condition (or (and (consp yas-buffer-local-condition)
1235 (yas--eval-condition yas-buffer-local-condition))
1236 yas-buffer-local-condition)))
1237 (when local-condition
1238 (if (eq local-condition t)
1240 (and (consp local-condition)
1241 (eq 'require-snippet-condition (car local-condition))
1242 (symbolp (cdr local-condition))
1243 (cdr local-condition)))))))
1245 (defun yas--template-can-expand-p (condition requirement)
1246 "Evaluate CONDITION and REQUIREMENT and return a boolean."
1247 (let* ((result (or (null condition)
1248 (yas--eval-condition condition))))
1249 (cond ((eq requirement t)
1252 (eq requirement result)))))
1254 (defun yas--table-templates (table)
1257 (maphash #'(lambda (_key namehash)
1258 (maphash #'(lambda (name template)
1259 (push (cons name template) acc))
1261 (yas--table-hash table))
1262 (yas--filter-templates-by-condition acc))))
1264 (defun yas--templates-for-key-at-point ()
1265 "Find `yas--template' objects for any trigger keys preceding point.
1266 Returns (TEMPLATES START END). This function respects
1267 `yas-key-syntaxes', which see."
1269 (let ((original (point))
1270 (methods yas-key-syntaxes)
1275 (unless (eq method (car methods))
1276 ;; TRICKY: `eq'-ness test means we can only be here if
1277 ;; `method' is a function that returned `again', and hence
1278 ;; don't revert back to original position as per
1279 ;; `yas-key-syntaxes'.
1280 (goto-char original))
1281 (setq method (car methods))
1282 (cond ((stringp method)
1283 (skip-syntax-backward method)
1284 (setq methods (cdr methods)))
1286 (unless (eq (funcall method original)
1288 (setq methods (cdr methods))))
1290 (setq methods (cdr methods))
1291 (yas--warning "Invalid element `%s' in `yas-key-syntaxes'" method)))
1292 (let ((possible-key (buffer-substring-no-properties (point) original)))
1294 (goto-char original)
1296 (mapcan #'(lambda (table)
1297 (yas--fetch table possible-key))
1298 (yas--get-snippet-tables))))))
1300 (list templates (point) original)))))
1302 (defun yas--table-all-keys (table)
1303 "Get trigger keys of all active snippets in TABLE."
1305 (maphash #'(lambda (key namehash)
1306 (when (yas--filter-templates-by-condition (yas--namehash-templates-alist namehash))
1308 (yas--table-hash table))
1311 (defun yas--table-mode (table)
1312 (intern (yas--table-name table)))
1315 ;;; Internal functions and macros:
1317 (defun yas--handle-error (err)
1318 "Handle error depending on value of `yas-good-grace'."
1319 (let ((msg (yas--format "elisp error: %s" (error-message-string err))))
1320 (if yas-good-grace msg
1323 (defun yas--eval-lisp (form)
1324 "Evaluate FORM and convert the result to string."
1325 (let ((retval (catch 'yas--exception
1331 (let ((result (eval form)))
1333 (format "%s" result))))))
1334 (error (yas--handle-error err))))))
1335 (when (and (consp retval)
1336 (eq 'yas--exception (car retval)))
1337 (error (cdr retval)))
1340 (defun yas--eval-lisp-no-saves (form)
1343 (error (message "%s" (yas--handle-error err)))))
1345 (defun yas--read-lisp (string &optional nil-on-error)
1346 "Read STRING as a elisp expression and return it.
1348 In case STRING in an invalid expression and NIL-ON-ERROR is nil,
1349 return an expression that when evaluated will issue an error."
1352 (error (and (not nil-on-error)
1353 `(error (error-message-string ,err))))))
1355 (defun yas--read-keybinding (keybinding)
1356 "Read KEYBINDING as a snippet keybinding, return a vector."
1357 (when (and keybinding
1358 (not (string-match "keybinding" keybinding)))
1360 (let ((res (or (and (string-match "^\\[.*\\]$" keybinding)
1362 (read-kbd-macro keybinding 'need-vector))))
1365 (yas--message 2 "warning: keybinding \"%s\" invalid since %s."
1366 keybinding (error-message-string err))
1369 (defun yas--table-get-create (mode)
1370 "Get or create the snippet table corresponding to MODE."
1371 (let ((table (gethash mode
1374 (setq table (yas--make-snippet-table (symbol-name mode)))
1375 (puthash mode table yas--tables)
1376 (push (cons (intern (format "yas--direct-%s" mode))
1377 (yas--table-direct-keymap table))
1378 yas--direct-keymaps))
1381 (defun yas--get-snippet-tables (&optional mode)
1382 "Get snippet tables for MODE.
1384 MODE defaults to the current buffer's `major-mode'.
1386 Return a list of `yas--table' objects. The list of modes to
1387 consider is returned by `yas--modes-to-activate'"
1389 (mapcar #'(lambda (name)
1390 (gethash name yas--tables))
1391 (yas--modes-to-activate mode))))
1393 (defun yas--menu-keymap-get-create (mode &optional parents)
1394 "Get or create the menu keymap for MODE and its PARENTS.
1396 This may very well create a plethora of menu keymaps and arrange
1397 them all in `yas--menu-table'"
1398 (let* ((menu-keymap (or (gethash mode yas--menu-table)
1399 (puthash mode (make-sparse-keymap) yas--menu-table))))
1400 (mapc #'yas--menu-keymap-get-create parents)
1401 (define-key yas--minor-mode-menu (vector mode)
1402 `(menu-item ,(symbol-name mode) ,menu-keymap
1403 :visible (yas--show-menu-p ',mode)))
1407 ;;; Template-related and snippet loading functions
1409 (defun yas--parse-template (&optional file)
1410 "Parse the template in the current buffer.
1412 Optional FILE is the absolute file name of the file being
1415 Optional GROUP is the group where the template is to go,
1416 otherwise we attempt to calculate it from FILE.
1418 Return a snippet-definition, i.e. a list
1420 (KEY TEMPLATE NAME CONDITION GROUP VARS LOAD-FILE KEYBINDING UUID)
1422 If the buffer contains a line of \"# --\" then the contents above
1423 this line are ignored. Directives can set most of these with the syntax:
1425 # directive-name : directive-value
1427 Here's a list of currently recognized directives:
1438 (goto-char (point-min))
1439 (let* ((type 'snippet)
1441 (file-name-nondirectory file)))
1447 (yas--calculate-group file)))
1451 (if (re-search-forward "^# --\n" nil t)
1452 (progn (setq template
1453 (buffer-substring-no-properties (point)
1455 (setq bound (point))
1456 (goto-char (point-min))
1457 (while (re-search-forward "^# *\\([^ ]+?\\) *: *\\(.*?\\)[[:space:]]*$" bound t)
1458 (when (string= "uuid" (match-string-no-properties 1))
1459 (setq uuid (match-string-no-properties 2)))
1460 (when (string= "type" (match-string-no-properties 1))
1461 (setq type (if (string= "command" (match-string-no-properties 2))
1464 (when (string= "key" (match-string-no-properties 1))
1465 (setq key (match-string-no-properties 2)))
1466 (when (string= "name" (match-string-no-properties 1))
1467 (setq name (match-string-no-properties 2)))
1468 (when (string= "condition" (match-string-no-properties 1))
1469 (setq condition (yas--read-lisp (match-string-no-properties 2))))
1470 (when (string= "group" (match-string-no-properties 1))
1471 (setq group (match-string-no-properties 2)))
1472 (when (string= "expand-env" (match-string-no-properties 1))
1473 (setq expand-env (yas--read-lisp (match-string-no-properties 2)
1475 (when (string= "binding" (match-string-no-properties 1))
1476 (setq binding (match-string-no-properties 2)))))
1478 (buffer-substring-no-properties (point-min) (point-max))))
1479 (unless (or key binding)
1480 (setq key (and file (file-name-nondirectory file))))
1481 (when (eq type 'command)
1482 (setq template (yas--read-lisp (concat "(progn" template ")"))))
1484 (setq group (split-string group "\\.")))
1485 (list key template name condition group expand-env file binding uuid)))
1487 (defun yas--calculate-group (file)
1488 "Calculate the group for snippet file path FILE."
1489 (let* ((dominating-dir (locate-dominating-file file
1490 ".yas-make-groups"))
1491 (extra-path (and dominating-dir
1492 (file-relative-name file dominating-dir)))
1493 (extra-dir (and extra-path
1494 (file-name-directory extra-path)))
1495 (group (and extra-dir
1496 (replace-regexp-in-string "/"
1498 (directory-file-name extra-dir)))))
1501 (defun yas--subdirs (directory &optional filep)
1502 "Return subdirs or files of DIRECTORY according to FILEP."
1503 (cl-remove-if (lambda (file)
1504 (or (string-match "\\`\\."
1505 (file-name-nondirectory file))
1506 (string-match "\\`#.*#\\'"
1507 (file-name-nondirectory file))
1508 (string-match "~\\'"
1509 (file-name-nondirectory file))
1511 (file-directory-p file)
1512 (not (file-directory-p file)))))
1513 (directory-files directory t)))
1515 (defun yas--make-menu-binding (template)
1516 (let ((mode (yas--table-mode (yas--template-table template))))
1517 `(lambda () (interactive) (yas--expand-or-visit-from-menu ',mode ,(yas--template-uuid template)))))
1519 (defun yas--expand-or-visit-from-menu (mode uuid)
1520 (let* ((table (yas--table-get-create mode))
1521 (yas--current-template (and table
1522 (gethash uuid (yas--table-uuidhash table)))))
1523 (when yas--current-template
1524 (if yas-visit-from-menu
1525 (yas--visit-snippet-file-1 yas--current-template)
1526 (let ((where (if (region-active-p)
1527 (cons (region-beginning) (region-end))
1528 (cons (point) (point)))))
1529 (yas-expand-snippet (yas--template-content yas--current-template)
1532 (yas--template-expand-env yas--current-template)))))))
1534 (defun yas--key-from-desc (text)
1535 "Return a yasnippet key from a description string TEXT."
1536 (replace-regexp-in-string "\\(\\w+\\).*" "\\1" text))
1539 ;;; Popping up for keys and templates
1541 (defun yas--prompt-for-template (templates &optional prompt)
1542 "Interactively choose a template from the list TEMPLATES.
1544 TEMPLATES is a list of `yas--template'.
1546 Optional PROMPT sets the prompt to use."
1549 (sort templates #'(lambda (t1 t2)
1550 (< (length (yas--template-name t1))
1551 (length (yas--template-name t2))))))
1552 (some #'(lambda (fn)
1553 (funcall fn (or prompt "Choose a snippet: ")
1555 #'yas--template-name))
1556 yas-prompt-functions)))
1558 (defun yas--prompt-for-keys (keys &optional prompt)
1559 "Interactively choose a template key from the list KEYS.
1561 Optional PROMPT sets the prompt to use."
1563 (some #'(lambda (fn)
1564 (funcall fn (or prompt "Choose a snippet key: ") keys))
1565 yas-prompt-functions)))
1567 (defun yas--prompt-for-table (tables &optional prompt)
1568 "Interactively choose a table from the list TABLES.
1570 Optional PROMPT sets the prompt to use."
1572 (some #'(lambda (fn)
1573 (funcall fn (or prompt "Choose a snippet table: ")
1576 yas-prompt-functions)))
1578 (defun yas-x-prompt (prompt choices &optional display-fn)
1579 "Display choices in a x-window prompt."
1580 (when (and window-system choices)
1581 ;; Let window position be recalculated to ensure that
1582 ;; `posn-at-point' returns non-nil.
1586 (if (fboundp 'posn-at-point)
1587 (let ((x-y (posn-x-y (posn-at-point (point)))))
1588 (list (list (+ (car x-y) 10)
1593 ,@(mapcar* (lambda (c d) `(,(concat " " d) . ,c))
1595 (if display-fn (mapcar display-fn choices) choices)))))
1598 (defun yas-maybe-ido-prompt (prompt choices &optional display-fn)
1599 (when (bound-and-true-p ido-mode)
1600 (yas-ido-prompt prompt choices display-fn)))
1602 (defun yas-ido-prompt (prompt choices &optional display-fn)
1604 (yas-completing-prompt prompt choices display-fn #'ido-completing-read))
1606 (defun yas-dropdown-prompt (_prompt choices &optional display-fn)
1607 (when (fboundp 'dropdown-list)
1608 (let* ((formatted-choices
1609 (if display-fn (mapcar display-fn choices) choices))
1610 (n (dropdown-list formatted-choices)))
1611 (if n (nth n choices)
1614 (defun yas-completing-prompt (prompt choices &optional display-fn completion-fn)
1615 (let* ((formatted-choices
1616 (if display-fn (mapcar display-fn choices) choices))
1617 (chosen (funcall (or completion-fn #'completing-read)
1618 prompt formatted-choices
1619 nil 'require-match nil nil)))
1620 (if (eq choices formatted-choices)
1622 (nth (or (position chosen formatted-choices :test #'string=) 0)
1625 (defun yas-no-prompt (_prompt choices &optional _display-fn)
1629 ;;; Defining snippets
1630 ;; This consists of creating and registering `yas--template' objects in the
1634 (defvar yas--creating-compiled-snippets nil)
1636 (defun yas--define-snippets-1 (snippet snippet-table)
1637 "Helper for `yas-define-snippets'."
1638 ;; Update the appropriate table. Also takes care of adding the
1639 ;; key indicators in the templates menu entry, if any.
1640 (yas--update-template
1641 snippet-table (apply #'yas--define-snippets-2 snippet-table snippet)))
1643 (defun yas-define-snippets (mode snippets)
1644 "Define SNIPPETS for MODE.
1646 SNIPPETS is a list of snippet definitions, each taking the
1649 (KEY TEMPLATE NAME CONDITION GROUP EXPAND-ENV LOAD-FILE KEYBINDING UUID SAVE-FILE)
1651 Within these, only KEY and TEMPLATE are actually mandatory.
1653 TEMPLATE might be a Lisp form or a string, depending on whether
1654 this is a snippet or a snippet-command.
1656 CONDITION, EXPAND-ENV and KEYBINDING are Lisp forms, they have
1657 been `yas--read-lisp'-ed and will eventually be
1658 `yas--eval-lisp'-ed.
1660 The remaining elements are strings.
1662 FILE is probably of very little use if you're programatically
1665 UUID is the snippet's \"unique-id\". Loading a second snippet
1666 file with the same uuid would replace the previous snippet.
1668 You can use `yas--parse-template' to return such lists based on
1669 the current buffers contents."
1670 (if yas--creating-compiled-snippets
1671 (let ((print-length nil))
1672 (insert ";;; Snippet definitions:\n;;;\n")
1673 (dolist (snippet snippets)
1674 ;; Fill in missing elements with nil.
1675 (setq snippet (append snippet (make-list (- 10 (length snippet)) nil)))
1676 ;; Move LOAD-FILE to SAVE-FILE because we will load from the
1677 ;; compiled file, not LOAD-FILE.
1678 (let ((load-file (nth 6 snippet)))
1679 (setcar (nthcdr 6 snippet) nil)
1680 (setcar (nthcdr 9 snippet) load-file)))
1681 (insert (pp-to-string
1682 `(yas-define-snippets ',mode ',snippets)))
1685 (let ((snippet-table (yas--table-get-create mode))
1687 (dolist (snippet snippets)
1688 (setq template (yas--define-snippets-1 snippet
1693 ;;; Loading snippets from files
1695 (defun yas--template-get-file (template)
1696 "Return TEMPLATE's LOAD-FILE or SAVE-FILE."
1697 (or (yas--template-load-file template)
1698 (let ((file (yas--template-save-file template)))
1700 (yas--message 3 "%s has no load file, using save file, %s, instead."
1701 (yas--template-name template) file))
1704 (defun yas--load-yas-setup-file (file)
1705 (if (not yas--creating-compiled-snippets)
1707 (load file 'noerror (<= yas-verbosity 4))
1708 (let ((elfile (concat file ".el")))
1709 (when (file-exists-p elfile)
1710 (insert ";;; contents of the .yas-setup.el support file:\n;;;\n")
1711 (insert-file-contents elfile)
1712 (goto-char (point-max))))))
1714 (defun yas--define-parents (mode parents)
1715 "Add PARENTS to the list of MODE's parents."
1716 (puthash mode (remove-duplicates
1718 (gethash mode yas--parents)))
1721 (defun yas-load-directory (top-level-dir &optional use-jit interactive)
1722 "Load snippets in directory hierarchy TOP-LEVEL-DIR.
1724 Below TOP-LEVEL-DIR each directory should be a mode name.
1726 With prefix argument USE-JIT do jit-loading of snippets."
1728 (list (read-directory-name "Select the root directory: " nil nil t)
1729 current-prefix-arg t))
1730 (unless yas-snippet-dirs
1731 (setq yas-snippet-dirs top-level-dir))
1732 (let ((impatient-buffers))
1733 (dolist (dir (yas--subdirs top-level-dir))
1734 (let* ((major-mode-and-parents (yas--compute-major-mode-and-parents
1735 (concat dir "/dummy")))
1736 (mode-sym (car major-mode-and-parents))
1737 (parents (cdr major-mode-and-parents)))
1738 ;; Attention: The parents and the menus are already defined
1739 ;; here, even if the snippets are later jit-loaded.
1741 ;; * We need to know the parents at this point since entering a
1742 ;; given mode should jit load for its parents
1743 ;; immediately. This could be reviewed, the parents could be
1744 ;; discovered just-in-time-as well
1746 ;; * We need to create the menus here to support the `full'
1747 ;; option to `yas-use-menu' (all known snippet menus are shown to the user)
1749 (yas--define-parents mode-sym parents)
1750 (yas--menu-keymap-get-create mode-sym)
1751 (let ((fun `(lambda () ;; FIXME: Simulating lexical-binding.
1752 (yas--load-directory-1 ',dir ',mode-sym))))
1754 (yas--schedule-jit mode-sym fun)
1756 ;; Look for buffers that are already in `mode-sym', and so
1757 ;; need the new snippets immediately...
1760 (cl-loop for buffer in (buffer-list)
1761 do (with-current-buffer buffer
1762 (when (eq major-mode mode-sym)
1763 (yas--message 4 "Discovered there was already %s in %s" buffer mode-sym)
1764 (push buffer impatient-buffers)))))))
1765 ;; ...after TOP-LEVEL-DIR has been completely loaded, call
1766 ;; `yas--load-pending-jits' in these impatient buffers.
1768 (cl-loop for buffer in impatient-buffers
1769 do (with-current-buffer buffer (yas--load-pending-jits))))
1771 (yas--message 3 "Loaded snippets from %s." top-level-dir)))
1773 (defun yas--load-directory-1 (directory mode-sym)
1774 "Recursively load snippet templates from DIRECTORY."
1775 (if yas--creating-compiled-snippets
1776 (let ((output-file (expand-file-name ".yas-compiled-snippets.el"
1778 (with-temp-file output-file
1779 (insert (format ";;; Compiled snippets and support files for `%s'\n"
1781 (yas--load-directory-2 directory mode-sym)
1782 (insert (format ";;; Do not edit! File generated at %s\n"
1783 (current-time-string)))))
1785 (unless (file-exists-p (expand-file-name ".yas-skip" directory))
1786 (unless (and (load (expand-file-name ".yas-compiled-snippets" directory) 'noerror (<= yas-verbosity 3))
1787 (progn (yas--message 4 "Loaded compiled snippets from %s" directory) t))
1788 (yas--message 4 "Loading snippet files from %s" directory)
1789 (yas--load-directory-2 directory mode-sym)))))
1791 (defun yas--load-directory-2 (directory mode-sym)
1792 ;; Load .yas-setup.el files wherever we find them
1794 (yas--load-yas-setup-file (expand-file-name ".yas-setup" directory))
1795 (let* ((default-directory directory)
1797 ;; load the snippet files
1800 (dolist (file (yas--subdirs directory 'no-subdirs-just-files))
1801 (when (file-readable-p file)
1802 (insert-file-contents file nil nil nil t)
1803 (push (yas--parse-template file)
1806 (yas-define-snippets mode-sym
1808 ;; now recurse to a lower level
1810 (dolist (subdir (yas--subdirs directory))
1811 (yas--load-directory-2 subdir
1814 (defun yas--load-snippet-dirs (&optional nojit)
1815 "Reload the directories listed in `yas-snippet-dirs' or
1816 prompt the user to select one."
1818 (if (null yas-snippet-dirs)
1819 (call-interactively 'yas-load-directory)
1820 (when (member yas--default-user-snippets-dir yas-snippet-dirs)
1821 (make-directory yas--default-user-snippets-dir t))
1822 (dolist (directory (reverse (yas-snippet-dirs)))
1823 (cond ((file-directory-p directory)
1824 (yas-load-directory directory (not nojit))
1826 (yas--message 4 "Loaded %s" directory)
1827 (yas--message 4 "Prepared just-in-time loading for %s" directory)))
1829 (push (yas--message 0 "Check your `yas-snippet-dirs': %s is not a directory" directory) errors)))))
1832 (defun yas-reload-all (&optional no-jit interactive)
1833 "Reload all snippets and rebuild the YASnippet menu.
1835 When NO-JIT is non-nil force immediate reload of all known
1836 snippets under `yas-snippet-dirs', otherwise use just-in-time
1839 When called interactively, use just-in-time loading when given a
1841 (interactive (list (not current-prefix-arg) t))
1844 (snippet-editing-buffers
1845 (remove-if-not #'(lambda (buffer)
1846 (with-current-buffer buffer yas--editing-template))
1848 ;; Warn if there are buffers visiting snippets, since reloading will break
1849 ;; any on-line editing of those buffers.
1851 (when snippet-editing-buffers
1853 (if (y-or-n-p "Some buffers editing live snippets, close them and proceed with reload? ")
1854 (mapc #'kill-buffer snippet-editing-buffers)
1855 (yas--message 1 "Aborted reload...")
1857 ;; in a non-interactive use, at least set
1858 ;; `yas--editing-template' to nil, make it guess it next time around
1859 (mapc #'(lambda (buffer)
1860 (with-current-buffer buffer
1861 (kill-local-variable 'yas--editing-template)))
1864 ;; Empty all snippet tables and parenting info
1866 (setq yas--tables (make-hash-table))
1867 (setq yas--parents (make-hash-table))
1869 ;; Before killing `yas--menu-table' use its keys to cleanup the
1870 ;; mode menu parts of `yas--minor-mode-menu' (thus also cleaning
1871 ;; up `yas-minor-mode-map', which points to it)
1873 (maphash #'(lambda (menu-symbol _keymap)
1874 (define-key yas--minor-mode-menu (vector menu-symbol) nil))
1876 ;; Now empty `yas--menu-table' as well
1877 (setq yas--menu-table (make-hash-table))
1879 ;; Cancel all pending 'yas--scheduled-jit-loads'
1881 (setq yas--scheduled-jit-loads (make-hash-table))
1883 ;; Reload the directories listed in `yas-snippet-dirs' or prompt
1884 ;; the user to select one.
1886 (setq errors (yas--load-snippet-dirs no-jit))
1887 ;; Reload the direct keybindings
1889 (yas-direct-keymaps-reload)
1891 (run-hooks 'yas-after-reload-hook)
1892 (yas--message (if errors 2 3) "Reloaded everything%s...%s."
1893 (if no-jit "" " (snippets will load just-in-time)")
1894 (if errors " (some errors, check *Messages*)" "")))))
1896 (defvar yas-after-reload-hook nil
1897 "Hooks run after `yas-reload-all'.")
1899 (defun yas--load-pending-jits ()
1900 (dolist (mode (yas--modes-to-activate))
1901 (let ((funs (reverse (gethash mode yas--scheduled-jit-loads))))
1902 ;; must reverse to maintain coherence with `yas-snippet-dirs'
1904 (yas--message 4 "Loading for `%s', just-in-time: %s!" mode fun)
1906 (remhash mode yas--scheduled-jit-loads))))
1908 ;; (when (<= emacs-major-version 22)
1909 ;; (add-hook 'after-change-major-mode-hook 'yas--load-pending-jits))
1911 (defun yas--quote-string (string)
1912 "Escape and quote STRING.
1913 foo\"bar\\! -> \"foo\\\"bar\\\\!\""
1915 (replace-regexp-in-string "[\\\"]"
1921 ;;; Snippet compilation function
1923 (defun yas-compile-directory (top-level-dir)
1924 "Create .yas-compiled-snippets.el files under subdirs of TOP-LEVEL-DIR.
1926 This works by stubbing a few functions, then calling
1927 `yas-load-directory'."
1928 (interactive "DTop level snippet directory?")
1929 (let ((yas--creating-compiled-snippets t))
1930 (yas-load-directory top-level-dir nil)))
1932 (defun yas-recompile-all ()
1933 "Compile every dir in `yas-snippet-dirs'."
1935 (mapc #'yas-compile-directory (yas-snippet-dirs)))
1941 (defvar yas--scheduled-jit-loads (make-hash-table)
1942 "Alist of mode-symbols to forms to be evaled when `yas-minor-mode' kicks in.")
1944 (defun yas--schedule-jit (mode fun)
1945 (push fun (gethash mode yas--scheduled-jit-loads)))
1949 ;;; Some user level functions
1953 (message (concat "yasnippet (version "
1955 ") -- pluskid/joaotavora/npostavs")))
1958 ;;; Apropos snippet menu:
1960 ;; The snippet menu keymaps are stored by mode in hash table called
1961 ;; `yas--menu-table'. They are linked to the main menu in
1962 ;; `yas--menu-keymap-get-create' and are initially created empty,
1963 ;; reflecting the table hierarchy.
1965 ;; They can be populated in two mutually exclusive ways: (1) by
1966 ;; reading `yas--template-group', which in turn is populated by the "#
1967 ;; group:" directives of the snippets or the ".yas-make-groups" file
1968 ;; or (2) by using a separate `yas-define-menu' call, which declares a
1969 ;; menu structure based on snippets uuids.
1971 ;; Both situations are handled in `yas--update-template-menu', which
1972 ;; uses the predicate `yas--template-menu-managed-by-yas-define-menu'
1973 ;; that can tell between the two situations.
1977 ;; * if `yas-define-menu' is used it must run before
1978 ;; `yas-define-snippets' and the UUIDS must match, otherwise we get
1979 ;; duplicate entries. The `yas--template' objects are created in
1980 ;; `yas-define-menu', holding nothing but the menu entry,
1981 ;; represented by a pair of ((menu-item NAME :keys KEYS) TYPE) and
1982 ;; stored in `yas--template-menu-binding-pair'. The (menu-item ...)
1983 ;; part is then stored in the menu keymap itself which make the item
1984 ;; appear to the user. These limitations could probably be revised.
1986 ;; * The `yas--template-perm-group' slot is only used in
1987 ;; `yas-describe-tables'.
1989 (defun yas--template-menu-binding-pair-get-create (template &optional type)
1990 "Get TEMPLATE's menu binding or assign it a new one.
1992 TYPE may be `:stay', signaling this menu binding should be
1993 static in the menu."
1994 (or (yas--template-menu-binding-pair template)
1995 (let (;; (key (yas--template-key template))
1996 ;; (keybinding (yas--template-keybinding template))
1998 (setf (yas--template-menu-binding-pair template)
1999 (cons `(menu-item ,(or (yas--template-name template)
2000 (yas--template-uuid template))
2001 ,(yas--make-menu-binding template)
2004 (defun yas--template-menu-managed-by-yas-define-menu (template)
2005 "Non-nil if TEMPLATE's menu entry was included in a `yas-define-menu' call."
2006 (cdr (yas--template-menu-binding-pair template)))
2009 (defun yas--show-menu-p (mode)
2010 (cond ((eq yas-use-menu 'abbreviate)
2012 (mapcar #'(lambda (table)
2013 (yas--table-mode table))
2014 (yas--get-snippet-tables))))
2017 (defun yas--delete-from-keymap (keymap uuid)
2018 "Recursively delete items with UUID from KEYMAP and its submenus."
2020 ;; XXX: This used to skip any submenus named \"parent mode\"
2022 ;; First of all, recursively enter submenus, i.e. the tree is
2023 ;; searched depth first so that stale submenus can be found in the
2026 (mapc #'(lambda (item)
2027 (when (and (listp (cdr item))
2028 (keymapp (third (cdr item))))
2029 (yas--delete-from-keymap (third (cdr item)) uuid)))
2031 ;; Set the uuid entry to nil
2033 (define-key keymap (vector (make-symbol uuid)) nil)
2034 ;; Destructively modify keymap
2036 (setcdr keymap (delete-if #'(lambda (item)
2037 (or (null (cdr item))
2038 (and (keymapp (third (cdr item)))
2039 (null (cdr (third (cdr item)))))))
2042 (defun yas-define-menu (mode menu &optional omit-items)
2043 "Define a snippet menu for MODE according to MENU, omitting OMIT-ITEMS.
2045 MENU is a list, its elements can be:
2047 - (yas-item UUID) : Creates an entry the snippet identified with
2048 UUID. The menu entry for a snippet thus identified is
2049 permanent, i.e. it will never move (be reordered) in the menu.
2051 - (yas-separator) : Creates a separator
2053 - (yas-submenu NAME SUBMENU) : Creates a submenu with NAME,
2054 SUBMENU has the same form as MENU. NAME is also added to the
2055 list of groups of the snippets defined thereafter.
2057 OMIT-ITEMS is a list of snippet uuid's that will always be
2058 omitted from MODE's menu, even if they're manually loaded."
2059 (let* ((table (yas--table-get-create mode))
2060 (hash (yas--table-uuidhash table)))
2061 (yas--define-menu-1 table
2062 (yas--menu-keymap-get-create mode)
2065 (dolist (uuid omit-items)
2066 (let ((template (or (gethash uuid hash)
2068 (yas--make-template :table table
2071 (setf (yas--template-menu-binding-pair template) (cons nil :none))))))
2073 (defun yas--define-menu-1 (table menu-keymap menu uuidhash &optional group-list)
2074 "Helper for `yas-define-menu'."
2075 (dolist (e (reverse menu))
2076 (cond ((eq (first e) 'yas-item)
2077 (let ((template (or (gethash (second e) uuidhash)
2081 :perm-group group-list
2084 (define-key menu-keymap (vector (gensym))
2085 (car (yas--template-menu-binding-pair-get-create template :stay)))))
2086 ((eq (first e) 'yas-submenu)
2087 (let ((subkeymap (make-sparse-keymap)))
2088 (define-key menu-keymap (vector (gensym))
2089 `(menu-item ,(second e) ,subkeymap))
2090 (yas--define-menu-1 table
2094 (append group-list (list (second e))))))
2095 ((eq (first e) 'yas-separator)
2096 (define-key menu-keymap (vector (gensym))
2097 '(menu-item "----")))
2099 (yas--message 1 "Don't know anything about menu entry %s" (first e))))))
2101 (defun yas--define (mode key template &optional name condition group)
2102 "Define a snippet. Expanding KEY into TEMPLATE.
2104 NAME is a description to this template. Also update the menu if
2105 `yas-use-menu' is t. CONDITION is the condition attached to
2106 this snippet. If you attach a condition to a snippet, then it
2107 will only be expanded when the condition evaluated to non-nil."
2108 (yas-define-snippets mode
2109 (list (list key template name condition group))))
2111 (defun yas-hippie-try-expand (first-time?)
2112 "Integrate with hippie expand.
2114 Just put this function in `hippie-expand-try-functions-list'."
2115 (when yas-minor-mode
2116 (if (not first-time?)
2117 (let ((yas-fallback-behavior 'return-nil))
2123 ;;; Apropos condition-cache:
2128 (defvar yas--condition-cache-timestamp nil)
2129 (defmacro yas-define-condition-cache (func doc &rest body)
2130 "Define a function FUNC with doc DOC and body BODY.
2131 BODY is executed at most once every snippet expansion attempt, to check
2132 expansion conditions.
2134 It doesn't make any sense to call FUNC programatically."
2135 `(defun ,func () ,(if (and doc
2138 "\n\nFor use in snippets' conditions. Within each
2139 snippet-expansion routine like `yas-expand', computes actual
2140 value for the first time then always returns a cached value.")
2141 (setq body (cons doc body))
2143 (let ((timestamp-and-value (get ',func 'yas--condition-cache)))
2144 (if (equal (car timestamp-and-value) yas--condition-cache-timestamp)
2145 (cdr timestamp-and-value)
2146 (let ((new-value (progn
2149 (put ',func 'yas--condition-cache (cons yas--condition-cache-timestamp new-value))
2152 (defalias 'yas-expand 'yas-expand-from-trigger-key)
2153 (defun yas-expand-from-trigger-key (&optional field)
2154 "Expand a snippet before point.
2156 If no snippet expansion is possible, fall back to the behaviour
2157 defined in `yas-fallback-behavior'.
2159 Optional argument FIELD is for non-interactive use and is an
2160 object satisfying `yas--field-p' to restrict the expansion to."
2162 (setq yas--condition-cache-timestamp (current-time))
2163 (let (templates-and-pos)
2164 (unless (and yas-expand-only-for-last-commands
2165 (not (member last-command yas-expand-only-for-last-commands)))
2166 (setq templates-and-pos (if field
2168 (narrow-to-region (yas--field-start field)
2169 (yas--field-end field))
2170 (yas--templates-for-key-at-point))
2171 (yas--templates-for-key-at-point))))
2172 (if templates-and-pos
2173 (yas--expand-or-prompt-for-template
2174 (nth 0 templates-and-pos)
2175 ;; Delete snippet key and active region when expanding.
2176 (min (if (use-region-p) (region-beginning) most-positive-fixnum)
2177 (nth 1 templates-and-pos))
2178 (max (if (use-region-p) (region-end) most-negative-fixnum)
2179 (nth 2 templates-and-pos)))
2182 (defun yas-expand-from-keymap ()
2183 "Directly expand some snippets, searching `yas--direct-keymaps'.
2185 If expansion fails, execute the previous binding for this key"
2187 (setq yas--condition-cache-timestamp (current-time))
2188 (let* ((vec (subseq (this-command-keys-vector) (if current-prefix-arg
2189 (length (this-command-keys))
2191 (templates (mapcan #'(lambda (table)
2192 (yas--fetch table vec))
2193 (yas--get-snippet-tables))))
2195 (yas--expand-or-prompt-for-template templates)
2196 (let ((yas-fallback-behavior 'call-other-command))
2199 (defun yas--expand-or-prompt-for-template (templates &optional start end)
2200 "Expand one of TEMPLATES from START to END.
2202 Prompt the user if TEMPLATES has more than one element, else
2203 expand immediately. Common gateway for
2204 `yas-expand-from-trigger-key' and `yas-expand-from-keymap'."
2205 (let ((yas--current-template (or (and (rest templates) ;; more than one
2206 (yas--prompt-for-template (mapcar #'cdr templates)))
2208 (when yas--current-template
2209 (yas-expand-snippet (yas--template-content yas--current-template)
2212 (yas--template-expand-env yas--current-template)))))
2214 ;; Apropos the trigger key and the fallback binding:
2216 ;; When `yas-minor-mode-map' binds <tab>, that correctly overrides
2217 ;; org-mode's <tab>, for example and searching for fallbacks correctly
2218 ;; returns `org-cycle'. However, most other modes bind "TAB". TODO,
2219 ;; improve this explanation.
2221 (defun yas--fallback ()
2222 "Fallback after expansion has failed.
2224 Common gateway for `yas-expand-from-trigger-key' and
2225 `yas-expand-from-keymap'."
2226 (cond ((eq yas-fallback-behavior 'return-nil)
2229 ((eq yas-fallback-behavior 'yas--fallback)
2230 (error (concat "yasnippet fallback loop!\n"
2231 "This can happen when you bind `yas-expand' "
2232 "outside of the `yas-minor-mode-map'.")))
2233 ((eq yas-fallback-behavior 'call-other-command)
2234 (let* ((yas-fallback-behavior 'yas--fallback)
2235 ;; Also bind `yas-minor-mode' to prevent fallback
2236 ;; loops when other extensions use mechanisms similar
2237 ;; to `yas--keybinding-beyond-yasnippet'. (github #525
2240 (yas-minor-mode nil)
2241 (beyond-yasnippet (yas--keybinding-beyond-yasnippet)))
2242 (yas--message 4 "Falling back to %s" beyond-yasnippet)
2243 (assert (or (null beyond-yasnippet) (commandp beyond-yasnippet)))
2244 (setq this-command beyond-yasnippet)
2245 (when beyond-yasnippet
2246 (call-interactively beyond-yasnippet))))
2247 ((and (listp yas-fallback-behavior)
2248 (cdr yas-fallback-behavior)
2249 (eq 'apply (car yas-fallback-behavior)))
2250 (let ((command-or-fn (cadr yas-fallback-behavior))
2251 (args (cddr yas-fallback-behavior))
2252 (yas-fallback-behavior 'yas--fallback)
2253 (yas-minor-mode nil))
2255 (apply command-or-fn args)
2256 (when (commandp command-or-fn)
2257 (setq this-command command-or-fn)
2258 (call-interactively command-or-fn)))))
2260 ;; also return nil if all the other fallbacks have failed
2263 (defun yas--keybinding-beyond-yasnippet ()
2264 "Get current keys's binding as if YASsnippet didn't exist."
2265 (let* ((yas-minor-mode nil)
2266 (yas--direct-keymaps nil)
2267 (keys (this-single-command-keys)))
2268 (or (key-binding keys t)
2269 (key-binding (yas--fallback-translate-input keys) t))))
2271 (defun yas--fallback-translate-input (keys)
2272 "Emulate `read-key-sequence', at least what I think it does.
2274 Keys should be an untranslated key vector. Returns a translated
2275 vector of keys. FIXME not thoroughly tested."
2278 (while (< i (length keys))
2280 (translated local-function-key-map))
2281 (while (and (< j (length keys))
2283 (keymapp translated))
2284 (setq translated (cdr (assoc (aref keys j) (remove 'keymap translated)))
2286 (setq retval (vconcat retval (cond ((symbolp translated)
2288 ((vectorp translated)
2291 (substring keys i j)))))
2296 ;;; Utils for snippet development:
2298 (defun yas--all-templates (tables)
2299 "Get `yas--template' objects in TABLES, applicable for buffer and point.
2301 Honours `yas-choose-tables-first', `yas-choose-keys-first' and
2302 `yas-buffer-local-condition'"
2303 (when yas-choose-tables-first
2304 (setq tables (list (yas--prompt-for-table tables))))
2306 (if yas-choose-keys-first
2307 (let ((key (yas--prompt-for-keys
2308 (mapcan #'yas--table-all-keys tables))))
2310 (mapcan #'(lambda (table)
2311 (yas--fetch table key))
2313 (remove-duplicates (mapcan #'yas--table-templates tables)
2316 (defun yas--lookup-snippet-1 (name mode)
2317 "Get the snippet called NAME in MODE's tables."
2318 (let ((yas-choose-tables-first nil) ; avoid prompts
2319 (yas-choose-keys-first nil))
2320 (cl-find name (yas--all-templates
2321 (yas--get-snippet-tables mode))
2322 :key #'yas--template-name :test #'string=)))
2324 (defun yas-lookup-snippet (name &optional mode noerror)
2325 "Get the snippet content for the snippet NAME in MODE's tables.
2327 MODE defaults to the current buffer's `major-mode'. If NOERROR
2328 is non-nil, then don't signal an error if there isn't any snippet
2331 Honours `yas-buffer-local-condition'."
2332 (let ((snippet (yas--lookup-snippet-1 name mode)))
2334 (snippet (yas--template-content snippet))
2336 (t (error "No snippet named: %s" name)))))
2338 (defun yas-insert-snippet (&optional no-condition)
2339 "Choose a snippet to expand, pop-up a list of choices according
2340 to `yas-prompt-functions'.
2342 With prefix argument NO-CONDITION, bypass filtering of snippets
2345 (setq yas--condition-cache-timestamp (current-time))
2346 (let* ((yas-buffer-local-condition (or (and no-condition
2348 yas-buffer-local-condition))
2349 (templates (yas--all-templates (yas--get-snippet-tables)))
2350 (yas--current-template (and templates
2351 (or (and (rest templates) ;; more than one template for same key
2352 (yas--prompt-for-template templates))
2354 (where (if (region-active-p)
2355 (cons (region-beginning) (region-end))
2356 (cons (point) (point)))))
2357 (if yas--current-template
2358 (yas-expand-snippet (yas--template-content yas--current-template)
2361 (yas--template-expand-env yas--current-template))
2362 (yas--message 1 "No snippets can be inserted here!"))))
2364 (defun yas-visit-snippet-file ()
2365 "Choose a snippet to edit, selection like `yas-insert-snippet'.
2367 Only success if selected snippet was loaded from a file. Put the
2368 visited file in `snippet-mode'."
2370 (let* ((yas-buffer-local-condition 'always)
2371 (templates (yas--all-templates (yas--get-snippet-tables)))
2372 (template (and templates
2373 (or (yas--prompt-for-template templates
2374 "Choose a snippet template to edit: ")
2378 (yas--visit-snippet-file-1 template)
2379 (message "No snippets tables active!"))))
2381 (defun yas--visit-snippet-file-1 (template)
2382 "Helper for `yas-visit-snippet-file'."
2383 (let ((file (yas--template-get-file template)))
2384 (cond ((and file (file-readable-p file))
2385 (find-file-other-window file)
2387 (set (make-local-variable 'yas--editing-template) template))
2389 (message "Original file %s no longer exists!" file))
2391 (switch-to-buffer (format "*%s*"(yas--template-name template)))
2392 (let ((type 'snippet))
2393 (when (listp (yas--template-content template))
2394 (insert (format "# type: command\n"))
2395 (setq type 'command))
2396 (insert (format "# key: %s\n" (yas--template-key template)))
2397 (insert (format "# name: %s\n" (yas--template-name template)))
2398 (when (yas--template-keybinding template)
2399 (insert (format "# binding: %s\n" (yas--template-keybinding template))))
2400 (when (yas--template-expand-env template)
2401 (insert (format "# expand-env: %s\n" (yas--template-expand-env template))))
2402 (when (yas--template-condition template)
2403 (insert (format "# condition: %s\n" (yas--template-condition template))))
2405 (insert (if (eq type 'command)
2406 (pp-to-string (yas--template-content template))
2407 (yas--template-content template))))
2409 (set (make-local-variable 'yas--editing-template) template)))))
2411 (defun yas--guess-snippet-directories-1 (table)
2412 "Guess possible snippet subdirectories for TABLE."
2413 (cons (yas--table-name table)
2414 (mapcan #'(lambda (parent)
2415 (yas--guess-snippet-directories-1
2417 (yas--table-parents table))))
2419 (defun yas--guess-snippet-directories (&optional table)
2420 "Try to guess suitable directories based on the current active
2421 tables (or optional TABLE).
2423 Returns a list of elements (TABLE . DIRS) where TABLE is a
2424 `yas--table' object and DIRS is a list of all possible directories
2425 where snippets of table might exist."
2426 (let ((main-dir (car (or (yas-snippet-dirs)
2427 (setq yas-snippet-dirs
2428 (list yas--default-user-snippets-dir)))))
2429 (tables (if table (list table)
2430 (yas--get-snippet-tables))))
2431 ;; HACK! the snippet table created here is actually registered!
2433 (unless (or table (gethash major-mode yas--tables))
2434 (push (yas--table-get-create major-mode)
2437 (mapcar #'(lambda (table)
2439 (mapcar #'(lambda (subdir)
2440 (expand-file-name subdir main-dir))
2441 (yas--guess-snippet-directories-1 table))))
2444 (defun yas--make-directory-maybe (table-and-dirs &optional main-table-string)
2445 "Return a dir inside TABLE-AND-DIRS, prompts for creation if none exists."
2446 (or (some #'(lambda (dir) (when (file-directory-p dir) dir)) (cdr table-and-dirs))
2447 (let ((candidate (first (cdr table-and-dirs))))
2448 (unless (file-writable-p (file-name-directory candidate))
2449 (error (yas--format "%s is not writable." candidate)))
2450 (if (y-or-n-p (format "Guessed directory (%s) for%s%s table \"%s\" does not exist! Create? "
2452 (if (gethash (yas--table-mode (car table-and-dirs))
2456 (or main-table-string
2458 (yas--table-name (car table-and-dirs))))
2460 (make-directory candidate 'also-make-parents)
2461 ;; create the .yas-parents file here...
2464 (defun yas-new-snippet (&optional no-template)
2465 "Pops a new buffer for writing a snippet.
2467 Expands a snippet-writing snippet, unless the optional prefix arg
2468 NO-TEMPLATE is non-nil."
2470 (let ((guessed-directories (yas--guess-snippet-directories)))
2472 (switch-to-buffer "*new snippet*")
2474 (kill-all-local-variables)
2477 (set (make-local-variable 'yas--guessed-modes) (mapcar #'(lambda (d)
2478 (yas--table-mode (car d)))
2479 guessed-directories))
2480 (if (and (not no-template) yas-new-snippet-default)
2481 (yas-expand-snippet yas-new-snippet-default))))
2483 (defun yas--compute-major-mode-and-parents (file)
2484 "Given FILE, find the nearest snippet directory for a given mode.
2486 Returns a list (MODE-SYM PARENTS), the mode's symbol and a list
2487 representing one or more of the mode's parents.
2489 Note that MODE-SYM need not be the symbol of a real major mode,
2490 neither do the elements of PARENTS."
2491 (let* ((file-dir (and file
2492 (directory-file-name (or (some #'(lambda (special)
2493 (locate-dominating-file file special))
2497 (directory-file-name (file-name-directory file))))))
2498 (parents-file-name (concat file-dir "/.yas-parents"))
2499 (major-mode-name (and file-dir
2500 (file-name-nondirectory file-dir)))
2501 (major-mode-sym (or (and major-mode-name
2502 (intern major-mode-name))))
2503 (parents (when (file-readable-p parents-file-name)
2507 (insert-file-contents parents-file-name)
2508 (buffer-substring-no-properties (point-min)
2510 (when major-mode-sym
2511 (cons major-mode-sym (remove major-mode-sym parents)))))
2513 (defvar yas--editing-template nil
2514 "Supporting variable for `yas-load-snippet-buffer' and `yas--visit-snippet'.")
2516 (defvar yas--current-template nil
2517 "Holds the current template being expanded into a snippet.")
2519 (defvar yas--guessed-modes nil
2520 "List of guessed modes supporting `yas-load-snippet-buffer'.")
2522 (defun yas--read-table ()
2523 "Ask user for a snippet table, help with some guessing."
2524 (let ((prompt (if (and (featurep 'ido)
2526 'ido-completing-read 'completing-read)))
2527 (unless yas--guessed-modes
2528 (set (make-local-variable 'yas--guessed-modes)
2529 (or (yas--compute-major-mode-and-parents buffer-file-name))))
2531 (funcall prompt (format "Choose or enter a table (yas guesses %s): "
2532 (if yas--guessed-modes
2533 (first yas--guessed-modes)
2535 (mapcar #'symbol-name yas--guessed-modes)
2540 (if (first yas--guessed-modes)
2541 (symbol-name (first yas--guessed-modes)))))))
2543 (defun yas-load-snippet-buffer (table &optional interactive)
2544 "Parse and load current buffer's snippet definition into TABLE.
2545 TABLE is a symbol name passed to `yas--table-get-create'. When
2546 called interactively, prompt for the table name."
2547 (interactive (list (yas--read-table) t))
2549 ;; We have `yas--editing-template', this buffer's content comes from a
2550 ;; template which is already loaded and neatly positioned,...
2552 (yas--editing-template
2553 (yas--define-snippets-1 (yas--parse-template (yas--template-load-file yas--editing-template))
2554 (yas--template-table yas--editing-template)))
2555 ;; Try to use `yas--guessed-modes'. If we don't have that use the
2556 ;; value from `yas--compute-major-mode-and-parents'
2559 (unless yas--guessed-modes
2560 (set (make-local-variable 'yas--guessed-modes) (or (yas--compute-major-mode-and-parents buffer-file-name))))
2561 (let* ((table (yas--table-get-create table)))
2562 (set (make-local-variable 'yas--editing-template)
2563 (yas--define-snippets-1 (yas--parse-template buffer-file-name)
2566 (yas--message 3 "Snippet \"%s\" loaded for %s."
2567 (yas--template-name yas--editing-template)
2568 (yas--table-name (yas--template-table yas--editing-template)))))
2570 (defun yas-load-snippet-buffer-and-close (table &optional kill)
2571 "Load and save the snippet, then `quit-window' if saved.
2572 Loading is performed by `yas-load-snippet-buffer'. If the
2573 snippet is new, ask the user whether (and where) to save it. If
2574 the snippet already has a file, just save it.
2576 The prefix argument KILL is passed to `quit-window'.
2578 Don't use this from a Lisp program, call `yas-load-snippet-buffer'
2579 and `kill-buffer' instead."
2580 (interactive (list (yas--read-table) current-prefix-arg))
2581 (yas-load-snippet-buffer table t)
2582 (let ((file (yas--template-get-file yas--editing-template)))
2584 ;; Only offer to save this if it looks like a library or new
2585 ;; snippet (loaded from elisp, from a dir in `yas-snippet-dirs'
2586 ;; which is not the first, or from an unwritable file)
2589 (not (file-writable-p file))
2590 (and (cdr-safe yas-snippet-dirs)
2591 (not (string-prefix-p (expand-file-name (car yas-snippet-dirs)) file))))
2592 (y-or-n-p (yas--format "Looks like a library or new snippet. Save to new file? ")))
2593 (let* ((option (first (yas--guess-snippet-directories (yas--template-table yas--editing-template))))
2595 (yas--make-directory-maybe option))))
2597 (let ((default-file-name (or (and file (file-name-nondirectory file))
2598 (yas--template-name yas--editing-template))))
2599 (write-file (expand-file-name
2600 (read-file-name (format "File name to create in %s? " chosen)
2601 chosen default-file-name)
2603 (setf (yas--template-load-file yas--editing-template) buffer-file-name))))))
2604 (when buffer-file-name
2606 (quit-window kill)))
2608 (defun yas-tryout-snippet (&optional debug)
2609 "Test current buffer's snippet template in other buffer."
2611 (let* ((major-mode-and-parent (yas--compute-major-mode-and-parents buffer-file-name))
2612 (parsed (yas--parse-template))
2613 (test-mode (or (and (car major-mode-and-parent)
2614 (fboundp (car major-mode-and-parent))
2615 (car major-mode-and-parent))
2616 (first yas--guessed-modes)
2617 (intern (read-from-minibuffer (yas--format "Please input a mode: ")))))
2618 (yas--current-template
2621 (yas--make-template :table nil ;; no tables for ephemeral snippets
2623 :content (nth 1 parsed)
2624 :name (nth 2 parsed)
2625 :expand-env (nth 5 parsed)))))
2626 (cond (yas--current-template
2627 (let ((buffer-name (format "*testing snippet: %s*" (yas--template-name yas--current-template))))
2628 (kill-buffer (get-buffer-create buffer-name))
2629 (switch-to-buffer (get-buffer-create buffer-name))
2630 (setq buffer-undo-list nil)
2631 (condition-case nil (funcall test-mode) (error nil))
2633 (setq buffer-read-only nil)
2634 (yas-expand-snippet (yas--template-content yas--current-template)
2637 (yas--template-expand-env yas--current-template))
2639 (require 'yasnippet-debug nil t))
2640 (add-hook 'post-command-hook 'yas-debug-snippet-vars nil t))))
2642 (yas--message 1 "Cannot test snippet for unknown major mode")))))
2644 (defun yas-active-keys ()
2645 "Return all active trigger keys for current buffer and point."
2647 (remove-if-not #'stringp (mapcan #'yas--table-all-keys (yas--get-snippet-tables)))
2650 (defun yas--template-fine-group (template)
2651 (car (last (or (yas--template-group template)
2652 (yas--template-perm-group template)))))
2654 (defun yas-describe-tables (&optional choose)
2655 "Display snippets for each table."
2657 (let* ((by-name-hash (and choose
2658 (y-or-n-p "Show by namehash? ")))
2659 (buffer (get-buffer-create "*YASnippet tables*"))
2660 (active-tables (yas--get-snippet-tables))
2661 (remain-tables (let ((all))
2662 (maphash #'(lambda (_k v)
2663 (unless (find v active-tables)
2667 (table-lists (list active-tables remain-tables))
2668 (original-buffer (current-buffer))
2670 (yas--condition-cache-timestamp (current-time)))
2671 (with-current-buffer buffer
2672 (setq buffer-read-only nil)
2674 (cond ((not by-name-hash)
2675 (insert "YASnippet tables:\n")
2676 (while (and table-lists
2678 (dolist (table (car table-lists))
2679 (yas--describe-pretty-table table original-buffer))
2680 (setq table-lists (cdr table-lists))
2682 (yas--create-snippet-xrefs)
2683 (display-buffer buffer)
2684 (setq continue (and choose (y-or-n-p "Show also non-active tables? ")))))
2685 (yas--create-snippet-xrefs)
2689 (insert "\n\nYASnippet tables by NAMEHASH: \n")
2690 (dolist (table (append active-tables remain-tables))
2691 (insert (format "\nSnippet table `%s':\n\n" (yas--table-name table)))
2693 (maphash #'(lambda (k _v)
2695 (yas--table-hash table))
2697 (insert (format " key %s maps snippets: %s\n" key
2699 (maphash #'(lambda (k _v)
2701 (gethash key (yas--table-hash table)))
2704 (setq buffer-read-only t))
2705 (display-buffer buffer)))
2707 (defun yas--describe-pretty-table (table &optional original-buffer)
2708 (insert (format "\nSnippet table `%s'"
2709 (yas--table-name table)))
2710 (if (yas--table-parents table)
2711 (insert (format " parents: %s\n"
2712 (mapcar #'yas--table-name
2713 (yas--table-parents table))))
2715 (insert (make-string 100 ?-) "\n")
2716 (insert "group state name key binding\n")
2717 (let ((groups-hash (make-hash-table :test #'equal)))
2718 (maphash #'(lambda (_k v)
2719 (let ((group (or (yas--template-fine-group v)
2721 (when (yas--template-name v)
2723 (cons v (gethash group groups-hash))
2725 (yas--table-uuidhash table))
2727 #'(lambda (group templates)
2728 (setq group (truncate-string-to-width group 25 0 ? "..."))
2729 (insert (make-string 100 ?-) "\n")
2730 (dolist (p templates)
2731 (let* ((name (truncate-string-to-width (propertize (format "\\\\snippet `%s'" (yas--template-name p))
2735 (setq group (make-string (length group) ? ))))
2736 (condition-string (let ((condition (yas--template-condition p)))
2739 (with-current-buffer original-buffer
2740 (if (yas--eval-condition condition)
2744 (key-description-string (key-description (yas--template-keybinding p)))
2745 (template-key-padding (if (string= key-description-string "") nil ? )))
2747 condition-string " "
2748 name (if (string-match "\\.\\.\\.$" name)
2751 (truncate-string-to-width (or (yas--template-key p) "")
2752 15 0 template-key-padding "...")
2753 (or template-key-padding "")
2754 (truncate-string-to-width key-description-string
2761 ;;; User convenience functions, for using in `yas-key-syntaxes'
2763 (defun yas-try-key-from-whitespace (_start-point)
2764 "As `yas-key-syntaxes' element, look for whitespace delimited key.
2766 A newline will be considered whitespace even if the mode syntax
2767 marks it as something else (typically comment ender)."
2768 (skip-chars-backward "^[:space:]\n"))
2770 (defun yas-shortest-key-until-whitespace (_start-point)
2771 "Like `yas-longest-key-from-whitespace' but take the shortest key."
2772 (when (/= (skip-chars-backward "^[:space:]\n" (1- (point))) 0)
2775 (defun yas-longest-key-from-whitespace (start-point)
2776 "As `yas-key-syntaxes' element, look for longest key between point and whitespace.
2778 A newline will be considered whitespace even if the mode syntax
2779 marks it as something else (typically comment ender)."
2780 (if (= (point) start-point)
2781 (yas-try-key-from-whitespace start-point)
2783 (unless (<= start-point (1+ (point)))
2788 ;;; User convenience functions, for using in snippet definitions
2790 (defvar yas-modified-p nil
2791 "Non-nil if field has been modified by user or transformation.")
2793 (defvar yas-moving-away-p nil
2794 "Non-nil if user is about to exit field.")
2796 (defvar yas-text nil
2797 "Contains current field text.")
2799 (defun yas-substr (str pattern &optional subexp)
2800 "Search PATTERN in STR and return SUBEXPth match.
2802 If found, the content of subexp group SUBEXP (default 0) is
2803 returned, or else the original STR will be returned."
2804 (let ((grp (or subexp 0)))
2806 (if (string-match pattern str)
2807 (match-string-no-properties grp str)
2810 (defun yas-choose-value (&rest possibilities)
2811 "Prompt for a string in POSSIBILITIES and return it.
2813 The last element of POSSIBILITIES may be a list of strings."
2814 (unless (or yas-moving-away-p
2816 (let* ((last-link (last possibilities))
2817 (last-elem (car last-link)))
2818 (when (listp last-elem)
2819 (setcar last-link (car last-elem))
2820 (setcdr last-link (cdr last-elem))))
2821 (some #'(lambda (fn)
2822 (funcall fn "Choose: " possibilities))
2823 yas-prompt-functions)))
2825 (defun yas-key-to-value (alist)
2826 (unless (or yas-moving-away-p
2828 (let ((key (read-key-sequence "")))
2830 (or (cdr (find key alist :key #'car :test #'string=))
2833 (defun yas-throw (text)
2834 "Throw a yas--exception with TEXT as the reason."
2835 (throw 'yas--exception (cons 'yas--exception text)))
2837 (defun yas-verify-value (possibilities)
2838 "Verify that the current field value is in POSSIBILITIES.
2840 Otherwise throw exception."
2841 (when (and yas-moving-away-p (notany #'(lambda (pos) (string= pos yas-text)) possibilities))
2842 (yas-throw (yas--format "Field only allows %s" possibilities))))
2844 (defun yas-field-value (number)
2845 "Get the string for field with NUMBER.
2847 Use this in primary and mirror transformations to tget."
2848 (let* ((snippet (car (yas--snippets-at-point)))
2850 (yas--snippet-find-field snippet number))))
2852 (yas--field-text-for-display field))))
2855 "Return `yas-text' if that exists and is non-empty, else nil."
2857 (not (string= "" yas-text)))
2860 (defun yas-selected-text ()
2861 "Return `yas-selected-text' if that exists and is non-empty, else nil."
2862 (if (and yas-selected-text
2863 (not (string= "" yas-selected-text)))
2866 (defun yas--get-field-once (number &optional transform-fn)
2867 (unless yas-modified-p
2869 (funcall transform-fn (yas-field-value number))
2870 (yas-field-value number))))
2872 (defun yas-default-from-field (number)
2873 (unless yas-modified-p
2874 (yas-field-value number)))
2876 (defun yas-inside-string ()
2877 "Return non-nil if the point is inside a string according to font-lock."
2878 (equal 'font-lock-string-face (get-char-property (1- (point)) 'face)))
2880 (defun yas-unimplemented (&optional missing-feature)
2881 (if yas--current-template
2882 (if (y-or-n-p (format "This snippet is unimplemented (missing %s) Visit the snippet definition? "
2885 (yas--visit-snippet-file-1 yas--current-template))
2886 (message "No implementation. Missing %s" (or missing-feature "something"))))
2889 ;;; Snippet expansion and field management
2891 (defvar yas--active-field-overlay nil
2892 "Overlays the currently active field.")
2894 (defvar yas--field-protection-overlays nil
2895 "Two overlays protect the current active field.")
2897 (defvar yas-selected-text nil
2898 "The selected region deleted on the last snippet expansion.")
2900 (defvar yas--start-column nil
2901 "The column where the snippet expansion started.")
2903 (make-variable-buffer-local 'yas--active-field-overlay)
2904 (make-variable-buffer-local 'yas--field-protection-overlays)
2905 (put 'yas--active-field-overlay 'permanent-local t)
2906 (put 'yas--field-protection-overlays 'permanent-local t)
2908 (defstruct (yas--snippet (:constructor yas--make-snippet ()))
2914 (id (yas--snippet-next-id) :read-only t)
2915 (control-overlay nil)
2917 ;; stacked expansion: the `previous-active-field' slot saves the
2918 ;; active field where the child expansion took place
2919 previous-active-field
2922 (defstruct (yas--field (:constructor yas--make-field (number start end parent-field)))
2925 NUMBER is the field number.
2926 START and END are mostly buffer markers, but see \"apropos markers-to-points\".
2927 PARENT-FIELD is a `yas--field' this field is nested under, or nil.
2928 MIRRORS is a list of `yas--mirror's
2929 TRANSFORM is a lisp form.
2930 MODIFIED-P is a boolean set to true once user inputs text.
2931 NEXT is another `yas--field' or `yas--mirror' or `yas--exit'.
2942 (defstruct (yas--mirror (:constructor yas--make-mirror (start end transform)))
2945 START and END are mostly buffer markers, but see \"apropos markers-to-points\".
2946 TRANSFORM is a lisp form.
2947 PARENT-FIELD is a `yas--field' this mirror is nested under, or nil.
2948 NEXT is another `yas--field' or `yas--mirror' or `yas--exit'
2949 DEPTH is a count of how many nested mirrors can affect this mirror"
2956 (defstruct (yas--exit (:constructor yas--make-exit (marker)))
2960 (defun yas--apply-transform (field-or-mirror field &optional empty-on-nil-p)
2961 "Calculate transformed string for FIELD-OR-MIRROR from FIELD.
2963 If there is no transform for ht field, return nil.
2965 If there is a transform but it returns nil, return the empty
2966 string iff EMPTY-ON-NIL-P is true."
2967 (let* ((yas-text (yas--field-text-for-display field))
2968 (yas-modified-p (yas--field-modified-p field))
2969 (transform (if (yas--mirror-p field-or-mirror)
2970 (yas--mirror-transform field-or-mirror)
2971 (yas--field-transform field-or-mirror)))
2972 (start-point (if (yas--mirror-p field-or-mirror)
2973 (yas--mirror-start field-or-mirror)
2974 (yas--field-start field-or-mirror)))
2975 (transformed (and transform
2977 (goto-char start-point)
2978 (let ((ret (yas--eval-lisp transform)))
2979 (or ret (and empty-on-nil-p "")))))))
2982 (defsubst yas--replace-all (from to &optional text)
2983 "Replace all occurrences from FROM to TO.
2985 With optional string TEXT do it in that string."
2987 (replace-regexp-in-string (regexp-quote from) to text t t)
2988 (goto-char (point-min))
2989 (while (search-forward from nil t)
2990 (replace-match to t t text))))
2992 (defun yas--snippet-find-field (snippet number)
2993 (find-if #'(lambda (field)
2994 (eq number (yas--field-number field)))
2995 (yas--snippet-fields snippet)))
2997 (defun yas--snippet-sort-fields (snippet)
2998 "Sort the fields of SNIPPET in navigation order."
2999 (setf (yas--snippet-fields snippet)
3000 (sort (yas--snippet-fields snippet)
3001 #'yas--snippet-field-compare)))
3003 (defun yas--snippet-field-compare (field1 field2)
3004 "Compare FIELD1 and FIELD2.
3006 The field with a number is sorted first. If they both have a
3007 number, compare through the number. If neither have, compare
3008 through the field's start point"
3009 (let ((n1 (yas--field-number field1))
3010 (n2 (yas--field-number field2)))
3013 (or (zerop n2) (and (not (zerop n1))
3018 (< (yas--field-start field1)
3019 (yas--field-start field2))))))
3021 (defun yas--field-probably-deleted-p (snippet field)
3022 "Guess if SNIPPET's FIELD should be skipped."
3024 ;; field must be zero length
3026 (zerop (- (yas--field-start field) (yas--field-end field)))
3027 ;; field must have been modified
3029 (yas--field-modified-p field)
3032 ;; 1) it's a nested field
3034 (yas--field-parent-field field)
3035 ;; 2) ends just before the snippet end
3037 (and (eq field (car (last (yas--snippet-fields snippet))))
3038 (= (yas--field-start field) (overlay-end (yas--snippet-control-overlay snippet)))))
3039 ;; the field numbered 0, just before the exit marker, should
3042 (not (and (yas--field-number field)
3043 (zerop (yas--field-number field))))))
3045 (defun yas--snippets-at-point (&optional all-snippets)
3046 "Return a sorted list of snippets at point.
3048 The most recently-inserted snippets are returned first."
3050 (delq nil (delete-dups
3051 (mapcar (lambda (ov) (overlay-get ov 'yas--snippet))
3052 (if all-snippets (overlays-in (point-min) (point-max))
3053 (nconc (overlays-at (point))
3054 (overlays-at (1- (point))))))))
3056 (<= (yas--snippet-id s2) (yas--snippet-id s1)))))
3058 (defun yas-next-field-or-maybe-expand ()
3059 "Try to expand a snippet at a key before point.
3061 Otherwise delegate to `yas-next-field'."
3063 (if yas-triggers-in-field
3064 (let ((yas-fallback-behavior 'return-nil)
3065 (active-field (overlay-get yas--active-field-overlay 'yas--field)))
3067 (unless (yas-expand-from-trigger-key active-field)
3071 (defun yas-next-field-will-exit-p (&optional arg)
3072 "Return non-nil if (yas-next-field ARG) would exit the current snippet."
3073 (let ((snippet (car (yas--snippets-at-point)))
3074 (active (overlay-get yas--active-field-overlay 'yas--field)))
3076 (not (yas--find-next-field arg snippet active)))))
3078 (defun yas--find-next-field (n snippet active)
3079 "Return the Nth field after the ACTIVE one in SNIPPET."
3080 (let ((live-fields (cl-remove-if
3082 (and (not (eq field active))
3083 (yas--field-probably-deleted-p snippet field)))
3084 (yas--snippet-fields snippet))))
3085 (if (>= n 0) (nth n (memq active live-fields))
3086 (car (last (memq active (reverse live-fields)) (- n))))))
3088 (defun yas-next-field (&optional arg)
3089 "Navigate to the ARGth next field.
3091 If there's none, exit the snippet."
3093 (unless arg (setq arg 1))
3094 (let* ((snippet (car (yas--snippets-at-point)))
3095 (active-field (overlay-get yas--active-field-overlay 'yas--field))
3096 (target-field (yas--find-next-field arg snippet active-field)))
3097 ;; Apply transform to active field.
3099 (let ((yas-moving-away-p t))
3100 (when (yas--field-update-display active-field)
3101 (yas--update-mirrors snippet))))
3102 ;; Now actually move...
3104 (yas--move-to-field snippet target-field)
3105 (yas-exit-snippet snippet))))
3107 (defun yas--place-overlays (snippet field)
3108 "Correctly place overlays for SNIPPET's FIELD."
3109 (yas--make-move-field-protection-overlays snippet field)
3110 (yas--make-move-active-field-overlay snippet field))
3112 (defun yas--move-to-field (snippet field)
3113 "Update SNIPPET to move to field FIELD.
3115 Also create some protection overlays"
3116 (goto-char (yas--field-start field))
3117 (yas--place-overlays snippet field)
3118 (overlay-put yas--active-field-overlay 'yas--field field)
3119 (let ((number (yas--field-number field)))
3120 ;; check for the special ${0: ...} field
3121 (if (and number (zerop number))
3123 (set-mark (yas--field-end field))
3124 (setf (yas--snippet-force-exit snippet)
3125 (or (yas--field-transform field)
3127 ;; make this field active
3128 (setf (yas--snippet-active-field snippet) field)
3129 ;; primary field transform: first call to snippet transform
3130 (unless (yas--field-modified-p field)
3131 (if (yas--field-update-display field)
3132 (yas--update-mirrors snippet)
3133 (setf (yas--field-modified-p field) nil))))))
3135 (defun yas-prev-field ()
3136 "Navigate to prev field. If there's none, exit the snippet."
3138 (yas-next-field -1))
3140 (defun yas-abort-snippet (&optional snippet)
3142 (let ((snippet (or snippet
3143 (car (yas--snippets-at-point)))))
3145 (setf (yas--snippet-force-exit snippet) t))))
3147 (defun yas-exit-snippet (snippet)
3148 "Goto exit-marker of SNIPPET."
3149 (interactive (list (first (yas--snippets-at-point))))
3151 (setf (yas--snippet-force-exit snippet) t)
3152 (goto-char (if (yas--snippet-exit snippet)
3153 (yas--exit-marker (yas--snippet-exit snippet))
3154 (overlay-end (yas--snippet-control-overlay snippet))))))
3156 (defun yas-exit-all-snippets ()
3157 "Exit all snippets."
3159 (mapc #'(lambda (snippet)
3160 (yas-exit-snippet snippet)
3161 (yas--check-commit-snippet))
3162 (yas--snippets-at-point 'all-snippets)))
3165 ;;; Some low level snippet-routines:
3167 (defvar yas--inhibit-overlay-hooks nil
3168 "Bind this temporarily to non-nil to prevent running `yas--on-*-modification'.")
3170 (defvar yas-snippet-beg nil "Beginning position of the last snippet committed.")
3171 (defvar yas-snippet-end nil "End position of the last snippet committed.")
3173 (defun yas--commit-snippet (snippet)
3174 "Commit SNIPPET, but leave point as it is.
3176 This renders the snippet as ordinary text."
3178 (let ((control-overlay (yas--snippet-control-overlay snippet)))
3180 ;; Save the end of the moribund snippet in case we need to revive it
3181 ;; its original expansion.
3183 (when (and control-overlay
3184 (overlay-buffer control-overlay))
3185 (setq yas-snippet-beg (overlay-start control-overlay))
3186 (setq yas-snippet-end (overlay-end control-overlay))
3187 (delete-overlay control-overlay))
3189 (let ((yas--inhibit-overlay-hooks t))
3190 (when yas--active-field-overlay
3191 (delete-overlay yas--active-field-overlay))
3192 (when yas--field-protection-overlays
3193 (mapc #'delete-overlay yas--field-protection-overlays)))
3195 ;; stacked expansion: if the original expansion took place from a
3196 ;; field, make sure we advance it here at least to
3197 ;; `yas-snippet-end'...
3199 (let ((previous-field (yas--snippet-previous-active-field snippet)))
3200 (when (and yas-snippet-end previous-field)
3201 (yas--advance-end-maybe previous-field yas-snippet-end)))
3203 ;; Convert all markers to points,
3205 (yas--markers-to-points snippet)
3207 ;; Take care of snippet revival
3209 (if yas-snippet-revival
3210 (push `(apply yas--snippet-revive ,yas-snippet-beg ,yas-snippet-end ,snippet)
3212 ;; Dismember the snippet... this is useful if we get called
3213 ;; again from `yas--take-care-of-redo'....
3214 (setf (yas--snippet-fields snippet) nil)))
3216 (yas--message 3 "Snippet %s exited." (yas--snippet-id snippet)))
3218 (defun yas--safely-run-hooks (hook-var)
3219 (condition-case error
3220 (run-hooks hook-var)
3222 (yas--message 2 "%s error: %s" hook-var (error-message-string error)))))
3225 (defun yas--check-commit-snippet ()
3226 "Check if point exited the currently active field of the snippet.
3228 If so cleans up the whole snippet up."
3229 (let* ((snippets (yas--snippets-at-point 'all-snippets))
3230 (snippets-left snippets)
3231 (snippet-exit-transform))
3232 (dolist (snippet snippets)
3233 (let ((active-field (yas--snippet-active-field snippet)))
3234 (setq snippet-exit-transform (yas--snippet-force-exit snippet))
3235 (cond ((or snippet-exit-transform
3236 (not (and active-field (yas--field-contains-point-p active-field))))
3237 (setq snippets-left (delete snippet snippets-left))
3238 (setf (yas--snippet-force-exit snippet) nil)
3239 (yas--commit-snippet snippet))
3241 (or (not yas--active-field-overlay)
3242 (not (overlay-buffer yas--active-field-overlay))))
3244 ;; stacked expansion: this case is mainly for recent
3245 ;; snippet exits that place us back int the field of
3249 (yas--move-to-field snippet active-field)
3250 (yas--update-mirrors snippet)))
3253 (unless (or (null snippets) snippets-left)
3254 (if snippet-exit-transform
3255 (yas--eval-lisp-no-saves snippet-exit-transform))
3256 (yas--safely-run-hooks 'yas-after-exit-snippet-hook))))
3258 ;; Apropos markers-to-points:
3260 ;; This was found useful for performance reasons, so that an
3261 ;; excessive number of live markers aren't kept around in the
3262 ;; `buffer-undo-list'. However, in `markers-to-points', the
3263 ;; set-to-nil markers can't simply be discarded and replaced with
3264 ;; fresh ones in `points-to-markers'. The original marker that was
3265 ;; just set to nil has to be reused.
3267 ;; This shouldn't bring horrible problems with undo/redo, but it
3270 (defun yas--markers-to-points (snippet)
3271 "Convert all markers in SNIPPET to a cons (POINT . MARKER)
3272 where POINT is the original position of the marker and MARKER is
3273 the original marker object with the position set to nil."
3274 (dolist (field (yas--snippet-fields snippet))
3275 (let ((start (marker-position (yas--field-start field)))
3276 (end (marker-position (yas--field-end field))))
3277 (set-marker (yas--field-start field) nil)
3278 (set-marker (yas--field-end field) nil)
3279 (setf (yas--field-start field) (cons start (yas--field-start field)))
3280 (setf (yas--field-end field) (cons end (yas--field-end field))))
3281 (dolist (mirror (yas--field-mirrors field))
3282 (let ((start (marker-position (yas--mirror-start mirror)))
3283 (end (marker-position (yas--mirror-end mirror))))
3284 (set-marker (yas--mirror-start mirror) nil)
3285 (set-marker (yas--mirror-end mirror) nil)
3286 (setf (yas--mirror-start mirror) (cons start (yas--mirror-start mirror)))
3287 (setf (yas--mirror-end mirror) (cons end (yas--mirror-end mirror))))))
3288 (let ((snippet-exit (yas--snippet-exit snippet)))
3290 (let ((exit (marker-position (yas--exit-marker snippet-exit))))
3291 (set-marker (yas--exit-marker snippet-exit) nil)
3292 (setf (yas--exit-marker snippet-exit) (cons exit (yas--exit-marker snippet-exit)))))))
3294 (defun yas--points-to-markers (snippet)
3295 "Convert all cons (POINT . MARKER) in SNIPPET to markers.
3297 This is done by setting MARKER to POINT with `set-marker'."
3298 (dolist (field (yas--snippet-fields snippet))
3299 (setf (yas--field-start field) (set-marker (cdr (yas--field-start field))
3300 (car (yas--field-start field))))
3301 (setf (yas--field-end field) (set-marker (cdr (yas--field-end field))
3302 (car (yas--field-end field))))
3303 (dolist (mirror (yas--field-mirrors field))
3304 (setf (yas--mirror-start mirror) (set-marker (cdr (yas--mirror-start mirror))
3305 (car (yas--mirror-start mirror))))
3306 (setf (yas--mirror-end mirror) (set-marker (cdr (yas--mirror-end mirror))
3307 (car (yas--mirror-end mirror))))))
3308 (let ((snippet-exit (yas--snippet-exit snippet)))
3310 (setf (yas--exit-marker snippet-exit) (set-marker (cdr (yas--exit-marker snippet-exit))
3311 (car (yas--exit-marker snippet-exit)))))))
3313 (defun yas--field-contains-point-p (field &optional point)
3314 (let ((point (or point
3316 (and (>= point (yas--field-start field))
3317 (<= point (yas--field-end field)))))
3319 (defun yas--field-text-for-display (field)
3320 "Return the propertized display text for field FIELD."
3321 (buffer-substring (yas--field-start field) (yas--field-end field)))
3323 (defun yas--undo-in-progress ()
3324 "True if some kind of undo is in progress."
3325 (or undo-in-progress
3326 (eq this-command 'undo)
3327 (eq this-command 'redo)))
3329 (defun yas--make-control-overlay (snippet start end)
3330 "Create the control overlay that surrounds the snippet and
3332 (let ((overlay (make-overlay start
3337 (overlay-put overlay 'keymap yas-keymap)
3338 (overlay-put overlay 'priority 100)
3339 (overlay-put overlay 'yas--snippet snippet)
3342 (defun yas-skip-and-clear-or-delete-char (&optional field)
3343 "Clears unmodified field if at field start, skips to next tab.
3345 Otherwise deletes a character normally by calling `delete-char'."
3347 (let ((field (or field
3348 (and yas--active-field-overlay
3349 (overlay-buffer yas--active-field-overlay)
3350 (overlay-get yas--active-field-overlay 'yas--field)))))
3352 (not (yas--field-modified-p field))
3353 (eq (point) (marker-position (yas--field-start field))))
3354 (yas--skip-and-clear field)
3357 (call-interactively 'delete-char)))))
3359 (defun yas--skip-and-clear (field &optional from)
3360 "Deletes the region of FIELD and sets it's modified state to t.
3361 If given, FROM indicates position to start at instead of FIELD's beginning."
3362 ;; Just before skipping-and-clearing the field, mark its children
3363 ;; fields as modified, too. If the children have mirrors-in-fields
3364 ;; this prevents them from updating erroneously (we're skipping and
3367 (yas--mark-this-and-children-modified field)
3368 (unless (= (yas--field-start field) (yas--field-end field))
3369 (delete-region (or from (yas--field-start field)) (yas--field-end field))))
3371 (defun yas--mark-this-and-children-modified (field)
3372 (setf (yas--field-modified-p field) t)
3373 (let ((fom (yas--field-next field)))
3375 (yas--fom-parent-field fom))
3376 (when (and (eq (yas--fom-parent-field fom) field)
3378 (yas--mark-this-and-children-modified fom))
3379 (setq fom (yas--fom-next fom)))))
3381 (defun yas--make-move-active-field-overlay (snippet field)
3382 "Place the active field overlay in SNIPPET's FIELD.
3384 Move the overlay, or create it if it does not exit."
3385 (if (and yas--active-field-overlay
3386 (overlay-buffer yas--active-field-overlay))
3387 (move-overlay yas--active-field-overlay
3388 (yas--field-start field)
3389 (yas--field-end field))
3390 (setq yas--active-field-overlay
3391 (make-overlay (yas--field-start field)
3392 (yas--field-end field)
3394 (overlay-put yas--active-field-overlay 'priority 100)
3395 (overlay-put yas--active-field-overlay 'face 'yas-field-highlight-face)
3396 (overlay-put yas--active-field-overlay 'yas--snippet snippet)
3397 (overlay-put yas--active-field-overlay 'modification-hooks '(yas--on-field-overlay-modification))
3398 (overlay-put yas--active-field-overlay 'insert-in-front-hooks
3399 '(yas--on-field-overlay-modification))
3400 (overlay-put yas--active-field-overlay 'insert-behind-hooks
3401 '(yas--on-field-overlay-modification))))
3403 (defun yas--skip-and-clear-field-p (field beg _end length)
3404 "Tell if newly modified FIELD should be cleared and skipped.
3405 BEG, END and LENGTH like overlay modification hooks."
3406 (and (= length 0) ; A 0 pre-change length indicates insertion.
3407 (= beg (yas--field-start field)) ; Insertion at field start?
3408 (not (yas--field-modified-p field))))
3410 (defun yas--on-field-overlay-modification (overlay after? beg end &optional length)
3411 "Clears the field and updates mirrors, conditionally.
3413 Only clears the field if it hasn't been modified and point is at
3414 field start. This hook does nothing if an undo is in progress."
3415 (unless (or (not after?)
3416 yas--inhibit-overlay-hooks
3417 (not (overlayp yas--active-field-overlay)) ; Avoid Emacs bug #21824.
3418 (yas--undo-in-progress))
3419 (let* ((inhibit-modification-hooks t)
3420 (field (overlay-get overlay 'yas--field))
3421 (snippet (overlay-get yas--active-field-overlay 'yas--snippet)))
3422 (when (yas--skip-and-clear-field-p field beg end length)
3423 ;; We delete text starting from the END of insertion.
3424 (yas--skip-and-clear field end))
3425 (setf (yas--field-modified-p field) t)
3426 (yas--advance-end-maybe field (overlay-end overlay))
3428 (yas--field-update-display field))
3429 (yas--update-mirrors snippet))))
3431 ;;; Apropos protection overlays:
3433 ;; These exist for nasty users who will try to delete parts of the
3434 ;; snippet outside the active field. Actual protection happens in
3435 ;; `yas--on-protection-overlay-modification'.
3437 ;; As of github #537 this no longer inhibits the command by issuing an
3438 ;; error: all the snippets at point, including nested snippets, are
3439 ;; automatically commited and the current command can proceed.
3441 (defun yas--make-move-field-protection-overlays (snippet field)
3442 "Place protection overlays surrounding SNIPPET's FIELD.
3444 Move the overlays, or create them if they do not exit."
3445 (let ((start (yas--field-start field))
3446 (end (yas--field-end field)))
3447 ;; First check if the (1+ end) is contained in the buffer,
3448 ;; otherwise we'll have to do a bit of cheating and silently
3449 ;; insert a newline. the `(1+ (buffer-size))' should prevent this
3450 ;; when using stacked expansion
3452 (when (< (buffer-size) end)
3454 (let ((yas--inhibit-overlay-hooks t))
3455 (goto-char (point-max))
3457 ;; go on to normal overlay creation/moving
3459 (cond ((and yas--field-protection-overlays
3460 (every #'overlay-buffer yas--field-protection-overlays))
3461 (move-overlay (first yas--field-protection-overlays) (1- start) start)
3462 (move-overlay (second yas--field-protection-overlays) end (1+ end)))
3464 (setq yas--field-protection-overlays
3465 (list (make-overlay (1- start) start nil t nil)
3466 (make-overlay end (1+ end) nil t nil)))
3467 (dolist (ov yas--field-protection-overlays)
3468 (overlay-put ov 'face 'yas--field-debug-face)
3469 (overlay-put ov 'yas--snippet snippet)
3470 ;; (overlay-put ov 'evaporate t)
3471 (overlay-put ov 'modification-hooks '(yas--on-protection-overlay-modification)))))))
3473 (defun yas--on-protection-overlay-modification (_overlay after? beg end &optional length)
3474 "Commit the snippet if the protection overlay is being killed."
3475 (unless (or yas--inhibit-overlay-hooks
3477 (= length (- end beg)) ; deletion or insertion
3478 (yas--undo-in-progress))
3479 (let ((snippets (yas--snippets-at-point)))
3480 (yas--message 2 "Committing snippets. Action would destroy a protection overlay.")
3481 (cl-loop for snippet in snippets
3482 do (yas--commit-snippet snippet)))))
3484 (add-to-list 'debug-ignored-errors "^Exit the snippet first!$")
3487 ;;; Snippet expansion and "stacked" expansion:
3489 ;; Stacked expansion is when you try to expand a snippet when already
3490 ;; inside a snippet expansion.
3492 ;; The parent snippet does not run its fields modification hooks
3493 ;; (`yas--on-field-overlay-modification' and
3494 ;; `yas--on-protection-overlay-modification') while the child snippet
3495 ;; is active. This means, among other things, that the mirrors of the
3496 ;; parent snippet are not updated, this only happening when one exits
3497 ;; the child snippet.
3499 ;; Unfortunately, this also puts some ugly (and not fully-tested)
3500 ;; bits of code in `yas-expand-snippet' and
3501 ;; `yas--commit-snippet'. I've tried to mark them with "stacked
3504 ;; This was thought to be safer in an undo/redo perspective, but
3505 ;; maybe the correct implementation is to make the globals
3506 ;; `yas--active-field-overlay' and `yas--field-protection-overlays' be
3507 ;; snippet-local and be active even while the child snippet is
3508 ;; running. This would mean a lot of overlay modification hooks
3509 ;; running, but if managed correctly (including overlay priorities)
3510 ;; they should account for all situations...
3512 (defun yas-expand-snippet (content &optional start end expand-env)
3513 "Expand snippet CONTENT at current point.
3515 Text between START and END will be deleted before inserting
3516 template. EXPAND-ENV is a list of (SYM VALUE) let-style dynamic bindings
3517 considered when expanding the snippet."
3518 (cl-assert (and yas-minor-mode
3519 (memq 'yas--post-command-handler post-command-hook))
3521 "[yas] `yas-expand-snippet' needs properly setup `yas-minor-mode'")
3522 (run-hooks 'yas-before-expand-snippet-hook)
3525 (let* ((yas-selected-text (or yas-selected-text
3526 (and (region-active-p)
3527 (buffer-substring-no-properties (region-beginning)
3530 (and (region-active-p)
3534 (and (region-active-p)
3537 (to-delete (and start
3539 (buffer-substring-no-properties start end)))
3542 (setq yas--indent-original-column (current-column))
3543 ;; Delete the region to delete, this *does* get undo-recorded.
3545 (when (and to-delete
3547 (delete-region start end))
3549 (cond ((listp content)
3550 ;; x) This is a snippet-command
3552 (yas--eval-lisp-no-saves content))
3554 ;; x) This is a snippet-snippet :-)
3556 ;; Narrow the region down to the content, shoosh the
3557 ;; `buffer-undo-list', and create the snippet, the new
3558 ;; snippet updates its mirrors once, so we are left with
3559 ;; some plain text. The undo action for deleting this
3560 ;; plain text will get recorded at the end.
3562 ;; stacked expansion: also shoosh the overlay modification hooks
3563 (let ((buffer-undo-list t))
3564 ;; snippet creation might evaluate users elisp, which
3565 ;; might generate errors, so we have to be ready to catch
3566 ;; them mostly to make the undo information
3568 (setq yas--start-column (current-column))
3569 (let ((yas--inhibit-overlay-hooks t))
3572 (eval `(let* ,expand-env
3574 (yas--snippet-create start (point))))
3576 (yas--snippet-create start (point))))))
3578 ;; stacked-expansion: This checks for stacked expansion, save the
3579 ;; `yas--previous-active-field' and advance its boundary.
3581 (let ((existing-field (and yas--active-field-overlay
3582 (overlay-buffer yas--active-field-overlay)
3583 (overlay-get yas--active-field-overlay 'yas--field))))
3584 (when existing-field
3585 (setf (yas--snippet-previous-active-field snippet) existing-field)
3586 (yas--advance-end-maybe existing-field (overlay-end yas--active-field-overlay))))
3588 ;; Exit the snippet immediately if no fields
3590 (unless (yas--snippet-fields snippet)
3591 (yas-exit-snippet snippet))
3593 ;; Push two undo actions: the deletion of the inserted contents of
3594 ;; the new snippet (without the "key") followed by an apply of
3595 ;; `yas--take-care-of-redo' on the newly inserted snippet boundaries
3597 ;; A small exception, if `yas-also-auto-indent-first-line'
3598 ;; is t and `yas--indent' decides to indent the line to a
3599 ;; point before the actual expansion point, undo would be
3600 ;; messed up. We call the early point "newstart"". case,
3601 ;; and attempt to fix undo.
3603 (let ((newstart (overlay-start (yas--snippet-control-overlay snippet)))
3604 (end (overlay-end (yas--snippet-control-overlay snippet))))
3605 (when (< newstart start)
3606 (push (cons (make-string (- start newstart) ? ) newstart) buffer-undo-list))
3607 (push (cons newstart end) buffer-undo-list)
3608 (push `(apply yas--take-care-of-redo ,start ,end ,snippet)
3610 ;; Now, schedule a move to the first field
3612 (let ((first-field (car (yas--snippet-fields snippet))))
3614 (sit-for 0) ;; fix issue 125
3615 (yas--move-to-field snippet first-field)))
3616 (yas--message 4 "snippet expanded.")
3619 (defun yas--take-care-of-redo (_beg _end snippet)
3620 "Commits SNIPPET, which in turn pushes an undo action for reviving it.
3622 Meant to exit in the `buffer-undo-list'."
3623 ;; slightly optimize: this action is only needed for snippets with
3624 ;; at least one field
3625 (when (yas--snippet-fields snippet)
3626 (yas--commit-snippet snippet)))
3628 (defun yas--snippet-revive (beg end snippet)
3629 "Revives SNIPPET and creates a control overlay from BEG to END.
3631 BEG and END are, we hope, the original snippets boundaries.
3632 All the markers/points exiting existing inside SNIPPET should point
3633 to their correct locations *at the time the snippet is revived*.
3635 After revival, push the `yas--take-care-of-redo' in the
3637 ;; Reconvert all the points to markers
3639 (yas--points-to-markers snippet)
3640 ;; When at least one editable field existed in the zombie snippet,
3641 ;; try to revive the whole thing...
3643 (let ((target-field (or (yas--snippet-active-field snippet)
3644 (car (yas--snippet-fields snippet)))))
3646 (setf (yas--snippet-control-overlay snippet) (yas--make-control-overlay snippet beg end))
3647 (overlay-put (yas--snippet-control-overlay snippet) 'yas--snippet snippet)
3649 (yas--move-to-field snippet target-field)
3651 (push `(apply yas--take-care-of-redo ,beg ,end ,snippet)
3652 buffer-undo-list))))
3654 (defun yas--snippet-create (begin end)
3655 "Create a snippet from a template inserted at BEGIN to END.
3657 Returns the newly created snippet."
3659 (narrow-to-region begin end)
3660 (let ((snippet (yas--make-snippet)))
3662 (yas--snippet-parse-create snippet)
3664 ;; Sort and link each field
3665 (yas--snippet-sort-fields snippet)
3667 ;; Create keymap overlay for snippet
3668 (setf (yas--snippet-control-overlay snippet)
3669 (yas--make-control-overlay snippet (point-min) (point-max)))
3672 (goto-char (point-max))
3677 ;;; Apropos adjacencies and "fom's":
3679 ;; Once the $-constructs bits like "$n" and "${:n" are deleted in the
3680 ;; recently expanded snippet, we might actually have many fields,
3681 ;; mirrors (and the snippet exit) in the very same position in the
3682 ;; buffer. Therefore we need to single-link the
3683 ;; fields-or-mirrors-or-exit (which I have abbreviated to "fom")
3684 ;; according to their original positions in the buffer.
3686 ;; Then we have operation `yas--advance-end-maybe' and
3687 ;; `yas--advance-start-maybe', which conditionally push the starts and
3688 ;; ends of these foms down the chain.
3690 ;; This allows for like the printf with the magic ",":
3692 ;; printf ("${1:%s}\\n"${1:$(if (string-match "%" text) "," "\);")} \
3693 ;; $2${1:$(if (string-match "%" text) "\);" "")}$0
3695 (defun yas--fom-start (fom)
3696 (cond ((yas--field-p fom)
3697 (yas--field-start fom))
3698 ((yas--mirror-p fom)
3699 (yas--mirror-start fom))
3701 (yas--exit-marker fom))))
3703 (defun yas--fom-end (fom)
3704 (cond ((yas--field-p fom)
3705 (yas--field-end fom))
3706 ((yas--mirror-p fom)
3707 (yas--mirror-end fom))
3709 (yas--exit-marker fom))))
3711 (defun yas--fom-next (fom)
3712 (cond ((yas--field-p fom)
3713 (yas--field-next fom))
3714 ((yas--mirror-p fom)
3715 (yas--mirror-next fom))
3717 (yas--exit-next fom))))
3719 (defun yas--fom-parent-field (fom)
3720 (cond ((yas--field-p fom)
3721 (yas--field-parent-field fom))
3722 ((yas--mirror-p fom)
3723 (yas--mirror-parent-field fom))
3727 (defun yas--calculate-adjacencies (snippet)
3728 "Calculate adjacencies for fields or mirrors of SNIPPET.
3730 This is according to their relative positions in the buffer, and
3731 has to be called before the $-constructs are deleted."
3732 (let* ((fom-set-next-fom
3733 (lambda (fom nextfom)
3734 (cond ((yas--field-p fom)
3735 (setf (yas--field-next fom) nextfom))
3736 ((yas--mirror-p fom)
3737 (setf (yas--mirror-next fom) nextfom))
3739 (setf (yas--exit-next fom) nextfom)))))
3742 (if (= (yas--fom-start fom2) (yas--fom-start fom1))
3743 (yas--mirror-p fom2)
3744 (>= (yas--fom-start fom2) (yas--fom-start fom1)))))
3745 (link-foms fom-set-next-fom))
3746 ;; make some yas--field, yas--mirror and yas--exit soup
3748 (when (yas--snippet-exit snippet)
3749 (push (yas--snippet-exit snippet) soup))
3750 (dolist (field (yas--snippet-fields snippet))
3752 (dolist (mirror (yas--field-mirrors field))
3753 (push mirror soup)))
3755 (sort soup compare-fom-begs))
3757 (reduce link-foms soup)))))
3759 (defun yas--calculate-mirrors-in-fields (snippet mirror)
3760 "Attempt to assign a parent field of SNIPPET to the mirror MIRROR.
3762 Use the tightest containing field if more than one field contains
3763 the mirror. Intended to be called *before* the dollar-regions are
3765 (let ((min (point-min))
3767 (dolist (field (yas--snippet-fields snippet))
3768 (when (and (<= (yas--field-start field) (yas--mirror-start mirror))
3769 (<= (yas--mirror-end mirror) (yas--field-end field))
3770 (< min (yas--field-start field))
3771 (< (yas--field-end field) max))
3772 (setq min (yas--field-start field)
3773 max (yas--field-end field))
3774 (setf (yas--mirror-parent-field mirror) field)))))
3776 (defun yas--advance-end-maybe (fom newend)
3777 "Maybe advance FOM's end to NEWEND if it needs it.
3781 * call `yas--advance-start-maybe' on FOM's next fom.
3783 * in case FOM is field call `yas--advance-end-maybe' on its parent
3786 Also, if FOM is an exit-marker, always call
3787 `yas--advance-start-maybe' on its next fom. This is because
3788 exit-marker have identical start and end markers."
3789 (cond ((and fom (< (yas--fom-end fom) newend))
3790 (set-marker (yas--fom-end fom) newend)
3791 (yas--advance-start-maybe (yas--fom-next fom) newend)
3792 (yas--advance-end-of-parents-maybe (yas--fom-parent-field fom) newend))
3794 (yas--advance-start-maybe (yas--fom-next fom) newend))))
3796 (defun yas--advance-start-maybe (fom newstart)
3797 "Maybe advance FOM's start to NEWSTART if it needs it.
3799 If it does, also call `yas--advance-end-maybe' on FOM."
3800 (when (and fom (< (yas--fom-start fom) newstart))
3801 (set-marker (yas--fom-start fom) newstart)
3802 (yas--advance-end-maybe fom newstart)))
3804 (defun yas--advance-end-of-parents-maybe (field newend)
3805 "Like `yas--advance-end-maybe' but for parent fields.
3807 Only works for fields and doesn't care about the start of the
3808 next FOM. Works its way up recursively for parents of parents."
3810 (< (yas--field-end field) newend))
3811 (set-marker (yas--field-end field) newend)
3812 (yas--advance-end-of-parents-maybe (yas--field-parent-field field) newend)))
3814 (defvar yas--dollar-regions nil
3815 "When expanding the snippet the \"parse-create\" functions add
3816 cons cells to this var.")
3818 (defvar yas--backquote-markers-and-strings nil
3819 "List of (MARKER . STRING) marking where the values from
3820 backquoted Lisp expressions should be inserted at the end of
3823 (defvar yas--indent-markers nil
3824 "List of markers for manual indentation.")
3826 (defun yas--snippet-parse-create (snippet)
3827 "Parse a recently inserted snippet template, creating all
3828 necessary fields, mirrors and exit points.
3830 Meant to be called in a narrowed buffer, does various passes"
3831 (let ((parse-start (point)))
3832 ;; Reset the yas--dollar-regions
3834 (setq yas--dollar-regions nil)
3835 ;; protect just the backquotes
3837 (yas--protect-escapes nil '(?`))
3838 ;; replace all backquoted expressions
3840 (goto-char parse-start)
3841 (yas--save-backquotes)
3842 ;; protect escaped characters
3844 (yas--protect-escapes)
3845 ;; Parse indent markers: `$>'.
3846 (goto-char parse-start)
3847 (yas--indent-parse-create snippet)
3848 ;; parse fields with {}
3850 (goto-char parse-start)
3851 (yas--field-parse-create snippet)
3852 ;; parse simple mirrors and fields
3854 (goto-char parse-start)
3855 (yas--simple-mirror-parse-create snippet)
3856 ;; parse mirror transforms
3858 (goto-char parse-start)
3859 (yas--transform-mirror-parse-create snippet)
3860 ;; calculate adjacencies of fields and mirrors
3862 (yas--calculate-adjacencies snippet)
3863 ;; Delete $-constructs
3867 (yas--delete-regions yas--dollar-regions))
3868 ;; Make sure to do this insertion *after* deleting the dollar
3869 ;; regions, otherwise we invalidate the calculated positions of
3870 ;; all the fields following $0.
3871 (let ((exit (yas--snippet-exit snippet)))
3872 (goto-char (if exit (yas--exit-marker exit) (point-max))))
3873 (when (eq yas-wrap-around-region 'cua)
3874 (setq yas-wrap-around-region ?0))
3875 (cond ((and yas-wrap-around-region yas-selected-text)
3876 (insert yas-selected-text))
3877 ((and (characterp yas-wrap-around-region)
3878 (get-register yas-wrap-around-region))
3879 (insert (prog1 (get-register yas-wrap-around-region)
3880 (set-register yas-wrap-around-region nil)))))
3881 ;; restore backquoted expression values
3883 (yas--restore-backquotes)
3886 (goto-char parse-start)
3887 (yas--restore-escapes)
3888 ;; update mirrors for the first time
3890 (yas--update-mirrors snippet)
3891 ;; indent the best we can
3893 (goto-char parse-start)
3894 (yas--indent snippet)))
3896 (defun yas--indent-region (from to snippet)
3897 "Indent the lines between FROM and TO with `indent-according-to-mode'.
3898 The SNIPPET's markers are preserved."
3899 ;;; Apropos indenting problems....
3901 ;; `indent-according-to-mode' uses whatever `indent-line-function'
3902 ;; is available. Some implementations of these functions delete text
3903 ;; before they insert. If there happens to be a marker just after
3904 ;; the text being deleted, the insertion actually happens after the
3905 ;; marker, which misplaces it.
3907 ;; This would also happen if we had used overlays with the
3908 ;; `front-advance' property set to nil.
3910 ;; This is why I have these `trouble-markers', they are the ones at
3911 ;; the first non-whitespace char at the line. After indentation
3912 ;; takes place we should be at the correct to restore them. All
3913 ;; other non-trouble-markers should have been *pushed* and don't
3914 ;; need special attention.
3915 (let* ((snippet-markers (yas--collect-snippet-markers snippet))
3916 (to (set-marker (make-marker) to)))
3921 ;; Indent each non-empty line.
3922 (cl-loop if (/= (line-beginning-position) (line-end-position)) do
3923 (back-to-indentation)
3924 (let ((trouble-markers ; The markers at (point).
3925 (cl-remove (point) snippet-markers :test #'/=)))
3927 (indent-according-to-mode)
3928 (dolist (marker trouble-markers)
3929 (set-marker marker (point)))))
3930 while (and (zerop (forward-line 1))
3931 (< (point) to)))))))
3933 (defvar yas--indent-original-column nil)
3934 (defun yas--indent (snippet)
3935 ;; Indent lines that had indent markers (`$>') on them.
3937 (dolist (marker yas--indent-markers)
3938 (unless (eq yas-indent-line 'auto)
3940 (yas--indent-region (line-beginning-position)
3943 ;; Finished with this marker.
3944 (set-marker marker nil))
3945 (setq yas--indent-markers nil))
3946 ;; Now do stuff for `fixed' and `auto'.
3948 (cond ((eq yas-indent-line 'fixed)
3949 (while (and (zerop (forward-line))
3950 (zerop (current-column)))
3951 (indent-to-column yas--indent-original-column)))
3952 ((eq yas-indent-line 'auto)
3953 (let ((end (set-marker (make-marker) (point-max))))
3954 (unless yas-also-auto-indent-first-line
3956 (yas--indent-region (line-beginning-position)
3960 (defun yas--collect-snippet-markers (snippet)
3961 "Make a list of all the markers used by SNIPPET."
3963 (dolist (field (yas--snippet-fields snippet))
3964 (push (yas--field-start field) markers)
3965 (push (yas--field-end field) markers)
3966 (dolist (mirror (yas--field-mirrors field))
3967 (push (yas--mirror-start mirror) markers)
3968 (push (yas--mirror-end mirror) markers)))
3969 (let ((snippet-exit (yas--snippet-exit snippet)))
3970 (when (and snippet-exit
3971 (marker-buffer (yas--exit-marker snippet-exit)))
3972 (push (yas--exit-marker snippet-exit) markers)))
3975 (defun yas--escape-string (escaped)
3976 (concat "YASESCAPE" (format "%d" escaped) "PROTECTGUARD"))
3978 (defun yas--protect-escapes (&optional text escaped)
3979 "Protect all escaped characters with their numeric ASCII value.
3981 With optional string TEXT do it in string instead of buffer."
3982 (let ((changed-text text)
3983 (text-provided-p text))
3984 (mapc #'(lambda (escaped)
3986 (yas--replace-all (concat "\\" (char-to-string escaped))
3987 (yas--escape-string escaped)
3988 (when text-provided-p changed-text))))
3989 (or escaped yas--escaped-characters))
3992 (defun yas--restore-escapes (&optional text escaped)
3993 "Restore all escaped characters from their numeric ASCII value.
3995 With optional string TEXT do it in string instead of the buffer."
3996 (let ((changed-text text)
3997 (text-provided-p text))
3998 (mapc #'(lambda (escaped)
4000 (yas--replace-all (yas--escape-string escaped)
4001 (char-to-string escaped)
4002 (when text-provided-p changed-text))))
4003 (or escaped yas--escaped-characters))
4006 (defun yas--save-backquotes ()
4007 "Save all the \"`(lisp-expression)`\"-style expressions
4008 with their evaluated value into `yas--backquote-markers-and-strings'."
4009 (while (re-search-forward yas--backquote-lisp-expression-regexp nil t)
4010 (let ((current-string (match-string-no-properties 1)) transformed)
4011 (save-restriction (widen)
4012 (delete-region (match-beginning 0) (match-end 0)))
4013 (setq transformed (yas--eval-lisp (yas--read-lisp (yas--restore-escapes current-string '(?`)))))
4014 (goto-char (match-beginning 0))
4016 (let ((marker (make-marker)))
4019 (insert "Y") ;; quite horrendous, I love it :)
4020 (set-marker marker (point))
4022 (push (cons marker transformed) yas--backquote-markers-and-strings))))))
4024 (defun yas--restore-backquotes ()
4025 "Replace markers in `yas--backquote-markers-and-strings' with their values."
4026 (while yas--backquote-markers-and-strings
4027 (let* ((marker-and-string (pop yas--backquote-markers-and-strings))
4028 (marker (car marker-and-string))
4029 (string (cdr marker-and-string)))
4037 (set-marker marker nil)))))
4039 (defun yas--scan-sexps (from count)
4041 (save-match-data ; `scan-sexps' may modify match data.
4042 (with-syntax-table (standard-syntax-table)
4043 (scan-sexps from count)))))
4045 (defun yas--make-marker (pos)
4046 "Create a marker at POS with nil `marker-insertion-type'."
4047 (let ((marker (set-marker (make-marker) pos)))
4048 (set-marker-insertion-type marker nil)
4051 (defun yas--indent-parse-create (snippet)
4052 "Parse the \"$>\" indentation markers in SNIPPET."
4053 (setq yas--indent-markers ())
4054 (while (search-forward "$>" nil t)
4055 (delete-region (match-beginning 0) (match-end 0))
4056 ;; Mark the beginning of the line.
4057 (push (yas--make-marker (line-beginning-position))
4058 yas--indent-markers))
4059 (setq yas--indent-markers (nreverse yas--indent-markers)))
4061 (defun yas--field-parse-create (snippet &optional parent-field)
4062 "Parse most field expressions in SNIPPET, except for the simple one \"$n\".
4064 The following count as a field:
4066 * \"${n: text}\", for a numbered field with default text, as long as N is not 0;
4068 * \"${n: text$(expression)}, the same with a Lisp expression;
4069 this is caught with the curiously named `yas--multi-dollar-lisp-expression-regexp'
4071 * the same as above but unnumbered, (no N:) and number is calculated automatically.
4073 When multiple expressions are found, only the last one counts."
4076 (while (re-search-forward yas--field-regexp nil t)
4077 (let* ((real-match-end-0 (yas--scan-sexps (1+ (match-beginning 0)) 1))
4078 (number (and (match-string-no-properties 1)
4079 (string-to-number (match-string-no-properties 1))))
4080 (brand-new-field (and real-match-end-0
4081 ;; break if on "$(" immediately
4082 ;; after the ":", this will be
4083 ;; caught as a mirror with
4085 (not (string-match-p "\\`\\$[ \t\n]*("
4086 (match-string-no-properties 2)))
4087 ;; allow ${0: some exit text}
4088 ;; (not (and number (zerop number)))
4089 (yas--make-field number
4090 (yas--make-marker (match-beginning 2))
4091 (yas--make-marker (1- real-match-end-0))
4093 (when brand-new-field
4094 (goto-char real-match-end-0)
4095 (push (cons (1- real-match-end-0) real-match-end-0)
4096 yas--dollar-regions)
4097 (push (cons (match-beginning 0) (match-beginning 2))
4098 yas--dollar-regions)
4099 (push brand-new-field (yas--snippet-fields snippet))
4102 (narrow-to-region (yas--field-start brand-new-field) (yas--field-end brand-new-field))
4103 (goto-char (point-min))
4104 (yas--field-parse-create snippet brand-new-field)))))))
4105 ;; if we entered from a parent field, now search for the
4106 ;; `yas--multi-dollar-lisp-expression-regexp'. This is used for
4107 ;; primary field transformations
4111 (while (re-search-forward yas--multi-dollar-lisp-expression-regexp nil t)
4112 (let* ((real-match-end-1 (yas--scan-sexps (match-beginning 1) 1)))
4113 ;; commit the primary field transformation if:
4115 ;; 1. we don't find it in yas--dollar-regions (a subnested
4116 ;; field) might have already caught it.
4118 ;; 2. we really make sure we have either two '$' or some
4119 ;; text and a '$' after the colon ':'. This is a FIXME: work
4120 ;; my regular expressions and end these ugly hacks.
4122 (when (and real-match-end-1
4123 (not (member (cons (match-beginning 0)
4125 yas--dollar-regions))
4127 (char-before (1- (match-beginning 1))))))
4128 (let ((lisp-expression-string (buffer-substring-no-properties (match-beginning 1)
4130 (setf (yas--field-transform parent-field)
4131 (yas--read-lisp (yas--restore-escapes lisp-expression-string))))
4132 (push (cons (match-beginning 0) real-match-end-1)
4133 yas--dollar-regions)))))))
4135 (defun yas--transform-mirror-parse-create (snippet)
4136 "Parse the \"${n:$(lisp-expression)}\" mirror transformations in SNIPPET."
4137 (while (re-search-forward yas--transform-mirror-regexp nil t)
4138 (let* ((real-match-end-0 (yas--scan-sexps (1+ (match-beginning 0)) 1))
4139 (number (string-to-number (match-string-no-properties 1)))
4141 (not (zerop number))
4142 (yas--snippet-find-field snippet number)))
4144 (and real-match-end-0
4146 (yas--make-mirror (yas--make-marker (match-beginning 0))
4147 (yas--make-marker (match-beginning 0))
4149 (yas--restore-escapes
4150 (buffer-substring-no-properties (match-beginning 2)
4151 (1- real-match-end-0))))))))
4152 (when brand-new-mirror
4153 (push brand-new-mirror
4154 (yas--field-mirrors field))
4155 (yas--calculate-mirrors-in-fields snippet brand-new-mirror)
4156 (push (cons (match-beginning 0) real-match-end-0) yas--dollar-regions)))))
4158 (defun yas--simple-mirror-parse-create (snippet)
4159 "Parse the simple \"$n\" fields/mirrors/exitmarkers in SNIPPET."
4160 (while (re-search-forward yas--simple-mirror-regexp nil t)
4161 (let ((number (string-to-number (match-string-no-properties 1))))
4162 (cond ((zerop number)
4163 (setf (yas--snippet-exit snippet)
4164 (yas--make-exit (yas--make-marker (match-end 0))))
4165 (push (cons (match-beginning 0) (yas--exit-marker (yas--snippet-exit snippet)))
4166 yas--dollar-regions))
4168 (let ((field (yas--snippet-find-field snippet number)))
4170 (let ((brand-new-mirror (yas--make-mirror
4171 (yas--make-marker (match-beginning 0))
4172 (yas--make-marker (match-beginning 0))
4174 (push brand-new-mirror
4175 (yas--field-mirrors field))
4176 (yas--calculate-mirrors-in-fields snippet brand-new-mirror))
4177 (push (yas--make-field number
4178 (yas--make-marker (match-beginning 0))
4179 (yas--make-marker (match-beginning 0))
4181 (yas--snippet-fields snippet))))
4182 (push (cons (match-beginning 0) (match-end 0))
4183 yas--dollar-regions))))))
4185 (defun yas--delete-regions (regions)
4186 "Sort disjuct REGIONS by start point, then delete from the back."
4187 (mapc #'(lambda (reg)
4188 (delete-region (car reg) (cdr reg)))
4191 (>= (car r1) (car r2))))))
4193 (defun yas--calculate-mirror-depth (mirror &optional traversed)
4194 (let* ((parent (yas--mirror-parent-field mirror))
4195 (parents-mirrors (and parent
4196 (yas--field-mirrors parent))))
4197 (or (yas--mirror-depth mirror)
4198 (setf (yas--mirror-depth mirror)
4199 (cond ((memq mirror traversed)
4201 ((and parent parents-mirrors)
4203 (mapcar #'(lambda (m)
4204 (yas--calculate-mirror-depth m
4213 (defun yas--update-mirrors (snippet)
4214 "Update all the mirrors of SNIPPET."
4218 (dolist (field-and-mirror
4220 ;; make a list of ((F1 . M1) (F1 . M2) (F2 . M3) (F2 . M4) ...)
4221 ;; where F is the field that M is mirroring
4223 (cl-mapcan #'(lambda (field)
4224 (mapcar #'(lambda (mirror)
4225 (cons field mirror))
4226 (yas--field-mirrors field)))
4227 (yas--snippet-fields snippet))
4228 ;; then sort this list so that entries with mirrors with parent
4229 ;; fields appear before. This was important for fixing #290, and
4230 ;; luckily also handles the case where a mirror in a field causes
4231 ;; another mirror to need reupdating
4233 #'(lambda (field-and-mirror1 field-and-mirror2)
4234 (> (yas--calculate-mirror-depth (cdr field-and-mirror1))
4235 (yas--calculate-mirror-depth (cdr field-and-mirror2))))))
4236 (let* ((field (car field-and-mirror))
4237 (mirror (cdr field-and-mirror))
4238 (parent-field (yas--mirror-parent-field mirror)))
4239 ;; before updating a mirror with a parent-field, maybe advance
4243 (yas--advance-start-maybe mirror (yas--fom-start parent-field)))
4244 ;; update this mirror
4246 (yas--mirror-update-display mirror field snippet)
4247 ;; `yas--place-overlays' is needed since the active field and
4248 ;; protected overlays might have been changed because of insertions
4249 ;; in `yas--mirror-update-display'.
4250 (let ((active-field (yas--snippet-active-field snippet)))
4251 (when active-field (yas--place-overlays snippet active-field))))))))
4253 (defun yas--mirror-update-display (mirror field snippet)
4254 "Update MIRROR according to FIELD (and mirror transform)."
4256 (let* ((mirror-parent-field (yas--mirror-parent-field mirror))
4257 (reflection (and (not (and mirror-parent-field
4258 (yas--field-modified-p mirror-parent-field)))
4259 (or (yas--apply-transform mirror field 'empty-on-nil)
4260 (yas--field-text-for-display field)))))
4261 (when (and reflection
4262 (not (string= reflection (buffer-substring-no-properties (yas--mirror-start mirror)
4263 (yas--mirror-end mirror)))))
4264 (goto-char (yas--mirror-start mirror))
4265 (let ((yas--inhibit-overlay-hooks t))
4266 (insert reflection))
4267 (if (> (yas--mirror-end mirror) (point))
4268 (delete-region (point) (yas--mirror-end mirror))
4269 (set-marker (yas--mirror-end mirror) (point))
4270 (yas--advance-start-maybe (yas--mirror-next mirror) (point))
4271 ;; super-special advance
4272 (yas--advance-end-of-parents-maybe mirror-parent-field (point)))
4273 (let ((yas--inhibit-overlay-hooks t))
4274 (yas--indent-region (yas--mirror-start mirror)
4275 (yas--mirror-end mirror)
4278 (defun yas--field-update-display (field)
4279 "Much like `yas--mirror-update-display', but for fields."
4280 (when (yas--field-transform field)
4281 (let ((transformed (and (not (eq (yas--field-number field) 0))
4282 (yas--apply-transform field field))))
4283 (when (and transformed
4284 (not (string= transformed (buffer-substring-no-properties (yas--field-start field)
4285 (yas--field-end field)))))
4286 (setf (yas--field-modified-p field) t)
4287 (goto-char (yas--field-start field))
4288 (let ((yas--inhibit-overlay-hooks t))
4289 (insert transformed)
4290 (if (> (yas--field-end field) (point))
4291 (delete-region (point) (yas--field-end field))
4292 (set-marker (yas--field-end field) (point))
4293 (yas--advance-start-maybe (yas--field-next field) (point)))
4297 ;;; Post-command hook:
4299 (defun yas--post-command-handler ()
4300 "Handles various yasnippet conditions after each command."
4301 (cond ((eq 'undo this-command)
4303 ;; After undo revival the correct field is sometimes not
4304 ;; restored correctly, this condition handles that
4306 (let* ((snippet (car (yas--snippets-at-point)))
4307 (target-field (and snippet
4308 (find-if-not #'(lambda (field)
4309 (yas--field-probably-deleted-p snippet field))
4311 (cons (yas--snippet-active-field snippet)
4312 (yas--snippet-fields snippet)))))))
4314 (yas--move-to-field snippet target-field))))
4315 ((not (yas--undo-in-progress))
4316 ;; When not in an undo, check if we must commit the snippet
4317 ;; (user exited it).
4318 (yas--check-commit-snippet))))
4322 ;; The docstrings for some functions are generated dynamically
4323 ;; depending on the context.
4325 (put 'yas-expand 'function-documentation
4326 '(yas--expand-from-trigger-key-doc t))
4327 (defun yas--expand-from-trigger-key-doc (context)
4328 "A doc synthesizer for `yas--expand-from-trigger-key-doc'."
4329 (let* ((yas-fallback-behavior (and context yas-fallback-behavior))
4330 (fallback-description
4331 (cond ((eq yas-fallback-behavior 'call-other-command)
4332 (let* ((fallback (yas--keybinding-beyond-yasnippet)))
4334 (format "call command `%s'."
4335 (pp-to-string fallback)))
4336 "do nothing (`yas-expand' doesn't override\nanything).")))
4337 ((eq yas-fallback-behavior 'return-nil)
4339 (t "defer to `yas-fallback-behavior' (which see)."))))
4340 (concat "Expand a snippet before point. If no snippet
4341 expansion is possible, "
4342 fallback-description
4343 "\n\nOptional argument FIELD is for non-interactive use and is an
4344 object satisfying `yas--field-p' to restrict the expansion to.")))
4346 (put 'yas-expand-from-keymap 'function-documentation
4347 '(yas--expand-from-keymap-doc t))
4348 (defun yas--expand-from-keymap-doc (context)
4349 "A doc synthesizer for `yas--expand-from-keymap-doc'."
4350 (add-hook 'temp-buffer-show-hook #'yas--snippet-description-finish-runonce)
4351 (concat "Expand/run snippets from keymaps, possibly falling back to original binding.\n"
4352 (when (and context (eq this-command 'describe-key))
4353 (let* ((vec (this-single-command-keys))
4354 (templates (mapcan #'(lambda (table)
4355 (yas--fetch table vec))
4356 (yas--get-snippet-tables)))
4357 (yas--direct-keymaps nil)
4358 (fallback (key-binding vec)))
4359 (concat "In this case, "
4361 (concat "these snippets are bound to this key:\n"
4362 (yas--template-pretty-list templates)
4363 "\n\nIf none of these expands, "))
4365 (format "fallback `%s' will be called." (pp-to-string fallback)))
4366 "no fallback keybinding is called."))))))
4368 (defun yas--template-pretty-list (templates)
4370 (yas-buffer-local-condition 'always))
4371 (dolist (plate templates)
4372 (setq acc (concat acc "\n*) "
4373 (propertize (concat "\\\\snippet `" (car plate) "'")
4374 'yasnippet (cdr plate)))))
4377 (define-button-type 'help-snippet-def
4378 :supertype 'help-xref
4379 'help-function (lambda (template) (yas--visit-snippet-file-1 template))
4380 'help-echo (purecopy "mouse-2, RET: find snippets's definition"))
4382 (defun yas--snippet-description-finish-runonce ()
4383 "Final adjustments for the help buffer when snippets are concerned."
4384 (yas--create-snippet-xrefs)
4385 (remove-hook 'temp-buffer-show-hook
4386 #'yas--snippet-description-finish-runonce))
4388 (defun yas--create-snippet-xrefs ()
4390 (goto-char (point-min))
4391 (while (search-forward-regexp "\\\\\\\\snippet[ \s\t]+`\\([^']+\\)'" nil t)
4392 (let ((template (get-text-property (match-beginning 1)
4395 (help-xref-button 1 'help-snippet-def template)
4396 (delete-region (match-end 1) (match-end 0))
4397 (delete-region (match-beginning 0) (match-beginning 1)))))))
4401 (defvar yas-verbosity 3
4402 "Log level for `yas--message' 4 means trace most anything, 0 means nothing.")
4404 (defun yas--message (level message &rest args)
4405 "When LEVEL is above `yas-verbosity-level', log MESSAGE and ARGS."
4406 (when (> yas-verbosity level)
4407 (message "%s" (apply #'yas--format message args))))
4409 (defun yas--warning (format-control &rest format-args)
4410 (let ((msg (apply #'format format-control format-args)))
4411 (display-warning 'yasnippet msg :warning)
4412 (yas--message 1 msg)))
4414 (defun yas--format (format-control &rest format-args)
4415 (apply #'format (concat "[yas] " format-control) format-args))
4422 ;; `locate-dominating-file'
4423 ;; `region-active-p'
4425 ;; added for compatibility in emacsen < 23
4426 (unless (>= emacs-major-version 23)
4427 (unless (fboundp 'region-active-p)
4428 (defun region-active-p () (and transient-mark-mode mark-active)))
4430 (unless (fboundp 'locate-dominating-file)
4431 (defvar locate-dominating-stop-dir-regexp
4432 "\\`\\(?:[\\/][\\/][^\\/]+[\\/]\\|/\\(?:net\\|afs\\|\\.\\.\\.\\)/\\)\\'"
4433 "Regexp of directory names which stop the search in `locate-dominating-file'.
4434 Any directory whose name matches this regexp will be treated like
4435 a kind of root directory by `locate-dominating-file' which will stop its search
4436 when it bumps into it.
4437 The default regexp prevents fruitless and time-consuming attempts to find
4438 special files in directories in which filenames are interpreted as hostnames,
4439 or mount points potentially requiring authentication as a different user.")
4441 (defun locate-dominating-file (file name)
4442 "Look up the directory hierarchy from FILE for a file named NAME.
4443 Stop at the first parent directory containing a file NAME,
4444 and return the directory. Return nil if not found."
4445 ;; We used to use the above locate-dominating-files code, but the
4446 ;; directory-files call is very costly, so we're much better off doing
4447 ;; multiple calls using the code in here.
4449 ;; Represent /home/luser/foo as ~/foo so that we don't try to look for
4450 ;; `name' in /home or in /.
4451 (setq file (abbreviate-file-name file))
4454 (while (not (or root
4456 ;; FIXME: Disabled this heuristic because it is sometimes
4458 ;; As a heuristic, we stop looking up the hierarchy of
4459 ;; directories as soon as we find a directory belonging
4460 ;; to another user. This should save us from looking in
4461 ;; things like /net and /afs. This assumes that all the
4462 ;; files inside a project belong to the same user.
4463 ;; (let ((prev-user user))
4464 ;; (setq user (nth 2 (file-attributes file)))
4465 ;; (and prev-user (not (equal user prev-user))))
4466 (string-match locate-dominating-stop-dir-regexp file)))
4467 (setq try (file-exists-p (expand-file-name name file)))
4468 (cond (try (setq root file))
4469 ((equal file (setq file (file-name-directory
4470 (directory-file-name file))))
4475 ;;; Backward compatibility to yasnippet <= 0.7
4477 (defun yas-initialize ()
4478 "For backward compatibility, enable `yas-minor-mode' globally."
4479 (declare (obsolete "Use (yas-global-mode 1) instead." "0.8"))
4480 (yas-global-mode 1))
4482 (defvar yas--backported-syms '(;; `defcustom's
4485 yas-prompt-functions
4487 yas-also-auto-indent-first-line
4489 yas-triggers-in-field
4490 yas-fallback-behavior
4491 yas-choose-keys-first
4492 yas-choose-tables-first
4495 yas-wrap-around-region
4498 yas-expand-only-for-last-commands
4499 yas-field-highlight-face
4501 ;; these vars can be customized as well
4507 yas-after-exit-snippet-hook
4508 yas-before-expand-snippet-hook
4509 yas-buffer-local-condition
4512 ;; prompting functions
4517 yas-completing-prompt
4520 ;; interactive functions
4525 yas-direct-keymaps-reload
4529 yas-compile-directory
4532 yas-expand-from-trigger-key
4533 yas-expand-from-keymap
4535 yas-visit-snippet-file
4537 yas-load-snippet-buffer
4540 yas-next-field-or-maybe-expand
4545 yas-exit-all-snippets
4546 yas-skip-and-clear-or-delete-char
4549 ;; symbols that I "exported" for use
4550 ;; in snippets and hookage
4567 yas-default-from-field
4570 yas-define-condition-cache
4571 yas-hippie-try-expand
4573 ;; debug definitions
4574 ;; yas-debug-snippet-vars
4575 ;; yas-exterminate-package
4578 ;; testing definitions
4579 ;; yas-should-expand
4580 ;; yas-should-not-expand
4582 ;; yas-make-file-or-dirs
4584 ;; yas-saving-variables
4585 ;; yas-call-with-snippet-dirs
4586 ;; yas-with-snippet-dirs
4588 "Backported yasnippet symbols.
4590 They are mapped to \"yas/*\" variants.")
4592 (dolist (sym yas--backported-syms)
4593 (let ((backported (intern (replace-regexp-in-string "\\`yas-" "yas/" (symbol-name sym)))))
4595 (make-obsolete-variable backported sym "yasnippet 0.8")
4596 (defvaralias backported sym))
4598 (make-obsolete backported sym "yasnippet 0.8")
4599 (defalias backported sym))))
4601 (defvar yas--exported-syms
4603 (mapatoms (lambda (atom)
4604 (if (and (or (and (boundp atom)
4605 (not (get atom 'byte-obsolete-variable)))
4607 (not (get atom 'byte-obsolete-info))))
4608 (string-match-p "\\`yas-[^-]" (symbol-name atom)))
4609 (push atom exported))))
4611 "Exported yasnippet symbols.
4613 i.e. the ones with \"yas-\" single dash prefix. I will try to
4614 keep them in future yasnippet versions and other elisp libraries
4615 can more or less safely rely upon them.")
4618 (provide 'yasnippet)
4621 ;; indent-tabs-mode: nil
4622 ;; byte-compile-warnings: (not cl-functions)
4624 ;;; yasnippet.el ends here