1 ;;; yasnippet.el --- Yet another snippet extension for Emacs.
3 ;; Copyright (C) 2008-2012 Free Software Foundation, Inc.
4 ;; Authors: pluskid <pluskid@gmail.com>, João Távora <joaotavora@gmail.com>
6 ;; Package-version: 0.8.0
7 ;; X-URL: http://github.com/capitaomorte/yasnippet
8 ;; Keywords: convenience, emulation
9 ;; URL: http://github.com/capitaomorte/yasnippet
10 ;; EmacsWiki: YaSnippetMode
12 ;; This program is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; This program is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
27 ;; Basic steps to setup:
29 ;; (add-to-list 'load-path
30 ;; "~/path-to-yasnippet")
31 ;; (require 'yasnippet)
32 ;; (yas-global-mode 1)
35 ;; Interesting variables are:
39 ;; The directory where user-created snippets are to be
40 ;; stored. Can also be a list of directories. In that case,
41 ;; when used for bulk (re)loading of snippets (at startup or
42 ;; via `yas-reload-all'), directories appearing earlier in
43 ;; the list shadow other dir's snippets. Also, the first
44 ;; directory is taken as the default for storing the user's
47 ;; The deprecated `yas/root-directory' aliases this variable
48 ;; for backward-compatibility.
52 ;; A local variable that you can set in a hook to override
53 ;; snippet-lookup based on major mode. It is a symbol (or
54 ;; list of symbols) that correspond to subdirectories of
55 ;; `yas-snippet-dirs' and is used for deciding which
56 ;; snippets to consider for the active buffer.
58 ;; Deprecated `yas/mode-symbol' aliases this variable for
59 ;; backward-compatibility.
61 ;; Major commands are:
65 ;; Try to expand snippets before point. In `yas-minor-mode',
66 ;; this is normally bound to TAB, but you can customize it in
67 ;; `yas-minor-mode-map'.
69 ;; M-x yas-load-directory
71 ;; Prompts you for a directory hierarchy of snippets to load.
73 ;; M-x yas-insert-snippet
75 ;; Prompts you for possible snippet expansion if that is
76 ;; possible according to buffer-local and snippet-local
77 ;; expansion conditions. With prefix argument, ignore these
80 ;; M-x yas-visit-snippet-file
82 ;; Prompts you for possible snippet expansions like
83 ;; `yas-insert-snippet', but instead of expanding it, takes
84 ;; you directly to the snippet definition's file, if it
87 ;; M-x yas-new-snippet
89 ;; Lets you create a new snippet file in the correct
90 ;; subdirectory of `yas-snippet-dirs', according to the
93 ;; M-x yas-load-snippet-buffer
95 ;; When editing a snippet, this loads the snippet. This is
96 ;; bound to "C-c C-c" while in the `snippet-mode' editing
99 ;; M-x yas-tryout-snippet
101 ;; When editing a snippet, this opens a new empty buffer,
102 ;; sets it to the appropriate major mode and inserts the
103 ;; snippet there, so you can see what it looks like. This is
104 ;; bound to "C-c C-t" while in `snippet-mode'.
106 ;; M-x yas-describe-tables
108 ;; Lists known snippets in a separate buffer. User is
109 ;; prompted as to whether only the currently active tables
110 ;; are to be displayed, or all the tables for all major
113 ;; If you have `dropdown-list' installed, you can optionally use it
114 ;; as the preferred "prompting method", putting in your .emacs file,
117 ;; (require 'dropdown-list)
118 ;; (setq yas-prompt-functions '(yas-dropdown-prompt
120 ;; yas-completing-prompt))
122 ;; Also check out the customization group
124 ;; M-x customize-group RET yasnippet RET
126 ;; If you use the customization group to set variables
127 ;; `yas-snippet-dirs' or `yas-global-mode', make sure the path to
128 ;; "yasnippet.el" is present in the `load-path' *before* the
129 ;; `custom-set-variables' is executed in your .emacs file.
131 ;; For more information and detailed usage, refer to the project page:
132 ;; http://github.com/capitaomorte/yasnippet
141 (defvar yas--editing-template)
142 (defvar yas--guessed-modes)
143 (defvar yas--indent-original-column)
144 (defvar yas--scheduled-jit-loads)
146 (defvar yas-selected-text)
147 (defvar yas-verbosity))
151 ;;; User customizable variables
153 (defgroup yasnippet nil
154 "Yet Another Snippet extension"
157 (defvar yas--load-file-name load-file-name
158 "Store the filename that yasnippet.el was originally loaded from.")
160 (defcustom yas-snippet-dirs (remove nil
161 (list "~/.emacs.d/snippets"
162 (when yas--load-file-name
163 (concat (file-name-directory yas--load-file-name) "snippets"))))
164 "Directory or list of snippet dirs for each major mode.
166 The directory where user-created snippets are to be stored. Can
167 also be a list of directories. In that case, when used for
168 bulk (re)loading of snippets (at startup or via
169 `yas-reload-all'), directories appearing earlier in the list
170 shadow other dir's snippets. Also, the first directory is taken
171 as the default for storing the user's new snippets."
172 :type '(choice (string :tag "Single directory (string)")
173 (repeat :args (string) :tag "List of directories (strings)"))
176 :set #'(lambda (symbol new)
177 (let ((old (and (boundp symbol)
178 (symbol-value symbol))))
179 (set-default symbol new)
180 (unless (or (not (fboundp 'yas-reload-all))
184 (defun yas-snippet-dirs ()
185 "Returns `yas-snippet-dirs' (which see) as a list."
186 (if (listp yas-snippet-dirs) yas-snippet-dirs (list yas-snippet-dirs)))
188 (defvaralias 'yas/root-directory 'yas-snippet-dirs)
190 (defcustom yas-prompt-functions '(yas-x-prompt
192 yas-completing-prompt
195 "Functions to prompt for keys, templates, etc interactively.
197 These functions are called with the following arguments:
199 - PROMPT: A string to prompt the user
201 - CHOICES: a list of strings or objects.
203 - optional DISPLAY-FN : A function that, when applied to each of
204 the objects in CHOICES will return a string.
206 The return value of any function you put here should be one of
207 the objects in CHOICES, properly formatted with DISPLAY-FN (if
210 - To signal that your particular style of prompting is
211 unavailable at the moment, you can also have the function return
214 - To signal that the user quit the prompting process, you can
217 (signal 'quit \"user quit!\")."
218 :type '(repeat function)
221 (defcustom yas-indent-line 'auto
222 "Controls indenting applied to a recent snippet expansion.
224 The following values are possible:
226 - `fixed' Indent the snippet to the current column;
228 - `auto' Indent each line of the snippet with `indent-according-to-mode'
230 Every other value means don't apply any snippet-side indentation
231 after expansion (the manual per-line \"$>\" indentation still
233 :type '(choice (const :tag "Nothing" nothing)
234 (const :tag "Fixed" fixed)
235 (const :tag "Auto" auto))
238 (defcustom yas-also-auto-indent-first-line nil
239 "Non-nil means also auto indent first line according to mode.
241 Naturally this is only valid when `yas-indent-line' is `auto'"
245 (defcustom yas-snippet-revival t
246 "Non-nil means re-activate snippet fields after undo/redo."
250 (defcustom yas-triggers-in-field nil
251 "If non-nil, allow stacked expansions (snippets inside snippets).
253 Otherwise `yas-next-field-or-maybe-expand' just moves on to the
258 (defcustom yas-fallback-behavior 'call-other-command
259 "How to act when `yas-expand' does *not* expand a snippet.
261 - `call-other-command' means try to temporarily disable YASnippet
262 and call the next command bound to whatever key was used to
265 - nil or the symbol `return-nil' mean do nothing. (and
266 `yas-expand' returns nil)
268 - A Lisp form (apply COMMAND . ARGS) means interactively call
269 COMMAND, if ARGS is non-nil, call COMMAND non-interactively
270 with ARGS as arguments."
271 :type '(choice (const :tag "Call previous command" call-other-command)
272 (const :tag "Do nothing" return-nil))
275 (defcustom yas-choose-keys-first nil
276 "If non-nil, prompt for snippet key first, then for template.
278 Otherwise prompts for all possible snippet names.
280 This affects `yas-insert-snippet' and `yas-visit-snippet-file'."
284 (defcustom yas-choose-tables-first nil
285 "If non-nil, and multiple eligible snippet tables, prompts user for tables first.
287 Otherwise, user chooses between the merging together of all
290 This affects `yas-insert-snippet', `yas-visit-snippet-file'"
294 (defcustom yas-use-menu 'abbreviate
295 "Display a YASnippet menu in the menu bar.
297 When non-nil, submenus for each snippet table will be listed
298 under the menu \"Yasnippet\".
300 - If set to `abbreviate', only the current major-mode
301 menu and the modes set in `yas-extra-modes' are listed.
303 - If set to `full', every submenu is listed
305 - It set to nil, don't display a menu at all (this requires a
306 `yas-reload-all' call if the menu is already visible).
308 Any other non-nil value, every submenu is listed."
309 :type '(choice (const :tag "Full" full)
310 (const :tag "Abbreviate" abbreviate)
311 (const :tag "No menu" nil))
314 (defcustom yas-trigger-symbol (or (and (eq window-system 'mac)
316 (char-to-string ?\x21E5))) ;; little ->| sign
318 "The text that will be used in menu to represent the trigger."
322 (defcustom yas-wrap-around-region nil
323 "If non-nil, snippet expansion wraps around selected region.
325 The wrapping occurs just before the snippet's exit marker. This
326 can be overridden on a per-snippet basis."
330 (defcustom yas-good-grace t
331 "If non-nil, don't raise errors in inline elisp evaluation.
333 An error string \"[yas] error\" is returned instead."
337 (defcustom yas-visit-from-menu nil
338 "If non-nil visit snippets's files from menu, instead of expanding them.
340 This can only work when snippets are loaded from files."
344 (defcustom yas-expand-only-for-last-commands nil
345 "List of `last-command' values to restrict tab-triggering to, or nil.
347 Leave this set at nil (the default) to be able to trigger an
348 expansion simply by placing the cursor after a valid tab trigger,
349 using whichever commands.
351 Optionally, set this to something like '(self-insert-command) if
352 you to wish restrict expansion to only happen when the last
353 letter of the snippet tab trigger was typed immediately before
354 the trigger key itself."
355 :type '(repeat function)
358 ;; Only two faces, and one of them shouldn't even be used...
360 (defface yas-field-highlight-face
361 '((t (:inherit 'region)))
362 "The face used to highlight the currently active field of a snippet"
365 (defface yas--field-debug-face
367 "The face used for debugging some overlays normally hidden"
371 ;;; User-visible variables
373 (defvar yas-keymap (let ((map (make-sparse-keymap)))
374 (define-key map [(tab)] 'yas-next-field-or-maybe-expand)
375 (define-key map (kbd "TAB") 'yas-next-field-or-maybe-expand)
376 (define-key map [(shift tab)] 'yas-prev-field)
377 (define-key map [backtab] 'yas-prev-field)
378 (define-key map (kbd "C-g") 'yas-abort-snippet)
379 (define-key map (kbd "C-d") 'yas-skip-and-clear-or-delete-char)
381 "The active keymap while a snippet expansion is in progress.")
383 (defvar yas-key-syntaxes (list "w" "w_" "w_." "w_.()" "^ ")
384 "List of character syntaxes used to find a trigger key before point.
385 The list is tried in the order while scanning characters
386 backwards from point. For example, if the list is '(\"w\" \"w_\")
387 first look for trigger keys which are composed exclusively of
388 \"word\"-syntax characters, and then, if that fails, look for
389 keys which are either of \"word\" or \"symbol\"
390 syntax. Triggering after
394 will, according to the \"w\" element first try \"bar\". If that
395 isn't a trigger key, \"foo-bar\" is tried, respecting a second
398 (defvar yas-after-exit-snippet-hook
400 "Hooks to run after a snippet exited.
402 The hooks will be run in an environment where some variables bound to
405 `yas-snippet-beg' : The beginning of the region of the snippet.
407 `yas-snippet-end' : Similar to beg.
409 Attention: These hooks are not run when exiting nested/stacked snippet expansion!")
411 (defvar yas-before-expand-snippet-hook
413 "Hooks to run just before expanding a snippet.")
415 (defvar yas-buffer-local-condition
416 '(if (and (or (fourth (syntax-ppss))
417 (fifth (syntax-ppss)))
419 (eq this-command 'yas-expand-from-trigger-key))
420 '(require-snippet-condition . force-in-comment)
422 "Snippet expanding condition.
424 This variable is a Lisp form which is evaluated every time a
425 snippet expansion is attempted:
427 * If it evaluates to nil, no snippets can be expanded.
429 * If it evaluates to the a cons (require-snippet-condition
432 * Snippets bearing no \"# condition:\" directive are not
435 * Snippets bearing conditions that evaluate to nil (or
436 produce an error) won't be considered.
438 * If the snippet has a condition that evaluates to non-nil
441 * If REQUIREMENT is t, the snippet is considered
443 * If REQUIREMENT is `eq' RESULT, the snippet is
446 * Otherwise, the snippet is not considered.
448 * If it evaluates to the symbol 'always, all snippets are
449 considered for expansion, regardless of any conditions.
451 * If it evaluates to t or some other non-nil value
453 * Snippet bearing no conditions, or conditions that
454 evaluate to non-nil, are considered for expansion.
456 * Otherwise, the snippet is not considered.
458 Here's an example preventing snippets from being expanded from
459 inside comments, in `python-mode' only, with the exception of
460 snippets returning the symbol 'force-in-comment in their
463 (add-hook 'python-mode-hook
465 (setq yas-buffer-local-condition
466 '(if (python-in-string/comment)
467 '(require-snippet-condition . force-in-comment)
470 The default value is similar, it filters out potential snippet
471 expansions inside comments and string literals, unless the
472 snippet itself contains a condition that returns the symbol
473 `force-in-comment'.")
476 ;;; Internal variables
478 (defvar yas--version "0.8.0beta")
480 (defvar yas--menu-table (make-hash-table)
481 "A hash table of MAJOR-MODE symbols to menu keymaps.")
483 (defvar yas--known-modes
484 '(ruby-mode rst-mode markdown-mode)
485 "A list of mode which is well known but not part of Emacs.")
487 (defvar yas--escaped-characters
488 '(?\\ ?` ?\" ?' ?$ ?} ?{ ?\( ?\))
489 "List of characters which *might* need to be escaped.")
491 (defconst yas--field-regexp
492 "${\\([0-9]+:\\)?\\([^}]*\\)}"
493 "A regexp to *almost* recognize a field.")
495 (defconst yas--multi-dollar-lisp-expression-regexp
496 "$+[ \t\n]*\\(([^)]*)\\)"
497 "A regexp to *almost* recognize a \"$(...)\" expression.")
499 (defconst yas--backquote-lisp-expression-regexp
501 "A regexp to recognize a \"`lisp-expression`\" expression." )
503 (defconst yas--transform-mirror-regexp
504 "${\\(?:\\([0-9]+\\):\\)?$\\([ \t\n]*([^}]*\\)"
505 "A regexp to *almost* recognize a mirror with a transform.")
507 (defconst yas--simple-mirror-regexp
509 "A regexp to recognize a simple mirror.")
511 (defvar yas--snippet-id-seed 0
512 "Contains the next id for a snippet.")
514 (defun yas--snippet-next-id ()
515 (let ((id yas--snippet-id-seed))
516 (incf yas--snippet-id-seed)
522 ;; XXX: `last-buffer-undo-list' is somehow needed in Carbon Emacs for MacOSX
523 (defvar last-buffer-undo-list nil)
525 (defvar yas--minor-mode-menu nil
526 "Holds the YASnippet menu.")
528 (defun yas--init-minor-keymap ()
529 "Set up the `yas-minor-mode' keymap."
530 (let ((map (make-sparse-keymap)))
532 (easy-menu-define yas--minor-mode-menu
534 "Menu used when `yas-minor-mode' is active."
537 ["Expand trigger" yas-expand
538 :help "Possibly expand tab trigger before point"]
539 ["Insert at point..." yas-insert-snippet
540 :help "Prompt for an expandable snippet and expand it at point"]
541 ["New snippet..." yas-new-snippet
542 :help "Create a new snippet in an appropriate directory"]
543 ["Visit snippet file..." yas-visit-snippet-file
544 :help "Prompt for an expandable snippet and find its file"]
546 ("Snippet menu behaviour"
547 ["Visit snippets" (setq yas-visit-from-menu t)
548 :help "Visit snippets from the menu"
549 :active t :style radio :selected yas-visit-from-menu]
550 ["Expand snippets" (setq yas-visit-from-menu nil)
551 :help "Expand snippets from the menu"
552 :active t :style radio :selected (not yas-visit-from-menu)]
554 ["Show all known modes" (setq yas-use-menu 'full)
555 :help "Show one snippet submenu for each loaded table"
556 :active t :style radio :selected (eq yas-use-menu 'full)]
557 ["Abbreviate according to current mode" (setq yas-use-menu 'abbreviate)
558 :help "Show only snippet submenus for the current active modes"
559 :active t :style radio :selected (eq yas-use-menu 'abbreviate)])
561 ["Auto" (setq yas-indent-line 'auto)
562 :help "Indent each line of the snippet with `indent-according-to-mode'"
563 :active t :style radio :selected (eq yas-indent-line 'auto)]
564 ["Fixed" (setq yas-indent-line 'fixed)
565 :help "Indent the snippet to the current column"
566 :active t :style radio :selected (eq yas-indent-line 'fixed)]
567 ["None" (setq yas-indent-line 'none)
568 :help "Don't apply any particular snippet indentation after expansion"
569 :active t :style radio :selected (not (member yas-indent-line '(fixed auto)))]
571 ["Also auto indent first line" (setq yas-also-auto-indent-first-line
572 (not yas-also-auto-indent-first-line))
573 :help "When auto-indenting also, auto indent the first line menu"
574 :active (eq yas-indent-line 'auto)
575 :style toggle :selected yas-also-auto-indent-first-line]
578 ["System X-widget" (setq yas-prompt-functions
580 (remove 'yas-x-prompt
581 yas-prompt-functions)))
582 :help "Use your windowing system's (gtk, mac, windows, etc...) default menu"
583 :active t :style radio :selected (eq (car yas-prompt-functions)
585 ["Dropdown-list" (setq yas-prompt-functions
586 (cons 'yas-dropdown-prompt
587 (remove 'yas-dropdown-prompt
588 yas-prompt-functions)))
589 :help "Use a special dropdown list"
590 :active t :style radio :selected (eq (car yas-prompt-functions)
591 'yas-dropdown-prompt)]
592 ["Ido" (setq yas-prompt-functions
593 (cons 'yas-ido-prompt
594 (remove 'yas-ido-prompt
595 yas-prompt-functions)))
596 :help "Use an ido-style minibuffer prompt"
597 :active t :style radio :selected (eq (car yas-prompt-functions)
599 ["Completing read" (setq yas-prompt-functions
600 (cons 'yas-completing-prompt
601 (remove 'yas-completing-prompt
602 yas-prompt-functions)))
603 :help "Use a normal minibuffer prompt"
604 :active t :style radio :selected (eq (car yas-prompt-functions)
605 'yas-completing-prompt)]
608 ["Wrap region in exit marker"
609 (setq yas-wrap-around-region
610 (not yas-wrap-around-region))
611 :help "If non-nil automatically wrap the selected text in the $0 snippet exit"
612 :style toggle :selected yas-wrap-around-region]
613 ["Allow stacked expansions "
614 (setq yas-triggers-in-field
615 (not yas-triggers-in-field))
616 :help "If non-nil allow snippets to be triggered inside other snippet fields"
617 :style toggle :selected yas-triggers-in-field]
618 ["Revive snippets on undo "
619 (setq yas-snippet-revival
620 (not yas-snippet-revival))
621 :help "If non-nil allow snippets to become active again after undo"
622 :style toggle :selected yas-snippet-revival]
625 (not yas-good-grace))
626 :help "If non-nil don't raise errors in bad embedded elisp in snippets"
627 :style toggle :selected yas-good-grace]
630 ["Load snippets..." yas-load-directory
631 :help "Load snippets from a specific directory"]
632 ["Reload everything" yas-reload-all
633 :help "Cleanup stuff, reload snippets, rebuild menus"]
635 :help "Display some information about YASnippet"])))
637 ;; Now for the stuff that has direct keybindings
639 (define-key map [(tab)] 'yas-expand)
640 (define-key map (kbd "TAB") 'yas-expand)
641 (define-key map "\C-c&\C-s" 'yas-insert-snippet)
642 (define-key map "\C-c&\C-n" 'yas-new-snippet)
643 (define-key map "\C-c&\C-v" 'yas-visit-snippet-file)
646 (defvar yas-minor-mode-map (yas--init-minor-keymap)
647 "The keymap used when `yas-minor-mode' is active.")
649 (defvar yas--tables (make-hash-table)
650 "A hash table of mode symbols to `yas--table' objects.")
652 (defvar yas--parents (make-hash-table)
653 "A hash table of mode symbols do lists of direct parent mode symbols.
655 This list is populated when reading the \".yas-parents\" files
656 found when traversing snippet directories with
657 `yas-load-directory'.
659 There might be additional parenting information stored in the
660 `derived-mode-parent' property of some mode symbols, but that is
663 (defvar yas--ancestors (make-hash-table)
664 "A hash table of mode symbols do lists of all parent mode symbols.
666 A cache managed by `yas--all-parents'")
668 (defvar yas--direct-keymaps (list)
669 "Keymap alist supporting direct snippet keybindings.
671 This variable is placed in `emulation-mode-map-alists'.
673 Its elements looks like (TABLE-NAME . KEYMAP). They're
674 instantiated on `yas-reload-all' but KEYMAP is added to only when
675 loading snippets. `yas--direct-TABLE-NAME' is then a variable set
676 buffer-locally when entering `yas-minor-mode'. KEYMAP binds all
677 defined direct keybindings to the command
678 `yas-expand-from-keymap' which then which snippet to expand.")
680 (defun yas-direct-keymaps-reload ()
681 "Force reload the direct keybinding for active snippet tables."
683 (setq yas--direct-keymaps nil)
684 (maphash #'(lambda (name table)
685 (push (cons (intern (format "yas--direct-%s" name))
686 (yas--table-direct-keymap table))
687 yas--direct-keymaps))
690 (defun yas--modes-to-activate ()
691 "Compute list of mode symbols that are active for `yas-expand'
693 (let ((modes-to-activate (list major-mode))
695 (while (setq mode (get mode 'derived-mode-parent))
696 (push mode modes-to-activate))
697 (dolist (mode (yas-extra-modes))
698 (push mode modes-to-activate))
700 (append modes-to-activate
701 (mapcan #'(lambda (mode)
702 (yas--all-parents mode))
703 modes-to-activate)))))
705 (defvar yas-minor-mode-hook nil
706 "Hook run when `yas-minor-mode' is turned on.")
709 (define-minor-mode yas-minor-mode
710 "Toggle YASnippet mode.
712 When YASnippet mode is enabled, `yas-expand', normally bound to
713 the TAB key, expands snippets of code depending on the major
716 With no argument, this command toggles the mode.
717 positive prefix argument turns on the mode.
718 Negative prefix argument turns off the mode.
721 \\{yas-minor-mode-map}"
723 ;; The indicator for the mode line.
726 (cond (yas-minor-mode
727 ;; Install the direct keymaps in `emulation-mode-map-alists'
728 ;; (we use `add-hook' even though it's not technically a hook,
729 ;; but it works). Then define variables named after modes to
730 ;; index `yas--direct-keymaps'.
732 ;; Also install the post-command-hook.
734 (add-hook 'emulation-mode-map-alists 'yas--direct-keymaps)
735 (add-hook 'post-command-hook 'yas--post-command-handler nil t)
736 ;; Set the `yas--direct-%s' vars for direct keymap expansion
738 (dolist (mode (yas--modes-to-activate))
739 (let ((name (intern (format "yas--direct-%s" mode))))
740 (set-default name nil)
741 (set (make-local-variable name) t)))
744 (yas--load-pending-jits))
746 ;; Uninstall the direct keymaps and the post-command hook
748 (remove-hook 'post-command-hook 'yas--post-command-handler t)
749 (remove-hook 'emulation-mode-map-alists 'yas--direct-keymaps))))
751 (defvar yas-dont-activate '(minibufferp)
752 "If non-nil don't let `yas-global-mode' affect some buffers.
754 If a function of zero arguments, then its result is used.
756 If a list of functions, then all functions must return nil to
757 activate yas for this buffer.
759 In Emacsen <= 23, this variable is buffer-local. Because
760 `yas-minor-mode-on' is called by `yas-global-mode' after
761 executing the buffer's major mode hook, setting this variable
762 there is an effective way to define exceptions to the \"global\"
763 activation behaviour.
765 In Emacsen > 23, only the global value is used. To define
766 per-mode exceptions to the \"global\" activation behaviour, call
767 `yas-minor-mode' with a negative argument directily in the major
769 (unless (> emacs-major-version 23)
770 (make-variable-buffer-local 'yas-dont-activate))
773 (defun yas-minor-mode-on ()
774 "Turn on YASnippet minor mode.
776 Honour `yas-dont-activate', which see."
778 ;; Check `yas-dont-activate'
779 (unless (cond ((functionp yas-dont-activate)
780 (funcall yas-dont-activate))
781 ((consp yas-dont-activate)
782 (some #'funcall yas-dont-activate))
787 (define-globalized-minor-mode yas-global-mode yas-minor-mode yas-minor-mode-on
791 (defun yas--global-mode-reload-with-jit-maybe ()
792 "Run `yas-reload-all' when `yas-global-mode' is on."
793 (when yas-global-mode (yas-reload-all)))
795 (add-hook 'yas-global-mode-hook 'yas--global-mode-reload-with-jit-maybe)
800 (defvar yas--font-lock-keywords
801 (append '(("^#.*$" . font-lock-comment-face))
802 lisp-font-lock-keywords
803 lisp-font-lock-keywords-1
804 lisp-font-lock-keywords-2
806 (0 font-lock-keyword-face)
807 (1 font-lock-string-face t))
809 (0 font-lock-keyword-face)
810 (1 font-lock-warning-face t))
811 ("${" font-lock-keyword-face)
812 ("$[0-9]+?" font-lock-preprocessor-face)
813 ("\\(\\$(\\)" 1 font-lock-preprocessor-face)
815 (0 font-lock-keyword-face)))))
817 (defun yas--init-major-keymap ()
818 "Setup YASnippet major-mode keymap."
819 (let ((map (make-sparse-keymap)))
820 (easy-menu-define nil
822 "Menu used when snippet-mode is active."
824 (mapcar #'(lambda (ent)
826 (define-key map (third ent) (second ent)))
827 (vector (first ent) (second ent) t))
829 (list "Load this snippet" 'yas-load-snippet-buffer "\C-c\C-c")
830 (list "Try out this snippet" 'yas-tryout-snippet "\C-c\C-t")))))
833 (defvar snippet-mode-map
834 (yas--init-major-keymap)
835 "The keymap used when `snippet-mode' is active.")
838 (define-derived-mode snippet-mode text-mode "Snippet"
839 "A mode for editing yasnippets"
840 (setq font-lock-defaults '(yas--font-lock-keywords))
841 (set (make-local-variable 'require-final-newline) nil)
842 (set (make-local-variable 'comment-start) "#")
843 (set (make-local-variable 'comment-start-skip) "#+[\t ]*"))
847 ;;; Internal structs for template management
849 (defstruct (yas--template (:constructor yas--make-blank-template))
850 "A template for a snippet."
860 group ;; as dictated by the #group: directive or .yas-make-groups
861 perm-group ;; as dictated by `yas-define-menu'
865 (defun yas--populate-template (template &rest args)
866 "Helper function to populate TEMPLATE with properties."
870 (position (intern (substring (symbol-name (car args)) 1))
871 (mapcar #'car (get 'yas--template 'cl-struct-slots)))
873 (setq args (cddr args)))
876 (defstruct (yas--table (:constructor yas--make-snippet-table (name)))
877 "A table to store snippets for a particular mode.
879 Has the following fields:
883 A symbol name normally corresponding to a major mode, but can
884 also be a pseudo major-mode to be referenced in
885 `yas-extra-modes', for example.
889 A hash table (KEY . NAMEHASH), known as the \"keyhash\". KEY is
890 a string or a vector, where the former is the snippet's trigger
891 and the latter means it's a direct keybinding. NAMEHASH is yet
892 another hash of (NAME . TEMPLATE) where NAME is the snippet's
893 name and TEMPLATE is a `yas--template' object.
895 `yas--table-direct-keymap'
897 A keymap for the snippets in this table that have direct
898 keybindings. This is kept in sync with the keyhash, i.e., all
899 the elements of the keyhash that are vectors appear here as
900 bindings to `yas-expand-from-keymap'.
902 `yas--table-uuidhash'
904 A hash table mapping snippets uuid's to the same `yas--template'
905 objects. A snippet uuid defaults to the snippet's name.
908 (hash (make-hash-table :test 'equal))
909 (uuidhash (make-hash-table :test 'equal))
911 (direct-keymap (make-sparse-keymap)))
913 (defun yas--get-template-by-uuid (mode uuid)
914 "Find the snippet template in MODE by its UUID."
915 (let* ((table (gethash mode yas--tables mode)))
917 (gethash uuid (yas--table-uuidhash table)))))
919 ;; Apropos storing/updating in TABLE, this works in two steps:
921 ;; 1. `yas--remove-template-by-uuid' removes any
922 ;; keyhash-namehash-template mappings from TABLE, grabbing the
923 ;; snippet by its uuid. Also removes mappings from TABLE's
924 ;; `yas--table-direct-keymap' (FIXME: and should probably take care
925 ;; of potentially stale menu bindings right?.)
927 ;; 2. `yas--add-template' adds this all over again.
929 ;; Create a new or add to an existing keyhash-namehash mapping.
931 ;; For reference on understanding this, consider three snippet
934 ;; A: # name: The Foo
936 ;; # binding: C-c M-l
938 ;; B: # name: Mrs Foo
941 ;; C: # name: The Bar
942 ;; # binding: C-c M-l
947 ;; keyhash namehashes(3) yas--template structs(4)
948 ;; -----------------------------------------------------
951 ;; "foo" ---> "The Foo" ---> [yas--template A] |
952 ;; "Mrs Foo" ---> [yas--template B] |
954 ;; [C-c M-l] ---> "The Foo" -------------------------/
955 ;; "The Bar" ---> [yas--template C]
957 ;; "baz" ---> "Baz" ---> [yas--template D]
959 ;; Additionally, since uuid defaults to the name, we have a
960 ;; `yas--table-uuidhash' for TABLE
962 ;; uuidhash yas--template structs
963 ;; -------------------------------
964 ;; "The Foo" ---> [yas--template A]
965 ;; "Mrs Foo" ---> [yas--template B]
966 ;; "The Bar" ---> [yas--template C]
967 ;; "Baz" ---> [yas--template D]
969 ;; FIXME: the more I look at this data-structure the more I think I'm
970 ;; stupid. There has to be an easier way (but beware lots of code
973 (defun yas--remove-template-by-uuid (table uuid)
974 "Remove from TABLE a template identified by UUID."
975 (let ((template (gethash uuid (yas--table-uuidhash table))))
977 (let* ((name (yas--template-name template))
979 ;; Remove the name from each of the targeted namehashes
981 (maphash #'(lambda (k v)
982 (let ((template (gethash name v)))
984 (eq uuid (yas--template-uuid template)))
986 (when (zerop (hash-table-count v))
987 (push k empty-keys)))))
988 (yas--table-hash table))
989 ;; Remove the namehash themselves if they've become empty
991 (dolist (key empty-keys)
993 (define-key (yas--table-direct-keymap table) key nil))
994 (remhash key (yas--table-hash table)))
996 ;; Finally, remove the uuid from the uuidhash
998 (remhash uuid (yas--table-uuidhash table))))))
1000 (defun yas--add-template (table template)
1001 "Store in TABLE the snippet template TEMPLATE.
1003 KEY can be a string (trigger key) of a vector (direct
1005 (let ((name (yas--template-name template))
1006 (key (yas--template-key template))
1007 (keybinding (yas--template-keybinding template))
1008 (menu-binding-pair (yas--template-menu-binding-pair-get-create template)))
1009 (dolist (k (remove nil (list key keybinding)))
1013 (yas--table-hash table))
1015 (make-hash-table :test 'equal)
1016 (yas--table-hash table))))
1018 (define-key (yas--table-direct-keymap table) k 'yas-expand-from-keymap)))
1020 ;; Update TABLE's `yas--table-uuidhash'
1021 (puthash (yas--template-uuid template)
1023 (yas--table-uuidhash table))))
1025 (defun yas--update-template (table template)
1026 "Add or update TEMPLATE in TABLE.
1028 Also takes care of adding and updating to the associated menu."
1029 ;; Remove from table by uuid
1031 (yas--remove-template-by-uuid table (yas--template-uuid template))
1032 ;; Add to table again
1034 (yas--add-template table template)
1035 ;; Take care of the menu
1038 (yas--update-template-menu table template)))
1040 (defun yas--update-template-menu (table template)
1041 "Update every menu-related for TEMPLATE."
1042 (let ((menu-binding-pair (yas--template-menu-binding-pair-get-create template))
1043 (key (yas--template-key template))
1044 (keybinding (yas--template-keybinding template)))
1045 ;; The snippet might have changed name or keys, so update
1046 ;; user-visible strings
1048 (unless (eq (cdr menu-binding-pair) :none)
1049 ;; the menu item name
1051 (setf (cadar menu-binding-pair) (yas--template-name template))
1052 ;; the :keys information (also visible to the user)
1053 (setf (getf (cdr (car menu-binding-pair)) :keys)
1054 (or (and keybinding (key-description keybinding))
1055 (and key (concat key yas-trigger-symbol))))))
1056 (unless (yas--template-menu-managed-by-yas-define-menu template)
1058 (yas--menu-keymap-get-create (yas--table-mode table)
1059 (mapcar #'yas--table-mode
1060 (yas--table-parents table))))
1061 (group (yas--template-group template)))
1062 ;; Remove from menu keymap
1064 (assert menu-keymap)
1065 (yas--delete-from-keymap menu-keymap (yas--template-uuid template))
1067 ;; Add necessary subgroups as necessary.
1069 (dolist (subgroup group)
1070 (let ((subgroup-keymap (lookup-key menu-keymap (vector (make-symbol subgroup)))))
1071 (unless (and subgroup-keymap
1072 (keymapp subgroup-keymap))
1073 (setq subgroup-keymap (make-sparse-keymap))
1074 (define-key menu-keymap (vector (make-symbol subgroup))
1075 `(menu-item ,subgroup ,subgroup-keymap)))
1076 (setq menu-keymap subgroup-keymap)))
1078 ;; Add this entry to the keymap
1080 (define-key menu-keymap
1081 (vector (make-symbol (yas--template-uuid template)))
1082 (car (yas--template-menu-binding-pair template))))))
1084 (defun yas--namehash-templates-alist (namehash)
1085 "Return NAMEHASH as an alist."
1087 (maphash #'(lambda (k v)
1088 (push (cons k v) alist))
1092 (defun yas--fetch (table key)
1093 "Fetch templates in TABLE by KEY.
1095 Return a list of cons (NAME . TEMPLATE) where NAME is a
1096 string and TEMPLATE is a `yas--template' structure."
1097 (let* ((keyhash (yas--table-hash table))
1098 (namehash (and keyhash (gethash key keyhash))))
1100 (yas--filter-templates-by-condition (yas--namehash-templates-alist namehash)))))
1103 ;;; Filtering/condition logic
1105 (defun yas--eval-condition (condition)
1112 (yas--message 1 "Error in condition evaluation: %s" (error-message-string err))
1116 (defun yas--filter-templates-by-condition (templates)
1117 "Filter the templates using the applicable condition.
1119 TEMPLATES is a list of cons (NAME . TEMPLATE) where NAME is a
1120 string and TEMPLATE is a `yas--template' structure.
1122 This function implements the rules described in
1123 `yas-buffer-local-condition'. See that variables documentation."
1124 (let ((requirement (yas--require-template-specific-condition-p)))
1125 (if (eq requirement 'always)
1127 (remove-if-not #'(lambda (pair)
1128 (yas--template-can-expand-p
1129 (yas--template-condition (cdr pair)) requirement))
1132 (defun yas--require-template-specific-condition-p ()
1133 "Decides if this buffer requests/requires snippet-specific
1134 conditions to filter out potential expansions."
1135 (if (eq 'always yas-buffer-local-condition)
1137 (let ((local-condition (or (and (consp yas-buffer-local-condition)
1138 (yas--eval-condition yas-buffer-local-condition))
1139 yas-buffer-local-condition)))
1140 (when local-condition
1141 (if (eq local-condition t)
1143 (and (consp local-condition)
1144 (eq 'require-snippet-condition (car local-condition))
1145 (symbolp (cdr local-condition))
1146 (cdr local-condition)))))))
1148 (defun yas--template-can-expand-p (condition requirement)
1149 "Evaluates CONDITION and REQUIREMENT and returns a boolean."
1150 (let* ((result (or (null condition)
1151 (yas--eval-condition condition))))
1152 (cond ((eq requirement t)
1155 (eq requirement result)))))
1157 (defun yas--all-parents (mode)
1158 "Returns a list of all parent modes of MODE."
1159 (or (gethash mode yas--ancestors)
1161 (labels ((yas--all-parents-1
1163 (cond ((memq m seen)
1165 "Cyclic parenthood: mode %s has already seen as a parent of mode %s"
1169 (let* ((parents (gethash m yas--parents)))
1170 (setq seen (append seen parents))
1171 (append parents (mapcan #'yas--all-parents-1 parents)))))))
1172 (puthash mode (yas--all-parents-1 mode)
1175 (defun yas--table-templates (table)
1178 (maphash #'(lambda (key namehash)
1179 (maphash #'(lambda (name template)
1180 (push (cons name template) acc))
1182 (yas--table-hash table))
1183 (yas--filter-templates-by-condition acc))))
1185 (defun yas--current-key ()
1186 "Get the key under current position. A key is used to find
1187 the template of a snippet in the current snippet-table."
1188 (let ((start (point))
1190 (syntaxes yas-key-syntaxes)
1194 (while (and (not done) syntaxes)
1195 (setq syntax (car syntaxes))
1196 (setq syntaxes (cdr syntaxes))
1198 (skip-syntax-backward syntax)
1199 (setq start (point)))
1201 (mapcan #'(lambda (table)
1202 (yas--fetch table (buffer-substring-no-properties start end)))
1203 (yas--get-snippet-tables)))
1212 (defun yas--table-all-keys (table)
1213 "Get trigger keys of all active snippets in TABLE."
1215 (maphash #'(lambda (key namehash)
1216 (when (yas--filter-templates-by-condition (yas--namehash-templates-alist namehash))
1218 (yas--table-hash table))
1221 (defun yas--table-mode (table)
1222 (intern (yas--table-name table)))
1225 ;;; Internal functions and macros:
1227 (defun yas--real-mode? (mode)
1228 "Try to find out if MODE is a real mode.
1230 The MODE bound to a function (like `c-mode') is considered real
1231 mode. Other well known mode like `ruby-mode' which is not part of
1232 Emacs might not bound to a function until it is loaded. So
1233 yasnippet keeps a list of modes like this to help the judgment."
1235 (find mode yas--known-modes)))
1237 (defun yas--eval-lisp (form)
1238 "Evaluate FORM and convert the result to string."
1239 (let ((retval (catch 'yas--exception
1245 (let ((result (eval form)))
1247 (format "%s" result))))))
1248 (error (if yas-good-grace
1249 (yas--format "elisp error! %s" (error-message-string err))
1250 (error (yas--format "elisp error: %s"
1251 (error-message-string err)))))))))
1252 (when (and (consp retval)
1253 (eq 'yas--exception (car retval)))
1254 (error (cdr retval)))
1257 (defun yas--eval-lisp-no-saves (form)
1260 (error (if yas-good-grace
1261 (yas--format "elisp error! %s" (error-message-string err))
1262 (error (yas--format "elisp error: %s"
1263 (error-message-string err)))))))
1265 (defun yas--read-lisp (string &optional nil-on-error)
1266 "Read STRING as a elisp expression and return it.
1268 In case STRING in an invalid expression and NIL-ON-ERROR is nil,
1269 return an expression that when evaluated will issue an error."
1272 (error (and (not nil-on-error)
1273 `(error (error-message-string ,err))))))
1275 (defun yas--read-keybinding (keybinding)
1276 "Read KEYBINDING as a snippet keybinding, return a vector."
1277 (when (and keybinding
1278 (not (string-match "keybinding" keybinding)))
1280 (let ((res (or (and (string-match "^\\[.*\\]$" keybinding)
1282 (read-kbd-macro keybinding 'need-vector))))
1285 (yas--message 3 "warning: keybinding \"%s\" invalid since %s."
1286 keybinding (error-message-string err))
1289 (defvar yas-extra-modes nil
1290 "If non-nil, also lookup snippets for this/these modes.
1292 Can be a symbol or a list of symbols.
1294 This variable probably makes more sense as buffer-local, so
1295 ensure your use `make-local-variable' when you set it.")
1296 (defun yas-extra-modes ()
1297 (if (listp yas-extra-modes) yas-extra-modes (list yas-extra-modes)))
1298 (defvaralias 'yas/mode-symbol 'yas-extra-modes)
1300 (defun yas--table-get-create (mode)
1301 "Get or create the snippet table corresponding to MODE."
1302 (let ((table (gethash mode
1305 (setq table (yas--make-snippet-table (symbol-name mode)))
1306 (puthash mode table yas--tables)
1307 (push (cons (intern (format "yas--direct-%s" mode))
1308 (yas--table-direct-keymap table))
1309 yas--direct-keymaps))
1312 (defun yas--get-snippet-tables ()
1313 "Get snippet tables for current buffer.
1315 Return a list of `yas--table' objects. The list of modes to
1316 consider is returned by `yas--modes-to-activate'"
1318 (mapcar #'(lambda (mode-name)
1319 (gethash mode-name yas--tables))
1320 (yas--modes-to-activate))))
1322 (defun yas--menu-keymap-get-create (mode &optional parents)
1323 "Get or create the menu keymap for MODE and its PARENTS.
1325 This may very well create a plethora of menu keymaps and arrange
1326 them all in `yas--menu-table'"
1327 (let* ((menu-keymap (or (gethash mode yas--menu-table)
1328 (puthash mode (make-sparse-keymap) yas--menu-table))))
1329 (mapc #'yas--menu-keymap-get-create parents)
1330 (define-key yas--minor-mode-menu (vector mode)
1331 `(menu-item ,(symbol-name mode) ,menu-keymap
1332 :visible (yas--show-menu-p ',mode)))
1336 (defmacro yas--called-interactively-p (&optional kind)
1337 "A backward-compatible version of `called-interactively-p'.
1339 Optional KIND is as documented at `called-interactively-p'
1340 in GNU Emacs 24.1 or higher."
1341 (if (string< emacs-version "24.1")
1342 '(called-interactively-p)
1343 `(called-interactively-p ,kind)))
1346 (defun yas--call-with-temporary-redefinitions (function
1347 &rest function-names-and-overriding-functions)
1348 (let* ((overrides (remove-if-not #'(lambda (fdef)
1349 (fboundp (first fdef)))
1350 function-names-and-overriding-functions))
1351 (definition-names (mapcar #'first overrides))
1352 (overriding-functions (mapcar #'second overrides))
1353 (saved-functions (mapcar #'symbol-function definition-names)))
1354 ;; saving all definitions before overriding anything ensures FDEFINITION
1355 ;; errors don't cause accidental permanent redefinitions.
1357 (labels ((set-fdefinitions (names functions)
1358 (loop for name in names
1360 do (fset name fn))))
1361 (set-fdefinitions definition-names overriding-functions)
1362 (unwind-protect (funcall function)
1363 (set-fdefinitions definition-names saved-functions)))))
1366 (defmacro yas--with-temporary-redefinitions (fdefinitions &rest body)
1367 ;; "Temporarily (but globally) redefine each function in FDEFINITIONS.
1368 ;; E.g.: (yas--with-temporary-redefinitions ((foo (x) ...)
1370 ;; ;; code that eventually calls foo, bar of (setf foo)
1372 `(yas--call-with-temporary-redefinitions
1374 ,@(mapcar #'(lambda (thingy)
1375 `(list ',(first thingy)
1376 (lambda ,@(rest thingy))))
1379 (put 'yas--with-temporary-redefinitions 'lisp-indent-function 1)
1380 (put 'yas--with-temporary-redefinitions 'edebug-form-spec '((&rest (defun*)) cl-declarations body))
1383 ;;; Template-related and snippet loading functions
1385 (defun yas--parse-template (&optional file)
1386 "Parse the template in the current buffer.
1388 Optional FILE is the absolute file name of the file being
1391 Optional GROUP is the group where the template is to go,
1392 otherwise we attempt to calculate it from FILE.
1394 Return a snippet-definition, i.e. a list
1396 (KEY TEMPLATE NAME CONDITION GROUP VARS FILE KEYBINDING UUID)
1398 If the buffer contains a line of \"# --\" then the contents above
1399 this line are ignored. Directives can set most of these with the syntax:
1401 # directive-name : directive-value
1403 Here's a list of currently recognized directives:
1414 (goto-char (point-min))
1415 (let* ((type 'snippet)
1417 (file-name-nondirectory file)))
1423 (yas--calculate-group file)))
1427 (if (re-search-forward "^# --\n" nil t)
1428 (progn (setq template
1429 (buffer-substring-no-properties (point)
1431 (setq bound (point))
1432 (goto-char (point-min))
1433 (while (re-search-forward "^# *\\([^ ]+?\\) *: *\\(.*\\)$" bound t)
1434 (when (string= "uuid" (match-string-no-properties 1))
1435 (setq uuid (match-string-no-properties 2)))
1436 (when (string= "type" (match-string-no-properties 1))
1437 (setq type (if (string= "command" (match-string-no-properties 2))
1440 (when (string= "key" (match-string-no-properties 1))
1441 (setq key (match-string-no-properties 2)))
1442 (when (string= "name" (match-string-no-properties 1))
1443 (setq name (match-string-no-properties 2)))
1444 (when (string= "condition" (match-string-no-properties 1))
1445 (setq condition (yas--read-lisp (match-string-no-properties 2))))
1446 (when (string= "group" (match-string-no-properties 1))
1447 (setq group (match-string-no-properties 2)))
1448 (when (string= "expand-env" (match-string-no-properties 1))
1449 (setq expand-env (yas--read-lisp (match-string-no-properties 2)
1451 (when (string= "binding" (match-string-no-properties 1))
1452 (setq binding (match-string-no-properties 2)))))
1454 (buffer-substring-no-properties (point-min) (point-max))))
1455 (unless (or key binding)
1456 (setq key (and file (file-name-nondirectory file))))
1457 (when (eq type 'command)
1458 (setq template (yas--read-lisp (concat "(progn" template ")"))))
1460 (setq group (split-string group "\\.")))
1461 (list key template name condition group expand-env file binding uuid)))
1463 (defun yas--calculate-group (file)
1464 "Calculate the group for snippet file path FILE."
1465 (let* ((dominating-dir (locate-dominating-file file
1466 ".yas-make-groups"))
1467 (extra-path (and dominating-dir
1468 (replace-regexp-in-string (concat "^"
1469 (expand-file-name dominating-dir))
1471 (expand-file-name file))))
1472 (extra-dir (and extra-path
1473 (file-name-directory extra-path)))
1474 (group (and extra-dir
1475 (replace-regexp-in-string "/"
1477 (directory-file-name extra-dir)))))
1480 (defun yas--subdirs (directory &optional filep)
1481 "Return subdirs or files of DIRECTORY according to FILEP."
1482 (remove-if (lambda (file)
1483 (or (string-match "^\\."
1484 (file-name-nondirectory file))
1485 (string-match "^#.*#$"
1486 (file-name-nondirectory file))
1488 (file-name-nondirectory file))
1490 (file-directory-p file)
1491 (not (file-directory-p file)))))
1492 (directory-files directory t)))
1494 (defun yas--make-menu-binding (template)
1495 (let ((mode (yas--table-mode (yas--template-table template))))
1496 `(lambda () (interactive) (yas--expand-or-visit-from-menu ',mode ,(yas--template-uuid template)))))
1498 (defun yas--expand-or-visit-from-menu (mode uuid)
1499 (let* ((table (yas--table-get-create mode))
1500 (yas--current-template (and table
1501 (gethash uuid (yas--table-uuidhash table)))))
1502 (when yas--current-template
1503 (if yas-visit-from-menu
1504 (yas--visit-snippet-file-1 yas--current-template)
1505 (let ((where (if (region-active-p)
1506 (cons (region-beginning) (region-end))
1507 (cons (point) (point)))))
1508 (yas-expand-snippet (yas--template-content yas--current-template)
1511 (yas--template-expand-env yas--current-template)))))))
1514 ;;; Popping up for keys and templates
1516 (defvar yas--x-pretty-prompt-templates nil
1517 "If non-nil, attempt to prompt for templates like TextMate.")
1520 (defun yas--prompt-for-template (templates &optional prompt)
1521 "Interactively choose a template from the list TEMPLATES.
1523 TEMPLATES is a list of `yas--template'.
1525 Optional PROMPT sets the prompt to use."
1528 (sort templates #'(lambda (t1 t2)
1529 (< (length (yas--template-name t1))
1530 (length (yas--template-name t2))))))
1531 (if yas--x-pretty-prompt-templates
1532 (yas--x-pretty-prompt-templates "Choose a snippet" templates)
1533 (some #'(lambda (fn)
1534 (funcall fn (or prompt "Choose a snippet: ")
1536 #'yas--template-name))
1537 yas-prompt-functions))))
1539 (defun yas--prompt-for-keys (keys &optional prompt)
1540 "Interactively choose a template key from the list KEYS.
1542 Optional PROMPT sets the prompt to use."
1544 (some #'(lambda (fn)
1545 (funcall fn (or prompt "Choose a snippet key: ") keys))
1546 yas-prompt-functions)))
1548 (defun yas--prompt-for-table (tables &optional prompt)
1549 "Interactively choose a table from the list TABLES.
1551 Optional PROMPT sets the prompt to use."
1553 (some #'(lambda (fn)
1554 (funcall fn (or prompt "Choose a snippet table: ")
1557 yas-prompt-functions)))
1559 (defun yas-x-prompt (prompt choices &optional display-fn)
1560 "Display choices in a x-window prompt."
1561 ;; FIXME: HACK: if we notice that one of the objects in choices is
1562 ;; actually a `yas--template', defer to `yas--x-prompt-pretty-templates'
1564 ;; This would be better implemented by passing CHOICES as a
1565 ;; structured tree rather than a list. Modifications would go as far
1566 ;; up as `yas--all-templates' I think.
1568 (when (and window-system choices)
1570 (let (menu d) ;; d for display
1572 (setq d (or (and display-fn (funcall display-fn c))
1575 (push (cons (concat " " d) c) menu))
1577 (push (car d) menu))))
1578 (setq menu (list prompt (push "title" menu)))
1579 (x-popup-menu (if (fboundp 'posn-at-point)
1580 (let ((x-y (posn-x-y (posn-at-point (point)))))
1581 (list (list (+ (car x-y) 10)
1589 (defun yas--x-pretty-prompt-templates (prompt templates)
1590 "Display TEMPLATES, grouping neatly by table name."
1591 (let ((organized (make-hash-table :test #'equal))
1595 (dolist (tl templates)
1596 (puthash (yas--template-table tl)
1598 (gethash (yas--template-table tl) organized))
1600 (setq more-than-one-table (> (hash-table-count organized) 1))
1601 (setq prefix (if more-than-one-table
1603 (if more-than-one-table
1604 (maphash #'(lambda (table templates)
1605 (push (yas--table-name table) menu)
1606 (dolist (tl templates)
1607 (push (cons (concat prefix (yas--template-name tl)) tl) menu))) organized)
1608 (setq menu (mapcar #'(lambda (tl) (cons (concat prefix (yas--template-name tl)) tl)) templates)))
1610 (setq menu (nreverse menu))
1611 (or (x-popup-menu (if (fboundp 'posn-at-point)
1612 (let ((x-y (posn-x-y (posn-at-point (point)))))
1613 (list (list (+ (car x-y) 10)
1617 (list prompt (push "title" menu)))
1620 (defun yas-ido-prompt (prompt choices &optional display-fn)
1621 (when (and (fboundp 'ido-completing-read)
1622 (or (>= emacs-major-version 24)
1624 (yas-completing-prompt prompt choices display-fn #'ido-completing-read)))
1627 (if (fboundp 'declare-function)
1628 (declare-function dropdown-list "dropdown-list")))
1630 (defun yas-dropdown-prompt (prompt choices &optional display-fn)
1631 (when (featurep 'dropdown-list)
1632 (let (formatted-choices
1636 (dolist (choice choices)
1637 (setq d (or (and display-fn (funcall display-fn choice))
1640 (push d formatted-choices)
1641 (push choice filtered-choices)))
1643 (setq n (and formatted-choices (dropdown-list formatted-choices)))
1645 (nth n filtered-choices)
1648 (defun yas-completing-prompt (prompt choices &optional display-fn completion-fn)
1649 (let (formatted-choices
1653 (completion-fn (or completion-fn
1654 #'completing-read)))
1655 (dolist (choice choices)
1656 (setq d (or (and display-fn (funcall display-fn choice))
1659 (push d formatted-choices)
1660 (push choice filtered-choices)))
1661 (setq chosen (and formatted-choices
1662 (funcall completion-fn prompt
1668 (let ((position (or (and chosen
1669 (position chosen formatted-choices :test #'string=))
1671 (nth position filtered-choices))))
1673 (defun yas-no-prompt (prompt choices &optional display-fn)
1677 ;;; Defining snippets
1678 ;; This consists of creating and registering `yas--template' objects in the
1682 (defun yas--define-snippets-1 (snippet snippet-table)
1683 "Helper for `yas-define-snippets'."
1684 ;; X) Calculate some more defaults on the values returned by
1685 ;; `yas--parse-template'.
1687 (let* ((file (seventh snippet))
1689 (name (or (third snippet)
1691 (file-name-directory file))))
1692 (condition (fourth snippet))
1693 (group (fifth snippet))
1694 (keybinding (yas--read-keybinding (eighth snippet)))
1695 (uuid (or (ninth snippet)
1697 (template (or (gethash uuid (yas--table-uuidhash snippet-table))
1698 (yas--make-blank-template))))
1699 ;; X) populate the template object
1701 (yas--populate-template template
1702 :table snippet-table
1704 :content (second snippet)
1707 :condition condition
1708 :expand-env (sixth snippet)
1709 :file (seventh snippet)
1710 :keybinding keybinding
1712 ;; X) Update this template in the appropriate table. This step
1713 ;; also will take care of adding the key indicators in the
1714 ;; templates menu entry, if any
1716 (yas--update-template snippet-table template)
1717 ;; X) Return the template
1722 (defun yas-define-snippets (mode snippets)
1723 "Define SNIPPETS for MODE.
1725 SNIPPETS is a list of snippet definitions, each taking the
1728 (KEY TEMPLATE NAME CONDITION GROUP EXPAND-ENV FILE KEYBINDING UUID)
1730 Within these, only KEY and TEMPLATE are actually mandatory.
1732 TEMPLATE might be a lisp form or a string, depending on whether
1733 this is a snippet or a snippet-command.
1735 CONDITION, EXPAND-ENV and KEYBINDING are lisp forms, they have
1736 been `yas--read-lisp'-ed and will eventually be
1737 `yas--eval-lisp'-ed.
1739 The remaining elements are strings.
1741 FILE is probably of very little use if you're programatically
1744 UUID is the snippets \"unique-id\". Loading a second snippet file
1745 with the same uuid replaced the previous snippet.
1747 You can use `yas--parse-template' to return such lists based on
1748 the current buffers contents."
1749 (let ((snippet-table (yas--table-get-create mode))
1751 (dolist (snippet snippets)
1752 (setq template (yas--define-snippets-1 snippet
1757 ;;; Loading snippets from files
1759 (defun yas--load-yas-setup-file (file)
1760 (load file 'noerror))
1762 (defun yas--define-parents (mode parents)
1763 "Add PARENTS to the list of MODE's parents."
1764 (puthash mode (remove-duplicates
1766 (gethash mode yas--parents)))
1769 (defun yas-load-directory (top-level-dir &optional use-jit)
1770 "Load snippets in directory hierarchy TOP-LEVEL-DIR.
1772 Below TOP-LEVEL-DIR each directory should be a mode name.
1774 Optional USE-JIT use jit-loading of snippets."
1775 (interactive "DSelect the root directory: ")
1776 (unless yas-snippet-dirs
1777 (setq yas-snippet-dirs top-level-dir))
1778 (dolist (dir (yas--subdirs top-level-dir))
1779 (let* ((major-mode-and-parents (yas--compute-major-mode-and-parents
1780 (concat dir "/dummy")))
1781 (mode-sym (car major-mode-and-parents))
1782 (parents (cdr major-mode-and-parents)))
1783 ;; Attention: The parents and the menus are already defined
1784 ;; here, even if the snippets are later jit-loaded.
1786 ;; * We need to know the parents at this point since entering a
1787 ;; given mode should jit load for its parents
1788 ;; immediately. This could be reviewed, the parents could be
1789 ;; discovered just-in-time-as well
1791 ;; * We need to create the menus here to support the `full'
1792 ;; option to `yas-use-menu' (all known snippet menus are shown to the user)
1794 (yas--define-parents mode-sym parents)
1795 (yas--menu-keymap-get-create mode-sym)
1796 (let ((form `(yas--load-directory-1 ,dir
1800 (not (some #'(lambda (buffer)
1801 (with-current-buffer buffer
1802 (when (eq major-mode mode-sym)
1803 (yas--message 3 "Discovered there was already %s in %s" buffer mode-sym)
1806 (yas--schedule-jit mode-sym form)
1808 (when (yas--called-interactively-p 'interactive)
1809 (yas--message 3 "Loaded snippets from %s." top-level-dir)))
1811 (defun yas--load-directory-1 (directory mode-sym parents &optional no-compiled-snippets)
1812 "Recursively load snippet templates from DIRECTORY."
1813 (unless (file-exists-p (concat directory "/" ".yas-skip"))
1814 (if (and (not no-compiled-snippets)
1815 (progn (yas--message 2 "Loading compiled snippets from %s" directory) t)
1816 (load (expand-file-name ".yas-compiled-snippets" directory) 'noerror (<= yas-verbosity 3)))
1817 (yas--message 2 "Loading snippet files from %s" directory)
1818 (yas--load-directory-2 directory mode-sym))))
1820 (defun yas--load-directory-2 (directory mode-sym)
1821 ;; Load .yas-setup.el files wherever we find them
1823 (yas--load-yas-setup-file (expand-file-name ".yas-setup" directory))
1824 (let* ((default-directory directory)
1826 ;; load the snippet files
1829 (dolist (file (yas--subdirs directory 'no-subdirs-just-files))
1830 (when (file-readable-p file)
1831 (insert-file-contents file nil nil nil t)
1832 (push (yas--parse-template file)
1835 (yas-define-snippets mode-sym
1837 ;; now recurse to a lower level
1839 (dolist (subdir (yas--subdirs directory))
1840 (yas--load-directory-2 subdir
1843 (defun yas--load-snippet-dirs (&optional nojit)
1844 "Reload the directories listed in `yas-snippet-dirs' or
1845 prompt the user to select one."
1847 (if yas-snippet-dirs
1848 (dolist (directory (reverse (yas-snippet-dirs)))
1849 (cond ((file-directory-p directory)
1850 (yas-load-directory directory (not nojit))
1852 (yas--message 3 "Loaded %s" directory)
1853 (yas--message 3 "Prepared just-in-time loading for %s" directory)))
1855 (push (yas--message 0 "Check your `yas-snippet-dirs': %s is not a directory" directory) errors))))
1856 (call-interactively 'yas-load-directory))
1859 (defun yas-reload-all (&optional interactive)
1860 "Reload all snippets and rebuild the YASnippet menu.
1862 When called interactively force immediate reload of all known
1863 snippets under `yas-snippet-dirs', otherwise use just-in-time
1868 (snippet-editing-buffers
1869 (remove-if-not #'(lambda (buffer)
1870 (with-current-buffer buffer yas--editing-template))
1872 ;; Warn if there are buffers visiting snippets, since reloading will break
1873 ;; any on-line editing of those buffers.
1875 (when snippet-editing-buffers
1877 (if (y-or-n-p "Some buffers editing live snippets, close them and proceed with reload? ")
1878 (mapc #'kill-buffer snippet-editing-buffers)
1879 (yas--message 1 "Aborted reload...")
1881 ;; in a non-interactive use, at least set
1882 ;; `yas--editing-template' to nil, make it guess it next time around
1883 (mapc #'(lambda (buffer) (setq yas--editing-template nil)) (buffer-list))))
1885 ;; Empty all snippet tables and parenting info
1887 (setq yas--tables (make-hash-table))
1888 (setq yas--parents (make-hash-table))
1889 (setq yas--ancestors (make-hash-table))
1891 ;; Before killing `yas--menu-table' use its keys to cleanup the
1892 ;; mode menu parts of `yas--minor-mode-menu' (thus also cleaning
1893 ;; up `yas-minor-mode-map', which points to it)
1895 (maphash #'(lambda (menu-symbol keymap)
1896 (define-key yas--minor-mode-menu (vector menu-symbol) nil))
1898 ;; Now empty `yas--menu-table' as well
1899 (setq yas--menu-table (make-hash-table))
1901 ;; Cancel all pending 'yas--scheduled-jit-loads'
1903 (setq yas--scheduled-jit-loads (make-hash-table))
1905 ;; Reload the directories listed in `yas-snippet-dirs' or prompt
1906 ;; the user to select one.
1908 (setq errors (yas--load-snippet-dirs interactive))
1909 ;; Reload the direct keybindings
1911 (yas-direct-keymaps-reload)
1913 (yas--message 3 "Reloaded everything%s...%s."
1914 (if interactive "" " (snippets will load just-in-time)")
1915 (if errors " (some errors, check *Messages*)" "")))))
1917 (defun yas--load-pending-jits ()
1918 (dolist (mode (yas--modes-to-activate))
1919 (let ((forms (reverse (gethash mode yas--scheduled-jit-loads))))
1920 ;; must reverse to maintain coherence with `yas-snippet-dirs'
1921 (dolist (form forms)
1922 (yas--message 3 "Loading for `%s', just-in-time: %s!" mode form)
1924 (remhash mode yas--scheduled-jit-loads))))
1926 ;; (when (<= emacs-major-version 22)
1927 ;; (add-hook 'after-change-major-mode-hook 'yas--load-pending-jits))
1929 (defun yas--quote-string (string)
1930 "Escape and quote STRING.
1931 foo\"bar\\! -> \"foo\\\"bar\\\\!\""
1933 (replace-regexp-in-string "[\\\"]"
1939 ;;; Snippet compilation function
1941 (defun yas--initialize ()
1942 "For backward compatibility, enable `yas-minor-mode' globally."
1943 (yas-global-mode 1))
1945 (defun yas-compile-directory (top-level-dir)
1946 "Create .yas-compiled-snippets.el files under subdirs of TOP-LEVEL-DIR.
1948 This works by stubbing a few functions, then calling
1949 `yas-load-directory'."
1950 (interactive "DTop level snippet directory?")
1951 (yas--with-temporary-redefinitions
1952 ((yas--load-yas-setup-file
1954 (let ((elfile (concat file ".el")))
1955 (when (file-exists-p elfile)
1956 (insert ";;; .yas-setup.el support file if any:\n;;;\n")
1957 (insert-file-contents elfile)
1958 (goto-char (point-max))
1960 (yas-define-snippets
1962 (insert ";;; Snippet definitions:\n;;;\n")
1963 (let ((literal-snippets (list))
1965 (dolist (snippet snippets)
1966 (let ((key (first snippet))
1967 (template-content (second snippet))
1968 (name (third snippet))
1969 (condition (fourth snippet))
1970 (group (fifth snippet))
1971 (expand-env (sixth snippet))
1972 (file nil) ;; (seventh snippet)) ;; omit on purpose
1973 (binding (eighth snippet))
1974 (uuid (ninth snippet)))
1985 (insert (pp-to-string `(yas-define-snippets ',mode ',literal-snippets)))
1987 (yas--load-directory-1
1988 (dir mode parents &rest ignore)
1989 (let ((output-file (concat (file-name-as-directory dir) ".yas-compiled-snippets.el")))
1990 (with-temp-file output-file
1991 (insert (format ";;; Compiled snippets and support files for `%s'\n" mode))
1992 (yas--load-directory-2 dir mode)
1993 (insert (format ";;; Do not edit! File generated at %s\n" (current-time-string)))))))
1994 (yas-load-directory top-level-dir nil)))
1996 (defun yas-recompile-all ()
1997 "Compile every dir in `yas-snippet-dirs'."
1999 (mapc #'yas-compile-directory (yas-snippet-dirs)))
2005 (defvar yas--scheduled-jit-loads (make-hash-table)
2006 "Alist of mode-symbols to forms to be evaled when `yas-minor-mode' kicks in.")
2008 (defun yas--schedule-jit (mode form)
2011 (gethash mode yas--scheduled-jit-loads))
2012 yas--scheduled-jit-loads))
2016 ;;; Some user level functions
2020 (message (concat "yasnippet (version "
2022 ") -- pluskid <pluskid@gmail.com>/joaotavora <joaotavora@gmail.com>")))
2025 ;;; Apropos snippet menu:
2027 ;; The snippet menu keymaps are store by mode in hash table called
2028 ;; `yas--menu-table'. They are linked to the main menu in
2029 ;; `yas--menu-keymap-get-create' and are initially created empty,
2030 ;; reflecting the table hierarchy.
2032 ;; They can be populated in two mutually exclusive ways: (1) by
2033 ;; reading `yas--template-group', which in turn is populated by the "#
2034 ;; group:" directives of the snippets or the ".yas-make-groups" file
2035 ;; or (2) by using a separate `yas-define-menu' call, which declares a
2036 ;; menu structure based on snippets uuids.
2038 ;; Both situations are handled in `yas--update-template-menu', which
2039 ;; uses the predicate `yas--template-menu-managed-by-yas-define-menu'
2040 ;; that can tell between the two situations.
2044 ;; * if `yas-define-menu' is used it must run before
2045 ;; `yas-define-snippets' and the UUIDS must match, otherwise we get
2046 ;; duplicate entries. The `yas--template' objects are created in
2047 ;; `yas-define-menu', holding nothing but the menu entry,
2048 ;; represented by a pair of ((menu-item NAME :keys KEYS) TYPE) and
2049 ;; stored in `yas--template-menu-binding-pair'. The (menu-item ...)
2050 ;; part is then stored in the menu keymap itself which make the item
2051 ;; appear to the user. These limitations could probably be revised.
2053 ;; * The `yas--template-perm-group' slot is only used in
2054 ;; `yas-describe-tables'.
2056 (defun yas--template-menu-binding-pair-get-create (template &optional type)
2057 "Get TEMPLATE's menu binding or assign it a new one.
2059 TYPE may be `:stay', signaling this menu binding should be
2060 static in the menu."
2061 (or (yas--template-menu-binding-pair template)
2062 (let ((key (yas--template-key template))
2063 (keybinding (yas--template-keybinding template)))
2064 (setf (yas--template-menu-binding-pair template)
2065 (cons `(menu-item ,(or (yas--template-name template)
2066 (yas--template-uuid template))
2067 ,(yas--make-menu-binding template)
2070 (defun yas--template-menu-managed-by-yas-define-menu (template)
2071 "Non-nil if TEMPLATE's menu entry was included in a `yas-define-menu' call."
2072 (cdr (yas--template-menu-binding-pair template)))
2075 (defun yas--show-menu-p (mode)
2076 (cond ((eq yas-use-menu 'abbreviate)
2078 (mapcar #'(lambda (table)
2079 (yas--table-mode table))
2080 (yas--get-snippet-tables))))
2081 ((eq yas-use-menu 'full)
2083 ((eq yas-use-menu t)
2086 (defun yas--delete-from-keymap (keymap uuid)
2087 "Recursively delete items with UUID from KEYMAP and its submenus."
2089 ;; XXX: This used to skip any submenus named \"parent mode\"
2091 ;; First of all, recursively enter submenus, i.e. the tree is
2092 ;; searched depth first so that stale submenus can be found in the
2095 (mapc #'(lambda (item)
2096 (when (and (listp (cdr item))
2097 (keymapp (third (cdr item))))
2098 (yas--delete-from-keymap (third (cdr item)) uuid)))
2100 ;; Set the uuid entry to nil
2102 (define-key keymap (vector (make-symbol uuid)) nil)
2103 ;; Destructively modify keymap
2105 (setcdr keymap (delete-if #'(lambda (item)
2106 (or (null (cdr item))
2107 (and (keymapp (third (cdr item)))
2108 (null (cdr (third (cdr item)))))))
2111 (defun yas-define-menu (mode menu &optional omit-items)
2112 "Define a snippet menu for MODE according to MENU, omitting OMIT-ITEMS.
2114 MENU is a list, its elements can be:
2116 - (yas-item UUID) : Creates an entry the snippet identified with
2117 UUID. The menu entry for a snippet thus identified is
2118 permanent, i.e. it will never move (be reordered) in the menu.
2120 - (yas-separator) : Creates a separator
2122 - (yas-submenu NAME SUBMENU) : Creates a submenu with NAME,
2123 SUBMENU has the same form as MENU. NAME is also added to the
2124 list of groups of the snippets defined thereafter.
2126 OMIT-ITEMS is a list of snippet uuid's that will always be
2127 omitted from MODE's menu, even if they're manually loaded.
2129 This function does nothing if `yas-use-menu' is nil."
2131 (let* ((table (yas--table-get-create mode))
2132 (hash (yas--table-uuidhash table)))
2133 (yas--define-menu-1 table
2134 (yas--menu-keymap-get-create mode)
2137 (dolist (uuid omit-items)
2138 (let ((template (or (gethash uuid hash)
2139 (yas--populate-template (puthash uuid
2140 (yas--make-blank-template)
2144 (setf (yas--template-menu-binding-pair template) (cons nil :none)))))))
2146 (defun yas--define-menu-1 (table menu-keymap menu uuidhash &optional group-list)
2147 "Helper for `yas-define-menu'."
2148 (dolist (e (reverse menu))
2149 (cond ((eq (first e) 'yas-item)
2150 (let ((template (or (gethash (second e) uuidhash)
2151 (yas--populate-template (puthash (second e)
2152 (yas--make-blank-template)
2155 :perm-group group-list
2156 :uuid (second e)))))
2157 (define-key menu-keymap (vector (gensym))
2158 (car (yas--template-menu-binding-pair-get-create template :stay)))))
2159 ((eq (first e) 'yas-submenu)
2160 (let ((subkeymap (make-sparse-keymap)))
2161 (define-key menu-keymap (vector (gensym))
2162 `(menu-item ,(second e) ,subkeymap))
2163 (yas--define-menu-1 table
2167 (append group-list (list (second e))))))
2168 ((eq (first e) 'yas-separator)
2169 (define-key menu-keymap (vector (gensym))
2170 '(menu-item "----")))
2172 (yas--message 3 "Don't know anything about menu entry %s" (first e))))))
2174 (defun yas--define (mode key template &optional name condition group)
2175 "Define a snippet. Expanding KEY into TEMPLATE.
2177 NAME is a description to this template. Also update the menu if
2178 `yas-use-menu' is t. CONDITION is the condition attached to
2179 this snippet. If you attach a condition to a snippet, then it
2180 will only be expanded when the condition evaluated to non-nil."
2181 (yas-define-snippets mode
2182 (list (list key template name condition group))))
2184 (defun yas-hippie-try-expand (first-time?)
2185 "Integrate with hippie expand.
2187 Just put this function in `hippie-expand-try-functions-list'."
2188 (when yas-minor-mode
2189 (if (not first-time?)
2190 (let ((yas-fallback-behavior 'return-nil))
2196 ;;; Apropos condition-cache:
2201 (defvar yas--condition-cache-timestamp nil)
2202 (defmacro yas-define-condition-cache (func doc &rest body)
2203 "Define a function FUNC with doc DOC and body BODY, BODY is
2204 executed at most once every snippet expansion attempt, to check
2205 expansion conditions.
2207 It doesn't make any sense to call FUNC programatically."
2208 `(defun ,func () ,(if (and doc
2211 "\n\nFor use in snippets' conditions. Within each
2212 snippet-expansion routine like `yas-expand', computes actual
2213 value for the first time then always returns a cached value.")
2214 (setq body (cons doc body))
2216 (let ((timestamp-and-value (get ',func 'yas--condition-cache)))
2217 (if (equal (car timestamp-and-value) yas--condition-cache-timestamp)
2218 (cdr timestamp-and-value)
2219 (let ((new-value (progn
2222 (put ',func 'yas--condition-cache (cons yas--condition-cache-timestamp new-value))
2225 (defalias 'yas-expand 'yas-expand-from-trigger-key)
2226 (defun yas-expand-from-trigger-key (&optional field)
2227 "Expand a snippet before point.
2229 If no snippet expansion is possible, fall back to the behaviour
2230 defined in `yas-fallback-behavior'.
2232 Optional argument FIELD is for non-interactive use and is an
2233 object satisfying `yas--field-p' to restrict the expansion to."
2235 (setq yas--condition-cache-timestamp (current-time))
2236 (let (templates-and-pos)
2237 (unless (and yas-expand-only-for-last-commands
2238 (not (member last-command yas-expand-only-for-last-commands)))
2239 (setq templates-and-pos (if field
2241 (narrow-to-region (yas--field-start field)
2242 (yas--field-end field))
2244 (yas--current-key))))
2245 (if (and templates-and-pos
2246 (first templates-and-pos))
2247 (yas--expand-or-prompt-for-template (first templates-and-pos)
2248 (second templates-and-pos)
2249 (third templates-and-pos))
2250 (yas--fallback 'trigger-key))))
2252 (defun yas-expand-from-keymap ()
2253 "Directly expand some snippets, searching `yas--direct-keymaps'.
2255 If expansion fails, execute the previous binding for this key"
2257 (setq yas--condition-cache-timestamp (current-time))
2258 (let* ((yas--prefix current-prefix-arg)
2259 (vec (subseq (this-command-keys-vector) (if current-prefix-arg
2260 universal-argument-num-events
2262 (templates (mapcan #'(lambda (table)
2263 (yas--fetch table vec))
2264 (yas--get-snippet-tables))))
2266 (yas--expand-or-prompt-for-template templates)
2267 (let ((yas-fallback-behavior 'call-other-command))
2270 (defun yas--expand-or-prompt-for-template (templates &optional start end)
2271 "Expand one of TEMPLATES from START to END.
2273 Prompt the user if TEMPLATES has more than one element, else
2274 expand immediately. Common gateway for
2275 `yas-expand-from-trigger-key' and `yas-expand-from-keymap'."
2276 (let ((yas--current-template (or (and (rest templates) ;; more than one
2277 (yas--prompt-for-template (mapcar #'cdr templates)))
2279 (when yas--current-template
2280 (yas-expand-snippet (yas--template-content yas--current-template)
2283 (yas--template-expand-env yas--current-template)))))
2285 ;; Apropos the trigger key and the fallback binding:
2287 ;; When `yas-minor-mode-map' binds <tab>, that correctly overrides
2288 ;; org-mode's <tab>, for example and searching for fallbacks correctly
2289 ;; returns `org-cycle'. However, most other modes bind "TAB". TODO,
2290 ;; improve this explanation.
2292 (defun yas--fallback (&optional from-trigger-key-p)
2293 "Fallback after expansion has failed.
2295 Common gateway for `yas-expand-from-trigger-key' and
2296 `yas-expand-from-keymap'."
2297 (cond ((eq yas-fallback-behavior 'return-nil)
2300 ((eq yas-fallback-behavior 'call-other-command)
2301 (let* ((beyond-yasnippet (yas--keybinding-beyond-yasnippet)))
2302 (yas--message 4 "Falling back to %s" beyond-yasnippet)
2303 (assert (or (null beyond-yasnippet) (commandp beyond-yasnippet)))
2304 (setq this-original-command beyond-yasnippet)
2305 (call-interactively beyond-yasnippet)))
2306 ((and (listp yas-fallback-behavior)
2307 (cdr yas-fallback-behavior)
2308 (eq 'apply (car yas-fallback-behavior)))
2309 (if (cddr yas-fallback-behavior)
2310 (apply (cadr yas-fallback-behavior)
2311 (cddr yas-fallback-behavior))
2312 (when (commandp (cadr yas-fallback-behavior))
2313 (setq this-command (cadr yas-fallback-behavior))
2314 (call-interactively (cadr yas-fallback-behavior)))))
2316 ;; also return nil if all the other fallbacks have failed
2319 (defun yas--keybinding-beyond-yasnippet ()
2321 (let* ((yas-minor-mode nil)
2322 (yas--direct-keymaps nil)
2323 (keys (this-single-command-keys)))
2324 (or (key-binding keys t)
2325 (key-binding (yas--fallback-translate-input keys) t))))
2327 (defun yas--fallback-translate-input (keys)
2328 "Emulate `read-key-sequence', at least what I think it does.
2330 Keys should be an untranslated key vector. Returns a translated
2331 vector of keys. FIXME not thoroughly tested"
2334 (while (< i (length keys))
2336 (translated local-function-key-map))
2337 (while (and (< j (length keys))
2339 (keymapp translated))
2340 (setq translated (cdr (assoc (aref keys j) (remove 'keymap translated)))
2342 (setq retval (vconcat retval (cond ((symbolp translated)
2344 ((vectorp translated)
2347 (substring keys i j)))))
2352 ;;; Utils for snippet development:
2354 (defun yas--all-templates (tables)
2355 "Get `yas--template' objects in TABLES, applicable for buffer and point.
2357 Honours `yas-choose-tables-first', `yas-choose-keys-first' and
2358 `yas-buffer-local-condition'"
2359 (when yas-choose-tables-first
2360 (setq tables (list (yas--prompt-for-table tables))))
2362 (if yas-choose-keys-first
2363 (let ((key (yas--prompt-for-keys
2364 (mapcan #'yas--table-all-keys tables))))
2366 (mapcan #'(lambda (table)
2367 (yas--fetch table key))
2369 (remove-duplicates (mapcan #'yas--table-templates tables)
2372 (defun yas-insert-snippet (&optional no-condition)
2373 "Choose a snippet to expand, pop-up a list of choices according
2374 to `yas--prompt-function'.
2376 With prefix argument NO-CONDITION, bypass filtering of snippets
2379 (setq yas--condition-cache-timestamp (current-time))
2380 (let* ((yas-buffer-local-condition (or (and no-condition
2382 yas-buffer-local-condition))
2383 (templates (yas--all-templates (yas--get-snippet-tables)))
2384 (yas--current-template (and templates
2385 (or (and (rest templates) ;; more than one template for same key
2386 (yas--prompt-for-template templates))
2388 (where (if (region-active-p)
2389 (cons (region-beginning) (region-end))
2390 (cons (point) (point)))))
2391 (if yas--current-template
2392 (yas-expand-snippet (yas--template-content yas--current-template)
2395 (yas--template-expand-env yas--current-template))
2396 (yas--message 3 "No snippets can be inserted here!"))))
2398 (defun yas-visit-snippet-file ()
2399 "Choose a snippet to edit, selection like `yas-insert-snippet'.
2401 Only success if selected snippet was loaded from a file. Put the
2402 visited file in `snippet-mode'."
2404 (let* ((yas-buffer-local-condition 'always)
2405 (templates (yas--all-templates (yas--get-snippet-tables)))
2406 (yas-prompt-functions '(yas-ido-prompt yas-completing-prompt))
2407 (template (and templates
2408 (or (yas--prompt-for-template templates
2409 "Choose a snippet template to edit: ")
2413 (yas--visit-snippet-file-1 template)
2414 (message "No snippets tables active!"))))
2416 (defun yas--visit-snippet-file-1 (template)
2417 "Helper for `yas-visit-snippet-file'."
2418 (let ((file (yas--template-file template)))
2419 (cond ((and file (file-readable-p file))
2420 (find-file-other-window file)
2422 (set (make-local-variable 'yas--editing-template) template))
2424 (message "Original file %s no longer exists!" file))
2426 (switch-to-buffer (format "*%s*"(yas--template-name template)))
2427 (let ((type 'snippet))
2428 (when (listp (yas--template-content template))
2429 (insert (format "# type: command\n"))
2430 (setq type 'command))
2431 (insert (format "# key: %s\n" (yas--template-key template)))
2432 (insert (format "# name: %s\n" (yas--template-name template)))
2433 (when (yas--template-keybinding template)
2434 (insert (format "# binding: %s\n" (yas--template-keybinding template))))
2435 (when (yas--template-expand-env template)
2436 (insert (format "# expand-env: %s\n" (yas--template-expand-env template))))
2437 (when (yas--template-condition template)
2438 (insert (format "# condition: %s\n" (yas--template-condition template))))
2440 (insert (if (eq type 'command)
2441 (pp-to-string (yas--template-content template))
2442 (yas--template-content template))))
2444 (set (make-local-variable 'yas--editing-template) template)))))
2446 (defun yas--guess-snippet-directories-1 (table)
2447 "Guesses possible snippet subdirectories for TABLE."
2448 (cons (yas--table-name table)
2449 (mapcan #'(lambda (parent)
2450 (yas--guess-snippet-directories-1
2452 (yas--table-parents table))))
2454 (defun yas--guess-snippet-directories (&optional table)
2455 "Try to guess suitable directories based on the current active
2456 tables (or optional TABLE).
2458 Returns a list of elements (TABLE . DIRS) where TABLE is a
2459 `yas--table' object and DIRS is a list of all possible directories
2460 where snippets of table might exist."
2461 (let ((main-dir (replace-regexp-in-string
2463 (or (first (or (yas-snippet-dirs)
2464 (setq yas-snippet-dirs '("~/.emacs.d/snippets")))))))
2465 (tables (or (and table
2467 (yas--get-snippet-tables))))
2468 ;; HACK! the snippet table created here is actually registered!
2470 (unless (or table (gethash major-mode yas--tables))
2471 (push (yas--table-get-create major-mode)
2474 (mapcar #'(lambda (table)
2476 (mapcar #'(lambda (subdir)
2477 (concat main-dir "/" subdir))
2478 (yas--guess-snippet-directories-1 table))))
2481 (defun yas--make-directory-maybe (table-and-dirs &optional main-table-string)
2482 "Returns a dir inside TABLE-AND-DIRS, prompts for creation if none exists."
2483 (or (some #'(lambda (dir) (when (file-directory-p dir) dir)) (cdr table-and-dirs))
2484 (let ((candidate (first (cdr table-and-dirs))))
2485 (unless (file-writable-p (file-name-directory candidate))
2486 (error (yas--format "%s is not writable." candidate)))
2487 (if (y-or-n-p (format "Guessed directory (%s) for%s%s table \"%s\" does not exist! Create? "
2489 (if (gethash (yas--table-mode (car table-and-dirs))
2493 (or main-table-string
2495 (yas--table-name (car table-and-dirs))))
2497 (make-directory candidate 'also-make-parents)
2498 ;; create the .yas-parents file here...
2501 (defun yas-new-snippet (&optional no-template)
2502 "Pops a new buffer for writing a snippet.
2504 Expands a snippet-writing snippet, unless the optional prefix arg
2505 NO-TEMPLATE is non-nil."
2507 (let ((guessed-directories (yas--guess-snippet-directories)))
2509 (switch-to-buffer "*new snippet*")
2511 (kill-all-local-variables)
2514 (set (make-local-variable 'yas--guessed-modes) (mapcar #'(lambda (d)
2515 (yas--table-mode (car d)))
2516 guessed-directories))
2517 (unless no-template (yas-expand-snippet "\
2518 # -*- mode: snippet -*-
2520 # key: ${2:${1:$(replace-regexp-in-string \"\\\\\\\\(\\\\\\\\w+\\\\\\\\).*\" \"\\\\\\\\1\" yas-text)}}${3:
2521 # binding: ${4:direct-keybinding}}${5:
2522 # expand-env: ((${6:some-var} ${7:some-value}))}${8:
2527 (defun yas--compute-major-mode-and-parents (file)
2528 "Given FILE, find the nearest snippet directory for a given mode.
2530 Returns a list (MODE-SYM PARENTS), the mode's symbol and a list
2531 representing one or more of the mode's parents.
2533 Note that MODE-SYM need not be the symbol of a real major mode,
2534 neither do the elements of PARENTS."
2535 (let* ((file-dir (and file
2536 (directory-file-name (or (some #'(lambda (special)
2537 (locate-dominating-file file special))
2541 (directory-file-name (file-name-directory file))))))
2542 (parents-file-name (concat file-dir "/.yas-parents"))
2543 (major-mode-name (and file-dir
2544 (file-name-nondirectory file-dir)))
2545 (major-mode-sym (or (and major-mode-name
2546 (intern major-mode-name))))
2547 (parents (when (file-readable-p parents-file-name)
2551 (insert-file-contents parents-file-name)
2552 (buffer-substring-no-properties (point-min)
2554 (when major-mode-sym
2555 (cons major-mode-sym (remove major-mode-sym parents)))))
2557 (defvar yas--editing-template nil
2558 "Supporting variable for `yas-load-snippet-buffer' and `yas--visit-snippet'.")
2560 (defvar yas--current-template nil
2561 "Holds the current template being expanded into a snippet.")
2563 (defvar yas--guessed-modes nil
2564 "List of guessed modes supporting `yas-load-snippet-buffer'.")
2566 (defun yas--read-table ()
2567 "Ask user for a snippet table, help with some guessing."
2568 (let ((prompt (if (and (featurep 'ido)
2570 'ido-completing-read 'completing-read)))
2571 (unless yas--guessed-modes
2572 (set (make-local-variable 'yas--guessed-modes)
2573 (or (yas--compute-major-mode-and-parents buffer-file-name))))
2575 (funcall prompt (format "Choose or enter a table (yas guesses %s): "
2576 (if yas--guessed-modes
2577 (first yas--guessed-modes)
2579 (mapcar #'symbol-name yas--guessed-modes)
2584 (if (first yas--guessed-modes)
2585 (symbol-name (first yas--guessed-modes)))))))
2587 (defun yas-load-snippet-buffer (table &optional interactive)
2588 "Parse and load current buffer's snippet definition into TABLE.
2590 TABLE is a symbol naming a passed to `yas--table-get-create'.
2592 When called interactively, prompt for the table name and
2593 whether (and where) to save the snippet, then quit the window."
2594 (interactive (list (yas--read-table) t))
2596 ;; We have `yas--editing-template', this buffer's content comes from a
2597 ;; template which is already loaded and neatly positioned,...
2599 (yas--editing-template
2600 (yas--define-snippets-1 (yas--parse-template (yas--template-file yas--editing-template))
2601 (yas--template-table yas--editing-template)))
2602 ;; Try to use `yas--guessed-modes'. If we don't have that use the
2603 ;; value from `yas--compute-major-mode-and-parents'
2606 (unless yas--guessed-modes
2607 (set (make-local-variable 'yas--guessed-modes) (or (yas--compute-major-mode-and-parents buffer-file-name))))
2608 (let* ((table (yas--table-get-create table)))
2609 (set (make-local-variable 'yas--editing-template)
2610 (yas--define-snippets-1 (yas--parse-template buffer-file-name)
2613 (when (and interactive
2615 ;; Only offer to save this if it looks like a library or new
2616 ;; snippet (loaded from elisp, from a dir in `yas-snippet-dirs'
2617 ;; which is not the first, or from an unwritable file)
2619 (not (yas--template-file yas--editing-template))
2620 (not (file-writable-p (yas--template-file yas--editing-template)))
2621 (and (listp yas-snippet-dirs)
2622 (second yas-snippet-dirs)
2623 (not (string-match (expand-file-name (first yas-snippet-dirs))
2624 (yas--template-file yas--editing-template)))))
2625 (y-or-n-p (yas--format "Looks like a library or new snippet. Save to new file? ")))
2626 (let* ((option (first (yas--guess-snippet-directories (yas--template-table yas--editing-template))))
2628 (yas--make-directory-maybe option))))
2630 (let ((default-file-name (or (and (yas--template-file yas--editing-template)
2631 (file-name-nondirectory (yas--template-file yas--editing-template)))
2632 (yas--template-name yas--editing-template))))
2633 (write-file (concat chosen "/"
2634 (read-from-minibuffer (format "File name to create in %s? " chosen)
2635 default-file-name)))
2636 (setf (yas--template-file yas--editing-template) buffer-file-name)))))
2638 (yas--message 3 "Snippet \"%s\" loaded for %s."
2639 (yas--template-name yas--editing-template)
2640 (yas--table-name (yas--template-table yas--editing-template)))
2641 (quit-window interactive)))
2643 (defun yas-tryout-snippet (&optional debug)
2644 "Test current buffer's snippet template in other buffer."
2646 (let* ((major-mode-and-parent (yas--compute-major-mode-and-parents buffer-file-name))
2647 (parsed (yas--parse-template))
2648 (test-mode (or (and (car major-mode-and-parent)
2649 (fboundp (car major-mode-and-parent))
2650 (car major-mode-and-parent))
2651 (first yas--guessed-modes)
2652 (intern (read-from-minibuffer (yas--format "Please input a mode: ")))))
2653 (yas--current-template
2656 (yas--populate-template (yas--make-blank-template)
2657 :table nil ;; no tables for ephemeral snippets
2659 :content (second parsed)
2660 :name (third parsed)
2661 :expand-env (sixth parsed)))))
2662 (cond (yas--current-template
2663 (let ((buffer-name (format "*testing snippet: %s*" (yas--template-name yas--current-template))))
2664 (kill-buffer (get-buffer-create buffer-name))
2665 (switch-to-buffer (get-buffer-create buffer-name))
2666 (setq buffer-undo-list nil)
2667 (condition-case nil (funcall test-mode) (error nil))
2669 (setq buffer-read-only nil)
2670 (yas-expand-snippet (yas--template-content yas--current-template)
2673 (yas--template-expand-env yas--current-template))
2675 (require 'yasnippet-debug nil t))
2676 (add-hook 'post-command-hook 'yas-debug-snippet-vars nil t))))
2678 (yas--message 3 "Cannot test snippet for unknown major mode")))))
2680 (defun yas-active-keys ()
2681 "Return all active trigger keys for current buffer and point."
2683 (remove-if-not #'stringp (mapcan #'yas--table-all-keys (yas--get-snippet-tables)))
2686 (defun yas--template-fine-group (template)
2687 (car (last (or (yas--template-group template)
2688 (yas--template-perm-group template)))))
2690 (defun yas-describe-tables (&optional choose)
2691 "Display snippets for each table."
2693 (let* ((by-name-hash (and choose
2694 (y-or-n-p "Show by namehash? ")))
2695 (buffer (get-buffer-create "*YASnippet tables*"))
2696 (active-tables (yas--get-snippet-tables))
2697 (remain-tables (let ((all))
2698 (maphash #'(lambda (k v)
2699 (unless (find v active-tables)
2703 (table-lists (list active-tables remain-tables))
2704 (original-buffer (current-buffer))
2706 (yas--condition-cache-timestamp (current-time)))
2707 (with-current-buffer buffer
2708 (setq buffer-read-only nil)
2710 (cond ((not by-name-hash)
2711 (insert "YASnippet tables: \n")
2712 (while (and table-lists
2714 (dolist (table (car table-lists))
2715 (yas--describe-pretty-table table original-buffer))
2716 (setq table-lists (cdr table-lists))
2718 (yas--create-snippet-xrefs)
2719 (display-buffer buffer)
2720 (setq continue (and choose (y-or-n-p "Show also non-active tables? ")))))
2721 (yas--create-snippet-xrefs)
2725 (insert "\n\nYASnippet tables by NAMEHASH: \n")
2726 (dolist (table (append active-tables remain-tables))
2727 (insert (format "\nSnippet table `%s':\n\n" (yas--table-name table)))
2729 (maphash #'(lambda (k v)
2731 (yas--table-hash table))
2733 (insert (format " key %s maps snippets: %s\n" key
2735 (maphash #'(lambda (k v)
2737 (gethash key (yas--table-hash table)))
2740 (setq buffer-read-only t))
2741 (display-buffer buffer)))
2743 (defun yas--describe-pretty-table (table &optional original-buffer)
2744 (insert (format "\nSnippet table `%s'"
2745 (yas--table-name table)))
2746 (if (yas--table-parents table)
2747 (insert (format " parents: %s\n"
2748 (mapcar #'yas--table-name
2749 (yas--table-parents table))))
2751 (insert (make-string 100 ?-) "\n")
2752 (insert "group state name key binding\n")
2753 (let ((groups-hash (make-hash-table :test #'equal)))
2754 (maphash #'(lambda (k v)
2755 (let ((group (or (yas--template-fine-group v)
2757 (when (yas--template-name v)
2759 (cons v (gethash group groups-hash))
2761 (yas--table-uuidhash table))
2763 #'(lambda (group templates)
2764 (setq group (truncate-string-to-width group 25 0 ? "..."))
2765 (insert (make-string 100 ?-) "\n")
2766 (dolist (p templates)
2767 (let ((name (truncate-string-to-width (propertize (format "\\\\snippet `%s'" (yas--template-name p))
2771 (setq group (make-string (length group) ? ))))
2772 (condition-string (let ((condition (yas--template-condition p)))
2775 (with-current-buffer original-buffer
2776 (if (yas--eval-condition condition)
2781 (insert condition-string " ")
2783 (if (string-match "\\.\\.\\.$" name)
2787 (insert (truncate-string-to-width (or (yas--template-key p) "")
2789 (insert (truncate-string-to-width (key-description (yas--template-keybinding p))
2796 ;;; User convenience functions, for using in snippet definitions
2798 (defvar yas-modified-p nil
2799 "Non-nil if field has been modified by user or transformation.")
2801 (defvar yas-moving-away-p nil
2802 "Non-nil if user is about to exit field.")
2804 (defvar yas-text nil
2805 "Contains current field text.")
2807 (defun yas-substr (str pattern &optional subexp)
2808 "Search PATTERN in STR and return SUBEXPth match.
2810 If found, the content of subexp group SUBEXP (default 0) is
2811 returned, or else the original STR will be returned."
2812 (let ((grp (or subexp 0)))
2814 (if (string-match pattern str)
2815 (match-string-no-properties grp str)
2818 (defun yas-choose-value (&rest possibilities)
2819 "Prompt for a string in POSSIBILITIES and return it.
2821 The last element of POSSIBILITIES may be a list of strings."
2822 (unless (or yas-moving-away-p
2824 (setq possibilities (nreverse possibilities))
2825 (setq possibilities (if (listp (car possibilities))
2826 (append (reverse (car possibilities)) (rest possibilities))
2828 (some #'(lambda (fn)
2829 (funcall fn "Choose: " possibilities))
2830 yas-prompt-functions)))
2832 (defun yas-key-to-value (alist)
2833 (unless (or yas-moving-away-p
2835 (let ((key (read-key-sequence "")))
2837 (or (cdr (find key alist :key #'car :test #'string=))
2840 (defun yas-throw (text)
2841 "Throw a yas--exception with TEXT as the reason."
2842 (throw 'yas--exception (cons 'yas--exception text)))
2844 (defun yas-verify-value (possibilities)
2845 "Verify that the current field value is in POSSIBILITIES.
2847 Otherwise throw exception."
2848 (when (and yas-moving-away-p (notany #'(lambda (pos) (string= pos yas-text)) possibilities))
2849 (yas-throw (yas--format "Field only allows %s" possibilities))))
2851 (defun yas-field-value (number)
2852 "Get the string for field with NUMBER.
2854 Use this in primary and mirror transformations to tget."
2855 (let* ((snippet (car (yas--snippets-at-point)))
2857 (yas--snippet-find-field snippet number))))
2859 (yas--field-text-for-display field))))
2862 "Return `yas-text' if that exists and is non-empty, else nil."
2864 (not (string= "" yas-text)))
2867 (defun yas-selected-text ()
2868 "Return `yas-selected-text' if that exists and is non-empty, else nil."
2869 (if (and yas-selected-text
2870 (not (string= "" yas-selected-text)))
2873 (defun yas--get-field-once (number &optional transform-fn)
2874 (unless yas-modified-p
2876 (funcall transform-fn (yas-field-value number))
2877 (yas-field-value number))))
2879 (defun yas-default-from-field (number)
2880 (unless yas-modified-p
2881 (yas-field-value number)))
2883 (defun yas-inside-string ()
2884 "Return non-nil if the point is inside a string according to font-lock."
2885 (equal 'font-lock-string-face (get-char-property (1- (point)) 'face)))
2887 (defun yas-unimplemented (&optional missing-feature)
2888 (if yas--current-template
2889 (if (y-or-n-p (format "This snippet is unimplemented (missing %s) Visit the snippet definition? "
2892 (yas--visit-snippet-file-1 yas--current-template))
2893 (message "No implementation. Missing %s" (or missing-feature "something"))))
2896 ;;; Snippet expansion and field management
2898 (defvar yas--active-field-overlay nil
2899 "Overlays the currently active field.")
2901 (defvar yas--field-protection-overlays nil
2902 "Two overlays protect the current active field.")
2904 (defconst yas--prefix nil
2905 "A prefix argument for expansion direct from keybindings.")
2907 (defvar yas-selected-text nil
2908 "The selected region deleted on the last snippet expansion.")
2910 (defvar yas--start-column nil
2911 "The column where the snippet expansion started.")
2913 (make-variable-buffer-local 'yas--active-field-overlay)
2914 (make-variable-buffer-local 'yas--field-protection-overlays)
2915 (put 'yas--active-field-overlay 'permanent-local t)
2916 (put 'yas--field-protection-overlays 'permanent-local t)
2918 (defstruct (yas--snippet (:constructor yas--make-snippet ()))
2924 (id (yas--snippet-next-id) :read-only t)
2925 (control-overlay nil)
2927 ;; stacked expansion: the `previous-active-field' slot saves the
2928 ;; active field where the child expansion took place
2929 previous-active-field
2932 (defstruct (yas--field (:constructor yas--make-field (number start end parent-field)))
2935 NUMBER is the field number.
2936 START and END are mostly buffer markers, but see \"apropos markers-to-points\".
2937 PARENT-FIELD is a `yas--field' this field is nested under, or nil.
2938 MIRRORS is a list of `yas--mirror's
2939 TRANSFORM is a lisp form.
2940 MODIFIED-P is a boolean set to true once user inputs text.
2941 NEXT is another `yas--field' or `yas--mirror' or `yas--exit'.
2952 (defstruct (yas--mirror (:constructor yas--make-mirror (start end transform)))
2955 START and END are mostly buffer markers, but see \"apropos markers-to-points\".
2956 TRANSFORM is a lisp form.
2957 PARENT-FIELD is a `yas--field' this mirror is nested under, or nil.
2958 NEXT is another `yas--field' or `yas--mirror' or `yas--exit'
2959 DEPTH is a count of how many nested mirrors can affect this mirror"
2966 (defstruct (yas--exit (:constructor yas--make-exit (marker)))
2970 (defun yas--apply-transform (field-or-mirror field &optional empty-on-nil-p)
2971 "Calculate transformed string for FIELD-OR-MIRROR from FIELD.
2973 If there is no transform for ht field, return nil.
2975 If there is a transform but it returns nil, return the empty
2976 string iff EMPTY-ON-NIL-P is true."
2977 (let* ((yas-text (yas--field-text-for-display field))
2979 (yas-modified-p (yas--field-modified-p field))
2980 (yas-moving-away-p nil)
2981 (transform (if (yas--mirror-p field-or-mirror)
2982 (yas--mirror-transform field-or-mirror)
2983 (yas--field-transform field-or-mirror)))
2984 (start-point (if (yas--mirror-p field-or-mirror)
2985 (yas--mirror-start field-or-mirror)
2986 (yas--field-start field-or-mirror)))
2987 (transformed (and transform
2989 (goto-char start-point)
2990 (let ((ret (yas--eval-lisp transform)))
2991 (or ret (and empty-on-nil-p "")))))))
2994 (defsubst yas--replace-all (from to &optional text)
2995 "Replace all occurrences from FROM to TO.
2997 With optional string TEXT do it in that string."
2999 (replace-regexp-in-string (regexp-quote from) to text t t)
3000 (goto-char (point-min))
3001 (while (search-forward from nil t)
3002 (replace-match to t t text))))
3004 (defun yas--snippet-find-field (snippet number)
3005 (find-if #'(lambda (field)
3006 (eq number (yas--field-number field)))
3007 (yas--snippet-fields snippet)))
3009 (defun yas--snippet-sort-fields (snippet)
3010 "Sort the fields of SNIPPET in navigation order."
3011 (setf (yas--snippet-fields snippet)
3012 (sort (yas--snippet-fields snippet)
3013 #'yas--snippet-field-compare)))
3015 (defun yas--snippet-field-compare (field1 field2)
3016 "Compare FIELD1 and FIELD2.
3018 The field with a number is sorted first. If they both have a
3019 number, compare through the number. If neither have, compare
3020 through the field's start point"
3021 (let ((n1 (yas--field-number field1))
3022 (n2 (yas--field-number field2)))
3025 (or (zerop n2) (and (not (zerop n1))
3030 (< (yas--field-start field1)
3031 (yas--field-start field2))))))
3033 (defun yas--field-probably-deleted-p (snippet field)
3034 "Guess if SNIPPET's FIELD should be skipped."
3036 ;; field must be zero length
3038 (zerop (- (yas--field-start field) (yas--field-end field)))
3041 ;; 1) is a nested field and it's been modified
3043 (and (yas--field-parent-field field)
3044 (yas--field-modified-p field))
3045 ;; 2) ends just before the snippet end
3047 (and (eq field (car (last (yas--snippet-fields snippet))))
3048 (= (yas--field-start field) (overlay-end (yas--snippet-control-overlay snippet)))))
3049 ;; the field numbered 0, just before the exit marker, should
3052 (not (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 (remove nil (remove-duplicates (mapcar #'(lambda (ov)
3060 (overlay-get ov 'yas--snippet))
3062 (overlays-in (point-min) (point-max))
3063 (nconc (overlays-at (point)) (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 (&optional arg)
3081 "Navigate to the ARGth next field.
3083 If there's none, exit the snippet."
3087 (snippet (first (yas--snippets-at-point)))
3088 (active-field (overlay-get yas--active-field-overlay 'yas--field))
3089 (live-fields (remove-if #'(lambda (field)
3090 (and (not (eq field active-field))
3091 (yas--field-probably-deleted-p snippet field)))
3092 (yas--snippet-fields snippet)))
3093 (active-field-pos (position active-field live-fields))
3094 (target-pos (and active-field-pos (+ arg active-field-pos)))
3095 (target-field (and target-pos (nth target-pos live-fields))))
3096 ;; First check if we're moving out of a field with a transform
3098 (when (and active-field
3099 (yas--field-transform active-field))
3100 (let* ((yas-moving-away-p t)
3101 (yas-text (yas--field-text-for-display active-field))
3103 (yas-modified-p (yas--field-modified-p active-field)))
3104 ;; primary field transform: exit call to field-transform
3105 (yas--eval-lisp (yas--field-transform active-field))))
3106 ;; Now actually move...
3107 (cond ((and target-pos (>= target-pos (length live-fields)))
3108 (yas-exit-snippet snippet))
3110 (yas--move-to-field snippet target-field))
3114 (defun yas--place-overlays (snippet field)
3115 "Correctly place overlays for SNIPPET's FIELD."
3116 (yas--make-move-field-protection-overlays snippet field)
3117 (yas--make-move-active-field-overlay snippet field))
3119 (defun yas--move-to-field (snippet field)
3120 "Update SNIPPET to move to field FIELD.
3122 Also create some protection overlays"
3123 (goto-char (yas--field-start field))
3124 (yas--place-overlays snippet field)
3125 (overlay-put yas--active-field-overlay 'yas--field field)
3126 (let ((number (yas--field-number field)))
3127 ;; check for the special ${0: ...} field
3128 (if (and number (zerop number))
3130 (set-mark (yas--field-end field))
3131 (setf (yas--snippet-force-exit snippet)
3132 (or (yas--field-transform field)
3134 ;; make this field active
3135 (setf (yas--snippet-active-field snippet) field)
3136 ;; primary field transform: first call to snippet transform
3137 (unless (yas--field-modified-p field)
3138 (if (yas--field-update-display field snippet)
3139 (yas--update-mirrors snippet)
3140 (setf (yas--field-modified-p field) nil))))))
3142 (defun yas-prev-field ()
3143 "Navigate to prev field. If there's none, exit the snippet."
3145 (yas-next-field -1))
3147 (defun yas-abort-snippet (&optional snippet)
3149 (let ((snippet (or snippet
3150 (car (yas--snippets-at-point)))))
3152 (setf (yas--snippet-force-exit snippet) t))))
3154 (defun yas-exit-snippet (snippet)
3155 "Goto exit-marker of SNIPPET."
3156 (interactive (list (first (yas--snippets-at-point))))
3158 (setf (yas--snippet-force-exit snippet) t)
3159 (goto-char (if (yas--snippet-exit snippet)
3160 (yas--exit-marker (yas--snippet-exit snippet))
3161 (overlay-end (yas--snippet-control-overlay snippet))))))
3163 (defun yas-exit-all-snippets ()
3164 "Exit all snippets."
3166 (mapc #'(lambda (snippet)
3167 (yas-exit-snippet snippet)
3168 (yas--check-commit-snippet))
3169 (yas--snippets-at-point 'all-snippets)))
3172 ;;; Some low level snippet-routines:
3174 (defmacro yas--inhibit-overlay-hooks (&rest body)
3175 "Run BODY with `yas--inhibit-overlay-hooks' set to t."
3176 (declare (indent 0))
3177 `(let ((yas--inhibit-overlay-hooks t))
3180 (defvar yas-snippet-beg nil "Beginning position of the last snippet committed.")
3181 (defvar yas-snippet-end nil "End position of the last snippet committed.")
3183 (defun yas--commit-snippet (snippet)
3184 "Commit SNIPPET, but leave point as it is.
3186 This renders the snippet as ordinary text."
3188 (let ((control-overlay (yas--snippet-control-overlay snippet)))
3190 ;; Save the end of the moribund snippet in case we need to revive it
3191 ;; its original expansion.
3193 (when (and control-overlay
3194 (overlay-buffer control-overlay))
3195 (setq yas-snippet-beg (overlay-start control-overlay))
3196 (setq yas-snippet-end (overlay-end control-overlay))
3197 (delete-overlay control-overlay))
3199 (yas--inhibit-overlay-hooks
3200 (when yas--active-field-overlay
3201 (delete-overlay yas--active-field-overlay))
3202 (when yas--field-protection-overlays
3203 (mapc #'delete-overlay yas--field-protection-overlays)))
3205 ;; stacked expansion: if the original expansion took place from a
3206 ;; field, make sure we advance it here at least to
3207 ;; `yas-snippet-end'...
3209 (let ((previous-field (yas--snippet-previous-active-field snippet)))
3210 (when (and yas-snippet-end previous-field)
3211 (yas--advance-end-maybe previous-field yas-snippet-end)))
3213 ;; Convert all markers to points,
3215 (yas--markers-to-points snippet)
3217 ;; Take care of snippet revival
3219 (if yas-snippet-revival
3220 (push `(apply yas--snippet-revive ,yas-snippet-beg ,yas-snippet-end ,snippet)
3222 ;; Dismember the snippet... this is useful if we get called
3223 ;; again from `yas--take-care-of-redo'....
3224 (setf (yas--snippet-fields snippet) nil)))
3226 (yas--message 3 "Snippet %s exited." (yas--snippet-id snippet)))
3228 (defun yas--safely-run-hooks (hook-var)
3229 (condition-case error
3230 (run-hooks hook-var)
3232 (yas--message 3 "%s error: %s" hook-var (error-message-string error)))))
3235 (defun yas--check-commit-snippet ()
3236 "Checks if point exited the currently active field of the snippet.
3238 If so cleans up the whole snippet up."
3239 (let* ((snippets (yas--snippets-at-point 'all-snippets))
3240 (snippets-left snippets)
3241 (snippet-exit-transform))
3242 (dolist (snippet snippets)
3243 (let ((active-field (yas--snippet-active-field snippet)))
3244 (setq snippet-exit-transform (yas--snippet-force-exit snippet))
3245 (cond ((or snippet-exit-transform
3246 (not (and active-field (yas--field-contains-point-p active-field))))
3247 (setq snippets-left (delete snippet snippets-left))
3248 (setf (yas--snippet-force-exit snippet) nil)
3249 (yas--commit-snippet snippet))
3251 (or (not yas--active-field-overlay)
3252 (not (overlay-buffer yas--active-field-overlay))))
3254 ;; stacked expansion: this case is mainly for recent
3255 ;; snippet exits that place us back int the field of
3259 (yas--move-to-field snippet active-field)
3260 (yas--update-mirrors snippet)))
3263 (unless (or (null snippets) snippets-left)
3264 (if snippet-exit-transform
3265 (yas--eval-lisp-no-saves snippet-exit-transform))
3266 (yas--safely-run-hooks 'yas-after-exit-snippet-hook))))
3268 ;; Apropos markers-to-points:
3270 ;; This was found useful for performance reasons, so that an
3271 ;; excessive number of live markers aren't kept around in the
3272 ;; `buffer-undo-list'. However, in `markers-to-points', the
3273 ;; set-to-nil markers can't simply be discarded and replaced with
3274 ;; fresh ones in `points-to-markers'. The original marker that was
3275 ;; just set to nil has to be reused.
3277 ;; This shouldn't bring horrible problems with undo/redo, but it
3280 (defun yas--markers-to-points (snippet)
3281 "Convert all markers in SNIPPET to a cons (POINT . MARKER)
3282 where POINT is the original position of the marker and MARKER is
3283 the original marker object with the position set to nil."
3284 (dolist (field (yas--snippet-fields snippet))
3285 (let ((start (marker-position (yas--field-start field)))
3286 (end (marker-position (yas--field-end field))))
3287 (set-marker (yas--field-start field) nil)
3288 (set-marker (yas--field-end field) nil)
3289 (setf (yas--field-start field) (cons start (yas--field-start field)))
3290 (setf (yas--field-end field) (cons end (yas--field-end field))))
3291 (dolist (mirror (yas--field-mirrors field))
3292 (let ((start (marker-position (yas--mirror-start mirror)))
3293 (end (marker-position (yas--mirror-end mirror))))
3294 (set-marker (yas--mirror-start mirror) nil)
3295 (set-marker (yas--mirror-end mirror) nil)
3296 (setf (yas--mirror-start mirror) (cons start (yas--mirror-start mirror)))
3297 (setf (yas--mirror-end mirror) (cons end (yas--mirror-end mirror))))))
3298 (let ((snippet-exit (yas--snippet-exit snippet)))
3300 (let ((exit (marker-position (yas--exit-marker snippet-exit))))
3301 (set-marker (yas--exit-marker snippet-exit) nil)
3302 (setf (yas--exit-marker snippet-exit) (cons exit (yas--exit-marker snippet-exit)))))))
3304 (defun yas--points-to-markers (snippet)
3305 "Convert all cons (POINT . MARKER) in SNIPPET to markers.
3307 This is done by setting MARKER to POINT with `set-marker'."
3308 (dolist (field (yas--snippet-fields snippet))
3309 (setf (yas--field-start field) (set-marker (cdr (yas--field-start field))
3310 (car (yas--field-start field))))
3311 (setf (yas--field-end field) (set-marker (cdr (yas--field-end field))
3312 (car (yas--field-end field))))
3313 (dolist (mirror (yas--field-mirrors field))
3314 (setf (yas--mirror-start mirror) (set-marker (cdr (yas--mirror-start mirror))
3315 (car (yas--mirror-start mirror))))
3316 (setf (yas--mirror-end mirror) (set-marker (cdr (yas--mirror-end mirror))
3317 (car (yas--mirror-end mirror))))))
3318 (let ((snippet-exit (yas--snippet-exit snippet)))
3320 (setf (yas--exit-marker snippet-exit) (set-marker (cdr (yas--exit-marker snippet-exit))
3321 (car (yas--exit-marker snippet-exit)))))))
3323 (defun yas--field-contains-point-p (field &optional point)
3324 (let ((point (or point
3326 (and (>= point (yas--field-start field))
3327 (<= point (yas--field-end field)))))
3329 (defun yas--field-text-for-display (field)
3330 "Return the propertized display text for field FIELD."
3331 (buffer-substring (yas--field-start field) (yas--field-end field)))
3333 (defun yas--undo-in-progress ()
3334 "True if some kind of undo is in progress."
3335 (or undo-in-progress
3336 (eq this-command 'undo)
3337 (eq this-command 'redo)))
3339 (defun yas--make-control-overlay (snippet start end)
3340 "Creates the control overlay that surrounds the snippet and
3342 (let ((overlay (make-overlay start
3347 (overlay-put overlay 'keymap yas-keymap)
3348 (overlay-put overlay 'priority 100)
3349 (overlay-put overlay 'yas--snippet snippet)
3352 (defun yas-skip-and-clear-or-delete-char (&optional field)
3353 "Clears unmodified field if at field start, skips to next tab.
3355 Otherwise deletes a character normally by calling `delete-char'."
3357 (let ((field (or field
3358 (and yas--active-field-overlay
3359 (overlay-buffer yas--active-field-overlay)
3360 (overlay-get yas--active-field-overlay 'yas--field)))))
3362 (not (yas--field-modified-p field))
3363 (eq (point) (marker-position (yas--field-start field))))
3364 (yas--skip-and-clear field)
3367 (call-interactively 'delete-char)))))
3369 (defun yas--skip-and-clear (field)
3370 "Deletes the region of FIELD and sets it's modified state to t."
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 (delete-region (yas--field-start field) (yas--field-end field)))
3379 (defun yas--mark-this-and-children-modified (field)
3380 (setf (yas--field-modified-p field) t)
3381 (let ((fom (yas--field-next field)))
3383 (yas--fom-parent-field fom))
3384 (when (and (eq (yas--fom-parent-field fom) field)
3386 (yas--mark-this-and-children-modified fom))
3387 (setq fom (yas--fom-next fom)))))
3389 (defun yas--make-move-active-field-overlay (snippet field)
3390 "Place the active field overlay in SNIPPET's FIELD.
3392 Move the overlay, or create it if it does not exit."
3393 (if (and yas--active-field-overlay
3394 (overlay-buffer yas--active-field-overlay))
3395 (move-overlay yas--active-field-overlay
3396 (yas--field-start field)
3397 (yas--field-end field))
3398 (setq yas--active-field-overlay
3399 (make-overlay (yas--field-start field)
3400 (yas--field-end field)
3402 (overlay-put yas--active-field-overlay 'priority 100)
3403 (overlay-put yas--active-field-overlay 'face 'yas-field-highlight-face)
3404 (overlay-put yas--active-field-overlay 'yas--snippet snippet)
3405 (overlay-put yas--active-field-overlay 'modification-hooks '(yas--on-field-overlay-modification))
3406 (overlay-put yas--active-field-overlay 'insert-in-front-hooks
3407 '(yas--on-field-overlay-modification))
3408 (overlay-put yas--active-field-overlay 'insert-behind-hooks
3409 '(yas--on-field-overlay-modification))))
3411 (defvar yas--inhibit-overlay-hooks nil
3412 "Bind this temporarily to non-nil to prevent running `yas--on-*-modification'.")
3414 (defun yas--on-field-overlay-modification (overlay after? beg end &optional length)
3415 "Clears the field and updates mirrors, conditionally.
3417 Only clears the field if it hasn't been modified and it point it
3418 at field start. This hook doesn't do anything if an undo is in
3420 (unless (or yas--inhibit-overlay-hooks
3421 (yas--undo-in-progress))
3422 (let* ((field (overlay-get overlay 'yas--field))
3423 (number (and field (yas--field-number field)))
3424 (snippet (overlay-get yas--active-field-overlay 'yas--snippet)))
3426 (yas--advance-end-maybe field (overlay-end overlay))
3428 (yas--field-update-display field snippet))
3429 (yas--update-mirrors snippet))
3431 (when (and (not after?)
3432 (not (yas--field-modified-p field))
3433 (eq (point) (if (markerp (yas--field-start field))
3434 (marker-position (yas--field-start field))
3435 (yas--field-start field))))
3436 (yas--skip-and-clear field))
3437 (setf (yas--field-modified-p field) t))))))
3439 ;;; Apropos protection overlays:
3441 ;; These exist for nasty users who will try to delete parts of the
3442 ;; snippet outside the active field. Actual protection happens in
3443 ;; `yas--on-protection-overlay-modification'.
3445 ;; Currently this signals an error which inhibits the command. For
3446 ;; commands that move point (like `kill-line'), point is restored in
3447 ;; the `yas--post-command-handler' using a global
3448 ;; `yas--protection-violation' variable.
3450 ;; Alternatively, I've experimented with an implementation that
3451 ;; commits the snippet before actually calling `this-command'
3452 ;; interactively, and then signals an error, which is ignored. but
3453 ;; blocks all other million modification hooks. This presented some
3454 ;; problems with stacked expansion.
3456 (defun yas--make-move-field-protection-overlays (snippet field)
3457 "Place protection overlays surrounding SNIPPET's FIELD.
3459 Move the overlays, or create them if they do not exit."
3460 (let ((start (yas--field-start field))
3461 (end (yas--field-end field)))
3462 ;; First check if the (1+ end) is contained in the buffer,
3463 ;; otherwise we'll have to do a bit of cheating and silently
3464 ;; insert a newline. the `(1+ (buffer-size))' should prevent this
3465 ;; when using stacked expansion
3467 (when (< (buffer-size) end)
3469 (yas--inhibit-overlay-hooks
3470 (goto-char (point-max))
3472 ;; go on to normal overlay creation/moving
3474 (cond ((and yas--field-protection-overlays
3475 (every #'overlay-buffer yas--field-protection-overlays))
3476 (move-overlay (first yas--field-protection-overlays) (1- start) start)
3477 (move-overlay (second yas--field-protection-overlays) end (1+ end)))
3479 (setq yas--field-protection-overlays
3480 (list (make-overlay (1- start) start nil t nil)
3481 (make-overlay end (1+ end) nil t nil)))
3482 (dolist (ov yas--field-protection-overlays)
3483 (overlay-put ov 'face 'yas--field-debug-face)
3484 (overlay-put ov 'yas--snippet snippet)
3485 ;; (overlay-put ov 'evaporate t)
3486 (overlay-put ov 'modification-hooks '(yas--on-protection-overlay-modification)))))))
3488 (defvar yas--protection-violation nil
3489 "When non-nil, signals attempts to erroneously exit or modify the snippet.
3491 Functions in the `post-command-hook', for example
3492 `yas--post-command-handler' can check it and reset its value to
3493 nil. The variables value is the point where the violation
3496 (defun yas--on-protection-overlay-modification (overlay after? beg end &optional length)
3497 "Signals a snippet violation, then issues error.
3499 The error should be ignored in `debug-ignored-errors'"
3500 (unless yas--inhibit-overlay-hooks
3501 (cond ((not (or after?
3502 (yas--undo-in-progress)))
3503 (setq yas--protection-violation (point))
3504 (error "Exit the snippet first!")))))
3506 (add-to-list 'debug-ignored-errors "^Exit the snippet first!$")
3509 ;;; Snippet expansion and "stacked" expansion:
3511 ;; Stacked expansion is when you try to expand a snippet when already
3512 ;; inside a snippet expansion.
3514 ;; The parent snippet does not run its fields modification hooks
3515 ;; (`yas--on-field-overlay-modification' and
3516 ;; `yas--on-protection-overlay-modification') while the child snippet
3517 ;; is active. This means, among other things, that the mirrors of the
3518 ;; parent snippet are not updated, this only happening when one exits
3519 ;; the child snippet.
3521 ;; Unfortunately, this also puts some ugly (and not fully-tested)
3522 ;; bits of code in `yas-expand-snippet' and
3523 ;; `yas--commit-snippet'. I've tried to mark them with "stacked
3526 ;; This was thought to be safer in an undo/redo perspective, but
3527 ;; maybe the correct implementation is to make the globals
3528 ;; `yas--active-field-overlay' and `yas--field-protection-overlays' be
3529 ;; snippet-local and be active even while the child snippet is
3530 ;; running. This would mean a lot of overlay modification hooks
3531 ;; running, but if managed correctly (including overlay priorities)
3532 ;; they should account for all situations...
3534 (defun yas-expand-snippet (content &optional start end expand-env)
3535 "Expand snippet CONTENT at current point.
3537 Text between START and END will be deleted before inserting
3538 template. EXPAND-ENV is are let-style variable to value bindings
3539 considered when expanding the snippet."
3540 (run-hooks 'yas-before-expand-snippet-hook)
3543 (let* ((yas-selected-text (or yas-selected-text
3544 (and (region-active-p)
3545 (buffer-substring-no-properties (region-beginning)
3548 (and (region-active-p)
3552 (and (region-active-p)
3555 (to-delete (and start
3557 (buffer-substring-no-properties start end)))
3560 (setq yas--indent-original-column (current-column))
3561 ;; Delete the region to delete, this *does* get undo-recorded.
3563 (when (and to-delete
3565 (delete-region start end))
3567 (cond ((listp content)
3568 ;; x) This is a snippet-command
3570 (yas--eval-lisp-no-saves content))
3572 ;; x) This is a snippet-snippet :-)
3574 ;; Narrow the region down to the content, shoosh the
3575 ;; `buffer-undo-list', and create the snippet, the new
3576 ;; snippet updates its mirrors once, so we are left with
3577 ;; some plain text. The undo action for deleting this
3578 ;; plain text will get recorded at the end.
3580 ;; stacked expansion: also shoosh the overlay modification hooks
3582 (narrow-to-region start start)
3583 (let ((buffer-undo-list t))
3584 ;; snippet creation might evaluate users elisp, which
3585 ;; might generate errors, so we have to be ready to catch
3586 ;; them mostly to make the undo information
3588 (setq yas--start-column (save-restriction (widen) (current-column)))
3589 (yas--inhibit-overlay-hooks
3592 (eval `(let* ,expand-env
3594 (yas--snippet-create (point-min) (point-max))))
3596 (yas--snippet-create (point-min) (point-max)))))))
3598 ;; stacked-expansion: This checks for stacked expansion, save the
3599 ;; `yas--previous-active-field' and advance its boundary.
3601 (let ((existing-field (and yas--active-field-overlay
3602 (overlay-buffer yas--active-field-overlay)
3603 (overlay-get yas--active-field-overlay 'yas--field))))
3604 (when existing-field
3605 (setf (yas--snippet-previous-active-field snippet) existing-field)
3606 (yas--advance-end-maybe existing-field (overlay-end yas--active-field-overlay))))
3608 ;; Exit the snippet immediately if no fields
3610 (unless (yas--snippet-fields snippet)
3611 (yas-exit-snippet snippet))
3613 ;; Push two undo actions: the deletion of the inserted contents of
3614 ;; the new snippet (without the "key") followed by an apply of
3615 ;; `yas--take-care-of-redo' on the newly inserted snippet boundaries
3617 ;; A small exception, if `yas-also-auto-indent-first-line'
3618 ;; is t and `yas--indent' decides to indent the line to a
3619 ;; point before the actual expansion point, undo would be
3620 ;; messed up. We call the early point "newstart"". case,
3621 ;; and attempt to fix undo.
3623 (let ((newstart (overlay-start (yas--snippet-control-overlay snippet)))
3624 (end (overlay-end (yas--snippet-control-overlay snippet))))
3625 (when (< newstart start)
3626 (push (cons (make-string (- start newstart) ? ) newstart) buffer-undo-list))
3627 (push (cons newstart end) buffer-undo-list)
3628 (push `(apply yas--take-care-of-redo ,start ,end ,snippet)
3630 ;; Now, schedule a move to the first field
3632 (let ((first-field (car (yas--snippet-fields snippet))))
3634 (sit-for 0) ;; fix issue 125
3635 (yas--move-to-field snippet first-field)))
3636 (yas--message 3 "snippet expanded.")
3639 (defun yas--take-care-of-redo (beg end snippet)
3640 "Commits SNIPPET, which in turn pushes an undo action for reviving it.
3642 Meant to exit in the `buffer-undo-list'."
3643 ;; slightly optimize: this action is only needed for snippets with
3644 ;; at least one field
3645 (when (yas--snippet-fields snippet)
3646 (yas--commit-snippet snippet)))
3648 (defun yas--snippet-revive (beg end snippet)
3649 "Revives SNIPPET and creates a control overlay from BEG to END.
3651 BEG and END are, we hope, the original snippets boundaries. All
3652 the markers/points exiting existing inside SNIPPET should point
3653 to their correct locations *at the time the snippet is revived*.
3655 After revival, push the `yas--take-care-of-redo' in the
3657 ;; Reconvert all the points to markers
3659 (yas--points-to-markers snippet)
3660 ;; When at least one editable field existed in the zombie snippet,
3661 ;; try to revive the whole thing...
3663 (let ((target-field (or (yas--snippet-active-field snippet)
3664 (car (yas--snippet-fields snippet)))))
3666 (setf (yas--snippet-control-overlay snippet) (yas--make-control-overlay snippet beg end))
3667 (overlay-put (yas--snippet-control-overlay snippet) 'yas--snippet snippet)
3669 (yas--move-to-field snippet target-field)
3671 (push `(apply yas--take-care-of-redo ,beg ,end ,snippet)
3672 buffer-undo-list))))
3674 (defun yas--snippet-create (begin end)
3675 "Creates a snippet from an template inserted between BEGIN and END.
3677 Returns the newly created snippet."
3678 (let ((snippet (yas--make-snippet)))
3680 (yas--snippet-parse-create snippet)
3682 ;; Sort and link each field
3683 (yas--snippet-sort-fields snippet)
3685 ;; Create keymap overlay for snippet
3686 (setf (yas--snippet-control-overlay snippet)
3687 (yas--make-control-overlay snippet (point-min) (point-max)))
3690 (goto-char (point-max))
3695 ;;; Apropos adjacencies and "fom's":
3697 ;; Once the $-constructs bits like "$n" and "${:n" are deleted in the
3698 ;; recently expanded snippet, we might actually have many fields,
3699 ;; mirrors (and the snippet exit) in the very same position in the
3700 ;; buffer. Therefore we need to single-link the
3701 ;; fields-or-mirrors-or-exit (which I have abbreviated to "fom")
3702 ;; according to their original positions in the buffer.
3704 ;; Then we have operation `yas--advance-end-maybe' and
3705 ;; `yas--advance-start-maybe', which conditionally push the starts and
3706 ;; ends of these foms down the chain.
3708 ;; This allows for like the printf with the magic ",":
3710 ;; printf ("${1:%s}\\n"${1:$(if (string-match "%" text) "," "\);")} \
3711 ;; $2${1:$(if (string-match "%" text) "\);" "")}$0
3713 (defun yas--fom-start (fom)
3714 (cond ((yas--field-p fom)
3715 (yas--field-start fom))
3716 ((yas--mirror-p fom)
3717 (yas--mirror-start fom))
3719 (yas--exit-marker fom))))
3721 (defun yas--fom-end (fom)
3722 (cond ((yas--field-p fom)
3723 (yas--field-end fom))
3724 ((yas--mirror-p fom)
3725 (yas--mirror-end fom))
3727 (yas--exit-marker fom))))
3729 (defun yas--fom-next (fom)
3730 (cond ((yas--field-p fom)
3731 (yas--field-next fom))
3732 ((yas--mirror-p fom)
3733 (yas--mirror-next fom))
3735 (yas--exit-next fom))))
3737 (defun yas--fom-parent-field (fom)
3738 (cond ((yas--field-p fom)
3739 (yas--field-parent-field fom))
3740 ((yas--mirror-p fom)
3741 (yas--mirror-parent-field fom))
3745 (defun yas--calculate-adjacencies (snippet)
3746 "Calculate adjacencies for fields or mirrors of SNIPPET.
3748 This is according to their relative positions in the buffer, and
3749 has to be called before the $-constructs are deleted."
3750 (labels ((yas--fom-set-next-fom (fom nextfom)
3751 (cond ((yas--field-p fom)
3752 (setf (yas--field-next fom) nextfom))
3753 ((yas--mirror-p fom)
3754 (setf (yas--mirror-next fom) nextfom))
3756 (setf (yas--exit-next fom) nextfom))))
3757 (yas--compare-fom-begs (fom1 fom2)
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 (yas--link-foms (fom1 fom2)
3762 (yas--fom-set-next-fom fom1 fom2)))
3763 ;; make some yas--field, yas--mirror and yas--exit soup
3765 (when (yas--snippet-exit snippet)
3766 (push (yas--snippet-exit snippet) soup))
3767 (dolist (field (yas--snippet-fields snippet))
3769 (dolist (mirror (yas--field-mirrors field))
3770 (push mirror soup)))
3773 #'yas--compare-fom-begs))
3775 (reduce #'yas--link-foms soup)))))
3777 (defun yas--calculate-mirrors-in-fields (snippet mirror)
3778 "Attempt to assign a parent field of SNIPPET to the mirror MIRROR.
3780 Use the tightest containing field if more than one field contains
3781 the mirror. Intended to be called *before* the dollar-regions are
3783 (let ((min (point-min))
3785 (dolist (field (yas--snippet-fields snippet))
3786 (when (and (<= (yas--field-start field) (yas--mirror-start mirror))
3787 (<= (yas--mirror-end mirror) (yas--field-end field))
3788 (< min (yas--field-start field))
3789 (< (yas--field-end field) max))
3790 (setq min (yas--field-start field)
3791 max (yas--field-end field))
3792 (setf (yas--mirror-parent-field mirror) field)))))
3794 (defun yas--advance-end-maybe (fom newend)
3795 "Maybe advance FOM's end to NEWEND if it needs it.
3799 * call `yas--advance-start-maybe' on FOM's next fom.
3801 * in case FOM is field call `yas--advance-end-maybe' on its parent
3804 Also, if FOM is an exit-marker, always call
3805 `yas--advance-start-maybe' on its next fom. This is because
3806 exit-marker have identical start and end markers."
3807 (cond ((and fom (< (yas--fom-end fom) newend))
3808 (set-marker (yas--fom-end fom) newend)
3809 (yas--advance-start-maybe (yas--fom-next fom) newend)
3810 (yas--advance-end-of-parents-maybe (yas--fom-parent-field fom) newend))
3812 (yas--advance-start-maybe (yas--fom-next fom) newend))))
3814 (defun yas--advance-start-maybe (fom newstart)
3815 "Maybe advance FOM's start to NEWSTART if it needs it.
3817 If it does, also call `yas--advance-end-maybe' on FOM."
3818 (when (and fom (< (yas--fom-start fom) newstart))
3819 (set-marker (yas--fom-start fom) newstart)
3820 (yas--advance-end-maybe fom newstart)))
3822 (defun yas--advance-end-of-parents-maybe (field newend)
3823 "Like `yas--advance-end-maybe' but for parent fields.
3825 Only works for fields and doesn't care about the start of the
3826 next FOM. Works its way up recursively for parents of parents."
3828 (< (yas--field-end field) newend))
3829 (set-marker (yas--field-end field) newend)
3830 (yas--advance-end-of-parents-maybe (yas--field-parent-field field) newend)))
3832 (defvar yas--dollar-regions nil
3833 "When expanding the snippet the \"parse-create\" functions add
3834 cons cells to this var.")
3836 (defvar yas--backquote-markers-and-strings nil
3837 "List of (MARKER . STRING) marking where the values from
3838 backquoted lisp expressions should be inserted at the end of
3841 (defun yas--snippet-parse-create (snippet)
3842 "Parse a recently inserted snippet template, creating all
3843 necessary fields, mirrors and exit points.
3845 Meant to be called in a narrowed buffer, does various passes"
3846 (let ((parse-start (point)))
3847 ;; Reset the yas--dollar-regions
3849 (setq yas--dollar-regions nil)
3850 ;; protect just the backquotes
3852 (yas--protect-escapes nil '(?`))
3853 ;; replace all backquoted expressions
3855 (goto-char parse-start)
3856 (yas--save-backquotes)
3857 ;; protect escaped characters
3859 (yas--protect-escapes)
3860 ;; parse fields with {}
3862 (goto-char parse-start)
3863 (yas--field-parse-create snippet)
3864 ;; parse simple mirrors and fields
3866 (goto-char parse-start)
3867 (yas--simple-mirror-parse-create snippet)
3868 ;; parse mirror transforms
3870 (goto-char parse-start)
3871 (yas--transform-mirror-parse-create snippet)
3872 ;; calculate adjacencies of fields and mirrors
3874 (yas--calculate-adjacencies snippet)
3875 ;; Delete $-constructs
3877 (yas--delete-regions yas--dollar-regions)
3878 ;; restore backquoted expression values
3880 (yas--restore-backquotes)
3883 (goto-char parse-start)
3884 (yas--restore-escapes)
3885 ;; update mirrors for the first time
3887 (yas--update-mirrors snippet)
3888 ;; indent the best we can
3890 (goto-char parse-start)
3891 (yas--indent snippet)))
3893 (defun yas--indent-according-to-mode (snippet-markers)
3894 "Indent current line according to mode, preserving SNIPPET-MARKERS."
3895 ;;; Apropos indenting problems....
3897 ;; `indent-according-to-mode' uses whatever `indent-line-function'
3898 ;; is available. Some implementations of these functions delete text
3899 ;; before they insert. If there happens to be a marker just after
3900 ;; the text being deleted, the insertion actually happens after the
3901 ;; marker, which misplaces it.
3903 ;; This would also happen if we had used overlays with the
3904 ;; `front-advance' property set to nil.
3906 ;; This is why I have these `trouble-markers', they are the ones at
3907 ;; they are the ones at the first non-whitespace char at the line
3908 ;; (i.e. at `yas--real-line-beginning'. After indentation takes place
3909 ;; we should be at the correct to restore them to. All other
3910 ;; non-trouble-markers have been *pushed* and don't need special
3913 (goto-char (yas--real-line-beginning))
3914 (let ((trouble-markers (remove-if-not #'(lambda (marker)
3920 (indent-according-to-mode)
3921 (error (yas--message 3 "Warning: `yas--indent-according-to-mode' having problems running %s" indent-line-function)
3923 (mapc #'(lambda (marker)
3924 (set-marker marker (point)))
3927 (defvar yas--indent-original-column nil)
3928 (defun yas--indent (snippet)
3929 (let ((snippet-markers (yas--collect-snippet-markers snippet)))
3930 ;; Look for those $>
3932 (while (re-search-forward "$>" nil t)
3933 (delete-region (match-beginning 0) (match-end 0))
3934 (when (not (eq yas-indent-line 'auto))
3935 (yas--indent-according-to-mode snippet-markers))))
3936 ;; Now do stuff for 'fixed and 'auto
3938 (cond ((eq yas-indent-line 'fixed)
3939 (while (and (zerop (forward-line))
3940 (zerop (current-column)))
3941 (indent-to-column yas--indent-original-column)))
3942 ((eq yas-indent-line 'auto)
3943 (let ((end (set-marker (make-marker) (point-max)))
3944 (indent-first-line-p yas-also-auto-indent-first-line))
3945 (while (and (zerop (if indent-first-line-p
3948 (setq indent-first-line-p nil))
3952 (yas--indent-according-to-mode snippet-markers))))
3956 (defun yas--collect-snippet-markers (snippet)
3957 "Make a list of all the markers used by SNIPPET."
3959 (dolist (field (yas--snippet-fields snippet))
3960 (push (yas--field-start field) markers)
3961 (push (yas--field-end field) markers)
3962 (dolist (mirror (yas--field-mirrors field))
3963 (push (yas--mirror-start mirror) markers)
3964 (push (yas--mirror-end mirror) markers)))
3965 (let ((snippet-exit (yas--snippet-exit snippet)))
3966 (when (and snippet-exit
3967 (marker-buffer (yas--exit-marker snippet-exit)))
3968 (push (yas--exit-marker snippet-exit) markers)))
3971 (defun yas--real-line-beginning ()
3972 (let ((c (char-after (line-beginning-position)))
3973 (n (line-beginning-position)))
3974 (while (or (eql c ?\ )
3977 (setq c (char-after n)))
3980 (defun yas--escape-string (escaped)
3981 (concat "YASESCAPE" (format "%d" escaped) "PROTECTGUARD"))
3983 (defun yas--protect-escapes (&optional text escaped)
3984 "Protect all escaped characters with their numeric ASCII value.
3986 With optional string TEXT do it in string instead of buffer."
3987 (let ((changed-text text)
3988 (text-provided-p text))
3989 (mapc #'(lambda (escaped)
3991 (yas--replace-all (concat "\\" (char-to-string escaped))
3992 (yas--escape-string escaped)
3993 (when text-provided-p changed-text))))
3994 (or escaped yas--escaped-characters))
3997 (defun yas--restore-escapes (&optional text escaped)
3998 "Restore all escaped characters from their numeric ASCII value.
4000 With optional string TEXT do it in string instead of the buffer."
4001 (let ((changed-text text)
4002 (text-provided-p text))
4003 (mapc #'(lambda (escaped)
4005 (yas--replace-all (yas--escape-string escaped)
4006 (char-to-string escaped)
4007 (when text-provided-p changed-text))))
4008 (or escaped yas--escaped-characters))
4011 (defun yas--save-backquotes ()
4012 "Save all the \"`(lisp-expression)`\"-style expressions
4013 with their evaluated value into `yas--backquote-markers-and-strings'."
4014 (while (re-search-forward yas--backquote-lisp-expression-regexp nil t)
4015 (let ((current-string (match-string-no-properties 1)) transformed)
4016 (delete-region (match-beginning 0) (match-end 0))
4017 (setq transformed (yas--eval-lisp (yas--read-lisp (yas--restore-escapes current-string '(?`)))))
4018 (goto-char (match-beginning 0))
4020 (let ((marker (make-marker)))
4021 (insert "Y") ;; quite horrendous, I love it :)
4022 (set-marker marker (point))
4024 (push (cons marker transformed) yas--backquote-markers-and-strings))))))
4026 (defun yas--restore-backquotes ()
4027 "Replace markers in `yas--backquote-markers-and-strings' with their values."
4028 (while yas--backquote-markers-and-strings
4029 (let* ((marker-and-string (pop yas--backquote-markers-and-strings))
4030 (marker (car marker-and-string))
4031 (string (cdr marker-and-string)))
4037 (set-marker marker nil)))))
4039 (defun yas--scan-sexps (from count)
4041 (with-syntax-table (standard-syntax-table)
4042 (scan-sexps from count))
4046 (defun yas--make-marker (pos)
4047 "Create a marker at POS with nil `marker-insertion-type'."
4048 (let ((marker (set-marker (make-marker) pos)))
4049 (set-marker-insertion-type marker nil)
4052 (defun yas--field-parse-create (snippet &optional parent-field)
4053 "Parse most field expressions in SNIPPET, except for the simple one \"$n\".
4055 The following count as a field:
4057 * \"${n: text}\", for a numbered field with default text, as long as N is not 0;
4059 * \"${n: text$(expression)}, the same with a lisp expression;
4060 this is caught with the curiously named `yas--multi-dollar-lisp-expression-regexp'
4062 * the same as above but unnumbered, (no N:) and number is calculated automatically.
4064 When multiple expressions are found, only the last one counts."
4067 (while (re-search-forward yas--field-regexp nil t)
4068 (let* ((real-match-end-0 (yas--scan-sexps (1+ (match-beginning 0)) 1))
4069 (number (and (match-string-no-properties 1)
4070 (string-to-number (match-string-no-properties 1))))
4071 (brand-new-field (and real-match-end-0
4072 ;; break if on "$(" immediately
4073 ;; after the ":", this will be
4074 ;; caught as a mirror with
4076 (not (save-match-data
4077 (eq (string-match "$[ \t\n]*("
4078 (match-string-no-properties 2)) 0)))
4079 ;; allow ${0: some exit text}
4080 ;; (not (and number (zerop number)))
4081 (yas--make-field number
4082 (yas--make-marker (match-beginning 2))
4083 (yas--make-marker (1- real-match-end-0))
4085 (when brand-new-field
4086 (goto-char real-match-end-0)
4087 (push (cons (1- real-match-end-0) real-match-end-0)
4088 yas--dollar-regions)
4089 (push (cons (match-beginning 0) (match-beginning 2))
4090 yas--dollar-regions)
4091 (push brand-new-field (yas--snippet-fields snippet))
4094 (narrow-to-region (yas--field-start brand-new-field) (yas--field-end brand-new-field))
4095 (goto-char (point-min))
4096 (yas--field-parse-create snippet brand-new-field)))))))
4097 ;; if we entered from a parent field, now search for the
4098 ;; `yas--multi-dollar-lisp-expression-regexp'. This is used for
4099 ;; primary field transformations
4103 (while (re-search-forward yas--multi-dollar-lisp-expression-regexp nil t)
4104 (let* ((real-match-end-1 (yas--scan-sexps (match-beginning 1) 1)))
4105 ;; commit the primary field transformation if:
4107 ;; 1. we don't find it in yas--dollar-regions (a subnested
4108 ;; field) might have already caught it.
4110 ;; 2. we really make sure we have either two '$' or some
4111 ;; text and a '$' after the colon ':'. This is a FIXME: work
4112 ;; my regular expressions and end these ugly hacks.
4114 (when (and real-match-end-1
4115 (not (member (cons (match-beginning 0)
4117 yas--dollar-regions))
4119 (char-before (1- (match-beginning 1))))))
4120 (let ((lisp-expression-string (buffer-substring-no-properties (match-beginning 1)
4122 (setf (yas--field-transform parent-field)
4123 (yas--read-lisp (yas--restore-escapes lisp-expression-string))))
4124 (push (cons (match-beginning 0) real-match-end-1)
4125 yas--dollar-regions)))))))
4127 (defun yas--transform-mirror-parse-create (snippet)
4128 "Parse the \"${n:$(lisp-expression)}\" mirror transformations in SNIPPET."
4129 (while (re-search-forward yas--transform-mirror-regexp nil t)
4130 (let* ((real-match-end-0 (yas--scan-sexps (1+ (match-beginning 0)) 1))
4131 (number (string-to-number (match-string-no-properties 1)))
4133 (not (zerop number))
4134 (yas--snippet-find-field snippet number)))
4136 (and real-match-end-0
4138 (yas--make-mirror (yas--make-marker (match-beginning 0))
4139 (yas--make-marker (match-beginning 0))
4141 (yas--restore-escapes
4142 (buffer-substring-no-properties (match-beginning 2)
4143 (1- real-match-end-0))))))))
4144 (when brand-new-mirror
4145 (push brand-new-mirror
4146 (yas--field-mirrors field))
4147 (yas--calculate-mirrors-in-fields snippet brand-new-mirror)
4148 (push (cons (match-beginning 0) real-match-end-0) yas--dollar-regions)))))
4150 (defun yas--simple-mirror-parse-create (snippet)
4151 "Parse the simple \"$n\" fields/mirrors/exitmarkers in SNIPPET."
4152 (while (re-search-forward yas--simple-mirror-regexp nil t)
4153 (let ((number (string-to-number (match-string-no-properties 1))))
4154 (cond ((zerop number)
4156 (setf (yas--snippet-exit snippet)
4157 (yas--make-exit (yas--make-marker (match-end 0))))
4159 (goto-char (match-beginning 0))
4160 (when yas-wrap-around-region
4161 (cond (yas-selected-text
4162 (insert yas-selected-text))
4163 ((and (eq yas-wrap-around-region 'cua)
4166 (insert (prog1 (get-register ?0)
4167 (set-register ?0 nil))))))
4168 (push (cons (point) (yas--exit-marker (yas--snippet-exit snippet)))
4169 yas--dollar-regions)))
4171 (let ((field (yas--snippet-find-field snippet number)))
4173 (let ((brand-new-mirror (yas--make-mirror
4174 (yas--make-marker (match-beginning 0))
4175 (yas--make-marker (match-beginning 0))
4177 (push brand-new-mirror
4178 (yas--field-mirrors field))
4179 (yas--calculate-mirrors-in-fields snippet brand-new-mirror))
4180 (push (yas--make-field number
4181 (yas--make-marker (match-beginning 0))
4182 (yas--make-marker (match-beginning 0))
4184 (yas--snippet-fields snippet))))
4185 (push (cons (match-beginning 0) (match-end 0))
4186 yas--dollar-regions))))))
4188 (defun yas--delete-regions (regions)
4189 "Sort disjuct REGIONS by start point, then delete from the back."
4190 (mapc #'(lambda (reg)
4191 (delete-region (car reg) (cdr reg)))
4194 (>= (car r1) (car r2))))))
4196 (defun yas--calculate-mirror-depth (mirror &optional traversed)
4197 (let* ((parent (yas--mirror-parent-field mirror))
4198 (parents-mirrors (and parent
4199 (yas--field-mirrors parent))))
4200 (or (yas--mirror-depth mirror)
4201 (setf (yas--mirror-depth mirror)
4202 (cond ((memq mirror traversed)
4204 ((and parent parents-mirrors)
4206 (mapcar #'(lambda (m)
4207 (yas--calculate-mirror-depth m
4216 (defun yas--update-mirrors (snippet)
4217 "Updates all the mirrors of SNIPPET."
4219 (dolist (field-and-mirror (sort
4220 ;; make a list of ((F1 . M1) (F1 . M2) (F2 . M3) (F2 . M4) ...)
4221 ;; where F is the field that M is mirroring
4223 (mapcan #'(lambda (field)
4224 (mapcar #'(lambda (mirror)
4225 (cons field mirror))
4226 (yas--field-mirrors field)))
4227 (yas--snippet-fields snippet))
4228 ;; then sort this list so that entries with mirrors with parent
4229 ;; fields appear before. This was important for fixing #290, and
4230 ;; luckily also handles the case where a mirror in a field causes
4231 ;; another mirror to need reupdating
4233 #'(lambda (field-and-mirror1 field-and-mirror2)
4234 (> (yas--calculate-mirror-depth (cdr field-and-mirror1))
4235 (yas--calculate-mirror-depth (cdr field-and-mirror2))))))
4236 (let* ((field (car field-and-mirror))
4237 (mirror (cdr field-and-mirror))
4238 (parent-field (yas--mirror-parent-field mirror)))
4239 ;; before updating a mirror with a parent-field, maybe advance
4243 (yas--advance-start-maybe mirror (yas--fom-start parent-field)))
4244 ;; update this mirror
4246 (yas--mirror-update-display mirror field)
4247 ;; `yas--place-overlays' is needed if the active field and
4248 ;; protected overlays have been changed because of insertions
4249 ;; in `yas--mirror-update-display'
4251 (when (eq field (yas--snippet-active-field snippet))
4252 (yas--place-overlays snippet field))))))
4254 (defun yas--mirror-update-display (mirror field)
4255 "Update MIRROR according to FIELD (and mirror transform)."
4257 (let* ((mirror-parent-field (yas--mirror-parent-field mirror))
4258 (reflection (and (not (and mirror-parent-field
4259 (yas--field-modified-p mirror-parent-field)))
4260 (or (yas--apply-transform mirror field 'empty-on-nil)
4261 (yas--field-text-for-display field)))))
4262 (when (and reflection
4263 (not (string= reflection (buffer-substring-no-properties (yas--mirror-start mirror)
4264 (yas--mirror-end mirror)))))
4265 (goto-char (yas--mirror-start mirror))
4266 (yas--inhibit-overlay-hooks
4267 (insert reflection))
4268 (if (> (yas--mirror-end mirror) (point))
4269 (delete-region (point) (yas--mirror-end mirror))
4270 (set-marker (yas--mirror-end mirror) (point))
4271 (yas--advance-start-maybe (yas--mirror-next mirror) (point))
4272 ;; super-special advance
4273 (yas--advance-end-of-parents-maybe mirror-parent-field (point))))))
4275 (defun yas--field-update-display (field snippet)
4276 "Much like `yas--mirror-update-display', but for fields."
4277 (when (yas--field-transform field)
4278 (let ((transformed (and (not (eq (yas--field-number field) 0))
4279 (yas--apply-transform field field)))
4281 (when (and transformed
4282 (not (string= transformed (buffer-substring-no-properties (yas--field-start field)
4283 (yas--field-end field)))))
4284 (setf (yas--field-modified-p field) t)
4285 (goto-char (yas--field-start field))
4286 (yas--inhibit-overlay-hooks
4287 (insert transformed)
4288 (if (> (yas--field-end field) (point))
4289 (delete-region (point) (yas--field-end field))
4290 (set-marker (yas--field-end field) (point))
4291 (yas--advance-start-maybe (yas--field-next field) (point)))
4295 ;;; Post-command hook:
4297 (defun yas--post-command-handler ()
4298 "Handles various yasnippet conditions after each command."
4299 (cond (yas--protection-violation
4300 (goto-char yas--protection-violation)
4301 (setq yas--protection-violation nil))
4302 ((eq 'undo this-command)
4304 ;; After undo revival the correct field is sometimes not
4305 ;; restored correctly, this condition handles that
4307 (let* ((snippet (car (yas--snippets-at-point)))
4308 (target-field (and snippet
4309 (find-if-not #'(lambda (field)
4310 (yas--field-probably-deleted-p snippet field))
4312 (cons (yas--snippet-active-field snippet)
4313 (yas--snippet-fields snippet)))))))
4315 (yas--move-to-field snippet target-field))))
4316 ((not (yas--undo-in-progress))
4317 ;; When not in an undo, check if we must commit the snippet
4318 ;; (user exited it).
4319 (yas--check-commit-snippet))))
4323 ;; The docstrings for some functions are generated dynamically
4324 ;; depending on the context.
4326 (put 'yas-expand 'function-documentation
4327 '(yas--expand-from-trigger-key-doc))
4328 (defun yas--expand-from-trigger-key-doc ()
4329 "A doc synthesizer for `yas--expand-from-trigger-key-doc'."
4330 (let ((fallback-description
4331 (cond ((eq yas-fallback-behavior 'call-other-command)
4332 (let* ((fallback (yas--keybinding-beyond-yasnippet)))
4334 (format " call command `%s'." (pp-to-string fallback)))
4335 " do nothing (`yas-expand' doesn't shadow\nanything)")))
4336 ((eq yas-fallback-behavior 'return-nil)
4339 ", defer to `yas-fallback-behaviour' (which see)"))))
4340 (concat "Expand a snippet before point. If no snippet
4341 expansion is possible,"
4342 fallback-description
4343 "\n\nOptional argument FIELD is for non-interactive use and is an
4344 object satisfying `yas--field-p' to restrict the expansion to.")))
4346 (put 'yas-expand-from-keymap 'function-documentation '(yas--expand-from-keymap-doc))
4347 (defun yas--expand-from-keymap-doc ()
4348 "A doc synthesizer for `yas--expand-from-keymap-doc'."
4349 (add-hook 'temp-buffer-show-hook 'yas--snippet-description-finish-runonce)
4350 (concat "Expand/run snippets from keymaps, possibly falling back to original binding.\n"
4351 (when (eq this-command 'describe-key)
4352 (let* ((vec (this-single-command-keys))
4353 (templates (mapcan #'(lambda (table)
4354 (yas--fetch table vec))
4355 (yas--get-snippet-tables)))
4356 (yas--direct-keymaps nil)
4357 (fallback (key-binding vec)))
4358 (concat "In this case, "
4360 (concat "these snippets are bound to this key:\n"
4361 (yas--template-pretty-list templates)
4362 "\n\nIf none of these expands, "))
4364 (format "fallback `%s' will be called." (pp-to-string fallback)))
4365 "no fallback keybinding is called."))))))
4367 (defun yas--template-pretty-list (templates)
4369 (yas-buffer-local-condition 'always))
4370 (dolist (plate templates)
4371 (setq acc (concat acc "\n*) "
4372 (propertize (concat "\\\\snippet `" (car plate) "'")
4373 'yasnippet (cdr plate)))))
4376 (define-button-type 'help-snippet-def
4377 :supertype 'help-xref
4378 'help-function (lambda (template) (yas--visit-snippet-file-1 template))
4379 'help-echo (purecopy "mouse-2, RET: find snippets's definition"))
4381 (defun yas--snippet-description-finish-runonce ()
4382 "Final adjustments for the help buffer when snippets are concerned."
4383 (yas--create-snippet-xrefs)
4384 (remove-hook 'temp-buffer-show-hook 'yas--snippet-description-finish-runonce))
4386 (defun yas--create-snippet-xrefs ()
4388 (goto-char (point-min))
4389 (while (search-forward-regexp "\\\\\\\\snippet[ \s\t]+`\\([^']+\\)'" nil t)
4390 (let ((template (get-text-property (match-beginning 1)
4393 (help-xref-button 1 'help-snippet-def template)
4394 (kill-region (match-end 1) (match-end 0))
4395 (kill-region (match-beginning 0) (match-beginning 1)))))))
4397 (defun yas--expand-uuid (mode-symbol uuid &optional start end expand-env)
4398 "Expand a snippet registered in MODE-SYMBOL's table with UUID.
4400 Remaining args as in `yas-expand-snippet'."
4401 (let* ((table (gethash mode-symbol yas--tables))
4402 (yas--current-template (and table
4403 (gethash uuid (yas--table-uuidhash table)))))
4404 (when yas--current-template
4405 (yas-expand-snippet (yas--template-content yas--current-template)))))
4409 (defvar yas-verbosity 4
4410 "Log level for `yas--message' 4 means trace most anything, 0 means nothing.")
4412 (defun yas--message (level message &rest args)
4413 "When LEVEL is above `yas-verbosity-level', log MESSAGE and ARGS."
4414 (when (> yas-verbosity level)
4415 (message "%s" (apply #'yas--format message args))))
4417 (defun yas--format (format-control &rest format-args)
4418 (apply #'format (concat "[yas] " format-control) format-args))
4425 ;; `locate-dominating-file'
4426 ;; `region-active-p'
4428 ;; added for compatibility in emacsen < 23
4429 (unless (>= emacs-major-version 23)
4430 (unless (fboundp 'region-active-p)
4431 (defun region-active-p () (and transient-mark-mode mark-active)))
4433 (unless (fboundp 'locate-dominating-file)
4434 (defvar locate-dominating-stop-dir-regexp
4435 "\\`\\(?:[\\/][\\/][^\\/]+[\\/]\\|/\\(?:net\\|afs\\|\\.\\.\\.\\)/\\)\\'"
4436 "Regexp of directory names which stop the search in `locate-dominating-file'.
4437 Any directory whose name matches this regexp will be treated like
4438 a kind of root directory by `locate-dominating-file' which will stop its search
4439 when it bumps into it.
4440 The default regexp prevents fruitless and time-consuming attempts to find
4441 special files in directories in which filenames are interpreted as hostnames,
4442 or mount points potentially requiring authentication as a different user.")
4444 (defun locate-dominating-file (file name)
4445 "Look up the directory hierarchy from FILE for a file named NAME.
4446 Stop at the first parent directory containing a file NAME,
4447 and return the directory. Return nil if not found."
4448 ;; We used to use the above locate-dominating-files code, but the
4449 ;; directory-files call is very costly, so we're much better off doing
4450 ;; multiple calls using the code in here.
4452 ;; Represent /home/luser/foo as ~/foo so that we don't try to look for
4453 ;; `name' in /home or in /.
4454 (setq file (abbreviate-file-name file))
4457 ;; `user' is not initialized outside the loop because
4458 ;; `file' may not exist, so we may have to walk up part of the
4459 ;; hierarchy before we find the "initial UUID".
4462 (while (not (or root
4464 ;; FIXME: Disabled this heuristic because it is sometimes
4466 ;; As a heuristic, we stop looking up the hierarchy of
4467 ;; directories as soon as we find a directory belonging
4468 ;; to another user. This should save us from looking in
4469 ;; things like /net and /afs. This assumes that all the
4470 ;; files inside a project belong to the same user.
4471 ;; (let ((prev-user user))
4472 ;; (setq user (nth 2 (file-attributes file)))
4473 ;; (and prev-user (not (equal user prev-user))))
4474 (string-match locate-dominating-stop-dir-regexp file)))
4475 (setq try (file-exists-p (expand-file-name name file)))
4476 (cond (try (setq root file))
4477 ((equal file (setq prev-file file
4478 file (file-name-directory
4479 (directory-file-name file))))
4483 ;; `c-neutralize-syntax-in-CPP` sometimes fires "End of Buffer" error
4484 ;; (when it execute forward-char) and interrupt the after change
4485 ;; hook. Thus prevent the insert-behind hook of yasnippet to be
4486 ;; invoked. Here's a way to reproduce it:
4488 ;; # open a *new* Emacs.
4489 ;; # load yasnippet.
4490 ;; # open a *new* .cpp file.
4491 ;; # input "inc" and press TAB to expand the snippet.
4492 ;; # select the `#include <...>` snippet.
4493 ;; # type inside `<>`
4495 (defadvice c-neutralize-syntax-in-CPP
4496 (around yas--mp/c-neutralize-syntax-in-CPP activate)
4497 "Adviced `c-neutralize-syntax-in-CPP' to properly
4498 handle the end-of-buffer error fired in it by calling
4499 `forward-char' at the end of buffer."
4502 (error (message (error-message-string err)))))
4504 ;; disable c-electric-* serial command in YAS fields
4505 (add-hook 'c-mode-common-hook
4507 (dolist (k '(":" ">" ";" "<" "{" "}"))
4508 (define-key (symbol-value (make-local-variable 'yas-keymap))
4509 k 'self-insert-command))))
4511 ;;; Backward compatibility to yasnippet <= 0.7
4513 (defvar yas--exported-syms '(;; `defcustom's
4516 yas-prompt-functions
4518 yas-also-auto-indent-first-line
4520 yas-triggers-in-field
4521 yas-fallback-behavior
4522 yas-choose-keys-first
4523 yas-choose-tables-first
4526 yas-wrap-around-region
4529 yas-expand-only-for-last-commands
4530 yas-field-highlight-face
4532 ;; these vars can be customized as well
4538 yas-after-exit-snippet-hook
4539 yas-before-expand-snippet-hook
4540 yas-buffer-local-condition
4543 ;; prompting functions
4548 yas-completing-prompt
4551 ;; interactive functions
4556 yas-direct-keymaps-reload
4560 yas-compile-directory
4563 yas-expand-from-trigger-key
4564 yas-expand-from-keymap
4566 yas-visit-snippet-file
4568 yas-load-snippet-buffer
4571 yas-next-field-or-maybe-expand
4576 yas-exit-all-snippets
4577 yas-skip-and-clear-or-delete-char
4579 ;; symbols that I "exported" for use
4580 ;; in snippets and hookage
4598 yas-default-from-field
4601 yas-define-condition-cache
4602 yas-hippie-try-expand
4605 ;; debug definitions
4606 ;; yas-debug-snippet-vars
4607 ;; yas-exterminate-package
4610 ;; testing definitions
4611 ;; yas-should-expand
4612 ;; yas-should-not-expand
4614 ;; yas-make-file-or-dirs
4616 ;; yas-saving-variables
4617 ;; yas-call-with-snippet-dirs
4618 ;; yas-with-snippet-dirs
4620 "Exported yasnippet symbols.
4622 i.e. ones that I will try to keep in future yasnippet versions
4623 and ones that other elisp libraries can more or less safely rely
4626 (defvar yas--dont-backport '(yas-active-keys)
4627 "Exported symbols that don't map back to \"yas/*\" variants.")
4629 (dolist (sym (set-difference yas--exported-syms yas--dont-backport))
4630 (let ((backported (intern (replace-regexp-in-string "^yas-" "yas/" (symbol-name sym)))))
4632 (make-obsolete-variable backported sym "yasnippet 0.8")
4633 (defvaralias backported sym))
4635 (make-obsolete backported sym "yasnippet 0.8")
4636 (defalias backported sym))))
4639 (provide 'yasnippet)
4641 ;;; yasnippet.el ends here
4644 ;; byte-compile-warnings: (not cl-functions)