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 ((and yas-minor-mode (featurep 'yasnippet))
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 (let ((prog-mode-hook nil)
888 (emacs-lisp-mode-hook nil))
889 (ignore-errors (emacs-lisp-mode)))
890 (font-lock-set-defaults)
891 (if (eq t (car-safe font-lock-keywords))
892 ;; They're "compiled", so extract the source.
893 (cadr font-lock-keywords)
896 (0 font-lock-keyword-face)
897 (1 font-lock-string-face t))
899 (0 font-lock-keyword-face)
900 (1 font-lock-warning-face t))
901 ("\\(\\$(\\)" 1 font-lock-preprocessor-face)
903 (0 font-lock-keyword-face)))))
905 (defvar snippet-mode-map
906 (let ((map (make-sparse-keymap)))
907 (easy-menu-define nil
909 "Menu used when snippet-mode is active."
911 (mapcar #'(lambda (ent)
913 (define-key map (third ent) (second ent)))
914 (vector (first ent) (second ent) t))
915 '(("Load this snippet" yas-load-snippet-buffer "\C-c\C-l")
916 ("Load and quit window" yas-load-snippet-buffer-and-close "\C-c\C-c")
917 ("Try out this snippet" yas-tryout-snippet "\C-c\C-t")))))
919 "The keymap used when `snippet-mode' is active.")
923 (define-derived-mode snippet-mode text-mode "Snippet"
924 "A mode for editing yasnippets"
925 (setq font-lock-defaults '(yas--font-lock-keywords))
926 (set (make-local-variable 'require-final-newline) nil)
927 (set (make-local-variable 'comment-start) "#")
928 (set (make-local-variable 'comment-start-skip) "#+[\t ]*"))
932 ;;; Internal structs for template management
934 (cl-defstruct (yas--template
935 (:constructor yas--make-template)
936 ;; Handles `yas-define-snippets' format, plus the
937 ;; initial TABLE argument.
939 yas--define-snippets-2
942 &optional xname condition group
943 expand-env load-file xkeybinding xuuid save-file
946 ;; A little redundant: we always get a name
947 ;; from `yas--parse-template' except when
948 ;; there isn't a file.
949 (and load-file (file-name-nondirectory load-file))
950 (and save-file (file-name-nondirectory save-file))
952 (keybinding (yas--read-keybinding xkeybinding))
953 (uuid (or xuuid name))
954 (old (gethash uuid (yas--table-uuidhash table)))
956 (and old (yas--template-menu-binding-pair old)))
958 (and old (yas--template-perm-group old))))))
959 "A template for a snippet."
970 group ;; as dictated by the #group: directive or .yas-make-groups
971 perm-group ;; as dictated by `yas-define-menu'
975 (defstruct (yas--table (:constructor yas--make-snippet-table (name)))
976 "A table to store snippets for a particular mode.
978 Has the following fields:
982 A symbol name normally corresponding to a major mode, but can
983 also be a pseudo major-mode to be used in
984 `yas-activate-extra-mode', for example.
988 A hash table (KEY . NAMEHASH), known as the \"keyhash\". KEY is
989 a string or a vector, where the former is the snippet's trigger
990 and the latter means it's a direct keybinding. NAMEHASH is yet
991 another hash of (NAME . TEMPLATE) where NAME is the snippet's
992 name and TEMPLATE is a `yas--template' object.
994 `yas--table-direct-keymap'
996 A keymap for the snippets in this table that have direct
997 keybindings. This is kept in sync with the keyhash, i.e., all
998 the elements of the keyhash that are vectors appear here as
999 bindings to `yas-expand-from-keymap'.
1001 `yas--table-uuidhash'
1003 A hash table mapping snippets uuid's to the same `yas--template'
1004 objects. A snippet uuid defaults to the snippet's name."
1006 (hash (make-hash-table :test 'equal))
1007 (uuidhash (make-hash-table :test 'equal))
1009 (direct-keymap (make-sparse-keymap)))
1011 (defun yas--get-template-by-uuid (mode uuid)
1012 "Find the snippet template in MODE by its UUID."
1013 (let* ((table (gethash mode yas--tables mode)))
1015 (gethash uuid (yas--table-uuidhash table)))))
1017 ;; Apropos storing/updating in TABLE, this works in two steps:
1019 ;; 1. `yas--remove-template-by-uuid' removes any
1020 ;; keyhash-namehash-template mappings from TABLE, grabbing the
1021 ;; snippet by its uuid. Also removes mappings from TABLE's
1022 ;; `yas--table-direct-keymap' (FIXME: and should probably take care
1023 ;; of potentially stale menu bindings right?.)
1025 ;; 2. `yas--add-template' adds this all over again.
1027 ;; Create a new or add to an existing keyhash-namehash mapping.
1029 ;; For reference on understanding this, consider three snippet
1032 ;; A: # name: The Foo
1034 ;; # binding: C-c M-l
1036 ;; B: # name: Mrs Foo
1039 ;; C: # name: The Bar
1040 ;; # binding: C-c M-l
1045 ;; keyhash namehashes(3) yas--template structs(4)
1046 ;; -----------------------------------------------------
1049 ;; "foo" ---> "The Foo" ---> [yas--template A] |
1050 ;; "Mrs Foo" ---> [yas--template B] |
1052 ;; [C-c M-l] ---> "The Foo" -------------------------/
1053 ;; "The Bar" ---> [yas--template C]
1055 ;; "baz" ---> "Baz" ---> [yas--template D]
1057 ;; Additionally, since uuid defaults to the name, we have a
1058 ;; `yas--table-uuidhash' for TABLE
1060 ;; uuidhash yas--template structs
1061 ;; -------------------------------
1062 ;; "The Foo" ---> [yas--template A]
1063 ;; "Mrs Foo" ---> [yas--template B]
1064 ;; "The Bar" ---> [yas--template C]
1065 ;; "Baz" ---> [yas--template D]
1067 ;; FIXME: the more I look at this data-structure the more I think I'm
1068 ;; stupid. There has to be an easier way (but beware lots of code
1069 ;; depends on this).
1071 (defun yas--remove-template-by-uuid (table uuid)
1072 "Remove from TABLE a template identified by UUID."
1073 (let ((template (gethash uuid (yas--table-uuidhash table))))
1075 (let* ((name (yas--template-name template))
1077 ;; Remove the name from each of the targeted namehashes
1079 (maphash #'(lambda (k v)
1080 (let ((template (gethash name v)))
1082 (eq uuid (yas--template-uuid template)))
1084 (when (zerop (hash-table-count v))
1085 (push k empty-keys)))))
1086 (yas--table-hash table))
1087 ;; Remove the namehash themselves if they've become empty
1089 (dolist (key empty-keys)
1091 (define-key (yas--table-direct-keymap table) key nil))
1092 (remhash key (yas--table-hash table)))
1094 ;; Finally, remove the uuid from the uuidhash
1096 (remhash uuid (yas--table-uuidhash table))))))
1098 (defun yas--add-template (table template)
1099 "Store in TABLE the snippet template TEMPLATE.
1101 KEY can be a string (trigger key) of a vector (direct
1103 (let ((name (yas--template-name template))
1104 (key (yas--template-key template))
1105 (keybinding (yas--template-keybinding template))
1106 (_menu-binding-pair (yas--template-menu-binding-pair-get-create template)))
1107 (dolist (k (remove nil (list key keybinding)))
1111 (yas--table-hash table))
1113 (make-hash-table :test 'equal)
1114 (yas--table-hash table))))
1116 (define-key (yas--table-direct-keymap table) k 'yas-expand-from-keymap)))
1118 ;; Update TABLE's `yas--table-uuidhash'
1119 (puthash (yas--template-uuid template)
1121 (yas--table-uuidhash table))))
1123 (defun yas--update-template (table template)
1124 "Add or update TEMPLATE in TABLE.
1126 Also takes care of adding and updating to the associated menu.
1128 ;; Remove from table by uuid
1130 (yas--remove-template-by-uuid table (yas--template-uuid template))
1131 ;; Add to table again
1133 (yas--add-template table template)
1134 ;; Take care of the menu
1136 (yas--update-template-menu table template)
1139 (defun yas--update-template-menu (table template)
1140 "Update every menu-related for TEMPLATE."
1141 (let ((menu-binding-pair (yas--template-menu-binding-pair-get-create template))
1142 (key (yas--template-key template))
1143 (keybinding (yas--template-keybinding template)))
1144 ;; The snippet might have changed name or keys, so update
1145 ;; user-visible strings
1147 (unless (eq (cdr menu-binding-pair) :none)
1148 ;; the menu item name
1150 (setf (cadar menu-binding-pair) (yas--template-name template))
1151 ;; the :keys information (also visible to the user)
1152 (setf (getf (cdr (car menu-binding-pair)) :keys)
1153 (or (and keybinding (key-description keybinding))
1154 (and key (concat key yas-trigger-symbol))))))
1155 (unless (yas--template-menu-managed-by-yas-define-menu template)
1157 (yas--menu-keymap-get-create (yas--table-mode table)
1158 (mapcar #'yas--table-mode
1159 (yas--table-parents table))))
1160 (group (yas--template-group template)))
1161 ;; Remove from menu keymap
1163 (assert menu-keymap)
1164 (yas--delete-from-keymap menu-keymap (yas--template-uuid template))
1166 ;; Add necessary subgroups as necessary.
1168 (dolist (subgroup group)
1169 (let ((subgroup-keymap (lookup-key menu-keymap (vector (make-symbol subgroup)))))
1170 (unless (and subgroup-keymap
1171 (keymapp subgroup-keymap))
1172 (setq subgroup-keymap (make-sparse-keymap))
1173 (define-key menu-keymap (vector (make-symbol subgroup))
1174 `(menu-item ,subgroup ,subgroup-keymap)))
1175 (setq menu-keymap subgroup-keymap)))
1177 ;; Add this entry to the keymap
1179 (define-key menu-keymap
1180 (vector (make-symbol (yas--template-uuid template)))
1181 (car (yas--template-menu-binding-pair template))))))
1183 (defun yas--namehash-templates-alist (namehash)
1184 "Return NAMEHASH as an alist."
1186 (maphash #'(lambda (k v)
1187 (push (cons k v) alist))
1191 (defun yas--fetch (table key)
1192 "Fetch templates in TABLE by KEY.
1194 Return a list of cons (NAME . TEMPLATE) where NAME is a
1195 string and TEMPLATE is a `yas--template' structure."
1196 (let* ((keyhash (yas--table-hash table))
1197 (namehash (and keyhash (gethash key keyhash))))
1199 (yas--filter-templates-by-condition (yas--namehash-templates-alist namehash)))))
1202 ;;; Filtering/condition logic
1204 (defun yas--eval-condition (condition)
1211 (yas--message 1 "Error in condition evaluation: %s" (error-message-string err))
1215 (defun yas--filter-templates-by-condition (templates)
1216 "Filter the templates using the applicable condition.
1218 TEMPLATES is a list of cons (NAME . TEMPLATE) where NAME is a
1219 string and TEMPLATE is a `yas--template' structure.
1221 This function implements the rules described in
1222 `yas-buffer-local-condition'. See that variables documentation."
1223 (let ((requirement (yas--require-template-specific-condition-p)))
1224 (if (eq requirement 'always)
1226 (remove-if-not #'(lambda (pair)
1227 (yas--template-can-expand-p
1228 (yas--template-condition (cdr pair)) requirement))
1231 (defun yas--require-template-specific-condition-p ()
1232 "Decide if this buffer requests/requires snippet-specific
1233 conditions to filter out potential expansions."
1234 (if (eq 'always yas-buffer-local-condition)
1236 (let ((local-condition (or (and (consp yas-buffer-local-condition)
1237 (yas--eval-condition yas-buffer-local-condition))
1238 yas-buffer-local-condition)))
1239 (when local-condition
1240 (if (eq local-condition t)
1242 (and (consp local-condition)
1243 (eq 'require-snippet-condition (car local-condition))
1244 (symbolp (cdr local-condition))
1245 (cdr local-condition)))))))
1247 (defun yas--template-can-expand-p (condition requirement)
1248 "Evaluate CONDITION and REQUIREMENT and return a boolean."
1249 (let* ((result (or (null condition)
1250 (yas--eval-condition condition))))
1251 (cond ((eq requirement t)
1254 (eq requirement result)))))
1256 (defun yas--table-templates (table)
1259 (maphash #'(lambda (_key namehash)
1260 (maphash #'(lambda (name template)
1261 (push (cons name template) acc))
1263 (yas--table-hash table))
1264 (yas--filter-templates-by-condition acc))))
1266 (defun yas--templates-for-key-at-point ()
1267 "Find `yas--template' objects for any trigger keys preceding point.
1268 Returns (TEMPLATES START END). This function respects
1269 `yas-key-syntaxes', which see."
1271 (let ((original (point))
1272 (methods yas-key-syntaxes)
1277 (unless (eq method (car methods))
1278 ;; TRICKY: `eq'-ness test means we can only be here if
1279 ;; `method' is a function that returned `again', and hence
1280 ;; don't revert back to original position as per
1281 ;; `yas-key-syntaxes'.
1282 (goto-char original))
1283 (setq method (car methods))
1284 (cond ((stringp method)
1285 (skip-syntax-backward method)
1286 (setq methods (cdr methods)))
1288 (unless (eq (funcall method original)
1290 (setq methods (cdr methods))))
1292 (setq methods (cdr methods))
1293 (yas--warning "Invalid element `%s' in `yas-key-syntaxes'" method)))
1294 (let ((possible-key (buffer-substring-no-properties (point) original)))
1296 (goto-char original)
1298 (mapcan #'(lambda (table)
1299 (yas--fetch table possible-key))
1300 (yas--get-snippet-tables))))))
1302 (list templates (point) original)))))
1304 (defun yas--table-all-keys (table)
1305 "Get trigger keys of all active snippets in TABLE."
1307 (maphash #'(lambda (key namehash)
1308 (when (yas--filter-templates-by-condition (yas--namehash-templates-alist namehash))
1310 (yas--table-hash table))
1313 (defun yas--table-mode (table)
1314 (intern (yas--table-name table)))
1317 ;;; Internal functions and macros:
1319 (defun yas--handle-error (err)
1320 "Handle error depending on value of `yas-good-grace'."
1321 (let ((msg (yas--format "elisp error: %s" (error-message-string err))))
1322 (if yas-good-grace msg
1325 (defun yas--eval-lisp (form)
1326 "Evaluate FORM and convert the result to string."
1327 (let ((retval (catch 'yas--exception
1333 (let ((result (eval form)))
1335 (format "%s" result))))))
1336 (error (yas--handle-error err))))))
1337 (when (and (consp retval)
1338 (eq 'yas--exception (car retval)))
1339 (error (cdr retval)))
1342 (defun yas--eval-lisp-no-saves (form)
1345 (error (message "%s" (yas--handle-error err)))))
1347 (defun yas--read-lisp (string &optional nil-on-error)
1348 "Read STRING as a elisp expression and return it.
1350 In case STRING in an invalid expression and NIL-ON-ERROR is nil,
1351 return an expression that when evaluated will issue an error."
1354 (error (and (not nil-on-error)
1355 `(error (error-message-string ,err))))))
1357 (defun yas--read-keybinding (keybinding)
1358 "Read KEYBINDING as a snippet keybinding, return a vector."
1359 (when (and keybinding
1360 (not (string-match "keybinding" keybinding)))
1362 (let ((res (or (and (string-match "^\\[.*\\]$" keybinding)
1364 (read-kbd-macro keybinding 'need-vector))))
1367 (yas--message 2 "warning: keybinding \"%s\" invalid since %s."
1368 keybinding (error-message-string err))
1371 (defun yas--table-get-create (mode)
1372 "Get or create the snippet table corresponding to MODE."
1373 (let ((table (gethash mode
1376 (setq table (yas--make-snippet-table (symbol-name mode)))
1377 (puthash mode table yas--tables)
1378 (push (cons (intern (format "yas--direct-%s" mode))
1379 (yas--table-direct-keymap table))
1380 yas--direct-keymaps))
1383 (defun yas--get-snippet-tables (&optional mode)
1384 "Get snippet tables for MODE.
1386 MODE defaults to the current buffer's `major-mode'.
1388 Return a list of `yas--table' objects. The list of modes to
1389 consider is returned by `yas--modes-to-activate'"
1391 (mapcar #'(lambda (name)
1392 (gethash name yas--tables))
1393 (yas--modes-to-activate mode))))
1395 (defun yas--menu-keymap-get-create (mode &optional parents)
1396 "Get or create the menu keymap for MODE and its PARENTS.
1398 This may very well create a plethora of menu keymaps and arrange
1399 them all in `yas--menu-table'"
1400 (let* ((menu-keymap (or (gethash mode yas--menu-table)
1401 (puthash mode (make-sparse-keymap) yas--menu-table))))
1402 (mapc #'yas--menu-keymap-get-create parents)
1403 (define-key yas--minor-mode-menu (vector mode)
1404 `(menu-item ,(symbol-name mode) ,menu-keymap
1405 :visible (yas--show-menu-p ',mode)))
1409 ;;; Template-related and snippet loading functions
1411 (defun yas--parse-template (&optional file)
1412 "Parse the template in the current buffer.
1414 Optional FILE is the absolute file name of the file being
1417 Optional GROUP is the group where the template is to go,
1418 otherwise we attempt to calculate it from FILE.
1420 Return a snippet-definition, i.e. a list
1422 (KEY TEMPLATE NAME CONDITION GROUP VARS LOAD-FILE KEYBINDING UUID)
1424 If the buffer contains a line of \"# --\" then the contents above
1425 this line are ignored. Directives can set most of these with the syntax:
1427 # directive-name : directive-value
1429 Here's a list of currently recognized directives:
1440 (goto-char (point-min))
1441 (let* ((type 'snippet)
1443 (file-name-nondirectory file)))
1449 (yas--calculate-group file)))
1453 (if (re-search-forward "^# --\n" nil t)
1454 (progn (setq template
1455 (buffer-substring-no-properties (point)
1457 (setq bound (point))
1458 (goto-char (point-min))
1459 (while (re-search-forward "^# *\\([^ ]+?\\) *: *\\(.*?\\)[[:space:]]*$" bound t)
1460 (when (string= "uuid" (match-string-no-properties 1))
1461 (setq uuid (match-string-no-properties 2)))
1462 (when (string= "type" (match-string-no-properties 1))
1463 (setq type (if (string= "command" (match-string-no-properties 2))
1466 (when (string= "key" (match-string-no-properties 1))
1467 (setq key (match-string-no-properties 2)))
1468 (when (string= "name" (match-string-no-properties 1))
1469 (setq name (match-string-no-properties 2)))
1470 (when (string= "condition" (match-string-no-properties 1))
1471 (setq condition (yas--read-lisp (match-string-no-properties 2))))
1472 (when (string= "group" (match-string-no-properties 1))
1473 (setq group (match-string-no-properties 2)))
1474 (when (string= "expand-env" (match-string-no-properties 1))
1475 (setq expand-env (yas--read-lisp (match-string-no-properties 2)
1477 (when (string= "binding" (match-string-no-properties 1))
1478 (setq binding (match-string-no-properties 2)))))
1480 (buffer-substring-no-properties (point-min) (point-max))))
1481 (unless (or key binding)
1482 (setq key (and file (file-name-nondirectory file))))
1483 (when (eq type 'command)
1484 (setq template (yas--read-lisp (concat "(progn" template ")"))))
1486 (setq group (split-string group "\\.")))
1487 (list key template name condition group expand-env file binding uuid)))
1489 (defun yas--calculate-group (file)
1490 "Calculate the group for snippet file path FILE."
1491 (let* ((dominating-dir (locate-dominating-file file
1492 ".yas-make-groups"))
1493 (extra-path (and dominating-dir
1494 (file-relative-name file dominating-dir)))
1495 (extra-dir (and extra-path
1496 (file-name-directory extra-path)))
1497 (group (and extra-dir
1498 (replace-regexp-in-string "/"
1500 (directory-file-name extra-dir)))))
1503 (defun yas--subdirs (directory &optional filep)
1504 "Return subdirs or files of DIRECTORY according to FILEP."
1505 (cl-remove-if (lambda (file)
1506 (or (string-match "\\`\\."
1507 (file-name-nondirectory file))
1508 (string-match "\\`#.*#\\'"
1509 (file-name-nondirectory file))
1510 (string-match "~\\'"
1511 (file-name-nondirectory file))
1513 (file-directory-p file)
1514 (not (file-directory-p file)))))
1515 (directory-files directory t)))
1517 (defun yas--make-menu-binding (template)
1518 (let ((mode (yas--table-mode (yas--template-table template))))
1519 `(lambda () (interactive) (yas--expand-or-visit-from-menu ',mode ,(yas--template-uuid template)))))
1521 (defun yas--expand-or-visit-from-menu (mode uuid)
1522 (let* ((table (yas--table-get-create mode))
1523 (yas--current-template (and table
1524 (gethash uuid (yas--table-uuidhash table)))))
1525 (when yas--current-template
1526 (if yas-visit-from-menu
1527 (yas--visit-snippet-file-1 yas--current-template)
1528 (let ((where (if (region-active-p)
1529 (cons (region-beginning) (region-end))
1530 (cons (point) (point)))))
1531 (yas-expand-snippet (yas--template-content yas--current-template)
1534 (yas--template-expand-env yas--current-template)))))))
1536 (defun yas--key-from-desc (text)
1537 "Return a yasnippet key from a description string TEXT."
1538 (replace-regexp-in-string "\\(\\w+\\).*" "\\1" text))
1541 ;;; Popping up for keys and templates
1543 (defun yas--prompt-for-template (templates &optional prompt)
1544 "Interactively choose a template from the list TEMPLATES.
1546 TEMPLATES is a list of `yas--template'.
1548 Optional PROMPT sets the prompt to use."
1551 (sort templates #'(lambda (t1 t2)
1552 (< (length (yas--template-name t1))
1553 (length (yas--template-name t2))))))
1554 (some #'(lambda (fn)
1555 (funcall fn (or prompt "Choose a snippet: ")
1557 #'yas--template-name))
1558 yas-prompt-functions)))
1560 (defun yas--prompt-for-keys (keys &optional prompt)
1561 "Interactively choose a template key from the list KEYS.
1563 Optional PROMPT sets the prompt to use."
1565 (some #'(lambda (fn)
1566 (funcall fn (or prompt "Choose a snippet key: ") keys))
1567 yas-prompt-functions)))
1569 (defun yas--prompt-for-table (tables &optional prompt)
1570 "Interactively choose a table from the list TABLES.
1572 Optional PROMPT sets the prompt to use."
1574 (some #'(lambda (fn)
1575 (funcall fn (or prompt "Choose a snippet table: ")
1578 yas-prompt-functions)))
1580 (defun yas-x-prompt (prompt choices &optional display-fn)
1581 "Display choices in a x-window prompt."
1582 (when (and window-system choices)
1583 ;; Let window position be recalculated to ensure that
1584 ;; `posn-at-point' returns non-nil.
1588 (if (fboundp 'posn-at-point)
1589 (let ((x-y (posn-x-y (posn-at-point (point)))))
1590 (list (list (+ (car x-y) 10)
1595 ,@(mapcar* (lambda (c d) `(,(concat " " d) . ,c))
1597 (if display-fn (mapcar display-fn choices) choices)))))
1600 (defun yas-maybe-ido-prompt (prompt choices &optional display-fn)
1601 (when (bound-and-true-p ido-mode)
1602 (yas-ido-prompt prompt choices display-fn)))
1604 (defun yas-ido-prompt (prompt choices &optional display-fn)
1606 (yas-completing-prompt prompt choices display-fn #'ido-completing-read))
1608 (defun yas-dropdown-prompt (_prompt choices &optional display-fn)
1609 (when (fboundp 'dropdown-list)
1610 (let* ((formatted-choices
1611 (if display-fn (mapcar display-fn choices) choices))
1612 (n (dropdown-list formatted-choices)))
1613 (if n (nth n choices)
1616 (defun yas-completing-prompt (prompt choices &optional display-fn completion-fn)
1617 (let* ((formatted-choices
1618 (if display-fn (mapcar display-fn choices) choices))
1619 (chosen (funcall (or completion-fn #'completing-read)
1620 prompt formatted-choices
1621 nil 'require-match nil nil)))
1622 (if (eq choices formatted-choices)
1624 (nth (or (position chosen formatted-choices :test #'string=) 0)
1627 (defun yas-no-prompt (_prompt choices &optional _display-fn)
1631 ;;; Defining snippets
1632 ;; This consists of creating and registering `yas--template' objects in the
1636 (defvar yas--creating-compiled-snippets nil)
1638 (defun yas--define-snippets-1 (snippet snippet-table)
1639 "Helper for `yas-define-snippets'."
1640 ;; Update the appropriate table. Also takes care of adding the
1641 ;; key indicators in the templates menu entry, if any.
1642 (yas--update-template
1643 snippet-table (apply #'yas--define-snippets-2 snippet-table snippet)))
1645 (defun yas-define-snippets (mode snippets)
1646 "Define SNIPPETS for MODE.
1648 SNIPPETS is a list of snippet definitions, each taking the
1651 (KEY TEMPLATE NAME CONDITION GROUP EXPAND-ENV LOAD-FILE KEYBINDING UUID SAVE-FILE)
1653 Within these, only KEY and TEMPLATE are actually mandatory.
1655 TEMPLATE might be a Lisp form or a string, depending on whether
1656 this is a snippet or a snippet-command.
1658 CONDITION, EXPAND-ENV and KEYBINDING are Lisp forms, they have
1659 been `yas--read-lisp'-ed and will eventually be
1660 `yas--eval-lisp'-ed.
1662 The remaining elements are strings.
1664 FILE is probably of very little use if you're programatically
1667 UUID is the snippet's \"unique-id\". Loading a second snippet
1668 file with the same uuid would replace the previous snippet.
1670 You can use `yas--parse-template' to return such lists based on
1671 the current buffers contents."
1672 (if yas--creating-compiled-snippets
1673 (let ((print-length nil))
1674 (insert ";;; Snippet definitions:\n;;;\n")
1675 (dolist (snippet snippets)
1676 ;; Fill in missing elements with nil.
1677 (setq snippet (append snippet (make-list (- 10 (length snippet)) nil)))
1678 ;; Move LOAD-FILE to SAVE-FILE because we will load from the
1679 ;; compiled file, not LOAD-FILE.
1680 (let ((load-file (nth 6 snippet)))
1681 (setcar (nthcdr 6 snippet) nil)
1682 (setcar (nthcdr 9 snippet) load-file)))
1683 (insert (pp-to-string
1684 `(yas-define-snippets ',mode ',snippets)))
1687 (let ((snippet-table (yas--table-get-create mode))
1689 (dolist (snippet snippets)
1690 (setq template (yas--define-snippets-1 snippet
1695 ;;; Loading snippets from files
1697 (defun yas--template-get-file (template)
1698 "Return TEMPLATE's LOAD-FILE or SAVE-FILE."
1699 (or (yas--template-load-file template)
1700 (let ((file (yas--template-save-file template)))
1702 (yas--message 3 "%s has no load file, using save file, %s, instead."
1703 (yas--template-name template) file))
1706 (defun yas--load-yas-setup-file (file)
1707 (if (not yas--creating-compiled-snippets)
1709 (load file 'noerror (<= yas-verbosity 4))
1710 (let ((elfile (concat file ".el")))
1711 (when (file-exists-p elfile)
1712 (insert ";;; contents of the .yas-setup.el support file:\n;;;\n")
1713 (insert-file-contents elfile)
1714 (goto-char (point-max))))))
1716 (defun yas--define-parents (mode parents)
1717 "Add PARENTS to the list of MODE's parents."
1718 (puthash mode (remove-duplicates
1720 (gethash mode yas--parents)))
1723 (defun yas-load-directory (top-level-dir &optional use-jit interactive)
1724 "Load snippets in directory hierarchy TOP-LEVEL-DIR.
1726 Below TOP-LEVEL-DIR each directory should be a mode name.
1728 With prefix argument USE-JIT do jit-loading of snippets."
1730 (list (read-directory-name "Select the root directory: " nil nil t)
1731 current-prefix-arg t))
1732 (unless yas-snippet-dirs
1733 (setq yas-snippet-dirs top-level-dir))
1734 (let ((impatient-buffers))
1735 (dolist (dir (yas--subdirs top-level-dir))
1736 (let* ((major-mode-and-parents (yas--compute-major-mode-and-parents
1737 (concat dir "/dummy")))
1738 (mode-sym (car major-mode-and-parents))
1739 (parents (cdr major-mode-and-parents)))
1740 ;; Attention: The parents and the menus are already defined
1741 ;; here, even if the snippets are later jit-loaded.
1743 ;; * We need to know the parents at this point since entering a
1744 ;; given mode should jit load for its parents
1745 ;; immediately. This could be reviewed, the parents could be
1746 ;; discovered just-in-time-as well
1748 ;; * We need to create the menus here to support the `full'
1749 ;; option to `yas-use-menu' (all known snippet menus are shown to the user)
1751 (yas--define-parents mode-sym parents)
1752 (yas--menu-keymap-get-create mode-sym)
1753 (let ((fun `(lambda () ;; FIXME: Simulating lexical-binding.
1754 (yas--load-directory-1 ',dir ',mode-sym))))
1756 (yas--schedule-jit mode-sym fun)
1758 ;; Look for buffers that are already in `mode-sym', and so
1759 ;; need the new snippets immediately...
1762 (cl-loop for buffer in (buffer-list)
1763 do (with-current-buffer buffer
1764 (when (eq major-mode mode-sym)
1765 (yas--message 4 "Discovered there was already %s in %s" buffer mode-sym)
1766 (push buffer impatient-buffers)))))))
1767 ;; ...after TOP-LEVEL-DIR has been completely loaded, call
1768 ;; `yas--load-pending-jits' in these impatient buffers.
1770 (cl-loop for buffer in impatient-buffers
1771 do (with-current-buffer buffer (yas--load-pending-jits))))
1773 (yas--message 3 "Loaded snippets from %s." top-level-dir)))
1775 (defun yas--load-directory-1 (directory mode-sym)
1776 "Recursively load snippet templates from DIRECTORY."
1777 (if yas--creating-compiled-snippets
1778 (let ((output-file (expand-file-name ".yas-compiled-snippets.el"
1780 (with-temp-file output-file
1781 (insert (format ";;; Compiled snippets and support files for `%s'\n"
1783 (yas--load-directory-2 directory mode-sym)
1784 (insert (format ";;; Do not edit! File generated at %s\n"
1785 (current-time-string)))))
1787 (unless (file-exists-p (expand-file-name ".yas-skip" directory))
1788 (unless (and (load (expand-file-name ".yas-compiled-snippets" directory) 'noerror (<= yas-verbosity 3))
1789 (progn (yas--message 4 "Loaded compiled snippets from %s" directory) t))
1790 (yas--message 4 "Loading snippet files from %s" directory)
1791 (yas--load-directory-2 directory mode-sym)))))
1793 (defun yas--load-directory-2 (directory mode-sym)
1794 ;; Load .yas-setup.el files wherever we find them
1796 (yas--load-yas-setup-file (expand-file-name ".yas-setup" directory))
1797 (let* ((default-directory directory)
1799 ;; load the snippet files
1802 (dolist (file (yas--subdirs directory 'no-subdirs-just-files))
1803 (when (file-readable-p file)
1804 (insert-file-contents file nil nil nil t)
1805 (push (yas--parse-template file)
1808 (yas-define-snippets mode-sym
1810 ;; now recurse to a lower level
1812 (dolist (subdir (yas--subdirs directory))
1813 (yas--load-directory-2 subdir
1816 (defun yas--load-snippet-dirs (&optional nojit)
1817 "Reload the directories listed in `yas-snippet-dirs' or
1818 prompt the user to select one."
1820 (if (null yas-snippet-dirs)
1821 (call-interactively 'yas-load-directory)
1822 (when (member yas--default-user-snippets-dir yas-snippet-dirs)
1823 (make-directory yas--default-user-snippets-dir t))
1824 (dolist (directory (reverse (yas-snippet-dirs)))
1825 (cond ((file-directory-p directory)
1826 (yas-load-directory directory (not nojit))
1828 (yas--message 4 "Loaded %s" directory)
1829 (yas--message 4 "Prepared just-in-time loading for %s" directory)))
1831 (push (yas--message 0 "Check your `yas-snippet-dirs': %s is not a directory" directory) errors)))))
1834 (defun yas-reload-all (&optional no-jit interactive)
1835 "Reload all snippets and rebuild the YASnippet menu.
1837 When NO-JIT is non-nil force immediate reload of all known
1838 snippets under `yas-snippet-dirs', otherwise use just-in-time
1841 When called interactively, use just-in-time loading when given a
1843 (interactive (list (not current-prefix-arg) t))
1846 (snippet-editing-buffers
1847 (remove-if-not #'(lambda (buffer)
1848 (with-current-buffer buffer yas--editing-template))
1850 ;; Warn if there are buffers visiting snippets, since reloading will break
1851 ;; any on-line editing of those buffers.
1853 (when snippet-editing-buffers
1855 (if (y-or-n-p "Some buffers editing live snippets, close them and proceed with reload? ")
1856 (mapc #'kill-buffer snippet-editing-buffers)
1857 (yas--message 1 "Aborted reload...")
1859 ;; in a non-interactive use, at least set
1860 ;; `yas--editing-template' to nil, make it guess it next time around
1861 (mapc #'(lambda (buffer)
1862 (with-current-buffer buffer
1863 (kill-local-variable 'yas--editing-template)))
1866 ;; Empty all snippet tables and parenting info
1868 (setq yas--tables (make-hash-table))
1869 (setq yas--parents (make-hash-table))
1871 ;; Before killing `yas--menu-table' use its keys to cleanup the
1872 ;; mode menu parts of `yas--minor-mode-menu' (thus also cleaning
1873 ;; up `yas-minor-mode-map', which points to it)
1875 (maphash #'(lambda (menu-symbol _keymap)
1876 (define-key yas--minor-mode-menu (vector menu-symbol) nil))
1878 ;; Now empty `yas--menu-table' as well
1879 (setq yas--menu-table (make-hash-table))
1881 ;; Cancel all pending 'yas--scheduled-jit-loads'
1883 (setq yas--scheduled-jit-loads (make-hash-table))
1885 ;; Reload the directories listed in `yas-snippet-dirs' or prompt
1886 ;; the user to select one.
1888 (setq errors (yas--load-snippet-dirs no-jit))
1889 ;; Reload the direct keybindings
1891 (yas-direct-keymaps-reload)
1893 (run-hooks 'yas-after-reload-hook)
1894 (yas--message (if errors 2 3) "Reloaded everything%s...%s."
1895 (if no-jit "" " (snippets will load just-in-time)")
1896 (if errors " (some errors, check *Messages*)" "")))))
1898 (defvar yas-after-reload-hook nil
1899 "Hooks run after `yas-reload-all'.")
1901 (defun yas--load-pending-jits ()
1902 (dolist (mode (yas--modes-to-activate))
1903 (let ((funs (reverse (gethash mode yas--scheduled-jit-loads))))
1904 ;; must reverse to maintain coherence with `yas-snippet-dirs'
1906 (yas--message 4 "Loading for `%s', just-in-time: %s!" mode fun)
1908 (remhash mode yas--scheduled-jit-loads))))
1910 ;; (when (<= emacs-major-version 22)
1911 ;; (add-hook 'after-change-major-mode-hook 'yas--load-pending-jits))
1913 (defun yas--quote-string (string)
1914 "Escape and quote STRING.
1915 foo\"bar\\! -> \"foo\\\"bar\\\\!\""
1917 (replace-regexp-in-string "[\\\"]"
1923 ;;; Snippet compilation function
1925 (defun yas-compile-directory (top-level-dir)
1926 "Create .yas-compiled-snippets.el files under subdirs of TOP-LEVEL-DIR.
1928 This works by stubbing a few functions, then calling
1929 `yas-load-directory'."
1930 (interactive "DTop level snippet directory?")
1931 (let ((yas--creating-compiled-snippets t))
1932 (yas-load-directory top-level-dir nil)))
1934 (defun yas-recompile-all ()
1935 "Compile every dir in `yas-snippet-dirs'."
1937 (mapc #'yas-compile-directory (yas-snippet-dirs)))
1943 (defvar yas--scheduled-jit-loads (make-hash-table)
1944 "Alist of mode-symbols to forms to be evaled when `yas-minor-mode' kicks in.")
1946 (defun yas--schedule-jit (mode fun)
1947 (push fun (gethash mode yas--scheduled-jit-loads)))
1951 ;;; Some user level functions
1955 (message (concat "yasnippet (version "
1957 ") -- pluskid/joaotavora/npostavs")))
1960 ;;; Apropos snippet menu:
1962 ;; The snippet menu keymaps are stored by mode in hash table called
1963 ;; `yas--menu-table'. They are linked to the main menu in
1964 ;; `yas--menu-keymap-get-create' and are initially created empty,
1965 ;; reflecting the table hierarchy.
1967 ;; They can be populated in two mutually exclusive ways: (1) by
1968 ;; reading `yas--template-group', which in turn is populated by the "#
1969 ;; group:" directives of the snippets or the ".yas-make-groups" file
1970 ;; or (2) by using a separate `yas-define-menu' call, which declares a
1971 ;; menu structure based on snippets uuids.
1973 ;; Both situations are handled in `yas--update-template-menu', which
1974 ;; uses the predicate `yas--template-menu-managed-by-yas-define-menu'
1975 ;; that can tell between the two situations.
1979 ;; * if `yas-define-menu' is used it must run before
1980 ;; `yas-define-snippets' and the UUIDS must match, otherwise we get
1981 ;; duplicate entries. The `yas--template' objects are created in
1982 ;; `yas-define-menu', holding nothing but the menu entry,
1983 ;; represented by a pair of ((menu-item NAME :keys KEYS) TYPE) and
1984 ;; stored in `yas--template-menu-binding-pair'. The (menu-item ...)
1985 ;; part is then stored in the menu keymap itself which make the item
1986 ;; appear to the user. These limitations could probably be revised.
1988 ;; * The `yas--template-perm-group' slot is only used in
1989 ;; `yas-describe-tables'.
1991 (defun yas--template-menu-binding-pair-get-create (template &optional type)
1992 "Get TEMPLATE's menu binding or assign it a new one.
1994 TYPE may be `:stay', signaling this menu binding should be
1995 static in the menu."
1996 (or (yas--template-menu-binding-pair template)
1997 (let (;; (key (yas--template-key template))
1998 ;; (keybinding (yas--template-keybinding template))
2000 (setf (yas--template-menu-binding-pair template)
2001 (cons `(menu-item ,(or (yas--template-name template)
2002 (yas--template-uuid template))
2003 ,(yas--make-menu-binding template)
2006 (defun yas--template-menu-managed-by-yas-define-menu (template)
2007 "Non-nil if TEMPLATE's menu entry was included in a `yas-define-menu' call."
2008 (cdr (yas--template-menu-binding-pair template)))
2011 (defun yas--show-menu-p (mode)
2012 (cond ((eq yas-use-menu 'abbreviate)
2014 (mapcar #'(lambda (table)
2015 (yas--table-mode table))
2016 (yas--get-snippet-tables))))
2019 (defun yas--delete-from-keymap (keymap uuid)
2020 "Recursively delete items with UUID from KEYMAP and its submenus."
2022 ;; XXX: This used to skip any submenus named \"parent mode\"
2024 ;; First of all, recursively enter submenus, i.e. the tree is
2025 ;; searched depth first so that stale submenus can be found in the
2028 (mapc #'(lambda (item)
2029 (when (and (listp (cdr item))
2030 (keymapp (third (cdr item))))
2031 (yas--delete-from-keymap (third (cdr item)) uuid)))
2033 ;; Set the uuid entry to nil
2035 (define-key keymap (vector (make-symbol uuid)) nil)
2036 ;; Destructively modify keymap
2038 (setcdr keymap (delete-if #'(lambda (item)
2039 (or (null (cdr item))
2040 (and (keymapp (third (cdr item)))
2041 (null (cdr (third (cdr item)))))))
2044 (defun yas-define-menu (mode menu &optional omit-items)
2045 "Define a snippet menu for MODE according to MENU, omitting OMIT-ITEMS.
2047 MENU is a list, its elements can be:
2049 - (yas-item UUID) : Creates an entry the snippet identified with
2050 UUID. The menu entry for a snippet thus identified is
2051 permanent, i.e. it will never move (be reordered) in the menu.
2053 - (yas-separator) : Creates a separator
2055 - (yas-submenu NAME SUBMENU) : Creates a submenu with NAME,
2056 SUBMENU has the same form as MENU. NAME is also added to the
2057 list of groups of the snippets defined thereafter.
2059 OMIT-ITEMS is a list of snippet uuid's that will always be
2060 omitted from MODE's menu, even if they're manually loaded."
2061 (let* ((table (yas--table-get-create mode))
2062 (hash (yas--table-uuidhash table)))
2063 (yas--define-menu-1 table
2064 (yas--menu-keymap-get-create mode)
2067 (dolist (uuid omit-items)
2068 (let ((template (or (gethash uuid hash)
2070 (yas--make-template :table table
2073 (setf (yas--template-menu-binding-pair template) (cons nil :none))))))
2075 (defun yas--define-menu-1 (table menu-keymap menu uuidhash &optional group-list)
2076 "Helper for `yas-define-menu'."
2077 (dolist (e (reverse menu))
2078 (cond ((eq (first e) 'yas-item)
2079 (let ((template (or (gethash (second e) uuidhash)
2083 :perm-group group-list
2086 (define-key menu-keymap (vector (gensym))
2087 (car (yas--template-menu-binding-pair-get-create template :stay)))))
2088 ((eq (first e) 'yas-submenu)
2089 (let ((subkeymap (make-sparse-keymap)))
2090 (define-key menu-keymap (vector (gensym))
2091 `(menu-item ,(second e) ,subkeymap))
2092 (yas--define-menu-1 table
2096 (append group-list (list (second e))))))
2097 ((eq (first e) 'yas-separator)
2098 (define-key menu-keymap (vector (gensym))
2099 '(menu-item "----")))
2101 (yas--message 1 "Don't know anything about menu entry %s" (first e))))))
2103 (defun yas--define (mode key template &optional name condition group)
2104 "Define a snippet. Expanding KEY into TEMPLATE.
2106 NAME is a description to this template. Also update the menu if
2107 `yas-use-menu' is t. CONDITION is the condition attached to
2108 this snippet. If you attach a condition to a snippet, then it
2109 will only be expanded when the condition evaluated to non-nil."
2110 (yas-define-snippets mode
2111 (list (list key template name condition group))))
2113 (defun yas-hippie-try-expand (first-time?)
2114 "Integrate with hippie expand.
2116 Just put this function in `hippie-expand-try-functions-list'."
2117 (when yas-minor-mode
2118 (if (not first-time?)
2119 (let ((yas-fallback-behavior 'return-nil))
2125 ;;; Apropos condition-cache:
2130 (defvar yas--condition-cache-timestamp nil)
2131 (defmacro yas-define-condition-cache (func doc &rest body)
2132 "Define a function FUNC with doc DOC and body BODY.
2133 BODY is executed at most once every snippet expansion attempt, to check
2134 expansion conditions.
2136 It doesn't make any sense to call FUNC programatically."
2137 `(defun ,func () ,(if (and doc
2140 "\n\nFor use in snippets' conditions. Within each
2141 snippet-expansion routine like `yas-expand', computes actual
2142 value for the first time then always returns a cached value.")
2143 (setq body (cons doc body))
2145 (let ((timestamp-and-value (get ',func 'yas--condition-cache)))
2146 (if (equal (car timestamp-and-value) yas--condition-cache-timestamp)
2147 (cdr timestamp-and-value)
2148 (let ((new-value (progn
2151 (put ',func 'yas--condition-cache (cons yas--condition-cache-timestamp new-value))
2154 (defalias 'yas-expand 'yas-expand-from-trigger-key)
2155 (defun yas-expand-from-trigger-key (&optional field)
2156 "Expand a snippet before point.
2158 If no snippet expansion is possible, fall back to the behaviour
2159 defined in `yas-fallback-behavior'.
2161 Optional argument FIELD is for non-interactive use and is an
2162 object satisfying `yas--field-p' to restrict the expansion to."
2164 (setq yas--condition-cache-timestamp (current-time))
2165 (let (templates-and-pos)
2166 (unless (and yas-expand-only-for-last-commands
2167 (not (member last-command yas-expand-only-for-last-commands)))
2168 (setq templates-and-pos (if field
2170 (narrow-to-region (yas--field-start field)
2171 (yas--field-end field))
2172 (yas--templates-for-key-at-point))
2173 (yas--templates-for-key-at-point))))
2174 (if templates-and-pos
2175 (yas--expand-or-prompt-for-template
2176 (nth 0 templates-and-pos)
2177 ;; Delete snippet key and active region when expanding.
2178 (min (if (use-region-p) (region-beginning) most-positive-fixnum)
2179 (nth 1 templates-and-pos))
2180 (max (if (use-region-p) (region-end) most-negative-fixnum)
2181 (nth 2 templates-and-pos)))
2184 (defun yas-expand-from-keymap ()
2185 "Directly expand some snippets, searching `yas--direct-keymaps'.
2187 If expansion fails, execute the previous binding for this key"
2189 (setq yas--condition-cache-timestamp (current-time))
2190 (let* ((vec (subseq (this-command-keys-vector) (if current-prefix-arg
2191 (length (this-command-keys))
2193 (templates (mapcan #'(lambda (table)
2194 (yas--fetch table vec))
2195 (yas--get-snippet-tables))))
2197 (yas--expand-or-prompt-for-template templates)
2198 (let ((yas-fallback-behavior 'call-other-command))
2201 (defun yas--expand-or-prompt-for-template (templates &optional start end)
2202 "Expand one of TEMPLATES from START to END.
2204 Prompt the user if TEMPLATES has more than one element, else
2205 expand immediately. Common gateway for
2206 `yas-expand-from-trigger-key' and `yas-expand-from-keymap'."
2207 (let ((yas--current-template (or (and (rest templates) ;; more than one
2208 (yas--prompt-for-template (mapcar #'cdr templates)))
2210 (when yas--current-template
2211 (yas-expand-snippet (yas--template-content yas--current-template)
2214 (yas--template-expand-env yas--current-template)))))
2216 ;; Apropos the trigger key and the fallback binding:
2218 ;; When `yas-minor-mode-map' binds <tab>, that correctly overrides
2219 ;; org-mode's <tab>, for example and searching for fallbacks correctly
2220 ;; returns `org-cycle'. However, most other modes bind "TAB". TODO,
2221 ;; improve this explanation.
2223 (defun yas--fallback ()
2224 "Fallback after expansion has failed.
2226 Common gateway for `yas-expand-from-trigger-key' and
2227 `yas-expand-from-keymap'."
2228 (cond ((eq yas-fallback-behavior 'return-nil)
2231 ((eq yas-fallback-behavior 'yas--fallback)
2232 (error (concat "yasnippet fallback loop!\n"
2233 "This can happen when you bind `yas-expand' "
2234 "outside of the `yas-minor-mode-map'.")))
2235 ((eq yas-fallback-behavior 'call-other-command)
2236 (let* ((yas-fallback-behavior 'yas--fallback)
2237 ;; Also bind `yas-minor-mode' to prevent fallback
2238 ;; loops when other extensions use mechanisms similar
2239 ;; to `yas--keybinding-beyond-yasnippet'. (github #525
2242 (yas-minor-mode nil)
2243 (beyond-yasnippet (yas--keybinding-beyond-yasnippet)))
2244 (yas--message 4 "Falling back to %s" beyond-yasnippet)
2245 (assert (or (null beyond-yasnippet) (commandp beyond-yasnippet)))
2246 (setq this-command beyond-yasnippet)
2247 (when beyond-yasnippet
2248 (call-interactively beyond-yasnippet))))
2249 ((and (listp yas-fallback-behavior)
2250 (cdr yas-fallback-behavior)
2251 (eq 'apply (car yas-fallback-behavior)))
2252 (let ((command-or-fn (cadr yas-fallback-behavior))
2253 (args (cddr yas-fallback-behavior))
2254 (yas-fallback-behavior 'yas--fallback)
2255 (yas-minor-mode nil))
2257 (apply command-or-fn args)
2258 (when (commandp command-or-fn)
2259 (setq this-command command-or-fn)
2260 (call-interactively command-or-fn)))))
2262 ;; also return nil if all the other fallbacks have failed
2265 (defun yas--keybinding-beyond-yasnippet ()
2266 "Get current keys's binding as if YASsnippet didn't exist."
2267 (let* ((yas-minor-mode nil)
2268 (yas--direct-keymaps nil)
2269 (keys (this-single-command-keys)))
2270 (or (key-binding keys t)
2271 (key-binding (yas--fallback-translate-input keys) t))))
2273 (defun yas--fallback-translate-input (keys)
2274 "Emulate `read-key-sequence', at least what I think it does.
2276 Keys should be an untranslated key vector. Returns a translated
2277 vector of keys. FIXME not thoroughly tested."
2280 (while (< i (length keys))
2282 (translated local-function-key-map))
2283 (while (and (< j (length keys))
2285 (keymapp translated))
2286 (setq translated (cdr (assoc (aref keys j) (remove 'keymap translated)))
2288 (setq retval (vconcat retval (cond ((symbolp translated)
2290 ((vectorp translated)
2293 (substring keys i j)))))
2298 ;;; Utils for snippet development:
2300 (defun yas--all-templates (tables)
2301 "Get `yas--template' objects in TABLES, applicable for buffer and point.
2303 Honours `yas-choose-tables-first', `yas-choose-keys-first' and
2304 `yas-buffer-local-condition'"
2305 (when yas-choose-tables-first
2306 (setq tables (list (yas--prompt-for-table tables))))
2308 (if yas-choose-keys-first
2309 (let ((key (yas--prompt-for-keys
2310 (mapcan #'yas--table-all-keys tables))))
2312 (mapcan #'(lambda (table)
2313 (yas--fetch table key))
2315 (remove-duplicates (mapcan #'yas--table-templates tables)
2318 (defun yas--lookup-snippet-1 (name mode)
2319 "Get the snippet called NAME in MODE's tables."
2320 (let ((yas-choose-tables-first nil) ; avoid prompts
2321 (yas-choose-keys-first nil))
2322 (cl-find name (yas--all-templates
2323 (yas--get-snippet-tables mode))
2324 :key #'yas--template-name :test #'string=)))
2326 (defun yas-lookup-snippet (name &optional mode noerror)
2327 "Get the snippet content for the snippet NAME in MODE's tables.
2329 MODE defaults to the current buffer's `major-mode'. If NOERROR
2330 is non-nil, then don't signal an error if there isn't any snippet
2333 Honours `yas-buffer-local-condition'."
2334 (let ((snippet (yas--lookup-snippet-1 name mode)))
2336 (snippet (yas--template-content snippet))
2338 (t (error "No snippet named: %s" name)))))
2340 (defun yas-insert-snippet (&optional no-condition)
2341 "Choose a snippet to expand, pop-up a list of choices according
2342 to `yas-prompt-functions'.
2344 With prefix argument NO-CONDITION, bypass filtering of snippets
2347 (setq yas--condition-cache-timestamp (current-time))
2348 (let* ((yas-buffer-local-condition (or (and no-condition
2350 yas-buffer-local-condition))
2351 (templates (yas--all-templates (yas--get-snippet-tables)))
2352 (yas--current-template (and templates
2353 (or (and (rest templates) ;; more than one template for same key
2354 (yas--prompt-for-template templates))
2356 (where (if (region-active-p)
2357 (cons (region-beginning) (region-end))
2358 (cons (point) (point)))))
2359 (if yas--current-template
2360 (yas-expand-snippet (yas--template-content yas--current-template)
2363 (yas--template-expand-env yas--current-template))
2364 (yas--message 1 "No snippets can be inserted here!"))))
2366 (defun yas-visit-snippet-file ()
2367 "Choose a snippet to edit, selection like `yas-insert-snippet'.
2369 Only success if selected snippet was loaded from a file. Put the
2370 visited file in `snippet-mode'."
2372 (let* ((yas-buffer-local-condition 'always)
2373 (templates (yas--all-templates (yas--get-snippet-tables)))
2374 (template (and templates
2375 (or (yas--prompt-for-template templates
2376 "Choose a snippet template to edit: ")
2380 (yas--visit-snippet-file-1 template)
2381 (message "No snippets tables active!"))))
2383 (defun yas--visit-snippet-file-1 (template)
2384 "Helper for `yas-visit-snippet-file'."
2385 (let ((file (yas--template-get-file template)))
2386 (cond ((and file (file-readable-p file))
2387 (find-file-other-window file)
2389 (set (make-local-variable 'yas--editing-template) template))
2391 (message "Original file %s no longer exists!" file))
2393 (switch-to-buffer (format "*%s*"(yas--template-name template)))
2394 (let ((type 'snippet))
2395 (when (listp (yas--template-content template))
2396 (insert (format "# type: command\n"))
2397 (setq type 'command))
2398 (insert (format "# key: %s\n" (yas--template-key template)))
2399 (insert (format "# name: %s\n" (yas--template-name template)))
2400 (when (yas--template-keybinding template)
2401 (insert (format "# binding: %s\n" (yas--template-keybinding template))))
2402 (when (yas--template-expand-env template)
2403 (insert (format "# expand-env: %s\n" (yas--template-expand-env template))))
2404 (when (yas--template-condition template)
2405 (insert (format "# condition: %s\n" (yas--template-condition template))))
2407 (insert (if (eq type 'command)
2408 (pp-to-string (yas--template-content template))
2409 (yas--template-content template))))
2411 (set (make-local-variable 'yas--editing-template) template)))))
2413 (defun yas--guess-snippet-directories-1 (table)
2414 "Guess possible snippet subdirectories for TABLE."
2415 (cons (yas--table-name table)
2416 (mapcan #'(lambda (parent)
2417 (yas--guess-snippet-directories-1
2419 (yas--table-parents table))))
2421 (defun yas--guess-snippet-directories (&optional table)
2422 "Try to guess suitable directories based on the current active
2423 tables (or optional TABLE).
2425 Returns a list of elements (TABLE . DIRS) where TABLE is a
2426 `yas--table' object and DIRS is a list of all possible directories
2427 where snippets of table might exist."
2428 (let ((main-dir (car (or (yas-snippet-dirs)
2429 (setq yas-snippet-dirs
2430 (list yas--default-user-snippets-dir)))))
2431 (tables (if table (list table)
2432 (yas--get-snippet-tables))))
2433 ;; HACK! the snippet table created here is actually registered!
2435 (unless (or table (gethash major-mode yas--tables))
2436 (push (yas--table-get-create major-mode)
2439 (mapcar #'(lambda (table)
2441 (mapcar #'(lambda (subdir)
2442 (expand-file-name subdir main-dir))
2443 (yas--guess-snippet-directories-1 table))))
2446 (defun yas--make-directory-maybe (table-and-dirs &optional main-table-string)
2447 "Return a dir inside TABLE-AND-DIRS, prompts for creation if none exists."
2448 (or (some #'(lambda (dir) (when (file-directory-p dir) dir)) (cdr table-and-dirs))
2449 (let ((candidate (first (cdr table-and-dirs))))
2450 (unless (file-writable-p (file-name-directory candidate))
2451 (error (yas--format "%s is not writable." candidate)))
2452 (if (y-or-n-p (format "Guessed directory (%s) for%s%s table \"%s\" does not exist! Create? "
2454 (if (gethash (yas--table-mode (car table-and-dirs))
2458 (or main-table-string
2460 (yas--table-name (car table-and-dirs))))
2462 (make-directory candidate 'also-make-parents)
2463 ;; create the .yas-parents file here...
2466 (defun yas-new-snippet (&optional no-template)
2467 "Pops a new buffer for writing a snippet.
2469 Expands a snippet-writing snippet, unless the optional prefix arg
2470 NO-TEMPLATE is non-nil."
2472 (let ((guessed-directories (yas--guess-snippet-directories)))
2474 (switch-to-buffer "*new snippet*")
2476 (kill-all-local-variables)
2479 (set (make-local-variable 'yas--guessed-modes) (mapcar #'(lambda (d)
2480 (yas--table-mode (car d)))
2481 guessed-directories))
2482 (if (and (not no-template) yas-new-snippet-default)
2483 (yas-expand-snippet yas-new-snippet-default))))
2485 (defun yas--compute-major-mode-and-parents (file)
2486 "Given FILE, find the nearest snippet directory for a given mode.
2488 Returns a list (MODE-SYM PARENTS), the mode's symbol and a list
2489 representing one or more of the mode's parents.
2491 Note that MODE-SYM need not be the symbol of a real major mode,
2492 neither do the elements of PARENTS."
2493 (let* ((file-dir (and file
2494 (directory-file-name (or (some #'(lambda (special)
2495 (locate-dominating-file file special))
2499 (directory-file-name (file-name-directory file))))))
2500 (parents-file-name (concat file-dir "/.yas-parents"))
2501 (major-mode-name (and file-dir
2502 (file-name-nondirectory file-dir)))
2503 (major-mode-sym (or (and major-mode-name
2504 (intern major-mode-name))))
2505 (parents (when (file-readable-p parents-file-name)
2509 (insert-file-contents parents-file-name)
2510 (buffer-substring-no-properties (point-min)
2512 (when major-mode-sym
2513 (cons major-mode-sym (remove major-mode-sym parents)))))
2515 (defvar yas--editing-template nil
2516 "Supporting variable for `yas-load-snippet-buffer' and `yas--visit-snippet'.")
2518 (defvar yas--current-template nil
2519 "Holds the current template being expanded into a snippet.")
2521 (defvar yas--guessed-modes nil
2522 "List of guessed modes supporting `yas-load-snippet-buffer'.")
2524 (defun yas--read-table ()
2525 "Ask user for a snippet table, help with some guessing."
2526 (let ((prompt (if (and (featurep 'ido)
2528 'ido-completing-read 'completing-read)))
2529 (unless yas--guessed-modes
2530 (set (make-local-variable 'yas--guessed-modes)
2531 (or (yas--compute-major-mode-and-parents buffer-file-name))))
2533 (funcall prompt (format "Choose or enter a table (yas guesses %s): "
2534 (if yas--guessed-modes
2535 (first yas--guessed-modes)
2537 (mapcar #'symbol-name yas--guessed-modes)
2542 (if (first yas--guessed-modes)
2543 (symbol-name (first yas--guessed-modes)))))))
2545 (defun yas-load-snippet-buffer (table &optional interactive)
2546 "Parse and load current buffer's snippet definition into TABLE.
2547 TABLE is a symbol name passed to `yas--table-get-create'. When
2548 called interactively, prompt for the table name."
2549 (interactive (list (yas--read-table) t))
2551 ;; We have `yas--editing-template', this buffer's content comes from a
2552 ;; template which is already loaded and neatly positioned,...
2554 (yas--editing-template
2555 (yas--define-snippets-1 (yas--parse-template (yas--template-load-file yas--editing-template))
2556 (yas--template-table yas--editing-template)))
2557 ;; Try to use `yas--guessed-modes'. If we don't have that use the
2558 ;; value from `yas--compute-major-mode-and-parents'
2561 (unless yas--guessed-modes
2562 (set (make-local-variable 'yas--guessed-modes) (or (yas--compute-major-mode-and-parents buffer-file-name))))
2563 (let* ((table (yas--table-get-create table)))
2564 (set (make-local-variable 'yas--editing-template)
2565 (yas--define-snippets-1 (yas--parse-template buffer-file-name)
2568 (yas--message 3 "Snippet \"%s\" loaded for %s."
2569 (yas--template-name yas--editing-template)
2570 (yas--table-name (yas--template-table yas--editing-template)))))
2572 (defun yas-load-snippet-buffer-and-close (table &optional kill)
2573 "Load and save the snippet, then `quit-window' if saved.
2574 Loading is performed by `yas-load-snippet-buffer'. If the
2575 snippet is new, ask the user whether (and where) to save it. If
2576 the snippet already has a file, just save it.
2578 The prefix argument KILL is passed to `quit-window'.
2580 Don't use this from a Lisp program, call `yas-load-snippet-buffer'
2581 and `kill-buffer' instead."
2582 (interactive (list (yas--read-table) current-prefix-arg))
2583 (yas-load-snippet-buffer table t)
2584 (let ((file (yas--template-get-file yas--editing-template)))
2586 ;; Only offer to save this if it looks like a library or new
2587 ;; snippet (loaded from elisp, from a dir in `yas-snippet-dirs'
2588 ;; which is not the first, or from an unwritable file)
2591 (not (file-writable-p file))
2592 (and (cdr-safe yas-snippet-dirs)
2593 (not (string-prefix-p (expand-file-name (car yas-snippet-dirs)) file))))
2594 (y-or-n-p (yas--format "Looks like a library or new snippet. Save to new file? ")))
2595 (let* ((option (first (yas--guess-snippet-directories (yas--template-table yas--editing-template))))
2597 (yas--make-directory-maybe option))))
2599 (let ((default-file-name (or (and file (file-name-nondirectory file))
2600 (yas--template-name yas--editing-template))))
2601 (write-file (expand-file-name
2602 (read-file-name (format "File name to create in %s? " chosen)
2603 chosen default-file-name)
2605 (setf (yas--template-load-file yas--editing-template) buffer-file-name))))))
2606 (when buffer-file-name
2608 (quit-window kill)))
2610 (defun yas-tryout-snippet (&optional debug)
2611 "Test current buffer's snippet template in other buffer."
2613 (let* ((major-mode-and-parent (yas--compute-major-mode-and-parents buffer-file-name))
2614 (parsed (yas--parse-template))
2615 (test-mode (or (and (car major-mode-and-parent)
2616 (fboundp (car major-mode-and-parent))
2617 (car major-mode-and-parent))
2618 (first yas--guessed-modes)
2619 (intern (read-from-minibuffer (yas--format "Please input a mode: ")))))
2620 (yas--current-template
2623 (yas--make-template :table nil ;; no tables for ephemeral snippets
2625 :content (nth 1 parsed)
2626 :name (nth 2 parsed)
2627 :expand-env (nth 5 parsed)))))
2628 (cond (yas--current-template
2629 (let ((buffer-name (format "*testing snippet: %s*" (yas--template-name yas--current-template))))
2630 (kill-buffer (get-buffer-create buffer-name))
2631 (switch-to-buffer (get-buffer-create buffer-name))
2632 (setq buffer-undo-list nil)
2633 (condition-case nil (funcall test-mode) (error nil))
2635 (setq buffer-read-only nil)
2636 (yas-expand-snippet (yas--template-content yas--current-template)
2639 (yas--template-expand-env yas--current-template))
2641 (require 'yasnippet-debug nil t))
2642 (add-hook 'post-command-hook 'yas-debug-snippet-vars nil t))))
2644 (yas--message 1 "Cannot test snippet for unknown major mode")))))
2646 (defun yas-active-keys ()
2647 "Return all active trigger keys for current buffer and point."
2649 (remove-if-not #'stringp (mapcan #'yas--table-all-keys (yas--get-snippet-tables)))
2652 (defun yas--template-fine-group (template)
2653 (car (last (or (yas--template-group template)
2654 (yas--template-perm-group template)))))
2656 (defun yas-describe-tables (&optional choose)
2657 "Display snippets for each table."
2659 (let* ((by-name-hash (and choose
2660 (y-or-n-p "Show by namehash? ")))
2661 (buffer (get-buffer-create "*YASnippet tables*"))
2662 (active-tables (yas--get-snippet-tables))
2663 (remain-tables (let ((all))
2664 (maphash #'(lambda (_k v)
2665 (unless (find v active-tables)
2669 (table-lists (list active-tables remain-tables))
2670 (original-buffer (current-buffer))
2672 (yas--condition-cache-timestamp (current-time)))
2673 (with-current-buffer buffer
2674 (setq buffer-read-only nil)
2676 (cond ((not by-name-hash)
2677 (insert "YASnippet tables:\n")
2678 (while (and table-lists
2680 (dolist (table (car table-lists))
2681 (yas--describe-pretty-table table original-buffer))
2682 (setq table-lists (cdr table-lists))
2684 (yas--create-snippet-xrefs)
2685 (display-buffer buffer)
2686 (setq continue (and choose (y-or-n-p "Show also non-active tables? ")))))
2687 (yas--create-snippet-xrefs)
2691 (insert "\n\nYASnippet tables by NAMEHASH: \n")
2692 (dolist (table (append active-tables remain-tables))
2693 (insert (format "\nSnippet table `%s':\n\n" (yas--table-name table)))
2695 (maphash #'(lambda (k _v)
2697 (yas--table-hash table))
2699 (insert (format " key %s maps snippets: %s\n" key
2701 (maphash #'(lambda (k _v)
2703 (gethash key (yas--table-hash table)))
2706 (setq buffer-read-only t))
2707 (display-buffer buffer)))
2709 (defun yas--describe-pretty-table (table &optional original-buffer)
2710 (insert (format "\nSnippet table `%s'"
2711 (yas--table-name table)))
2712 (if (yas--table-parents table)
2713 (insert (format " parents: %s\n"
2714 (mapcar #'yas--table-name
2715 (yas--table-parents table))))
2717 (insert (make-string 100 ?-) "\n")
2718 (insert "group state name key binding\n")
2719 (let ((groups-hash (make-hash-table :test #'equal)))
2720 (maphash #'(lambda (_k v)
2721 (let ((group (or (yas--template-fine-group v)
2723 (when (yas--template-name v)
2725 (cons v (gethash group groups-hash))
2727 (yas--table-uuidhash table))
2729 #'(lambda (group templates)
2730 (setq group (truncate-string-to-width group 25 0 ? "..."))
2731 (insert (make-string 100 ?-) "\n")
2732 (dolist (p templates)
2733 (let* ((name (truncate-string-to-width (propertize (format "\\\\snippet `%s'" (yas--template-name p))
2737 (setq group (make-string (length group) ? ))))
2738 (condition-string (let ((condition (yas--template-condition p)))
2741 (with-current-buffer original-buffer
2742 (if (yas--eval-condition condition)
2746 (key-description-string (key-description (yas--template-keybinding p)))
2747 (template-key-padding (if (string= key-description-string "") nil ? )))
2749 condition-string " "
2750 name (if (string-match "\\.\\.\\.$" name)
2753 (truncate-string-to-width (or (yas--template-key p) "")
2754 15 0 template-key-padding "...")
2755 (or template-key-padding "")
2756 (truncate-string-to-width key-description-string
2763 ;;; User convenience functions, for using in `yas-key-syntaxes'
2765 (defun yas-try-key-from-whitespace (_start-point)
2766 "As `yas-key-syntaxes' element, look for whitespace delimited key.
2768 A newline will be considered whitespace even if the mode syntax
2769 marks it as something else (typically comment ender)."
2770 (skip-chars-backward "^[:space:]\n"))
2772 (defun yas-shortest-key-until-whitespace (_start-point)
2773 "Like `yas-longest-key-from-whitespace' but take the shortest key."
2774 (when (/= (skip-chars-backward "^[:space:]\n" (1- (point))) 0)
2777 (defun yas-longest-key-from-whitespace (start-point)
2778 "As `yas-key-syntaxes' element, look for longest key between point and whitespace.
2780 A newline will be considered whitespace even if the mode syntax
2781 marks it as something else (typically comment ender)."
2782 (if (= (point) start-point)
2783 (yas-try-key-from-whitespace start-point)
2785 (unless (<= start-point (1+ (point)))
2790 ;;; User convenience functions, for using in snippet definitions
2792 (defvar yas-modified-p nil
2793 "Non-nil if field has been modified by user or transformation.")
2795 (defvar yas-moving-away-p nil
2796 "Non-nil if user is about to exit field.")
2798 (defvar yas-text nil
2799 "Contains current field text.")
2801 (defun yas-substr (str pattern &optional subexp)
2802 "Search PATTERN in STR and return SUBEXPth match.
2804 If found, the content of subexp group SUBEXP (default 0) is
2805 returned, or else the original STR will be returned."
2806 (let ((grp (or subexp 0)))
2808 (if (string-match pattern str)
2809 (match-string-no-properties grp str)
2812 (defun yas-choose-value (&rest possibilities)
2813 "Prompt for a string in POSSIBILITIES and return it.
2815 The last element of POSSIBILITIES may be a list of strings."
2816 (unless (or yas-moving-away-p
2818 (let* ((last-link (last possibilities))
2819 (last-elem (car last-link)))
2820 (when (listp last-elem)
2821 (setcar last-link (car last-elem))
2822 (setcdr last-link (cdr last-elem))))
2823 (some #'(lambda (fn)
2824 (funcall fn "Choose: " possibilities))
2825 yas-prompt-functions)))
2827 (defun yas-key-to-value (alist)
2828 (unless (or yas-moving-away-p
2830 (let ((key (read-key-sequence "")))
2832 (or (cdr (find key alist :key #'car :test #'string=))
2835 (defun yas-throw (text)
2836 "Throw a yas--exception with TEXT as the reason."
2837 (throw 'yas--exception (cons 'yas--exception text)))
2839 (defun yas-verify-value (possibilities)
2840 "Verify that the current field value is in POSSIBILITIES.
2842 Otherwise throw exception."
2843 (when (and yas-moving-away-p (notany #'(lambda (pos) (string= pos yas-text)) possibilities))
2844 (yas-throw (yas--format "Field only allows %s" possibilities))))
2846 (defun yas-field-value (number)
2847 "Get the string for field with NUMBER.
2849 Use this in primary and mirror transformations to tget."
2850 (let* ((snippet (car (yas--snippets-at-point)))
2852 (yas--snippet-find-field snippet number))))
2854 (yas--field-text-for-display field))))
2857 "Return `yas-text' if that exists and is non-empty, else nil."
2859 (not (string= "" yas-text)))
2862 (defun yas-selected-text ()
2863 "Return `yas-selected-text' if that exists and is non-empty, else nil."
2864 (if (and yas-selected-text
2865 (not (string= "" yas-selected-text)))
2868 (defun yas--get-field-once (number &optional transform-fn)
2869 (unless yas-modified-p
2871 (funcall transform-fn (yas-field-value number))
2872 (yas-field-value number))))
2874 (defun yas-default-from-field (number)
2875 (unless yas-modified-p
2876 (yas-field-value number)))
2878 (defun yas-inside-string ()
2879 "Return non-nil if the point is inside a string according to font-lock."
2880 (equal 'font-lock-string-face (get-char-property (1- (point)) 'face)))
2882 (defun yas-unimplemented (&optional missing-feature)
2883 (if yas--current-template
2884 (if (y-or-n-p (format "This snippet is unimplemented (missing %s) Visit the snippet definition? "
2887 (yas--visit-snippet-file-1 yas--current-template))
2888 (message "No implementation. Missing %s" (or missing-feature "something"))))
2891 ;;; Snippet expansion and field management
2893 (defvar yas--active-field-overlay nil
2894 "Overlays the currently active field.")
2896 (defvar yas--field-protection-overlays nil
2897 "Two overlays protect the current active field.")
2899 (defvar yas-selected-text nil
2900 "The selected region deleted on the last snippet expansion.")
2902 (defvar yas--start-column nil
2903 "The column where the snippet expansion started.")
2905 (make-variable-buffer-local 'yas--active-field-overlay)
2906 (make-variable-buffer-local 'yas--field-protection-overlays)
2907 (put 'yas--active-field-overlay 'permanent-local t)
2908 (put 'yas--field-protection-overlays 'permanent-local t)
2910 (defstruct (yas--snippet (:constructor yas--make-snippet ()))
2916 (id (yas--snippet-next-id) :read-only t)
2917 (control-overlay nil)
2919 ;; stacked expansion: the `previous-active-field' slot saves the
2920 ;; active field where the child expansion took place
2921 previous-active-field
2924 (defstruct (yas--field (:constructor yas--make-field (number start end parent-field)))
2927 NUMBER is the field number.
2928 START and END are mostly buffer markers, but see \"apropos markers-to-points\".
2929 PARENT-FIELD is a `yas--field' this field is nested under, or nil.
2930 MIRRORS is a list of `yas--mirror's
2931 TRANSFORM is a lisp form.
2932 MODIFIED-P is a boolean set to true once user inputs text.
2933 NEXT is another `yas--field' or `yas--mirror' or `yas--exit'.
2944 (defstruct (yas--mirror (:constructor yas--make-mirror (start end transform)))
2947 START and END are mostly buffer markers, but see \"apropos markers-to-points\".
2948 TRANSFORM is a lisp form.
2949 PARENT-FIELD is a `yas--field' this mirror is nested under, or nil.
2950 NEXT is another `yas--field' or `yas--mirror' or `yas--exit'
2951 DEPTH is a count of how many nested mirrors can affect this mirror"
2958 (defstruct (yas--exit (:constructor yas--make-exit (marker)))
2962 (defun yas--apply-transform (field-or-mirror field &optional empty-on-nil-p)
2963 "Calculate transformed string for FIELD-OR-MIRROR from FIELD.
2965 If there is no transform for ht field, return nil.
2967 If there is a transform but it returns nil, return the empty
2968 string iff EMPTY-ON-NIL-P is true."
2969 (let* ((yas-text (yas--field-text-for-display field))
2970 (yas-modified-p (yas--field-modified-p field))
2971 (transform (if (yas--mirror-p field-or-mirror)
2972 (yas--mirror-transform field-or-mirror)
2973 (yas--field-transform field-or-mirror)))
2974 (start-point (if (yas--mirror-p field-or-mirror)
2975 (yas--mirror-start field-or-mirror)
2976 (yas--field-start field-or-mirror)))
2977 (transformed (and transform
2979 (goto-char start-point)
2980 (let ((ret (yas--eval-lisp transform)))
2981 (or ret (and empty-on-nil-p "")))))))
2984 (defsubst yas--replace-all (from to &optional text)
2985 "Replace all occurrences from FROM to TO.
2987 With optional string TEXT do it in that string."
2989 (replace-regexp-in-string (regexp-quote from) to text t t)
2990 (goto-char (point-min))
2991 (while (search-forward from nil t)
2992 (replace-match to t t text))))
2994 (defun yas--snippet-find-field (snippet number)
2995 (find-if #'(lambda (field)
2996 (eq number (yas--field-number field)))
2997 (yas--snippet-fields snippet)))
2999 (defun yas--snippet-sort-fields (snippet)
3000 "Sort the fields of SNIPPET in navigation order."
3001 (setf (yas--snippet-fields snippet)
3002 (sort (yas--snippet-fields snippet)
3003 #'yas--snippet-field-compare)))
3005 (defun yas--snippet-field-compare (field1 field2)
3006 "Compare FIELD1 and FIELD2.
3008 The field with a number is sorted first. If they both have a
3009 number, compare through the number. If neither have, compare
3010 through the field's start point"
3011 (let ((n1 (yas--field-number field1))
3012 (n2 (yas--field-number field2)))
3015 (or (zerop n2) (and (not (zerop n1))
3020 (< (yas--field-start field1)
3021 (yas--field-start field2))))))
3023 (defun yas--field-probably-deleted-p (snippet field)
3024 "Guess if SNIPPET's FIELD should be skipped."
3026 ;; field must be zero length
3028 (zerop (- (yas--field-start field) (yas--field-end field)))
3029 ;; field must have been modified
3031 (yas--field-modified-p field)
3034 ;; 1) it's a nested field
3036 (yas--field-parent-field field)
3037 ;; 2) ends just before the snippet end
3039 (and (eq field (car (last (yas--snippet-fields snippet))))
3040 (= (yas--field-start field) (overlay-end (yas--snippet-control-overlay snippet)))))
3041 ;; the field numbered 0, just before the exit marker, should
3044 (not (and (yas--field-number field)
3045 (zerop (yas--field-number field))))))
3047 (defun yas--snippets-at-point (&optional all-snippets)
3048 "Return a sorted list of snippets at point.
3050 The most recently-inserted snippets are returned first."
3052 (delq nil (delete-dups
3053 (mapcar (lambda (ov) (overlay-get ov 'yas--snippet))
3054 (if all-snippets (overlays-in (point-min) (point-max))
3055 (nconc (overlays-at (point))
3056 (overlays-at (1- (point))))))))
3058 (<= (yas--snippet-id s2) (yas--snippet-id s1)))))
3060 (defun yas-next-field-or-maybe-expand ()
3061 "Try to expand a snippet at a key before point.
3063 Otherwise delegate to `yas-next-field'."
3065 (if yas-triggers-in-field
3066 (let ((yas-fallback-behavior 'return-nil)
3067 (active-field (overlay-get yas--active-field-overlay 'yas--field)))
3069 (unless (yas-expand-from-trigger-key active-field)
3073 (defun yas-next-field-will-exit-p (&optional arg)
3074 "Return non-nil if (yas-next-field ARG) would exit the current snippet."
3075 (let ((snippet (car (yas--snippets-at-point)))
3076 (active (overlay-get yas--active-field-overlay 'yas--field)))
3078 (not (yas--find-next-field arg snippet active)))))
3080 (defun yas--find-next-field (n snippet active)
3081 "Return the Nth field after the ACTIVE one in SNIPPET."
3082 (let ((live-fields (cl-remove-if
3084 (and (not (eq field active))
3085 (yas--field-probably-deleted-p snippet field)))
3086 (yas--snippet-fields snippet))))
3087 (if (>= n 0) (nth n (memq active live-fields))
3088 (car (last (memq active (reverse live-fields)) (- n))))))
3090 (defun yas-next-field (&optional arg)
3091 "Navigate to the ARGth next field.
3093 If there's none, exit the snippet."
3095 (unless arg (setq arg 1))
3096 (let* ((snippet (car (yas--snippets-at-point)))
3097 (active-field (overlay-get yas--active-field-overlay 'yas--field))
3098 (target-field (yas--find-next-field arg snippet active-field)))
3099 ;; Apply transform to active field.
3101 (let ((yas-moving-away-p t))
3102 (when (yas--field-update-display active-field)
3103 (yas--update-mirrors snippet))))
3104 ;; Now actually move...
3106 (yas--move-to-field snippet target-field)
3107 (yas-exit-snippet snippet))))
3109 (defun yas--place-overlays (snippet field)
3110 "Correctly place overlays for SNIPPET's FIELD."
3111 (yas--make-move-field-protection-overlays snippet field)
3112 (yas--make-move-active-field-overlay snippet field))
3114 (defun yas--move-to-field (snippet field)
3115 "Update SNIPPET to move to field FIELD.
3117 Also create some protection overlays"
3118 (goto-char (yas--field-start field))
3119 (yas--place-overlays snippet field)
3120 (overlay-put yas--active-field-overlay 'yas--field field)
3121 (let ((number (yas--field-number field)))
3122 ;; check for the special ${0: ...} field
3123 (if (and number (zerop number))
3125 (set-mark (yas--field-end field))
3126 (setf (yas--snippet-force-exit snippet)
3127 (or (yas--field-transform field)
3129 ;; make this field active
3130 (setf (yas--snippet-active-field snippet) field)
3131 ;; primary field transform: first call to snippet transform
3132 (unless (yas--field-modified-p field)
3133 (if (yas--field-update-display field)
3134 (yas--update-mirrors snippet)
3135 (setf (yas--field-modified-p field) nil))))))
3137 (defun yas-prev-field ()
3138 "Navigate to prev field. If there's none, exit the snippet."
3140 (yas-next-field -1))
3142 (defun yas-abort-snippet (&optional snippet)
3144 (let ((snippet (or snippet
3145 (car (yas--snippets-at-point)))))
3147 (setf (yas--snippet-force-exit snippet) t))))
3149 (defun yas-exit-snippet (snippet)
3150 "Goto exit-marker of SNIPPET."
3151 (interactive (list (first (yas--snippets-at-point))))
3153 (setf (yas--snippet-force-exit snippet) t)
3154 (goto-char (if (yas--snippet-exit snippet)
3155 (yas--exit-marker (yas--snippet-exit snippet))
3156 (overlay-end (yas--snippet-control-overlay snippet))))))
3158 (defun yas-exit-all-snippets ()
3159 "Exit all snippets."
3161 (mapc #'(lambda (snippet)
3162 (yas-exit-snippet snippet)
3163 (yas--check-commit-snippet))
3164 (yas--snippets-at-point 'all-snippets)))
3167 ;;; Some low level snippet-routines:
3169 (defvar yas--inhibit-overlay-hooks nil
3170 "Bind this temporarily to non-nil to prevent running `yas--on-*-modification'.")
3172 (defvar yas-snippet-beg nil "Beginning position of the last snippet committed.")
3173 (defvar yas-snippet-end nil "End position of the last snippet committed.")
3175 (defun yas--commit-snippet (snippet)
3176 "Commit SNIPPET, but leave point as it is.
3178 This renders the snippet as ordinary text."
3180 (let ((control-overlay (yas--snippet-control-overlay snippet)))
3182 ;; Save the end of the moribund snippet in case we need to revive it
3183 ;; its original expansion.
3185 (when (and control-overlay
3186 (overlay-buffer control-overlay))
3187 (setq yas-snippet-beg (overlay-start control-overlay))
3188 (setq yas-snippet-end (overlay-end control-overlay))
3189 (delete-overlay control-overlay))
3191 (let ((yas--inhibit-overlay-hooks t))
3192 (when yas--active-field-overlay
3193 (delete-overlay yas--active-field-overlay))
3194 (when yas--field-protection-overlays
3195 (mapc #'delete-overlay yas--field-protection-overlays)))
3197 ;; stacked expansion: if the original expansion took place from a
3198 ;; field, make sure we advance it here at least to
3199 ;; `yas-snippet-end'...
3201 (let ((previous-field (yas--snippet-previous-active-field snippet)))
3202 (when (and yas-snippet-end previous-field)
3203 (yas--advance-end-maybe previous-field yas-snippet-end)))
3205 ;; Convert all markers to points,
3207 (yas--markers-to-points snippet)
3209 ;; Take care of snippet revival
3211 (if yas-snippet-revival
3212 (push `(apply yas--snippet-revive ,yas-snippet-beg ,yas-snippet-end ,snippet)
3214 ;; Dismember the snippet... this is useful if we get called
3215 ;; again from `yas--take-care-of-redo'....
3216 (setf (yas--snippet-fields snippet) nil)))
3218 (yas--message 3 "Snippet %s exited." (yas--snippet-id snippet)))
3220 (defun yas--safely-run-hooks (hook-var)
3221 (condition-case error
3222 (run-hooks hook-var)
3224 (yas--message 2 "%s error: %s" hook-var (error-message-string error)))))
3227 (defun yas--check-commit-snippet ()
3228 "Check if point exited the currently active field of the snippet.
3230 If so cleans up the whole snippet up."
3231 (let* ((snippets (yas--snippets-at-point 'all-snippets))
3232 (snippets-left snippets)
3233 (snippet-exit-transform))
3234 (dolist (snippet snippets)
3235 (let ((active-field (yas--snippet-active-field snippet)))
3236 (setq snippet-exit-transform (yas--snippet-force-exit snippet))
3237 (cond ((or snippet-exit-transform
3238 (not (and active-field (yas--field-contains-point-p active-field))))
3239 (setq snippets-left (delete snippet snippets-left))
3240 (setf (yas--snippet-force-exit snippet) nil)
3241 (yas--commit-snippet snippet))
3243 (or (not yas--active-field-overlay)
3244 (not (overlay-buffer yas--active-field-overlay))))
3246 ;; stacked expansion: this case is mainly for recent
3247 ;; snippet exits that place us back int the field of
3251 (yas--move-to-field snippet active-field)
3252 (yas--update-mirrors snippet)))
3255 (unless (or (null snippets) snippets-left)
3256 (if snippet-exit-transform
3257 (yas--eval-lisp-no-saves snippet-exit-transform))
3258 (yas--safely-run-hooks 'yas-after-exit-snippet-hook))))
3260 ;; Apropos markers-to-points:
3262 ;; This was found useful for performance reasons, so that an
3263 ;; excessive number of live markers aren't kept around in the
3264 ;; `buffer-undo-list'. However, in `markers-to-points', the
3265 ;; set-to-nil markers can't simply be discarded and replaced with
3266 ;; fresh ones in `points-to-markers'. The original marker that was
3267 ;; just set to nil has to be reused.
3269 ;; This shouldn't bring horrible problems with undo/redo, but it
3272 (defun yas--markers-to-points (snippet)
3273 "Convert all markers in SNIPPET to a cons (POINT . MARKER)
3274 where POINT is the original position of the marker and MARKER is
3275 the original marker object with the position set to nil."
3276 (dolist (field (yas--snippet-fields snippet))
3277 (let ((start (marker-position (yas--field-start field)))
3278 (end (marker-position (yas--field-end field))))
3279 (set-marker (yas--field-start field) nil)
3280 (set-marker (yas--field-end field) nil)
3281 (setf (yas--field-start field) (cons start (yas--field-start field)))
3282 (setf (yas--field-end field) (cons end (yas--field-end field))))
3283 (dolist (mirror (yas--field-mirrors field))
3284 (let ((start (marker-position (yas--mirror-start mirror)))
3285 (end (marker-position (yas--mirror-end mirror))))
3286 (set-marker (yas--mirror-start mirror) nil)
3287 (set-marker (yas--mirror-end mirror) nil)
3288 (setf (yas--mirror-start mirror) (cons start (yas--mirror-start mirror)))
3289 (setf (yas--mirror-end mirror) (cons end (yas--mirror-end mirror))))))
3290 (let ((snippet-exit (yas--snippet-exit snippet)))
3292 (let ((exit (marker-position (yas--exit-marker snippet-exit))))
3293 (set-marker (yas--exit-marker snippet-exit) nil)
3294 (setf (yas--exit-marker snippet-exit) (cons exit (yas--exit-marker snippet-exit)))))))
3296 (defun yas--points-to-markers (snippet)
3297 "Convert all cons (POINT . MARKER) in SNIPPET to markers.
3299 This is done by setting MARKER to POINT with `set-marker'."
3300 (dolist (field (yas--snippet-fields snippet))
3301 (setf (yas--field-start field) (set-marker (cdr (yas--field-start field))
3302 (car (yas--field-start field))))
3303 (setf (yas--field-end field) (set-marker (cdr (yas--field-end field))
3304 (car (yas--field-end field))))
3305 (dolist (mirror (yas--field-mirrors field))
3306 (setf (yas--mirror-start mirror) (set-marker (cdr (yas--mirror-start mirror))
3307 (car (yas--mirror-start mirror))))
3308 (setf (yas--mirror-end mirror) (set-marker (cdr (yas--mirror-end mirror))
3309 (car (yas--mirror-end mirror))))))
3310 (let ((snippet-exit (yas--snippet-exit snippet)))
3312 (setf (yas--exit-marker snippet-exit) (set-marker (cdr (yas--exit-marker snippet-exit))
3313 (car (yas--exit-marker snippet-exit)))))))
3315 (defun yas--field-contains-point-p (field &optional point)
3316 (let ((point (or point
3318 (and (>= point (yas--field-start field))
3319 (<= point (yas--field-end field)))))
3321 (defun yas--field-text-for-display (field)
3322 "Return the propertized display text for field FIELD."
3323 (buffer-substring (yas--field-start field) (yas--field-end field)))
3325 (defun yas--undo-in-progress ()
3326 "True if some kind of undo is in progress."
3327 (or undo-in-progress
3328 (eq this-command 'undo)
3329 (eq this-command 'redo)))
3331 (defun yas--make-control-overlay (snippet start end)
3332 "Create the control overlay that surrounds the snippet and
3334 (let ((overlay (make-overlay start
3339 (overlay-put overlay 'keymap yas-keymap)
3340 (overlay-put overlay 'priority 100)
3341 (overlay-put overlay 'yas--snippet snippet)
3344 (defun yas-skip-and-clear-or-delete-char (&optional field)
3345 "Clears unmodified field if at field start, skips to next tab.
3347 Otherwise deletes a character normally by calling `delete-char'."
3349 (let ((field (or field
3350 (and yas--active-field-overlay
3351 (overlay-buffer yas--active-field-overlay)
3352 (overlay-get yas--active-field-overlay 'yas--field)))))
3354 (not (yas--field-modified-p field))
3355 (eq (point) (marker-position (yas--field-start field))))
3356 (yas--skip-and-clear field)
3359 (call-interactively 'delete-char)))))
3361 (defun yas--skip-and-clear (field &optional from)
3362 "Deletes the region of FIELD and sets it's modified state to t.
3363 If given, FROM indicates position to start at instead of FIELD's beginning."
3364 ;; Just before skipping-and-clearing the field, mark its children
3365 ;; fields as modified, too. If the children have mirrors-in-fields
3366 ;; this prevents them from updating erroneously (we're skipping and
3369 (yas--mark-this-and-children-modified field)
3370 (unless (= (yas--field-start field) (yas--field-end field))
3371 (delete-region (or from (yas--field-start field)) (yas--field-end field))))
3373 (defun yas--mark-this-and-children-modified (field)
3374 (setf (yas--field-modified-p field) t)
3375 (let ((fom (yas--field-next field)))
3377 (yas--fom-parent-field fom))
3378 (when (and (eq (yas--fom-parent-field fom) field)
3380 (yas--mark-this-and-children-modified fom))
3381 (setq fom (yas--fom-next fom)))))
3383 (defun yas--make-move-active-field-overlay (snippet field)
3384 "Place the active field overlay in SNIPPET's FIELD.
3386 Move the overlay, or create it if it does not exit."
3387 (if (and yas--active-field-overlay
3388 (overlay-buffer yas--active-field-overlay))
3389 (move-overlay yas--active-field-overlay
3390 (yas--field-start field)
3391 (yas--field-end field))
3392 (setq yas--active-field-overlay
3393 (make-overlay (yas--field-start field)
3394 (yas--field-end field)
3396 (overlay-put yas--active-field-overlay 'priority 100)
3397 (overlay-put yas--active-field-overlay 'face 'yas-field-highlight-face)
3398 (overlay-put yas--active-field-overlay 'yas--snippet snippet)
3399 (overlay-put yas--active-field-overlay 'modification-hooks '(yas--on-field-overlay-modification))
3400 (overlay-put yas--active-field-overlay 'insert-in-front-hooks
3401 '(yas--on-field-overlay-modification))
3402 (overlay-put yas--active-field-overlay 'insert-behind-hooks
3403 '(yas--on-field-overlay-modification))))
3405 (defun yas--skip-and-clear-field-p (field beg _end length)
3406 "Tell if newly modified FIELD should be cleared and skipped.
3407 BEG, END and LENGTH like overlay modification hooks."
3408 (and (= length 0) ; A 0 pre-change length indicates insertion.
3409 (= beg (yas--field-start field)) ; Insertion at field start?
3410 (not (yas--field-modified-p field))))
3412 (defun yas--on-field-overlay-modification (overlay after? beg end &optional length)
3413 "Clears the field and updates mirrors, conditionally.
3415 Only clears the field if it hasn't been modified and point is at
3416 field start. This hook does nothing if an undo is in progress."
3417 (unless (or (not after?)
3418 yas--inhibit-overlay-hooks
3419 (not (overlayp yas--active-field-overlay)) ; Avoid Emacs bug #21824.
3420 (yas--undo-in-progress))
3421 (let* ((inhibit-modification-hooks t)
3422 (field (overlay-get overlay 'yas--field))
3423 (snippet (overlay-get yas--active-field-overlay 'yas--snippet)))
3424 (when (yas--skip-and-clear-field-p field beg end length)
3425 ;; We delete text starting from the END of insertion.
3426 (yas--skip-and-clear field end))
3427 (setf (yas--field-modified-p field) t)
3428 (yas--advance-end-maybe field (overlay-end overlay))
3430 (yas--field-update-display field))
3431 (yas--update-mirrors snippet))))
3433 ;;; Apropos protection overlays:
3435 ;; These exist for nasty users who will try to delete parts of the
3436 ;; snippet outside the active field. Actual protection happens in
3437 ;; `yas--on-protection-overlay-modification'.
3439 ;; As of github #537 this no longer inhibits the command by issuing an
3440 ;; error: all the snippets at point, including nested snippets, are
3441 ;; automatically commited and the current command can proceed.
3443 (defun yas--make-move-field-protection-overlays (snippet field)
3444 "Place protection overlays surrounding SNIPPET's FIELD.
3446 Move the overlays, or create them if they do not exit."
3447 (let ((start (yas--field-start field))
3448 (end (yas--field-end field)))
3449 ;; First check if the (1+ end) is contained in the buffer,
3450 ;; otherwise we'll have to do a bit of cheating and silently
3451 ;; insert a newline. the `(1+ (buffer-size))' should prevent this
3452 ;; when using stacked expansion
3454 (when (< (buffer-size) end)
3456 (let ((yas--inhibit-overlay-hooks t))
3457 (goto-char (point-max))
3459 ;; go on to normal overlay creation/moving
3461 (cond ((and yas--field-protection-overlays
3462 (every #'overlay-buffer yas--field-protection-overlays))
3463 (move-overlay (first yas--field-protection-overlays) (1- start) start)
3464 (move-overlay (second yas--field-protection-overlays) end (1+ end)))
3466 (setq yas--field-protection-overlays
3467 (list (make-overlay (1- start) start nil t nil)
3468 (make-overlay end (1+ end) nil t nil)))
3469 (dolist (ov yas--field-protection-overlays)
3470 (overlay-put ov 'face 'yas--field-debug-face)
3471 (overlay-put ov 'yas--snippet snippet)
3472 ;; (overlay-put ov 'evaporate t)
3473 (overlay-put ov 'modification-hooks '(yas--on-protection-overlay-modification)))))))
3475 (defun yas--on-protection-overlay-modification (_overlay after? beg end &optional length)
3476 "Commit the snippet if the protection overlay is being killed."
3477 (unless (or yas--inhibit-overlay-hooks
3479 (= length (- end beg)) ; deletion or insertion
3480 (yas--undo-in-progress))
3481 (let ((snippets (yas--snippets-at-point)))
3482 (yas--message 2 "Committing snippets. Action would destroy a protection overlay.")
3483 (cl-loop for snippet in snippets
3484 do (yas--commit-snippet snippet)))))
3486 (add-to-list 'debug-ignored-errors "^Exit the snippet first!$")
3489 ;;; Snippet expansion and "stacked" expansion:
3491 ;; Stacked expansion is when you try to expand a snippet when already
3492 ;; inside a snippet expansion.
3494 ;; The parent snippet does not run its fields modification hooks
3495 ;; (`yas--on-field-overlay-modification' and
3496 ;; `yas--on-protection-overlay-modification') while the child snippet
3497 ;; is active. This means, among other things, that the mirrors of the
3498 ;; parent snippet are not updated, this only happening when one exits
3499 ;; the child snippet.
3501 ;; Unfortunately, this also puts some ugly (and not fully-tested)
3502 ;; bits of code in `yas-expand-snippet' and
3503 ;; `yas--commit-snippet'. I've tried to mark them with "stacked
3506 ;; This was thought to be safer in an undo/redo perspective, but
3507 ;; maybe the correct implementation is to make the globals
3508 ;; `yas--active-field-overlay' and `yas--field-protection-overlays' be
3509 ;; snippet-local and be active even while the child snippet is
3510 ;; running. This would mean a lot of overlay modification hooks
3511 ;; running, but if managed correctly (including overlay priorities)
3512 ;; they should account for all situations...
3514 (defun yas-expand-snippet (content &optional start end expand-env)
3515 "Expand snippet CONTENT at current point.
3517 Text between START and END will be deleted before inserting
3518 template. EXPAND-ENV is a list of (SYM VALUE) let-style dynamic bindings
3519 considered when expanding the snippet."
3520 (cl-assert (and yas-minor-mode
3521 (memq 'yas--post-command-handler post-command-hook))
3523 "[yas] `yas-expand-snippet' needs properly setup `yas-minor-mode'")
3524 (run-hooks 'yas-before-expand-snippet-hook)
3527 (let* ((yas-selected-text (or yas-selected-text
3528 (and (region-active-p)
3529 (buffer-substring-no-properties (region-beginning)
3532 (and (region-active-p)
3536 (and (region-active-p)
3539 (to-delete (and start
3541 (buffer-substring-no-properties start end)))
3544 (setq yas--indent-original-column (current-column))
3545 ;; Delete the region to delete, this *does* get undo-recorded.
3547 (when (and to-delete
3549 (delete-region start end))
3551 (cond ((listp content)
3552 ;; x) This is a snippet-command
3554 (yas--eval-lisp-no-saves content))
3556 ;; x) This is a snippet-snippet :-)
3558 ;; Narrow the region down to the content, shoosh the
3559 ;; `buffer-undo-list', and create the snippet, the new
3560 ;; snippet updates its mirrors once, so we are left with
3561 ;; some plain text. The undo action for deleting this
3562 ;; plain text will get recorded at the end.
3564 ;; stacked expansion: also shoosh the overlay modification hooks
3565 (let ((buffer-undo-list t))
3566 ;; snippet creation might evaluate users elisp, which
3567 ;; might generate errors, so we have to be ready to catch
3568 ;; them mostly to make the undo information
3570 (setq yas--start-column (current-column))
3571 (let ((yas--inhibit-overlay-hooks t)
3572 ;; Avoid major-mode's syntax propertizing function,
3573 ;; since we mess with the syntax-table and also
3574 ;; insert things that are not valid in the
3575 ;; major-mode language syntax anyway.
3576 (syntax-propertize-function nil))
3579 (eval `(let* ,expand-env
3581 (yas--snippet-create start (point))))
3583 (yas--snippet-create start (point)))))
3584 ;; Invalidate any syntax-propertizing done while `syntax-propertize-function' was nil
3585 (syntax-ppss-flush-cache start))
3587 ;; stacked-expansion: This checks for stacked expansion, save the
3588 ;; `yas--previous-active-field' and advance its boundary.
3590 (let ((existing-field (and yas--active-field-overlay
3591 (overlay-buffer yas--active-field-overlay)
3592 (overlay-get yas--active-field-overlay 'yas--field))))
3593 (when existing-field
3594 (setf (yas--snippet-previous-active-field snippet) existing-field)
3595 (yas--advance-end-maybe existing-field (overlay-end yas--active-field-overlay))))
3597 ;; Exit the snippet immediately if no fields
3599 (unless (yas--snippet-fields snippet)
3600 (yas-exit-snippet snippet))
3602 ;; Push two undo actions: the deletion of the inserted contents of
3603 ;; the new snippet (without the "key") followed by an apply of
3604 ;; `yas--take-care-of-redo' on the newly inserted snippet boundaries
3606 ;; A small exception, if `yas-also-auto-indent-first-line'
3607 ;; is t and `yas--indent' decides to indent the line to a
3608 ;; point before the actual expansion point, undo would be
3609 ;; messed up. We call the early point "newstart"". case,
3610 ;; and attempt to fix undo.
3612 (let ((newstart (overlay-start (yas--snippet-control-overlay snippet)))
3613 (end (overlay-end (yas--snippet-control-overlay snippet))))
3614 (when (< newstart start)
3615 (push (cons (make-string (- start newstart) ? ) newstart) buffer-undo-list))
3616 (push (cons newstart end) buffer-undo-list)
3617 (push `(apply yas--take-care-of-redo ,start ,end ,snippet)
3619 ;; Now, schedule a move to the first field
3621 (let ((first-field (car (yas--snippet-fields snippet))))
3623 (sit-for 0) ;; fix issue 125
3624 (yas--move-to-field snippet first-field)))
3625 (yas--message 4 "snippet expanded.")
3628 (defun yas--take-care-of-redo (_beg _end snippet)
3629 "Commits SNIPPET, which in turn pushes an undo action for reviving it.
3631 Meant to exit in the `buffer-undo-list'."
3632 ;; slightly optimize: this action is only needed for snippets with
3633 ;; at least one field
3634 (when (yas--snippet-fields snippet)
3635 (yas--commit-snippet snippet)))
3637 (defun yas--snippet-revive (beg end snippet)
3638 "Revives SNIPPET and creates a control overlay from BEG to END.
3640 BEG and END are, we hope, the original snippets boundaries.
3641 All the markers/points exiting existing inside SNIPPET should point
3642 to their correct locations *at the time the snippet is revived*.
3644 After revival, push the `yas--take-care-of-redo' in the
3646 ;; Reconvert all the points to markers
3648 (yas--points-to-markers snippet)
3649 ;; When at least one editable field existed in the zombie snippet,
3650 ;; try to revive the whole thing...
3652 (let ((target-field (or (yas--snippet-active-field snippet)
3653 (car (yas--snippet-fields snippet)))))
3655 (setf (yas--snippet-control-overlay snippet) (yas--make-control-overlay snippet beg end))
3656 (overlay-put (yas--snippet-control-overlay snippet) 'yas--snippet snippet)
3658 (yas--move-to-field snippet target-field)
3660 (push `(apply yas--take-care-of-redo ,beg ,end ,snippet)
3661 buffer-undo-list))))
3663 (defun yas--snippet-create (begin end)
3664 "Create a snippet from a template inserted at BEGIN to END.
3666 Returns the newly created snippet."
3668 (narrow-to-region begin end)
3669 (let ((snippet (yas--make-snippet)))
3671 (yas--snippet-parse-create snippet)
3673 ;; Sort and link each field
3674 (yas--snippet-sort-fields snippet)
3676 ;; Create keymap overlay for snippet
3677 (setf (yas--snippet-control-overlay snippet)
3678 (yas--make-control-overlay snippet (point-min) (point-max)))
3681 (goto-char (point-max))
3686 ;;; Apropos adjacencies and "fom's":
3688 ;; Once the $-constructs bits like "$n" and "${:n" are deleted in the
3689 ;; recently expanded snippet, we might actually have many fields,
3690 ;; mirrors (and the snippet exit) in the very same position in the
3691 ;; buffer. Therefore we need to single-link the
3692 ;; fields-or-mirrors-or-exit (which I have abbreviated to "fom")
3693 ;; according to their original positions in the buffer.
3695 ;; Then we have operation `yas--advance-end-maybe' and
3696 ;; `yas--advance-start-maybe', which conditionally push the starts and
3697 ;; ends of these foms down the chain.
3699 ;; This allows for like the printf with the magic ",":
3701 ;; printf ("${1:%s}\\n"${1:$(if (string-match "%" text) "," "\);")} \
3702 ;; $2${1:$(if (string-match "%" text) "\);" "")}$0
3704 (defun yas--fom-start (fom)
3705 (cond ((yas--field-p fom)
3706 (yas--field-start fom))
3707 ((yas--mirror-p fom)
3708 (yas--mirror-start fom))
3710 (yas--exit-marker fom))))
3712 (defun yas--fom-end (fom)
3713 (cond ((yas--field-p fom)
3714 (yas--field-end fom))
3715 ((yas--mirror-p fom)
3716 (yas--mirror-end fom))
3718 (yas--exit-marker fom))))
3720 (defun yas--fom-next (fom)
3721 (cond ((yas--field-p fom)
3722 (yas--field-next fom))
3723 ((yas--mirror-p fom)
3724 (yas--mirror-next fom))
3726 (yas--exit-next fom))))
3728 (defun yas--fom-parent-field (fom)
3729 (cond ((yas--field-p fom)
3730 (yas--field-parent-field fom))
3731 ((yas--mirror-p fom)
3732 (yas--mirror-parent-field fom))
3736 (defun yas--calculate-adjacencies (snippet)
3737 "Calculate adjacencies for fields or mirrors of SNIPPET.
3739 This is according to their relative positions in the buffer, and
3740 has to be called before the $-constructs are deleted."
3741 (let* ((fom-set-next-fom
3742 (lambda (fom nextfom)
3743 (cond ((yas--field-p fom)
3744 (setf (yas--field-next fom) nextfom))
3745 ((yas--mirror-p fom)
3746 (setf (yas--mirror-next fom) nextfom))
3748 (setf (yas--exit-next fom) nextfom)))))
3751 (if (= (yas--fom-start fom2) (yas--fom-start fom1))
3752 (yas--mirror-p fom2)
3753 (>= (yas--fom-start fom2) (yas--fom-start fom1)))))
3754 (link-foms fom-set-next-fom))
3755 ;; make some yas--field, yas--mirror and yas--exit soup
3757 (when (yas--snippet-exit snippet)
3758 (push (yas--snippet-exit snippet) soup))
3759 (dolist (field (yas--snippet-fields snippet))
3761 (dolist (mirror (yas--field-mirrors field))
3762 (push mirror soup)))
3764 (sort soup compare-fom-begs))
3766 (reduce link-foms soup)))))
3768 (defun yas--calculate-mirrors-in-fields (snippet mirror)
3769 "Attempt to assign a parent field of SNIPPET to the mirror MIRROR.
3771 Use the tightest containing field if more than one field contains
3772 the mirror. Intended to be called *before* the dollar-regions are
3774 (let ((min (point-min))
3776 (dolist (field (yas--snippet-fields snippet))
3777 (when (and (<= (yas--field-start field) (yas--mirror-start mirror))
3778 (<= (yas--mirror-end mirror) (yas--field-end field))
3779 (< min (yas--field-start field))
3780 (< (yas--field-end field) max))
3781 (setq min (yas--field-start field)
3782 max (yas--field-end field))
3783 (setf (yas--mirror-parent-field mirror) field)))))
3785 (defun yas--advance-end-maybe (fom newend)
3786 "Maybe advance FOM's end to NEWEND if it needs it.
3790 * call `yas--advance-start-maybe' on FOM's next fom.
3792 * in case FOM is field call `yas--advance-end-maybe' on its parent
3795 Also, if FOM is an exit-marker, always call
3796 `yas--advance-start-maybe' on its next fom. This is because
3797 exit-marker have identical start and end markers."
3798 (cond ((and fom (< (yas--fom-end fom) newend))
3799 (set-marker (yas--fom-end fom) newend)
3800 (yas--advance-start-maybe (yas--fom-next fom) newend)
3801 (yas--advance-end-of-parents-maybe (yas--fom-parent-field fom) newend))
3803 (yas--advance-start-maybe (yas--fom-next fom) newend))))
3805 (defun yas--advance-start-maybe (fom newstart)
3806 "Maybe advance FOM's start to NEWSTART if it needs it.
3808 If it does, also call `yas--advance-end-maybe' on FOM."
3809 (when (and fom (< (yas--fom-start fom) newstart))
3810 (set-marker (yas--fom-start fom) newstart)
3811 (yas--advance-end-maybe fom newstart)))
3813 (defun yas--advance-end-of-parents-maybe (field newend)
3814 "Like `yas--advance-end-maybe' but for parent fields.
3816 Only works for fields and doesn't care about the start of the
3817 next FOM. Works its way up recursively for parents of parents."
3819 (< (yas--field-end field) newend))
3820 (set-marker (yas--field-end field) newend)
3821 (yas--advance-end-of-parents-maybe (yas--field-parent-field field) newend)))
3823 (defvar yas--dollar-regions nil
3824 "When expanding the snippet the \"parse-create\" functions add
3825 cons cells to this var.")
3827 (defvar yas--backquote-markers-and-strings nil
3828 "List of (MARKER . STRING) marking where the values from
3829 backquoted Lisp expressions should be inserted at the end of
3832 (defvar yas--indent-markers nil
3833 "List of markers for manual indentation.")
3835 (defun yas--snippet-parse-create (snippet)
3836 "Parse a recently inserted snippet template, creating all
3837 necessary fields, mirrors and exit points.
3839 Meant to be called in a narrowed buffer, does various passes"
3840 (let ((parse-start (point)))
3841 ;; Reset the yas--dollar-regions
3843 (setq yas--dollar-regions nil)
3844 ;; protect just the backquotes
3846 (yas--protect-escapes nil '(?`))
3847 ;; replace all backquoted expressions
3849 (goto-char parse-start)
3850 (yas--save-backquotes)
3851 ;; protect escaped characters
3853 (yas--protect-escapes)
3854 ;; Parse indent markers: `$>'.
3855 (goto-char parse-start)
3856 (yas--indent-parse-create snippet)
3857 ;; parse fields with {}
3859 (goto-char parse-start)
3860 (yas--field-parse-create snippet)
3861 ;; parse simple mirrors and fields
3863 (goto-char parse-start)
3864 (yas--simple-mirror-parse-create snippet)
3865 ;; parse mirror transforms
3867 (goto-char parse-start)
3868 (yas--transform-mirror-parse-create snippet)
3869 ;; calculate adjacencies of fields and mirrors
3871 (yas--calculate-adjacencies snippet)
3872 ;; Delete $-constructs
3876 (yas--delete-regions yas--dollar-regions))
3877 ;; Make sure to do this insertion *after* deleting the dollar
3878 ;; regions, otherwise we invalidate the calculated positions of
3879 ;; all the fields following $0.
3880 (let ((exit (yas--snippet-exit snippet)))
3881 (goto-char (if exit (yas--exit-marker exit) (point-max))))
3882 (when (eq yas-wrap-around-region 'cua)
3883 (setq yas-wrap-around-region ?0))
3884 (cond ((and yas-wrap-around-region yas-selected-text)
3885 (insert yas-selected-text))
3886 ((and (characterp yas-wrap-around-region)
3887 (get-register yas-wrap-around-region))
3888 (insert (prog1 (get-register yas-wrap-around-region)
3889 (set-register yas-wrap-around-region nil)))))
3890 ;; restore backquoted expression values
3892 (yas--restore-backquotes)
3895 (goto-char parse-start)
3896 (yas--restore-escapes)
3897 ;; update mirrors for the first time
3899 (yas--update-mirrors snippet)
3900 ;; indent the best we can
3902 (goto-char parse-start)
3903 (yas--indent snippet)))
3905 (defun yas--indent-region (from to snippet)
3906 "Indent the lines between FROM and TO with `indent-according-to-mode'.
3907 The SNIPPET's markers are preserved."
3908 ;;; Apropos indenting problems....
3910 ;; `indent-according-to-mode' uses whatever `indent-line-function'
3911 ;; is available. Some implementations of these functions delete text
3912 ;; before they insert. If there happens to be a marker just after
3913 ;; the text being deleted, the insertion actually happens after the
3914 ;; marker, which misplaces it.
3916 ;; This would also happen if we had used overlays with the
3917 ;; `front-advance' property set to nil.
3919 ;; This is why I have these `trouble-markers', they are the ones at
3920 ;; the first non-whitespace char at the line. After indentation
3921 ;; takes place we should be at the correct to restore them. All
3922 ;; other non-trouble-markers should have been *pushed* and don't
3923 ;; need special attention.
3924 (let* ((snippet-markers (yas--collect-snippet-markers snippet))
3925 (to (set-marker (make-marker) to)))
3930 ;; Indent each non-empty line.
3931 (cl-loop if (/= (line-beginning-position) (line-end-position)) do
3932 (back-to-indentation)
3933 (let ((trouble-markers ; The markers at (point).
3934 (cl-remove (point) snippet-markers :test #'/=)))
3936 (indent-according-to-mode)
3937 (dolist (marker trouble-markers)
3938 (set-marker marker (point)))))
3939 while (and (zerop (forward-line 1))
3940 (< (point) to)))))))
3942 (defvar yas--indent-original-column nil)
3943 (defun yas--indent (snippet)
3944 ;; Indent lines that had indent markers (`$>') on them.
3946 (dolist (marker yas--indent-markers)
3947 (unless (eq yas-indent-line 'auto)
3949 (yas--indent-region (line-beginning-position)
3952 ;; Finished with this marker.
3953 (set-marker marker nil))
3954 (setq yas--indent-markers nil))
3955 ;; Now do stuff for `fixed' and `auto'.
3957 (cond ((eq yas-indent-line 'fixed)
3958 (while (and (zerop (forward-line))
3959 (zerop (current-column)))
3960 (indent-to-column yas--indent-original-column)))
3961 ((eq yas-indent-line 'auto)
3962 (let ((end (set-marker (make-marker) (point-max))))
3963 (unless yas-also-auto-indent-first-line
3965 (yas--indent-region (line-beginning-position)
3969 (defun yas--collect-snippet-markers (snippet)
3970 "Make a list of all the markers used by SNIPPET."
3972 (dolist (field (yas--snippet-fields snippet))
3973 (push (yas--field-start field) markers)
3974 (push (yas--field-end field) markers)
3975 (dolist (mirror (yas--field-mirrors field))
3976 (push (yas--mirror-start mirror) markers)
3977 (push (yas--mirror-end mirror) markers)))
3978 (let ((snippet-exit (yas--snippet-exit snippet)))
3979 (when (and snippet-exit
3980 (marker-buffer (yas--exit-marker snippet-exit)))
3981 (push (yas--exit-marker snippet-exit) markers)))
3984 (defun yas--escape-string (escaped)
3985 (concat "YASESCAPE" (format "%d" escaped) "PROTECTGUARD"))
3987 (defun yas--protect-escapes (&optional text escaped)
3988 "Protect all escaped characters with their numeric ASCII value.
3990 With optional string TEXT do it in string instead of buffer."
3991 (let ((changed-text text)
3992 (text-provided-p text))
3993 (mapc #'(lambda (escaped)
3995 (yas--replace-all (concat "\\" (char-to-string escaped))
3996 (yas--escape-string escaped)
3997 (when text-provided-p changed-text))))
3998 (or escaped yas--escaped-characters))
4001 (defun yas--restore-escapes (&optional text escaped)
4002 "Restore all escaped characters from their numeric ASCII value.
4004 With optional string TEXT do it in string instead of the buffer."
4005 (let ((changed-text text)
4006 (text-provided-p text))
4007 (mapc #'(lambda (escaped)
4009 (yas--replace-all (yas--escape-string escaped)
4010 (char-to-string escaped)
4011 (when text-provided-p changed-text))))
4012 (or escaped yas--escaped-characters))
4015 (defun yas--save-backquotes ()
4016 "Save all the \"`(lisp-expression)`\"-style expressions
4017 with their evaluated value into `yas--backquote-markers-and-strings'."
4018 (while (re-search-forward yas--backquote-lisp-expression-regexp nil t)
4019 (let ((current-string (match-string-no-properties 1)) transformed)
4020 (save-restriction (widen)
4021 (delete-region (match-beginning 0) (match-end 0)))
4022 (setq transformed (yas--eval-lisp (yas--read-lisp (yas--restore-escapes current-string '(?`)))))
4023 (goto-char (match-beginning 0))
4025 (let ((marker (make-marker)))
4028 (insert "Y") ;; quite horrendous, I love it :)
4029 (set-marker marker (point))
4031 (push (cons marker transformed) yas--backquote-markers-and-strings))))))
4033 (defun yas--restore-backquotes ()
4034 "Replace markers in `yas--backquote-markers-and-strings' with their values."
4035 (while yas--backquote-markers-and-strings
4036 (let* ((marker-and-string (pop yas--backquote-markers-and-strings))
4037 (marker (car marker-and-string))
4038 (string (cdr marker-and-string)))
4046 (set-marker marker nil)))))
4048 (defun yas--scan-sexps (from count)
4050 (save-match-data ; `scan-sexps' may modify match data.
4051 (with-syntax-table (standard-syntax-table)
4052 (scan-sexps from count)))))
4054 (defun yas--make-marker (pos)
4055 "Create a marker at POS with nil `marker-insertion-type'."
4056 (let ((marker (set-marker (make-marker) pos)))
4057 (set-marker-insertion-type marker nil)
4060 (defun yas--indent-parse-create (snippet)
4061 "Parse the \"$>\" indentation markers in SNIPPET."
4062 (setq yas--indent-markers ())
4063 (while (search-forward "$>" nil t)
4064 (delete-region (match-beginning 0) (match-end 0))
4065 ;; Mark the beginning of the line.
4066 (push (yas--make-marker (line-beginning-position))
4067 yas--indent-markers))
4068 (setq yas--indent-markers (nreverse yas--indent-markers)))
4070 (defun yas--field-parse-create (snippet &optional parent-field)
4071 "Parse most field expressions in SNIPPET, except for the simple one \"$n\".
4073 The following count as a field:
4075 * \"${n: text}\", for a numbered field with default text, as long as N is not 0;
4077 * \"${n: text$(expression)}, the same with a Lisp expression;
4078 this is caught with the curiously named `yas--multi-dollar-lisp-expression-regexp'
4080 * the same as above but unnumbered, (no N:) and number is calculated automatically.
4082 When multiple expressions are found, only the last one counts."
4085 (while (re-search-forward yas--field-regexp nil t)
4086 (let* ((real-match-end-0 (yas--scan-sexps (1+ (match-beginning 0)) 1))
4087 (number (and (match-string-no-properties 1)
4088 (string-to-number (match-string-no-properties 1))))
4089 (brand-new-field (and real-match-end-0
4090 ;; break if on "$(" immediately
4091 ;; after the ":", this will be
4092 ;; caught as a mirror with
4094 (not (string-match-p "\\`\\$[ \t\n]*("
4095 (match-string-no-properties 2)))
4096 ;; allow ${0: some exit text}
4097 ;; (not (and number (zerop number)))
4098 (yas--make-field number
4099 (yas--make-marker (match-beginning 2))
4100 (yas--make-marker (1- real-match-end-0))
4102 (when brand-new-field
4103 (goto-char real-match-end-0)
4104 (push (cons (1- real-match-end-0) real-match-end-0)
4105 yas--dollar-regions)
4106 (push (cons (match-beginning 0) (match-beginning 2))
4107 yas--dollar-regions)
4108 (push brand-new-field (yas--snippet-fields snippet))
4111 (narrow-to-region (yas--field-start brand-new-field) (yas--field-end brand-new-field))
4112 (goto-char (point-min))
4113 (yas--field-parse-create snippet brand-new-field)))))))
4114 ;; if we entered from a parent field, now search for the
4115 ;; `yas--multi-dollar-lisp-expression-regexp'. This is used for
4116 ;; primary field transformations
4120 (while (re-search-forward yas--multi-dollar-lisp-expression-regexp nil t)
4121 (let* ((real-match-end-1 (yas--scan-sexps (match-beginning 1) 1)))
4122 ;; commit the primary field transformation if:
4124 ;; 1. we don't find it in yas--dollar-regions (a subnested
4125 ;; field) might have already caught it.
4127 ;; 2. we really make sure we have either two '$' or some
4128 ;; text and a '$' after the colon ':'. This is a FIXME: work
4129 ;; my regular expressions and end these ugly hacks.
4131 (when (and real-match-end-1
4132 (not (member (cons (match-beginning 0)
4134 yas--dollar-regions))
4136 (char-before (1- (match-beginning 1))))))
4137 (let ((lisp-expression-string (buffer-substring-no-properties (match-beginning 1)
4139 (setf (yas--field-transform parent-field)
4140 (yas--read-lisp (yas--restore-escapes lisp-expression-string))))
4141 (push (cons (match-beginning 0) real-match-end-1)
4142 yas--dollar-regions)))))))
4144 (defun yas--transform-mirror-parse-create (snippet)
4145 "Parse the \"${n:$(lisp-expression)}\" mirror transformations in SNIPPET."
4146 (while (re-search-forward yas--transform-mirror-regexp nil t)
4147 (let* ((real-match-end-0 (yas--scan-sexps (1+ (match-beginning 0)) 1))
4148 (number (string-to-number (match-string-no-properties 1)))
4150 (not (zerop number))
4151 (yas--snippet-find-field snippet number)))
4153 (and real-match-end-0
4155 (yas--make-mirror (yas--make-marker (match-beginning 0))
4156 (yas--make-marker (match-beginning 0))
4158 (yas--restore-escapes
4159 (buffer-substring-no-properties (match-beginning 2)
4160 (1- real-match-end-0))))))))
4161 (when brand-new-mirror
4162 (push brand-new-mirror
4163 (yas--field-mirrors field))
4164 (yas--calculate-mirrors-in-fields snippet brand-new-mirror)
4165 (push (cons (match-beginning 0) real-match-end-0) yas--dollar-regions)))))
4167 (defun yas--simple-mirror-parse-create (snippet)
4168 "Parse the simple \"$n\" fields/mirrors/exitmarkers in SNIPPET."
4169 (while (re-search-forward yas--simple-mirror-regexp nil t)
4170 (let ((number (string-to-number (match-string-no-properties 1))))
4171 (cond ((zerop number)
4172 (setf (yas--snippet-exit snippet)
4173 (yas--make-exit (yas--make-marker (match-end 0))))
4174 (push (cons (match-beginning 0) (yas--exit-marker (yas--snippet-exit snippet)))
4175 yas--dollar-regions))
4177 (let ((field (yas--snippet-find-field snippet number)))
4179 (let ((brand-new-mirror (yas--make-mirror
4180 (yas--make-marker (match-beginning 0))
4181 (yas--make-marker (match-beginning 0))
4183 (push brand-new-mirror
4184 (yas--field-mirrors field))
4185 (yas--calculate-mirrors-in-fields snippet brand-new-mirror))
4186 (push (yas--make-field number
4187 (yas--make-marker (match-beginning 0))
4188 (yas--make-marker (match-beginning 0))
4190 (yas--snippet-fields snippet))))
4191 (push (cons (match-beginning 0) (match-end 0))
4192 yas--dollar-regions))))))
4194 (defun yas--delete-regions (regions)
4195 "Sort disjuct REGIONS by start point, then delete from the back."
4196 (mapc #'(lambda (reg)
4197 (delete-region (car reg) (cdr reg)))
4200 (>= (car r1) (car r2))))))
4202 (defun yas--calculate-mirror-depth (mirror &optional traversed)
4203 (let* ((parent (yas--mirror-parent-field mirror))
4204 (parents-mirrors (and parent
4205 (yas--field-mirrors parent))))
4206 (or (yas--mirror-depth mirror)
4207 (setf (yas--mirror-depth mirror)
4208 (cond ((memq mirror traversed)
4210 ((and parent parents-mirrors)
4212 (mapcar #'(lambda (m)
4213 (yas--calculate-mirror-depth m
4222 (defun yas--update-mirrors (snippet)
4223 "Update all the mirrors of SNIPPET."
4227 (dolist (field-and-mirror
4229 ;; make a list of ((F1 . M1) (F1 . M2) (F2 . M3) (F2 . M4) ...)
4230 ;; where F is the field that M is mirroring
4232 (cl-mapcan #'(lambda (field)
4233 (mapcar #'(lambda (mirror)
4234 (cons field mirror))
4235 (yas--field-mirrors field)))
4236 (yas--snippet-fields snippet))
4237 ;; then sort this list so that entries with mirrors with parent
4238 ;; fields appear before. This was important for fixing #290, and
4239 ;; luckily also handles the case where a mirror in a field causes
4240 ;; another mirror to need reupdating
4242 #'(lambda (field-and-mirror1 field-and-mirror2)
4243 (> (yas--calculate-mirror-depth (cdr field-and-mirror1))
4244 (yas--calculate-mirror-depth (cdr field-and-mirror2))))))
4245 (let* ((field (car field-and-mirror))
4246 (mirror (cdr field-and-mirror))
4247 (parent-field (yas--mirror-parent-field mirror)))
4248 ;; before updating a mirror with a parent-field, maybe advance
4252 (yas--advance-start-maybe mirror (yas--fom-start parent-field)))
4253 ;; update this mirror
4255 (yas--mirror-update-display mirror field snippet)
4256 ;; `yas--place-overlays' is needed since the active field and
4257 ;; protected overlays might have been changed because of insertions
4258 ;; in `yas--mirror-update-display'.
4259 (let ((active-field (yas--snippet-active-field snippet)))
4260 (when active-field (yas--place-overlays snippet active-field))))))))
4262 (defun yas--mirror-update-display (mirror field snippet)
4263 "Update MIRROR according to FIELD (and mirror transform)."
4265 (let* ((mirror-parent-field (yas--mirror-parent-field mirror))
4266 (reflection (and (not (and mirror-parent-field
4267 (yas--field-modified-p mirror-parent-field)))
4268 (or (yas--apply-transform mirror field 'empty-on-nil)
4269 (yas--field-text-for-display field)))))
4270 (when (and reflection
4271 (not (string= reflection (buffer-substring-no-properties (yas--mirror-start mirror)
4272 (yas--mirror-end mirror)))))
4273 (goto-char (yas--mirror-start mirror))
4274 (let ((yas--inhibit-overlay-hooks t))
4275 (insert reflection))
4276 (if (> (yas--mirror-end mirror) (point))
4277 (delete-region (point) (yas--mirror-end mirror))
4278 (set-marker (yas--mirror-end mirror) (point))
4279 (yas--advance-start-maybe (yas--mirror-next mirror) (point))
4280 ;; super-special advance
4281 (yas--advance-end-of-parents-maybe mirror-parent-field (point)))
4282 (let ((yas--inhibit-overlay-hooks t))
4283 (yas--indent-region (yas--mirror-start mirror)
4284 (yas--mirror-end mirror)
4287 (defun yas--field-update-display (field)
4288 "Much like `yas--mirror-update-display', but for fields."
4289 (when (yas--field-transform field)
4290 (let ((transformed (and (not (eq (yas--field-number field) 0))
4291 (yas--apply-transform field field))))
4292 (when (and transformed
4293 (not (string= transformed (buffer-substring-no-properties (yas--field-start field)
4294 (yas--field-end field)))))
4295 (setf (yas--field-modified-p field) t)
4296 (goto-char (yas--field-start field))
4297 (let ((yas--inhibit-overlay-hooks t))
4298 (insert transformed)
4299 (if (> (yas--field-end field) (point))
4300 (delete-region (point) (yas--field-end field))
4301 (set-marker (yas--field-end field) (point))
4302 (yas--advance-start-maybe (yas--field-next field) (point)))
4306 ;;; Post-command hook:
4308 (defun yas--post-command-handler ()
4309 "Handles various yasnippet conditions after each command."
4310 (cond ((eq 'undo this-command)
4312 ;; After undo revival the correct field is sometimes not
4313 ;; restored correctly, this condition handles that
4315 (let* ((snippet (car (yas--snippets-at-point)))
4316 (target-field (and snippet
4317 (find-if-not #'(lambda (field)
4318 (yas--field-probably-deleted-p snippet field))
4320 (cons (yas--snippet-active-field snippet)
4321 (yas--snippet-fields snippet)))))))
4323 (yas--move-to-field snippet target-field))))
4324 ((not (yas--undo-in-progress))
4325 ;; When not in an undo, check if we must commit the snippet
4326 ;; (user exited it).
4327 (yas--check-commit-snippet))))
4331 ;; The docstrings for some functions are generated dynamically
4332 ;; depending on the context.
4334 (put 'yas-expand 'function-documentation
4335 '(yas--expand-from-trigger-key-doc t))
4336 (defun yas--expand-from-trigger-key-doc (context)
4337 "A doc synthesizer for `yas--expand-from-trigger-key-doc'."
4338 (let* ((yas-fallback-behavior (and context yas-fallback-behavior))
4339 (fallback-description
4340 (cond ((eq yas-fallback-behavior 'call-other-command)
4341 (let* ((fallback (yas--keybinding-beyond-yasnippet)))
4343 (format "call command `%s'."
4344 (pp-to-string fallback)))
4345 "do nothing (`yas-expand' doesn't override\nanything).")))
4346 ((eq yas-fallback-behavior 'return-nil)
4348 (t "defer to `yas-fallback-behavior' (which see)."))))
4349 (concat "Expand a snippet before point. If no snippet
4350 expansion is possible, "
4351 fallback-description
4352 "\n\nOptional argument FIELD is for non-interactive use and is an
4353 object satisfying `yas--field-p' to restrict the expansion to.")))
4355 (put 'yas-expand-from-keymap 'function-documentation
4356 '(yas--expand-from-keymap-doc t))
4357 (defun yas--expand-from-keymap-doc (context)
4358 "A doc synthesizer for `yas--expand-from-keymap-doc'."
4359 (add-hook 'temp-buffer-show-hook #'yas--snippet-description-finish-runonce)
4360 (concat "Expand/run snippets from keymaps, possibly falling back to original binding.\n"
4361 (when (and context (eq this-command 'describe-key))
4362 (let* ((vec (this-single-command-keys))
4363 (templates (mapcan #'(lambda (table)
4364 (yas--fetch table vec))
4365 (yas--get-snippet-tables)))
4366 (yas--direct-keymaps nil)
4367 (fallback (key-binding vec)))
4368 (concat "In this case, "
4370 (concat "these snippets are bound to this key:\n"
4371 (yas--template-pretty-list templates)
4372 "\n\nIf none of these expands, "))
4374 (format "fallback `%s' will be called." (pp-to-string fallback)))
4375 "no fallback keybinding is called."))))))
4377 (defun yas--template-pretty-list (templates)
4379 (yas-buffer-local-condition 'always))
4380 (dolist (plate templates)
4381 (setq acc (concat acc "\n*) "
4382 (propertize (concat "\\\\snippet `" (car plate) "'")
4383 'yasnippet (cdr plate)))))
4386 (define-button-type 'help-snippet-def
4387 :supertype 'help-xref
4388 'help-function (lambda (template) (yas--visit-snippet-file-1 template))
4389 'help-echo (purecopy "mouse-2, RET: find snippets's definition"))
4391 (defun yas--snippet-description-finish-runonce ()
4392 "Final adjustments for the help buffer when snippets are concerned."
4393 (yas--create-snippet-xrefs)
4394 (remove-hook 'temp-buffer-show-hook
4395 #'yas--snippet-description-finish-runonce))
4397 (defun yas--create-snippet-xrefs ()
4399 (goto-char (point-min))
4400 (while (search-forward-regexp "\\\\\\\\snippet[ \s\t]+`\\([^']+\\)'" nil t)
4401 (let ((template (get-text-property (match-beginning 1)
4404 (help-xref-button 1 'help-snippet-def template)
4405 (delete-region (match-end 1) (match-end 0))
4406 (delete-region (match-beginning 0) (match-beginning 1)))))))
4410 (defvar yas-verbosity 3
4411 "Log level for `yas--message' 4 means trace most anything, 0 means nothing.")
4413 (defun yas--message (level message &rest args)
4414 "When LEVEL is above `yas-verbosity-level', log MESSAGE and ARGS."
4415 (when (> yas-verbosity level)
4416 (message "%s" (apply #'yas--format message args))))
4418 (defun yas--warning (format-control &rest format-args)
4419 (let ((msg (apply #'format format-control format-args)))
4420 (display-warning 'yasnippet msg :warning)
4421 (yas--message 1 msg)))
4423 (defun yas--format (format-control &rest format-args)
4424 (apply #'format (concat "[yas] " format-control) format-args))
4431 ;; `locate-dominating-file'
4432 ;; `region-active-p'
4434 ;; added for compatibility in emacsen < 23
4435 (unless (>= emacs-major-version 23)
4436 (unless (fboundp 'region-active-p)
4437 (defun region-active-p () (and transient-mark-mode mark-active)))
4439 (unless (fboundp 'locate-dominating-file)
4440 (defvar locate-dominating-stop-dir-regexp
4441 "\\`\\(?:[\\/][\\/][^\\/]+[\\/]\\|/\\(?:net\\|afs\\|\\.\\.\\.\\)/\\)\\'"
4442 "Regexp of directory names which stop the search in `locate-dominating-file'.
4443 Any directory whose name matches this regexp will be treated like
4444 a kind of root directory by `locate-dominating-file' which will stop its search
4445 when it bumps into it.
4446 The default regexp prevents fruitless and time-consuming attempts to find
4447 special files in directories in which filenames are interpreted as hostnames,
4448 or mount points potentially requiring authentication as a different user.")
4450 (defun locate-dominating-file (file name)
4451 "Look up the directory hierarchy from FILE for a file named NAME.
4452 Stop at the first parent directory containing a file NAME,
4453 and return the directory. Return nil if not found."
4454 ;; We used to use the above locate-dominating-files code, but the
4455 ;; directory-files call is very costly, so we're much better off doing
4456 ;; multiple calls using the code in here.
4458 ;; Represent /home/luser/foo as ~/foo so that we don't try to look for
4459 ;; `name' in /home or in /.
4460 (setq file (abbreviate-file-name file))
4463 (while (not (or root
4465 ;; FIXME: Disabled this heuristic because it is sometimes
4467 ;; As a heuristic, we stop looking up the hierarchy of
4468 ;; directories as soon as we find a directory belonging
4469 ;; to another user. This should save us from looking in
4470 ;; things like /net and /afs. This assumes that all the
4471 ;; files inside a project belong to the same user.
4472 ;; (let ((prev-user user))
4473 ;; (setq user (nth 2 (file-attributes file)))
4474 ;; (and prev-user (not (equal user prev-user))))
4475 (string-match locate-dominating-stop-dir-regexp file)))
4476 (setq try (file-exists-p (expand-file-name name file)))
4477 (cond (try (setq root file))
4478 ((equal file (setq file (file-name-directory
4479 (directory-file-name file))))
4484 ;;; Backward compatibility to yasnippet <= 0.7
4486 (defun yas-initialize ()
4487 "For backward compatibility, enable `yas-minor-mode' globally."
4488 (declare (obsolete "Use (yas-global-mode 1) instead." "0.8"))
4489 (yas-global-mode 1))
4491 (defvar yas--backported-syms '(;; `defcustom's
4494 yas-prompt-functions
4496 yas-also-auto-indent-first-line
4498 yas-triggers-in-field
4499 yas-fallback-behavior
4500 yas-choose-keys-first
4501 yas-choose-tables-first
4504 yas-wrap-around-region
4507 yas-expand-only-for-last-commands
4508 yas-field-highlight-face
4510 ;; these vars can be customized as well
4516 yas-after-exit-snippet-hook
4517 yas-before-expand-snippet-hook
4518 yas-buffer-local-condition
4521 ;; prompting functions
4526 yas-completing-prompt
4529 ;; interactive functions
4534 yas-direct-keymaps-reload
4538 yas-compile-directory
4541 yas-expand-from-trigger-key
4542 yas-expand-from-keymap
4544 yas-visit-snippet-file
4546 yas-load-snippet-buffer
4549 yas-next-field-or-maybe-expand
4554 yas-exit-all-snippets
4555 yas-skip-and-clear-or-delete-char
4558 ;; symbols that I "exported" for use
4559 ;; in snippets and hookage
4576 yas-default-from-field
4579 yas-define-condition-cache
4580 yas-hippie-try-expand
4582 ;; debug definitions
4583 ;; yas-debug-snippet-vars
4584 ;; yas-exterminate-package
4587 ;; testing definitions
4588 ;; yas-should-expand
4589 ;; yas-should-not-expand
4591 ;; yas-make-file-or-dirs
4593 ;; yas-saving-variables
4594 ;; yas-call-with-snippet-dirs
4595 ;; yas-with-snippet-dirs
4597 "Backported yasnippet symbols.
4599 They are mapped to \"yas/*\" variants.")
4601 (dolist (sym yas--backported-syms)
4602 (let ((backported (intern (replace-regexp-in-string "\\`yas-" "yas/" (symbol-name sym)))))
4604 (make-obsolete-variable backported sym "yasnippet 0.8")
4605 (defvaralias backported sym))
4607 (make-obsolete backported sym "yasnippet 0.8")
4608 (defalias backported sym))))
4610 (defvar yas--exported-syms
4612 (mapatoms (lambda (atom)
4613 (if (and (or (and (boundp atom)
4614 (not (get atom 'byte-obsolete-variable)))
4616 (not (get atom 'byte-obsolete-info))))
4617 (string-match-p "\\`yas-[^-]" (symbol-name atom)))
4618 (push atom exported))))
4620 "Exported yasnippet symbols.
4622 i.e. the ones with \"yas-\" single dash prefix. I will try to
4623 keep them in future yasnippet versions and other elisp libraries
4624 can more or less safely rely upon them.")
4627 (provide 'yasnippet)
4630 ;; indent-tabs-mode: nil
4631 ;; byte-compile-warnings: (not cl-functions)
4633 ;;; yasnippet.el ends here