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